Spaces:
Running on Zero

File size: 29,371 Bytes
38af57e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1b6b0b8
38af57e
 
 
 
 
1b6b0b8
 
38af57e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14a4c0b
 
38af57e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d384429
 
 
 
 
 
 
 
 
 
 
 
 
38af57e
 
 
d384429
38af57e
d384429
38af57e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0044b15
3ac7299
 
 
 
 
 
 
 
 
 
 
 
 
0044b15
 
 
3ac7299
0044b15
3ac7299
 
 
 
38af57e
 
 
 
 
 
 
d384429
 
38af57e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3ac7299
38af57e
 
 
 
 
 
 
 
 
 
 
 
3ac7299
38af57e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3ac7299
38af57e
 
 
 
 
 
 
 
 
 
 
 
 
 
3ac7299
38af57e
3ac7299
38af57e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14a4c0b
38af57e
14a4c0b
 
 
38af57e
14a4c0b
38af57e
 
 
 
 
 
 
14a4c0b
38af57e
14a4c0b
38af57e
 
 
 
14a4c0b
38af57e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14a4c0b
 
38af57e
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
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


@torch.inference_mode()
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


@torch.inference_mode()
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)


@torch.inference_mode()
def vae_encode(pixels):
    z = vae.encode(pixels.float()).latent_dist.mode()
    return (z - LAT_MEAN.to(z)) / LAT_STD.to(z)


@torch.inference_mode()
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()


@torch.inference_mode()
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


@spaces.GPU(duration=_estimate, size="xlarge")
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)