Spaces:
Paused
Paused
Download dual_faces.py from Simzy/wan22-extend: direct link, hf CLI and curl.
- Browser
- Download file 7.91 kB
-
https://huggingface.co/spaces/Simzy/wan22-extend/resolve/main/dual_faces.py
- Command line
-
hf download hf://spaces/Simzy/wan22-extend/dual_faces.py
-
curl -L -o dual_faces.py https://huggingface.co/spaces/Simzy/wan22-extend/resolve/main/dual_faces.py
7.91 kB
| """Swap two people in one scene: left face onto the left person, right face onto the right person. | |
| The RunPod worker replaces a single head. This module crops each person, runs that | |
| one-head swap twice, and pastes the results back. Video clips are sampled so a | |
| short clip does not fire a job for every source frame. | |
| """ | |
| from __future__ import annotations | |
| from collections.abc import Callable | |
| from pathlib import Path | |
| import cv2 | |
| import numpy as np | |
| from PIL import Image, ImageFilter | |
| SwapOne = Callable[[Image.Image, Image.Image], Image.Image] | |
| DetectFn = Callable[[Image.Image], list[tuple[int, int, int, int]]] | |
| MAX_CLIP_SECONDS = 5.0 | |
| SAMPLE_FPS = 2.0 | |
| MAX_FRAMES = 10 | |
| def sample_frame_indexes( | |
| frame_count: int, | |
| fps: float, | |
| *, | |
| sample_fps: float = SAMPLE_FPS, | |
| max_seconds: float = MAX_CLIP_SECONDS, | |
| max_frames: int = MAX_FRAMES, | |
| ) -> list[int]: | |
| """Frame indexes to swap. Caps length and rate so a clip stays a small job batch.""" | |
| if frame_count <= 0: | |
| return [] | |
| fps = fps if fps and fps > 0 else 24.0 | |
| sample_fps = sample_fps if sample_fps > 0 else SAMPLE_FPS | |
| step = max(1, int(round(fps / sample_fps))) | |
| limit = min(frame_count, max(1, int(max_seconds * fps))) | |
| indexes = list(range(0, limit, step)) | |
| if len(indexes) > max_frames: | |
| indexes = indexes[:max_frames] | |
| return indexes or [0] | |
| def detect_faces(image: Image.Image) -> list[tuple[int, int, int, int]]: | |
| """Frontal faces as (x, y, w, h), left to right. Empty when none are found. | |
| OpenCV 5.x main/headless wheels dropped ``CascadeClassifier`` (moved to contrib). | |
| Pin ``opencv-python-headless`` to 4.x so Haar works; if the attribute is still | |
| missing, return no boxes so ``person_regions`` falls back to left/right halves. | |
| """ | |
| if not hasattr(cv2, "CascadeClassifier"): | |
| return [] | |
| rgb = np.asarray(image.convert("RGB")) | |
| gray = cv2.cvtColor(rgb, cv2.COLOR_RGB2GRAY) | |
| cascade_path = getattr(cv2, "data", None) | |
| cascade_dir = getattr(cascade_path, "haarcascades", None) if cascade_path is not None else None | |
| if not cascade_dir: | |
| return [] | |
| cascade = cv2.CascadeClassifier(cascade_dir + "haarcascade_frontalface_default.xml") | |
| if cascade.empty(): | |
| return [] | |
| found = cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(32, 32)) | |
| boxes = [(int(x), int(y), int(w), int(h)) for (x, y, w, h) in found] | |
| boxes.sort(key=lambda box: box[0]) | |
| return boxes | |
| def _region(size: tuple[int, int], box: tuple[int, int, int, int]) -> tuple[int, int, int, int]: | |
| width, height = size | |
| x, y, w, h = box | |
| pad_x = int(w * 0.75) | |
| pad_top = int(h * 0.75) | |
| pad_bottom = int(h * 1.35) | |
| x0 = max(0, x - pad_x) | |
| y0 = max(0, y - pad_top) | |
| x1 = min(width, x + w + pad_x) | |
| y1 = min(height, y + h + pad_bottom) | |
| if x1 - x0 < 8 or y1 - y0 < 8: | |
| return 0, 0, width, height | |
| return x0, y0, x1, y1 | |
| def person_regions( | |
| size: tuple[int, int], | |
| boxes: list[tuple[int, int, int, int]], | |
| ) -> tuple[list[tuple[int, int, int, int]], str]: | |
| """Left and right crop boxes. Halves of the scene when two faces are not found.""" | |
| width, height = size | |
| if len(boxes) >= 2: | |
| left = _region(size, boxes[0]) | |
| right = _region(size, boxes[-1]) | |
| if left[2] > right[0]: | |
| mid = (boxes[0][0] + boxes[0][2] // 2 + boxes[-1][0] + boxes[-1][2] // 2) // 2 | |
| mid = max(1, min(width - 1, mid)) | |
| left = (left[0], left[1], min(left[2], mid), left[3]) | |
| right = (max(right[0], mid), right[1], right[2], right[3]) | |
| return [left, right], "faces" | |
| half = width // 2 | |
| return [(0, 0, half, height), (half, 0, width, height)], "halves" | |
| def _feather_mask(size: tuple[int, int]) -> Image.Image: | |
| width, height = size | |
| inset = max(2, int(min(width, height) * 0.1)) | |
| mask = Image.new("L", (width, height), 0) | |
| inner_w = max(1, width - 2 * inset) | |
| inner_h = max(1, height - 2 * inset) | |
| mask.paste(Image.new("L", (inner_w, inner_h), 255), (inset, inset)) | |
| return mask.filter(ImageFilter.GaussianBlur(radius=max(1, inset // 2))) | |
| def _paste(base: Image.Image, swapped: Image.Image, box: tuple[int, int, int, int]) -> Image.Image: | |
| x0, y0, x1, y1 = box | |
| width, height = max(1, x1 - x0), max(1, y1 - y0) | |
| patch = swapped.convert("RGB").resize((width, height), Image.Resampling.LANCZOS) | |
| out = base.convert("RGB").copy() | |
| out.paste(patch, (x0, y0), _feather_mask((width, height))) | |
| return out | |
| def swap_two_faces( | |
| scene: Image.Image, | |
| left_face: Image.Image, | |
| right_face: Image.Image, | |
| swap_one: SwapOne, | |
| *, | |
| detect: DetectFn | None = None, | |
| ) -> tuple[Image.Image, dict]: | |
| """Replace the left person with ``left_face`` and the right person with ``right_face``.""" | |
| scene = scene.convert("RGB") | |
| finder = detect or detect_faces | |
| boxes = finder(scene) | |
| regions, method = person_regions(scene.size, boxes) | |
| result = scene | |
| for face, region in ((left_face, regions[0]), (right_face, regions[1])): | |
| crop = scene.crop(region) | |
| swapped = swap_one(face.convert("RGB"), crop) | |
| result = _paste(result, swapped, region) | |
| return result, {"method": method, "regions": regions, "faces": len(boxes)} | |
| def swap_video_frames( | |
| frames: list[Image.Image], | |
| left_face: Image.Image, | |
| right_face: Image.Image, | |
| swap_one: SwapOne, | |
| *, | |
| detect: DetectFn | None = None, | |
| on_frame: Callable[[int, int], None] | None = None, | |
| ) -> list[Image.Image]: | |
| swapped: list[Image.Image] = [] | |
| total = len(frames) | |
| for index, frame in enumerate(frames): | |
| if on_frame: | |
| on_frame(index, total) | |
| image, _info = swap_two_faces(frame, left_face, right_face, swap_one, detect=detect) | |
| swapped.append(image) | |
| return swapped | |
| def read_sampled_frames(path: str | Path, *, sample_fps: float = SAMPLE_FPS, max_seconds: float = MAX_CLIP_SECONDS, max_frames: int = MAX_FRAMES) -> tuple[list[Image.Image], float]: | |
| """Read a short sample of frames. Playback fps is the sample rate, not the source rate.""" | |
| cap = cv2.VideoCapture(str(path)) | |
| if not cap.isOpened(): | |
| raise ValueError("Could not open that video clip.") | |
| try: | |
| fps = float(cap.get(cv2.CAP_PROP_FPS) or 0.0) | |
| count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT) or 0) | |
| indexes = sample_frame_indexes(count, fps, sample_fps=sample_fps, max_seconds=max_seconds, max_frames=max_frames) | |
| frames: list[Image.Image] = [] | |
| if indexes and count > 0: | |
| for index in indexes: | |
| cap.set(cv2.CAP_PROP_POS_FRAMES, index) | |
| ok, frame = cap.read() | |
| if not ok or frame is None: | |
| continue | |
| frames.append(Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))) | |
| if not frames: | |
| cap.set(cv2.CAP_PROP_POS_FRAMES, 0) | |
| step = max(1, int(round((fps or 24.0) / sample_fps))) | |
| seen = 0 | |
| while len(frames) < max_frames: | |
| ok, frame = cap.read() | |
| if not ok or frame is None: | |
| break | |
| if seen % step == 0: | |
| frames.append(Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))) | |
| seen += 1 | |
| if seen >= int(max_seconds * (fps or 24.0)): | |
| break | |
| finally: | |
| cap.release() | |
| if not frames: | |
| raise ValueError("That video clip has no readable frames.") | |
| return frames, sample_fps | |
| def write_video(frames: list[Image.Image], dest: str | Path, fps: float) -> Path: | |
| import imageio.v2 as imageio | |
| dest = Path(dest) | |
| dest.parent.mkdir(parents=True, exist_ok=True) | |
| arrays = [np.asarray(frame.convert("RGB")) for frame in frames] | |
| imageio.mimwrite(dest, arrays, fps=max(1.0, fps), codec="libx264", quality=8) | |
| return dest | |