Spaces:
Running on Zero
Running on Zero
Download app.py from hugging-apps/duoedit: direct link, hf CLI and curl.
- Browser
- Download file 29.4 kB
-
https://huggingface.co/spaces/hugging-apps/duoedit/resolve/main/app.py
- Command line
-
hf download hf://spaces/hugging-apps/duoedit/app.py
-
curl -L -o app.py https://huggingface.co/spaces/hugging-apps/duoedit/resolve/main/app.py
29.4 kB
| import os | |
| os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True") | |
| import spaces # noqa: E402 — must precede torch / CUDA-touching imports | |
| import torch # noqa: E402 | |
| import gc # noqa: E402 | |
| import math # noqa: E402 | |
| import random # noqa: E402 | |
| import tempfile # noqa: E402 | |
| import time # noqa: E402 | |
| import cv2 # noqa: E402 | |
| import gradio as gr # noqa: E402 | |
| import imageio # noqa: E402 | |
| import numpy as np # noqa: E402 | |
| import torch.nn as nn # noqa: E402 | |
| import torch.nn.functional as F # noqa: E402 | |
| from accelerate import init_empty_weights # noqa: E402 | |
| from diffusers import AutoencoderKLWan, FlowMatchEulerDiscreteScheduler # noqa: E402 | |
| from diffusers.loaders.single_file_utils import convert_wan_transformer_to_diffusers # noqa: E402 | |
| from diffusers.models.transformers.transformer_wan import WanTransformer3DModel # noqa: E402 | |
| from huggingface_hub import hf_hub_download # noqa: E402 | |
| from PIL import Image, ImageDraw # noqa: E402 | |
| from safetensors.torch import load_file # noqa: E402 | |
| from torchao.quantization import Float8DynamicActivationFloat8WeightConfig, quantize_ # noqa: E402 | |
| from torchvision import transforms # noqa: E402 | |
| from transformers import ( # noqa: E402 | |
| AutoModelForImageSegmentation, | |
| AutoTokenizer, | |
| Sam2VideoModel, | |
| Sam2VideoProcessor, | |
| UMT5EncoderModel, | |
| ) | |
| # --------------------------------------------------------------------------- | |
| # DuoEdit = Wan2.2-Fun-A14B-Control + (per expert) rank-64 LoRA on q/k/v/ffn and | |
| # retrained input projections: the 52-ch `patch_embedding` | |
| # u = [z_t ; E(box video) ; P(1 - erase mask) ; E(full source video)] | |
| # and a 32-ch `ref_conv` taking [E(appearance canvas) ; E(identity canvas)], whose | |
| # tokens are prepended to the video tokens as an extra leading latent frame. | |
| # The official code repo is empty, so this follows the paper's appendix (A.1-A.5) | |
| # and the VideoX-Fun Wan2.2-Fun-Control reference pipeline it builds on. | |
| # --------------------------------------------------------------------------- | |
| BASE_ID = "alibaba-pai/Wan2.2-Fun-A14B-Control" | |
| DUOEDIT_ID = "JiayiWuLeo/DuoEdit" | |
| COMPONENTS_ID = "Wan-AI/Wan2.2-I2V-A14B-Diffusers" # same umt5-xxl + Wan2.1 VAE, diffusers layout | |
| SAM2_ID = "facebook/sam2.1-hiera-large" | |
| BIREFNET_ID = "ZhengPeng7/BiRefNet" | |
| LORA_SCALE = 32 / 64 # lora_alpha / rank (config.json) | |
| BOUNDARY = 0.9 # high-noise expert for t >= 900 | |
| SHIFT = 5.0 | |
| FPS = 16 | |
| DEFAULT_NEG = "bad detailed" # config.json negative_prompt | |
| DEFAULT_STEPS = 25 | |
| DEFAULT_CFG = 4.5 | |
| DEFAULT_FRAMES = 49 | |
| DEFAULT_RES = "480p" | |
| RESOLUTIONS = {"480p": 832 * 480, "576p": 1024 * 576, "720p": 1280 * 720} | |
| MAX_SEED = np.iinfo(np.int32).max | |
| # Subject-ID colour shared by the box video and the identity canvas. | |
| ID_COLOR = (255, 0, 0) | |
| DEVICE = "cuda" | |
| DTYPE = torch.bfloat16 | |
| WAN_CONFIG = dict( | |
| patch_size=(1, 2, 2), | |
| num_attention_heads=40, | |
| attention_head_dim=128, | |
| in_channels=52, | |
| out_channels=16, | |
| text_dim=4096, | |
| freq_dim=256, | |
| ffn_dim=13824, | |
| num_layers=40, | |
| cross_attn_norm=True, | |
| qk_norm="rms_norm_across_heads", | |
| eps=1e-6, | |
| image_dim=None, | |
| added_kv_proj_dim=None, | |
| rope_max_seq_len=1024, | |
| ) | |
| class DuoEditTransformer(WanTransformer3DModel): | |
| """Wan2.2 DiT with the Fun `ref_conv` reference branch (32 input channels for DuoEdit).""" | |
| def __init__(self, **kwargs): | |
| super().__init__(**kwargs) | |
| self.ref_conv = nn.Conv2d(32, 5120, kernel_size=(2, 2), stride=(2, 2)) | |
| def duo_forward(self, x, timestep, context, ref): | |
| b, _, f, h, w = x.shape | |
| p_t, p_h, p_w = self.config.patch_size | |
| # reference tokens occupy a leading latent frame in the shared RoPE grid | |
| rotary_emb = self.rope(x.new_empty((1, 1, f + 1, h, w))) | |
| hs = self.patch_embedding(x).flatten(2).transpose(1, 2) | |
| rt = self.ref_conv(ref).flatten(2).transpose(1, 2) | |
| n_ref = rt.shape[1] | |
| hs = torch.cat([rt, hs], dim=1).contiguous() | |
| temb, timestep_proj, context, _ = self.condition_embedder(timestep, context, None) | |
| timestep_proj = timestep_proj.unflatten(1, (6, -1)) | |
| for block in self.blocks: | |
| hs = block(hs, context, timestep_proj, rotary_emb) | |
| hs = hs[:, n_ref:] | |
| shift, scale = (self.scale_shift_table.to(temb.device) + temb.unsqueeze(1)).chunk(2, dim=1) | |
| hs = (self.norm_out(hs.float()) * (1 + scale) + shift).type_as(hs) | |
| hs = self.proj_out(hs) | |
| hs = hs.reshape(b, f // p_t, h // p_h, w // p_w, p_t, p_h, p_w, -1) | |
| hs = hs.permute(0, 7, 1, 4, 2, 5, 3, 6) | |
| return hs.flatten(6, 7).flatten(4, 5).flatten(2, 3) | |
| def build_expert(base_file: str, duo_file: str) -> DuoEditTransformer: | |
| sd = load_file(hf_hub_download(BASE_ID, base_file)) | |
| duo = load_file(hf_hub_download(DUOEDIT_ID, duo_file)) | |
| n_lora = 0 | |
| for k in list(duo.keys()): | |
| if k.endswith(".lora_A.weight"): | |
| base_k = k.replace(".lora_A.weight", ".weight") | |
| a = duo[k].float() | |
| bmat = duo[k.replace("lora_A", "lora_B")].float() | |
| w = sd[base_k] | |
| sd[base_k] = (w.float() + LORA_SCALE * (bmat @ a)).to(w.dtype) | |
| n_lora += 1 | |
| elif not k.endswith(".lora_B.weight"): | |
| # patch_embedding / ref_conv (weights + biases) are replaced outright | |
| assert k in sd, k | |
| sd[k] = duo[k].to(sd[k].dtype) | |
| del duo | |
| print(f"[load] {duo_file}: merged {n_lora} LoRA pairs", flush=True) | |
| sd = convert_wan_transformer_to_diffusers(sd) | |
| with init_empty_weights(): | |
| model = DuoEditTransformer(**WAN_CONFIG) | |
| missing, unexpected = model.load_state_dict(sd, strict=False, assign=True) | |
| assert not missing and not unexpected, (missing, unexpected) | |
| del sd | |
| for name, module in model.named_modules(): | |
| if any(p in name.split(".")[-1] for p in ("time_embedder", "norm1", "norm2", "norm3")): | |
| module.float() | |
| for blk in model.blocks: | |
| blk.scale_shift_table.data = blk.scale_shift_table.data.float() | |
| model.scale_shift_table.data = model.scale_shift_table.data.float() | |
| model.rope.freqs_cos = model.rope.freqs_cos.float() | |
| model.rope.freqs_sin = model.rope.freqs_sin.float() | |
| model.eval().requires_grad_(False) | |
| model.to(DEVICE) | |
| quantize_( | |
| model, | |
| Float8DynamicActivationFloat8WeightConfig(), | |
| filter_fn=lambda m, fqn: isinstance(m, nn.Linear) and fqn.startswith("blocks."), | |
| ) | |
| gc.collect() | |
| return model | |
| # --- load everything at module scope ---------------------------------------- | |
| t0 = time.time() | |
| transformer_high = build_expert("high_noise_model/diffusion_pytorch_model.safetensors", "duoedit_high_noise.safetensors") | |
| transformer_low = build_expert("low_noise_model/diffusion_pytorch_model.safetensors", "duoedit_low_noise.safetensors") | |
| tokenizer = AutoTokenizer.from_pretrained(COMPONENTS_ID, subfolder="tokenizer") | |
| text_encoder = UMT5EncoderModel.from_pretrained(COMPONENTS_ID, subfolder="text_encoder", dtype=DTYPE).to(DEVICE).eval() | |
| vae = AutoencoderKLWan.from_pretrained(COMPONENTS_ID, subfolder="vae", torch_dtype=torch.float32).to(DEVICE).eval() | |
| LAT_MEAN = torch.tensor(vae.config.latents_mean).view(1, 16, 1, 1, 1) | |
| LAT_STD = torch.tensor(vae.config.latents_std).view(1, 16, 1, 1, 1) | |
| sam_processor = Sam2VideoProcessor.from_pretrained(SAM2_ID) | |
| sam_model = Sam2VideoModel.from_pretrained(SAM2_ID, dtype=DTYPE).to(DEVICE).eval() | |
| birefnet = AutoModelForImageSegmentation.from_pretrained(BIREFNET_ID, trust_remote_code=True).float().to(DEVICE).eval() | |
| print(f"[load] all models ready in {time.time() - t0:.0f}s", flush=True) | |
| BIREF_TF = transforms.Compose( | |
| [ | |
| transforms.Resize((1024, 1024)), | |
| transforms.ToTensor(), | |
| transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]), | |
| ] | |
| ) | |
| # --- helpers ------------------------------------------------------------------ | |
| def read_video(path: str, max_frames: int): | |
| """Read a video resampled to 16 fps; returns list of RGB uint8 frames.""" | |
| cap = cv2.VideoCapture(path) | |
| src_fps = cap.get(cv2.CAP_PROP_FPS) or FPS | |
| step = src_fps / FPS | |
| frames, i, k = [], 0, 0 | |
| while len(frames) < max_frames: | |
| ok, fr = cap.read() | |
| if not ok: | |
| break | |
| if i >= round(k * step): | |
| frames.append(cv2.cvtColor(fr, cv2.COLOR_BGR2RGB)) | |
| k += 1 | |
| i += 1 | |
| cap.release() | |
| return frames | |
| def first_frame(path): | |
| if not path: | |
| return None | |
| frames = read_video(path, 1) | |
| return frames[0] if frames else None | |
| def target_size(w, h, area): | |
| s = math.sqrt(area / (w * h)) | |
| return max(16, int(round(w * s / 16)) * 16), max(16, int(round(h * s / 16)) * 16) | |
| def parse_region(region: str): | |
| try: | |
| vals = [float(v) for v in str(region).replace(" ", "").split(",")] | |
| assert len(vals) == 4 | |
| except Exception: | |
| raise gr.Error("Region must be 'x1,y1,x2,y2' in 0-1 coordinates — paint over the first frame to set it.") | |
| x1, y1, x2, y2 = vals | |
| x1, x2 = sorted((min(max(x1, 0), 1), min(max(x2, 0), 1))) | |
| y1, y2 = sorted((min(max(y1, 0), 1), min(max(y2, 0), 1))) | |
| if x2 - x1 < 0.01 or y2 - y1 < 0.01: | |
| raise gr.Error("The region is empty — paint over the subject / target area on the first frame.") | |
| return x1, y1, x2, y2 | |
| def region_from_editor(editor): | |
| """Bounding box (normalized) of everything painted in the ImageEditor layers.""" | |
| if not editor or not editor.get("layers"): | |
| return gr.update() | |
| alpha = None | |
| for layer in editor["layers"]: | |
| if layer is None: | |
| continue | |
| arr = np.asarray(layer) | |
| a = arr[..., 3] > 0 if arr.ndim == 3 and arr.shape[-1] == 4 else arr.sum(-1) > 0 | |
| alpha = a if alpha is None else (alpha | a) | |
| if alpha is None or not alpha.any(): | |
| return gr.update() | |
| ys, xs = np.nonzero(alpha) | |
| h, w = alpha.shape | |
| return f"{xs.min() / w:.3f},{ys.min() / h:.3f},{(xs.max() + 1) / w:.3f},{(ys.max() + 1) / h:.3f}" | |
| def load_editor(video): | |
| fr = first_frame(video) | |
| if fr is None: | |
| return None | |
| return {"background": fr, "layers": [], "composite": fr} | |
| def mask_bbox(m): | |
| ys, xs = np.nonzero(m) | |
| if len(xs) == 0: | |
| return None | |
| return xs.min(), ys.min(), xs.max() + 1, ys.max() + 1 | |
| def track_subject(frames, box_px): | |
| """SAM2.1 video tracking of the subject selected by a box on frame 0.""" | |
| h, w = frames[0].shape[:2] | |
| session = sam_processor.init_video_session(video=frames, inference_device=DEVICE, dtype=DTYPE) | |
| sam_processor.add_inputs_to_inference_session( | |
| inference_session=session, frame_idx=0, obj_ids=1, input_boxes=[[list(map(float, box_px))]] | |
| ) | |
| sam_model(inference_session=session, frame_idx=0) | |
| masks = np.zeros((len(frames), h, w), dtype=bool) | |
| for out in sam_model.propagate_in_video_iterator(session): | |
| m = sam_processor.post_process_masks([out.pred_masks], original_sizes=[[h, w]], binarize=True)[0] | |
| masks[out.frame_idx] = m[0, 0].cpu().numpy() > 0 | |
| return masks | |
| def cutout_reference(img: Image.Image): | |
| """Returns (RGB crop, silhouette mask crop) of the reference subject.""" | |
| img = img.convert("RGBA") | |
| rgba = np.asarray(img) | |
| alpha = rgba[..., 3] | |
| if (alpha < 250).mean() > 0.01: # user supplied a cutout | |
| sil = alpha > 127 | |
| else: | |
| x = BIREF_TF(img.convert("RGB")).unsqueeze(0).to(DEVICE) | |
| pred = birefnet(x)[-1].sigmoid()[0, 0].float().cpu().numpy() | |
| sil = cv2.resize(pred, img.size, interpolation=cv2.INTER_LINEAR) > 0.5 | |
| if sil.mean() < 0.005: | |
| sil = np.ones_like(sil) | |
| bb = mask_bbox(sil) | |
| x1, y1, x2, y2 = bb | |
| return rgba[y1:y2, x1:x2, :3], sil[y1:y2, x1:x2] | |
| def build_canvases(ref_rgb, ref_sil, w, h): | |
| """Appearance canvas (subject on black) + identity canvas (ID colour in its silhouette).""" | |
| app = np.zeros((h, w, 3), np.uint8) | |
| idc = np.zeros((h, w, 3), np.uint8) | |
| rh, rw = ref_sil.shape | |
| s = min(0.9 * w / rw, 0.9 * h / rh) | |
| nw, nh = max(1, int(rw * s)), max(1, int(rh * s)) | |
| rgb = cv2.resize(ref_rgb, (nw, nh), interpolation=cv2.INTER_AREA) | |
| sil = cv2.resize(ref_sil.astype(np.uint8), (nw, nh), interpolation=cv2.INTER_NEAREST).astype(bool) | |
| ox, oy = (w - nw) // 2, (h - nh) // 2 | |
| app[oy:oy + nh, ox:ox + nw][sil] = rgb[sil] | |
| idc[oy:oy + nh, ox:ox + nw][sil] = ID_COLOR | |
| return app, idc | |
| def to_pixels(frames): | |
| """list/array of HxWx3 uint8 -> (1,3,T,H,W) float in [-1,1] on cuda.""" | |
| arr = torch.from_numpy(np.stack(frames)).to(DEVICE) | |
| return (arr.permute(3, 0, 1, 2).unsqueeze(0).float() / 127.5 - 1.0) | |
| def vae_encode(pixels): | |
| z = vae.encode(pixels.float()).latent_dist.mode() | |
| return (z - LAT_MEAN.to(z)) / LAT_STD.to(z) | |
| def vae_decode(z): | |
| z = z.float() * LAT_STD.to(z.device) + LAT_MEAN.to(z.device) | |
| video = vae.decode(z).sample[0] # 3,T,H,W | |
| video = ((video.clamp(-1, 1) + 1) * 127.5).round().byte() | |
| return video.permute(1, 2, 3, 0).cpu().numpy() | |
| def encode_text(prompts): | |
| tok = tokenizer( | |
| prompts, padding="max_length", max_length=512, truncation=True, add_special_tokens=True, | |
| return_attention_mask=True, return_tensors="pt", | |
| ) | |
| ids, mask = tok.input_ids.to(DEVICE), tok.attention_mask.to(DEVICE) | |
| lens = mask.gt(0).sum(dim=1) | |
| emb = text_encoder(ids, mask).last_hidden_state.to(DTYPE) | |
| out = torch.zeros_like(emb) | |
| for i, n in enumerate(lens.tolist()): | |
| out[i, :n] = emb[i, :n] | |
| return out | |
| def make_preview(frame, mask0, box0, app, idc): | |
| im = Image.fromarray(frame).convert("RGB") | |
| if mask0 is not None and mask0.any(): | |
| ov = np.asarray(im).copy() | |
| ov[mask0] = (0.45 * ov[mask0] + 0.55 * np.array([128, 128, 128])).astype(np.uint8) | |
| im = Image.fromarray(ov) | |
| d = ImageDraw.Draw(im) | |
| if box0 is not None: | |
| d.rectangle(list(box0), outline=ID_COLOR, width=4) | |
| w, h = im.size | |
| tiles = [im] | |
| if app is not None: | |
| tiles += [Image.fromarray(app), Image.fromarray(idc)] | |
| out = Image.new("RGB", (w * len(tiles), h)) | |
| for i, t in enumerate(tiles): | |
| out.paste(t, (i * w, 0)) | |
| out.thumbnail((1536, 1536)) | |
| return out | |
| MAX_GPU_SECONDS = 600 | |
| def _estimate_seconds(resolution, num_frames, steps): | |
| # Measured on xlarge (fp8 experts, CFG batch of 2): 848x480 / 49 frames / 25 steps -> 193 s | |
| # (~7.2 s per step at ~22k tokens + ~10 s of VAE/SAM/text). Below adds ~15% headroom. | |
| area = RESOLUTIONS.get(resolution, RESOLUTIONS[DEFAULT_RES]) | |
| lat_f = (int(num_frames) - 1) // 4 + 2 # + reference frame | |
| tokens = lat_f * area / 256 | |
| per_step = 8.0 * (tokens / 22000) ** 1.3 | |
| return int(25 + int(steps) * per_step) | |
| def _estimate(source_video=None, mode="Remove", region="", prompt="", reference_image=None, | |
| resolution=DEFAULT_RES, num_frames=DEFAULT_FRAMES, steps=DEFAULT_STEPS, *args, **kwargs): | |
| try: | |
| return min(MAX_GPU_SECONDS, _estimate_seconds(resolution, num_frames, steps)) | |
| except Exception: | |
| return 240 | |
| def edit_video( | |
| source_video: str, | |
| mode: str = "Remove", | |
| region: str = "", | |
| prompt: str = "", | |
| reference_image: Image.Image | None = None, | |
| resolution: str = DEFAULT_RES, | |
| num_frames: int = DEFAULT_FRAMES, | |
| steps: int = DEFAULT_STEPS, | |
| guidance_scale: float = DEFAULT_CFG, | |
| motion_x: float = 0.0, | |
| motion_y: float = 0.0, | |
| negative_prompt: str = DEFAULT_NEG, | |
| seed: int = 42, | |
| randomize_seed: bool = False, | |
| progress=gr.Progress(track_tqdm=True), | |
| ): | |
| """Edit a local subject in a video with DuoEdit (remove / insert / replace). | |
| Args: | |
| source_video: Path to the source video. | |
| mode: "Remove" (erase the subject in `region`), "Insert" (place the reference subject into `region`), | |
| or "Replace" (erase the subject in `region` and put the reference subject on its trajectory). | |
| region: Normalized box "x1,y1,x2,y2" on the first frame (0-1). For Remove/Replace it selects the | |
| subject to track; for Insert it is where the new subject goes. | |
| prompt: Text describing the edited scene (motion, actions, effects). For removal a generic | |
| removal instruction works best. | |
| reference_image: Appearance reference for Insert / Replace (a photo or a transparent cut-out). | |
| resolution: Output resolution bucket ("480p", "576p", "720p"); aspect ratio is preserved. | |
| num_frames: Number of frames at 16 fps (4k+1, up to 81). | |
| steps: Denoising steps (paper: 25). | |
| guidance_scale: Text classifier-free guidance (paper: 4.5). | |
| motion_x: Insert only — horizontal drift of the box over the clip, as a fraction of frame width. | |
| motion_y: Insert only — vertical drift of the box over the clip, as a fraction of frame height. | |
| negative_prompt: Negative text prompt. | |
| seed: Random seed. | |
| randomize_seed: Draw a fresh seed. | |
| Returns: | |
| (edited mp4 path, conditions preview image, used seed) | |
| """ | |
| _T0[0] = time.perf_counter() | |
| print(f"[call] start mode={mode} region={region} frames={num_frames} res={resolution}", flush=True) | |
| try: | |
| return _edit_video(source_video, mode, region, prompt, reference_image, resolution, num_frames, steps, | |
| guidance_scale, motion_x, motion_y, negative_prompt, seed, randomize_seed, progress) | |
| except gr.Error: | |
| raise | |
| except Exception: | |
| import traceback | |
| traceback.print_exc() | |
| raise | |
| _T0 = [0.0] | |
| def _log(msg): | |
| print(f"[call] +{time.perf_counter() - _T0[0]:.1f}s {msg} | cuda mem {torch.cuda.memory_allocated() / 2**30:.1f} GB", flush=True) | |
| def _edit_video(source_video, mode, region, prompt, reference_image, resolution, num_frames, steps, | |
| guidance_scale, motion_x, motion_y, negative_prompt, seed, randomize_seed, progress): | |
| if not source_video: | |
| raise gr.Error("Upload a source video.") | |
| if mode not in ("Remove", "Insert", "Replace"): | |
| raise gr.Error("Mode must be Remove, Insert or Replace.") | |
| if mode in ("Insert", "Replace") and reference_image is None: | |
| raise gr.Error(f"{mode} needs a reference image of the new subject.") | |
| rx1, ry1, rx2, ry2 = parse_region(region) | |
| if _estimate_seconds(resolution, num_frames, steps) > MAX_GPU_SECONDS: | |
| raise gr.Error("This resolution / frame count / step combination exceeds the GPU time limit — lower one of them.") | |
| seed = random.randint(0, MAX_SEED) if randomize_seed else int(seed) | |
| t_start = time.perf_counter() | |
| num_frames = int(min(max(int(num_frames), 5), 81)) | |
| num_frames = (num_frames - 1) // 4 * 4 + 1 | |
| frames = read_video(source_video, num_frames) | |
| if len(frames) < 5: | |
| raise gr.Error("The video is too short (need at least 5 frames at 16 fps).") | |
| num_frames = (len(frames) - 1) // 4 * 4 + 1 | |
| frames = frames[:num_frames] | |
| h0, w0 = frames[0].shape[:2] | |
| W, H = target_size(w0, h0, RESOLUTIONS.get(resolution, RESOLUTIONS[DEFAULT_RES])) | |
| frames = [cv2.resize(f, (W, H), interpolation=cv2.INTER_AREA) for f in frames] | |
| box_px = (rx1 * W, ry1 * H, rx2 * W, ry2 * H) | |
| _log(f"read {num_frames} frames at {W}x{H}") | |
| # ---- erasure mask M ---- | |
| erase = np.zeros((num_frames, H, W), dtype=bool) | |
| tracked = None | |
| if mode in ("Remove", "Replace"): | |
| tracked = track_subject(frames, box_px) | |
| if not tracked[0].any(): # fall back to box footprint | |
| tracked[:] = False | |
| x1, y1, x2, y2 = map(int, box_px) | |
| tracked[:, y1:y2, x1:x2] = True | |
| kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (9, 9)) # dilate by 4 px | |
| erase = np.stack([cv2.dilate(m.astype(np.uint8), kernel) > 0 for m in tracked]) | |
| _log("mask ready") | |
| # ---- box trajectory B + reference canvases R ---- | |
| box_video = np.zeros((num_frames, H, W, 3), np.uint8) | |
| boxes = [] | |
| app_canvas = np.zeros((H, W, 3), np.uint8) | |
| id_canvas = np.zeros((H, W, 3), np.uint8) | |
| if mode in ("Insert", "Replace"): | |
| if mode == "Insert": | |
| for t in range(num_frames): | |
| a = t / max(num_frames - 1, 1) | |
| dx, dy = motion_x * W * a, motion_y * H * a | |
| boxes.append((box_px[0] + dx, box_px[1] + dy, box_px[2] + dx, box_px[3] + dy)) | |
| else: | |
| prev = box_px | |
| for t in range(num_frames): | |
| bb = mask_bbox(tracked[t]) | |
| prev = bb if bb is not None else prev | |
| boxes.append(prev) | |
| for t, (x1, y1, x2, y2) in enumerate(boxes): | |
| x1, x2 = int(np.clip(round(x1), 0, W)), int(np.clip(round(x2), 0, W)) | |
| y1, y2 = int(np.clip(round(y1), 0, H)), int(np.clip(round(y2), 0, H)) | |
| box_video[t, y1:y2, x1:x2] = ID_COLOR | |
| ref_rgb, ref_sil = cutout_reference(reference_image) | |
| app_canvas, id_canvas = build_canvases(ref_rgb, ref_sil, W, H) | |
| preview = make_preview( | |
| frames[0], | |
| erase[0] if mode != "Insert" else None, | |
| boxes[0] if boxes else None, | |
| app_canvas if mode != "Remove" else None, | |
| id_canvas, | |
| ) | |
| _log("canvases ready") | |
| # ---- latent conditions ---- | |
| with torch.inference_mode(): | |
| src_lat = vae_encode(to_pixels(frames)) # E(S), full unmasked source | |
| box_lat = vae_encode(to_pixels(box_video)) # E(B) | |
| lat_f, lat_h, lat_w = src_lat.shape[2:] | |
| m = torch.from_numpy(erase).to(DEVICE).float()[None, None] # 1,1,T,H,W ; 1 = erase | |
| m = torch.cat([m[:, :, :1].repeat(1, 1, 4, 1, 1), m[:, :, 1:]], dim=2) | |
| m = m.view(1, m.shape[2] // 4, 4, H, W).transpose(1, 2) # 1,4,T',H,W | |
| mask_lat = F.interpolate(1 - m, size=(lat_f, lat_h, lat_w), mode="trilinear", align_corners=False) | |
| app_lat = vae_encode(to_pixels([app_canvas]))[:, :, 0] | |
| id_lat = vae_encode(to_pixels([id_canvas]))[:, :, 0] | |
| ref = torch.cat([app_lat, id_lat], dim=1).to(DTYPE) # 1,32,h,w | |
| cond = torch.cat([box_lat, mask_lat, src_lat], dim=1).to(DTYPE) # 1,36,T',h,w | |
| _log("vae encoded") | |
| ctx = encode_text([prompt or "", negative_prompt or ""]) | |
| _log("text encoded") | |
| do_cfg = float(guidance_scale) > 1.0 | |
| if not do_cfg: | |
| ctx = ctx[:1] | |
| bsz = ctx.shape[0] | |
| cond_b = cond.expand(bsz, -1, -1, -1, -1) | |
| ref_b = ref.expand(bsz, -1, -1, -1) | |
| scheduler = FlowMatchEulerDiscreteScheduler(num_train_timesteps=1000, shift=SHIFT) | |
| scheduler.set_timesteps(int(steps), device=DEVICE) | |
| gen = torch.Generator(device=DEVICE).manual_seed(seed) | |
| latents = torch.randn((1, 16, lat_f, lat_h, lat_w), generator=gen, device=DEVICE, dtype=torch.float32) | |
| for t in progress.tqdm(scheduler.timesteps, desc="Denoising"): | |
| model = transformer_high if t >= BOUNDARY * 1000 else transformer_low | |
| x = torch.cat([latents.to(DTYPE).expand(bsz, -1, -1, -1, -1), cond_b], dim=1) | |
| ts = t.expand(bsz).to(DEVICE) | |
| pred = model.duo_forward(x, ts, ctx, ref_b).float() | |
| if do_cfg: | |
| p_c, p_u = pred.chunk(2) | |
| pred = p_u + float(guidance_scale) * (p_c - p_u) | |
| latents = scheduler.step(pred, t, latents, return_dict=False)[0] | |
| video = vae_decode(latents) | |
| out_path = tempfile.NamedTemporaryFile(suffix=".mp4", delete=False).name | |
| imageio.mimwrite(out_path, list(video), fps=FPS, quality=8, macro_block_size=1) | |
| print( | |
| f"[timing] {mode} {W}x{H} {num_frames}f {int(steps)} steps cfg={guidance_scale} " | |
| f"-> {time.perf_counter() - t_start:.1f}s", | |
| flush=True, | |
| ) | |
| return out_path, preview, seed | |
| # --- UI --------------------------------------------------------------------------- | |
| CSS = """ | |
| #col-container { max-width: 1200px; margin: 0 auto; } | |
| .dark .gradio-container { color: var(--body-text-color); } | |
| """ | |
| REMOVE_PROMPT = "Remove the marked subject together with its associated effects, such as shadows and reflections, and fill in the background naturally." | |
| with gr.Blocks() as demo: | |
| with gr.Column(elem_id="col-container"): | |
| gr.Markdown( | |
| """ | |
| # DuoEdit — local video editing with two primitives | |
| Remove, insert or replace a subject in a video. DuoEdit learns only **removal** (erasure mask) and **insertion** | |
| (box trajectory + appearance reference) on top of Wan2.2-Fun-A14B-Control; replacement is the two combined zero-shot. | |
| [Paper](https://huggingface.co/papers/2611.35509) · [Project page](https://jiayi-wu-leo.github.io/duoedit/) · [Model](https://huggingface.co/JiayiWuLeo/DuoEdit) | |
| **How to use:** upload a video → paint roughly over the subject (Remove / Replace) or over where the new subject should | |
| be (Insert) on the first frame → for Insert / Replace add a reference image and describe the result → Edit. | |
| """ | |
| ) | |
| with gr.Row(): | |
| with gr.Column(): | |
| source_video = gr.Video(label="Source video", sources=["upload"]) | |
| mode = gr.Radio(["Remove", "Insert", "Replace"], value="Remove", label="Edit") | |
| editor = gr.ImageEditor( | |
| label="First frame — paint over the subject / target area", | |
| type="numpy", | |
| sources=[], | |
| brush=gr.Brush(colors=["#ff0000"], default_size=24), | |
| eraser=gr.Eraser(), | |
| layers=False, | |
| transforms=[], | |
| height=360, | |
| ) | |
| region = gr.Textbox( | |
| label="Region (x1,y1,x2,y2 in 0-1, filled from your painting)", | |
| placeholder="0.2,0.3,0.6,0.7", | |
| ) | |
| reference_image = gr.Image(label="Reference image (Insert / Replace)", type="pil", image_mode="RGBA") | |
| prompt = gr.Textbox(label="Prompt", lines=3, value=REMOVE_PROMPT) | |
| run = gr.Button("Edit video", variant="primary") | |
| with gr.Column(): | |
| video_out = gr.Video(label="Edited video", autoplay=True, interactive=False) | |
| preview_out = gr.Image(label="Conditions: erase mask (grey) + box | appearance canvas | identity canvas", interactive=False) | |
| with gr.Accordion("Advanced settings", open=False): | |
| resolution = gr.Radio(list(RESOLUTIONS), value=DEFAULT_RES, label="Resolution (pixel area; paper used ~960²)") | |
| num_frames = gr.Slider(17, 81, value=DEFAULT_FRAMES, step=4, label="Frames (16 fps)") | |
| steps = gr.Slider(4, 40, value=DEFAULT_STEPS, step=1, label="Steps") | |
| guidance_scale = gr.Slider(1.0, 10.0, value=DEFAULT_CFG, step=0.5, label="Guidance scale") | |
| with gr.Row(): | |
| motion_x = gr.Slider(-1, 1, value=0.0, step=0.05, label="Insert: horizontal drift") | |
| motion_y = gr.Slider(-1, 1, value=0.0, step=0.05, label="Insert: vertical drift") | |
| negative_prompt = gr.Textbox(label="Negative prompt", value=DEFAULT_NEG) | |
| with gr.Row(): | |
| seed = gr.Slider(0, MAX_SEED, value=42, step=1, label="Seed") | |
| randomize_seed = gr.Checkbox(value=False, label="Randomize seed") | |
| gr.Examples( | |
| examples=[ | |
| ["examples/cat_on_a_tree.mp4", "Remove", "0.200,0.300,0.670,0.740", REMOVE_PROMPT], | |
| ], | |
| inputs=[source_video, mode, region, prompt], | |
| outputs=[video_out, preview_out, seed], | |
| fn=edit_video, | |
| cache_examples=True, | |
| cache_mode="lazy", | |
| label="Removal example", | |
| ) | |
| gr.Examples( | |
| examples=[ | |
| [ | |
| "examples/golden_retriever_grass.mp4", "Replace", "0.330,0.420,0.530,0.580", | |
| "A red fox rolls playfully on its back in the grass of a sunny park, then gets up and lies down.", | |
| "examples/red_fox.jpg", | |
| ], | |
| [ | |
| "examples/landscape.mp4", "Insert", "0.560,0.060,0.720,0.400", | |
| "A hot air balloon floats slowly in the blue sky above a green mountain valley.", | |
| "examples/hot_air_balloon.jpg", | |
| ], | |
| ], | |
| inputs=[source_video, mode, region, prompt, reference_image], | |
| outputs=[video_out, preview_out, seed], | |
| fn=edit_video, | |
| cache_examples=True, | |
| cache_mode="lazy", | |
| label="Replacement / insertion examples", | |
| ) | |
| source_video.change(load_editor, inputs=source_video, outputs=editor, api_name=False) | |
| editor.change(region_from_editor, inputs=editor, outputs=region, api_name=False) | |
| run.click( | |
| edit_video, | |
| inputs=[ | |
| source_video, mode, region, prompt, reference_image, resolution, num_frames, steps, | |
| guidance_scale, motion_x, motion_y, negative_prompt, seed, randomize_seed, | |
| ], | |
| outputs=[video_out, preview_out, seed], | |
| api_name="edit_video", | |
| ) | |
| if __name__ == "__main__": | |
| demo.queue().launch(theme=gr.themes.Citrus(), css=CSS, mcp_server=True) | |