-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
1624 lines (1358 loc) · 69.2 KB
/
app.py
File metadata and controls
1624 lines (1358 loc) · 69.2 KB
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
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
CorridorKey GUI — Neural Network Green Screen Keyer
A Gradio web interface for Corridor Digital's CorridorKey AI keying engine.
Upload green screen footage + click to create masks → get VFX-quality mattes.
"""
import os
os.environ["OPENCV_IO_ENABLE_OPENEXR"] = "1"
import sys
import gc
import json
import threading
import tempfile
import shutil
import time
import traceback
from pathlib import Path
import numpy as np
import cv2
import gradio as gr
# ─── Constants ────────────────────────────────────────────────────────────────
CHECKPOINT_PATH = os.path.join(os.path.dirname(__file__), "CorridorKeyModule", "checkpoints", "CorridorKey.pth")
SAM_CHECKPOINT_PATH = os.path.join(os.path.dirname(__file__), "checkpoints", "sam_vit_b.pth")
MATANYONE_MODEL_ID = "PeiqingYang/MatAnyone"
SUPPORTED_VIDEO_EXT = {".mp4", ".mov", ".avi", ".mkv", ".webm"}
OUTPUT_DIR = os.path.join(os.path.dirname(__file__), "output")
os.makedirs(OUTPUT_DIR, exist_ok=True)
def _make_output_dir(prefix):
"""Create a timestamped output subdirectory under OUTPUT_DIR."""
stamp = time.strftime("%Y%m%d_%H%M%S")
d = os.path.join(OUTPUT_DIR, f"{prefix}_{stamp}")
os.makedirs(d, exist_ok=True)
return d
# Point visualization colors (BGR converted to RGB for display)
COLOR_POSITIVE = (0, 200, 80) # green dots for "include"
COLOR_NEGATIVE = (220, 50, 50) # red dots for "exclude"
COLOR_MASK = (80, 120, 255) # blue-ish mask overlay
MASK_ALPHA = 0.45
POINT_RADIUS = 8
# ─── Engine Singletons (lazy load, VRAM-managed) ─────────────────────────────
_engine = None
_engine_lock = threading.Lock()
_sam_predictor = None
_sam_lock = threading.Lock()
_matanyone = None
_matanyone_lock = threading.Lock()
def _unload_all_models():
"""Unload all GPU models to free VRAM."""
global _engine, _sam_predictor, _matanyone
import torch
if _engine is not None:
del _engine
_engine = None
if _sam_predictor is not None:
del _sam_predictor
_sam_predictor = None
if _matanyone is not None:
del _matanyone
_matanyone = None
torch.cuda.empty_cache()
gc.collect()
def get_engine():
"""Lazy-load CorridorKey. Unloads SAM/MatAnyone first."""
global _engine, _sam_predictor, _matanyone
if _engine is not None:
return _engine
with _engine_lock:
if _engine is not None:
return _engine
# Free VRAM from other models
if _sam_predictor is not None:
with _sam_lock:
del _sam_predictor
_sam_predictor = None
if _matanyone is not None:
with _matanyone_lock:
del _matanyone
_matanyone = None
import torch
torch.cuda.empty_cache()
gc.collect()
from CorridorKeyModule import CorridorKeyEngine
device = "cuda" if torch.cuda.is_available() else "cpu"
_engine = CorridorKeyEngine(
checkpoint_path=CHECKPOINT_PATH,
device=device,
img_size=2048,
)
return _engine
def get_sam_predictor():
"""Lazy-load SAM predictor. Lightweight (~1GB VRAM for vit_b)."""
global _sam_predictor
if _sam_predictor is not None:
return _sam_predictor
with _sam_lock:
if _sam_predictor is not None:
return _sam_predictor
from segment_anything import sam_model_registry, SamPredictor
import torch
device = "cuda" if torch.cuda.is_available() else "cpu"
sam = sam_model_registry["vit_b"](checkpoint=SAM_CHECKPOINT_PATH)
sam.to(device)
sam.eval()
_sam_predictor = SamPredictor(sam)
return _sam_predictor
def load_matanyone():
"""Load MatAnyone. Unloads SAM and CorridorKey first."""
global _matanyone, _engine, _sam_predictor
with _matanyone_lock:
if _matanyone is not None:
return _matanyone
# Free VRAM
if _engine is not None:
with _engine_lock:
del _engine
_engine = None
if _sam_predictor is not None:
with _sam_lock:
del _sam_predictor
_sam_predictor = None
import torch
torch.cuda.empty_cache()
gc.collect()
from matanyone import InferenceCore
_matanyone = InferenceCore(MATANYONE_MODEL_ID)
return _matanyone
def unload_matanyone():
"""Unload MatAnyone and free VRAM."""
global _matanyone
with _matanyone_lock:
if _matanyone is not None:
del _matanyone
_matanyone = None
import torch
torch.cuda.empty_cache()
gc.collect()
# ─── GPU Status ──────────────────────────────────────────────────────────────
def check_gpu_status():
try:
import torch
if torch.cuda.is_available():
name = torch.cuda.get_device_name(0)
vram = torch.cuda.get_device_properties(0).total_memory / (1024 ** 3)
return f"**GPU:** {name} — {vram:.1f} GB VRAM"
else:
return "**GPU:** None detected — running on CPU (slow)"
except Exception:
return "**GPU:** Unknown"
# ─── Image Helpers ───────────────────────────────────────────────────────────
def to_float32(img):
if img is None:
return None
if img.dtype == np.uint8:
return img.astype(np.float32) / 255.0
return img.astype(np.float32)
def to_uint8(img):
return np.clip(img * 255.0, 0, 255).astype(np.uint8)
def load_mask(path):
if path is None:
return None
ext = Path(path).suffix.lower()
if ext == ".exr":
img = cv2.imread(path, cv2.IMREAD_ANYCOLOR | cv2.IMREAD_ANYDEPTH)
else:
img = cv2.imread(path, cv2.IMREAD_UNCHANGED)
if img is None:
return None
if img.ndim == 3:
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
if img.dtype == np.uint8:
img = img.astype(np.float32) / 255.0
elif img.dtype == np.uint16:
img = img.astype(np.float32) / 65535.0
else:
img = img.astype(np.float32)
return img
def save_exr(path, image):
if image.ndim == 3 and image.shape[2] >= 3:
bgr = cv2.cvtColor(image, cv2.COLOR_RGB2BGR) if image.shape[2] == 3 else cv2.cvtColor(image, cv2.COLOR_RGBA2BGRA)
else:
bgr = image
cv2.imwrite(path, bgr.astype(np.float32))
def save_png(path, image):
img_u8 = to_uint8(image)
if img_u8.ndim == 3 and img_u8.shape[2] >= 3:
bgr = cv2.cvtColor(img_u8, cv2.COLOR_RGB2BGR) if img_u8.shape[2] == 3 else cv2.cvtColor(img_u8, cv2.COLOR_RGBA2BGRA)
else:
bgr = img_u8
cv2.imwrite(path, bgr)
def frames_to_mp4(frame_dir, output_path, fps=24.0):
"""Compile a directory of image frames into an MP4 video."""
files = sorted([f for f in os.listdir(frame_dir)
if f.lower().endswith(('.png', '.exr', '.jpg', '.jpeg', '.tif', '.tiff'))])
if not files:
return None
first = cv2.imread(os.path.join(frame_dir, files[0]), cv2.IMREAD_ANYCOLOR | cv2.IMREAD_ANYDEPTH)
if first is None:
return None
h, w = first.shape[:2]
# Try H264 first for browser playback, fall back to mp4v
writer = None
for codec in ['avc1', 'mp4v']:
fourcc = cv2.VideoWriter_fourcc(*codec)
writer = cv2.VideoWriter(output_path, fourcc, fps, (w, h), True)
if writer.isOpened():
break
if writer is None or not writer.isOpened():
return None
for fname in files:
frame = cv2.imread(os.path.join(frame_dir, fname), cv2.IMREAD_ANYCOLOR | cv2.IMREAD_ANYDEPTH)
if frame is None:
continue
if frame.dtype != np.uint8:
frame = np.clip(frame * 255, 0, 255).astype(np.uint8)
if frame.ndim == 2:
frame = cv2.cvtColor(frame, cv2.COLOR_GRAY2BGR)
elif frame.shape[2] == 4:
frame = frame[:, :, :3]
writer.write(frame)
writer.release()
return output_path
# ─── SAM Interactive Masking ─────────────────────────────────────────────────
def paint_mask_on_image(image, mask, points, labels):
"""Paint mask overlay + point markers onto image for display."""
painted = image.copy()
if mask is not None:
# Blue-ish semi-transparent overlay where mask is 1
overlay = painted.copy()
overlay[mask > 0.5] = (
np.array(overlay[mask > 0.5], dtype=np.float32) * (1 - MASK_ALPHA)
+ np.array(COLOR_MASK, dtype=np.float32) * MASK_ALPHA
).astype(np.uint8)
# Contour around mask
mask_u8 = (mask > 0.5).astype(np.uint8) * 255
contours, _ = cv2.findContours(mask_u8, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(overlay, contours, -1, (255, 255, 255), 2)
painted = overlay
# Draw points
if points is not None and len(points) > 0:
for pt, lbl in zip(points, labels):
color = COLOR_POSITIVE if lbl == 1 else COLOR_NEGATIVE
x, y = int(pt[0]), int(pt[1])
cv2.circle(painted, (x, y), POINT_RADIUS, color, -1)
cv2.circle(painted, (x, y), POINT_RADIUS, (255, 255, 255), 2)
return painted
def extract_first_frame(video_file):
"""Extract the first frame from a video file for masking."""
if video_file is None:
return None, None, "Upload a video first."
video_path = video_file if isinstance(video_file, str) else video_file.name if hasattr(video_file, "name") else str(video_file)
cap = cv2.VideoCapture(video_path)
if not cap.isOpened():
return None, None, "Failed to open video."
ret, frame_bgr = cap.read()
total = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
fps = cap.get(cv2.CAP_PROP_FPS) or 24.0
cap.release()
if not ret or frame_bgr is None:
return None, None, "Failed to read first frame."
frame_rgb = cv2.cvtColor(frame_bgr, cv2.COLOR_BGR2RGB)
# Embed in SAM
predictor = get_sam_predictor()
predictor.set_image(frame_rgb)
status = f"Loaded: {total} frames @ {fps:.1f}fps, {frame_rgb.shape[1]}x{frame_rgb.shape[0]}"
# Return frame for display, frame as state (original), status, total frames, fps
return frame_rgb, frame_rgb, status, total, fps
def sam_click(original_frame, click_state_json, point_mode, evt: gr.SelectData):
"""Handle click on the frame image. Run SAM with accumulated points."""
try:
if original_frame is None:
raise gr.Error("Load a video first.")
# Parse accumulated state
if click_state_json:
click_state = json.loads(click_state_json)
if "points" not in click_state:
click_state = {"points": [], "labels": []}
else:
click_state = {"points": [], "labels": []}
# Add new point
x, y = int(evt.index[0]), int(evt.index[1])
label = 1 if point_mode == "Positive (include)" else 0
click_state["points"].append([x, y])
click_state["labels"].append(label)
points = np.array(click_state["points"])
labels = np.array(click_state["labels"])
# Re-embed image in SAM (needed after model might have been reloaded)
predictor = get_sam_predictor()
if not predictor.is_image_set:
predictor.set_image(original_frame)
# Run SAM prediction
masks, scores, logits = predictor.predict(
point_coords=points,
point_labels=labels,
multimask_output=True,
)
# Pick best mask
best_idx = np.argmax(scores)
mask = masks[best_idx]
# Refine with logit feedback (two-pass like Wan2GP)
masks2, scores2, logits2 = predictor.predict(
point_coords=points,
point_labels=labels,
mask_input=logits[best_idx:best_idx+1],
multimask_output=False,
)
mask = masks2[0]
# Paint visualization
painted = paint_mask_on_image(original_frame, mask, points, labels)
# Return raw mask separately so expansion can re-roll from it
return painted, json.dumps(click_state), mask, mask
except gr.Error:
raise
except Exception as e:
print(f"[SAM Click ERROR] {type(e).__name__}: {e}")
traceback.print_exc()
raise gr.Error(f"SAM click failed: {e}")
def clear_clicks(original_frame):
"""Reset all clicks and mask."""
if original_frame is None:
return None, "{}", None, None
return original_frame.copy(), "{}", None, None
def add_sub_mask(current_mask, saved_masks_json):
"""Save current mask to the multi-mask list."""
if current_mask is None:
raise gr.Error("Create a mask first by clicking on the image.")
saved = json.loads(saved_masks_json) if saved_masks_json else []
# Serialize mask as base64 for state storage
mask_u8 = (current_mask > 0.5).astype(np.uint8) * 255
_, encoded = cv2.imencode(".png", mask_u8)
import base64
saved.append(base64.b64encode(encoded.tobytes()).decode("ascii"))
count = len(saved)
return json.dumps(saved), f"{count} mask(s) saved. Click more points for next mask, or Generate."
def combine_masks(saved_masks_json, current_mask):
"""Combine all saved masks + current into one binary mask."""
import base64
saved = json.loads(saved_masks_json) if saved_masks_json else []
combined = None
for b64 in saved:
buf = np.frombuffer(base64.b64decode(b64), dtype=np.uint8)
m = cv2.imdecode(buf, cv2.IMREAD_GRAYSCALE)
if combined is None:
combined = (m > 127).astype(np.uint8)
else:
combined = np.clip(combined + (m > 127).astype(np.uint8), 0, 1)
if current_mask is not None:
m = (current_mask > 0.5).astype(np.uint8)
if combined is None:
combined = m
else:
combined = np.clip(combined + m, 0, 1)
return combined
def expand_mask(raw_mask, expansion_px):
"""Dilate a mask by N pixels using an elliptical kernel."""
if raw_mask is None or expansion_px <= 0:
return raw_mask
kernel_size = int(expansion_px * 2 + 1)
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (kernel_size, kernel_size))
mask_u8 = (raw_mask > 0.5).astype(np.uint8)
dilated = cv2.dilate(mask_u8, kernel)
return dilated
def apply_expansion(raw_mask, original_frame, click_state_json, expansion_px):
"""Re-dilate raw SAM mask by expansion_px and repaint the preview."""
if raw_mask is None or original_frame is None:
return original_frame, raw_mask if expansion_px <= 0 else None
expanded = expand_mask(raw_mask, expansion_px)
# Repaint with points
click_state = json.loads(click_state_json) if click_state_json else {}
points = np.array(click_state.get("points", []))
labels = np.array(click_state.get("labels", []))
pts = points if len(points) > 0 else None
lbls = labels if len(labels) > 0 else None
painted = paint_mask_on_image(original_frame, expanded, pts, lbls)
return painted, expanded
# ─── Multi-Keyframe SAM Masking ──────────────────────────────────────────────
def extract_frame_at(video_path, frame_num):
"""Seek to any frame, convert BGR→RGB, embed in SAM. Returns RGB numpy array."""
cap = cv2.VideoCapture(video_path)
if not cap.isOpened():
return None
cap.set(cv2.CAP_PROP_POS_FRAMES, int(frame_num))
ret, frame_bgr = cap.read()
cap.release()
if not ret or frame_bgr is None:
return None
frame_rgb = cv2.cvtColor(frame_bgr, cv2.COLOR_BGR2RGB)
predictor = get_sam_predictor()
predictor.set_image(frame_rgb)
return frame_rgb
def on_frame_slider_change(video_file, frame_num, keyframes_json):
"""Handle frame slider change. Extract frame, load saved keyframe mask if exists."""
import base64
if video_file is None:
return None, None, "{}", None, "[]", "No video loaded."
video_path = video_file if isinstance(video_file, str) else video_file.name if hasattr(video_file, "name") else str(video_file)
frame_num = int(frame_num)
frame_rgb = extract_frame_at(video_path, frame_num)
if frame_rgb is None:
return None, None, "{}", None, "[]", f"Failed to read frame {frame_num}."
# Check if this frame has a saved keyframe
keyframes = json.loads(keyframes_json) if keyframes_json else {}
frame_key = str(frame_num)
if frame_key in keyframes:
# Load and display the saved mask
kf = keyframes[frame_key]
buf = np.frombuffer(base64.b64decode(kf["mask_b64"]), dtype=np.uint8)
mask = cv2.imdecode(buf, cv2.IMREAD_GRAYSCALE)
mask_bool = (mask > 127).astype(np.uint8)
painted = paint_mask_on_image(frame_rgb, mask_bool, None, None)
# Restore sub-masks
sub_masks = json.dumps(kf.get("sub_masks_b64", []))
return painted, frame_rgb, "{}", mask_bool, sub_masks, f"Frame {frame_num} — keyframe mask loaded"
else:
return frame_rgb.copy(), frame_rgb, "{}", None, "[]", f"Frame {frame_num}"
def save_keyframe(frame_num, current_mask, saved_masks_json, keyframes_json):
"""Save current mask + sub-masks as a keyframe at the given frame number."""
import base64
combined = combine_masks(saved_masks_json, current_mask)
if combined is None:
raise gr.Error("Create a mask first by clicking on the image.")
# Encode combined mask as base64 PNG
mask_u8 = (combined > 0.5).astype(np.uint8) * 255
_, encoded = cv2.imencode(".png", mask_u8)
mask_b64 = base64.b64encode(encoded.tobytes()).decode("ascii")
# Save sub-masks for later editing
saved = json.loads(saved_masks_json) if saved_masks_json else []
sub_masks_b64 = list(saved)
if current_mask is not None:
curr_u8 = (current_mask > 0.5).astype(np.uint8) * 255
_, curr_enc = cv2.imencode(".png", curr_u8)
sub_masks_b64.append(base64.b64encode(curr_enc.tobytes()).decode("ascii"))
keyframes = json.loads(keyframes_json) if keyframes_json else {}
frame_key = str(int(frame_num))
keyframes[frame_key] = {
"mask_b64": mask_b64,
"sub_masks_b64": sub_masks_b64,
}
sorted_keys = sorted(keyframes.keys(), key=int)
info = f"{len(sorted_keys)} keyframe(s): " + ", ".join(f"Frame {k}" for k in sorted_keys)
return json.dumps(keyframes), info
def delete_keyframe(frame_num, keyframes_json):
"""Remove a keyframe at the given frame number."""
keyframes = json.loads(keyframes_json) if keyframes_json else {}
frame_key = str(int(frame_num))
if frame_key in keyframes:
del keyframes[frame_key]
if keyframes:
sorted_keys = sorted(keyframes.keys(), key=int)
info = f"{len(sorted_keys)} keyframe(s): " + ", ".join(f"Frame {k}" for k in sorted_keys)
else:
info = "No keyframes saved."
return json.dumps(keyframes), info
def extract_video_segment(video_path, start_frame, end_frame, output_path, fps):
"""Write a sub-range of frames to a new MP4 for MatAnyone processing."""
cap = cv2.VideoCapture(video_path)
if not cap.isOpened():
raise gr.Error(f"Failed to open video for segment extraction.")
w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
writer = None
for codec in ['avc1', 'mp4v']:
fourcc = cv2.VideoWriter_fourcc(*codec)
writer = cv2.VideoWriter(output_path, fourcc, fps, (w, h), True)
if writer.isOpened():
break
if writer is None or not writer.isOpened():
cap.release()
raise gr.Error("Failed to create video writer for segment.")
cap.set(cv2.CAP_PROP_POS_FRAMES, start_frame)
for i in range(end_frame - start_frame + 1):
ret, frame = cap.read()
if not ret:
break
writer.write(frame)
writer.release()
cap.release()
return output_path
# ─── Batch / Sequence Processing ─────────────────────────────────────────────
def process_batch(
video_file,
mask_input,
frame_start,
frame_end,
input_is_linear,
despill_strength,
auto_despeckle,
despeckle_size,
refiner_scale,
progress=gr.Progress(track_tqdm=False),
):
"""Process a video sequence with pre-made alpha hints."""
if video_file is None:
raise gr.Error("Upload a video file first.")
if mask_input is None:
raise gr.Error("Upload an alpha hint mask or generate one in the Hint Generator tab.")
video_path = video_file if isinstance(video_file, str) else video_file.name if hasattr(video_file, "name") else str(video_file)
ext = Path(video_path).suffix.lower()
if ext not in SUPPORTED_VIDEO_EXT:
raise gr.Error(f"Unsupported video format: {ext}. Use MP4, MOV, AVI, or MKV.")
cap = cv2.VideoCapture(video_path)
if not cap.isOpened():
raise gr.Error("Failed to open video file.")
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
fps = cap.get(cv2.CAP_PROP_FPS) or 24.0
start = max(0, int(frame_start) if frame_start else 0)
end = min(total_frames - 1, int(frame_end) if frame_end and frame_end > 0 else total_frames - 1)
num_frames = end - start + 1
if num_frames <= 0:
cap.release()
raise gr.Error(f"Invalid frame range: {start}-{end} (video has {total_frames} frames)")
mask_path = mask_input if isinstance(mask_input, str) else mask_input.name if hasattr(mask_input, "name") else str(mask_input)
# Detect if mask is a video (per-frame alpha) or single image
mask_ext = Path(mask_path).suffix.lower()
mask_is_video = mask_ext in SUPPORTED_VIDEO_EXT
mask_base = None
mask_cap = None
if mask_is_video:
mask_cap = cv2.VideoCapture(mask_path)
if not mask_cap.isOpened():
raise gr.Error("Failed to open alpha hint video.")
mask_cap.set(cv2.CAP_PROP_POS_FRAMES, start)
else:
mask_base = load_mask(mask_path)
if mask_base is None:
raise gr.Error("Failed to load mask image.")
tmp_dir = _make_output_dir("batch")
alpha_dir = os.path.join(tmp_dir, "alpha")
fg_dir = os.path.join(tmp_dir, "foreground")
comp_dir = os.path.join(tmp_dir, "composite")
processed_dir = os.path.join(tmp_dir, "processed_rgba")
for d in [alpha_dir, fg_dir, comp_dir, processed_dir]:
os.makedirs(d, exist_ok=True)
engine = get_engine()
gallery_previews = []
cap.set(cv2.CAP_PROP_POS_FRAMES, start)
for i in range(num_frames):
frame_idx = start + i
progress((i + 1) / num_frames, desc=f"Processing frame {frame_idx} ({i+1}/{num_frames})")
ret, frame_bgr = cap.read()
if not ret:
break
frame_rgb = cv2.cvtColor(frame_bgr, cv2.COLOR_BGR2RGB).astype(np.float32) / 255.0
# Get mask for this frame
if mask_is_video:
mret, mask_bgr = mask_cap.read()
if mret and mask_bgr is not None:
mask = cv2.cvtColor(mask_bgr, cv2.COLOR_BGR2GRAY).astype(np.float32) / 255.0 if mask_bgr.ndim == 3 else mask_bgr.astype(np.float32) / 255.0
else:
mask = np.ones(frame_rgb.shape[:2], dtype=np.float32)
else:
mask = mask_base.copy()
if mask.shape[:2] != frame_rgb.shape[:2]:
mask = cv2.resize(mask, (frame_rgb.shape[1], frame_rgb.shape[0]), interpolation=cv2.INTER_LINEAR)
try:
result = engine.process_frame(
image=frame_rgb, mask_linear=mask, refiner_scale=refiner_scale,
input_is_linear=input_is_linear, fg_is_straight=True,
despill_strength=despill_strength, auto_despeckle=auto_despeckle,
despeckle_size=int(despeckle_size),
)
except RuntimeError as e:
if "out of memory" in str(e).lower():
import torch; torch.cuda.empty_cache()
raise gr.Error(f"GPU OOM at frame {frame_idx}. Try a shorter range.")
raise gr.Error(f"Failed at frame {frame_idx}: {e}")
frame_name = f"{frame_idx:06d}"
alpha = result["alpha"]
if alpha.ndim == 2:
alpha = alpha[:, :, np.newaxis]
save_exr(os.path.join(alpha_dir, f"{frame_name}.exr"), alpha)
save_exr(os.path.join(fg_dir, f"{frame_name}.exr"), result["fg"])
save_png(os.path.join(comp_dir, f"{frame_name}.png"), result["comp"])
save_exr(os.path.join(processed_dir, f"{frame_name}.exr"), result["processed"])
step = max(1, num_frames // 20)
if i % step == 0 or i == num_frames - 1:
gallery_previews.append((to_uint8(result["comp"]), f"Frame {frame_idx}"))
cap.release()
if mask_cap is not None:
mask_cap.release()
# Compile output MP4s
comp_mp4 = os.path.join(tmp_dir, "composite.mp4")
alpha_mp4 = os.path.join(tmp_dir, "alpha_matte.mp4")
frames_to_mp4(comp_dir, comp_mp4, fps)
frames_to_mp4(alpha_dir, alpha_mp4, fps)
status = f"Done — processed {num_frames} frames ({start}–{end})"
return status, gallery_previews, comp_mp4, alpha_mp4
# ─── MatAnyone Hint Generation ───────────────────────────────────────────────
def generate_hints_segmented(
video_file,
current_mask,
saved_masks_json,
keyframes_json,
expansion_px,
max_size,
n_warmup,
r_erode,
r_dilate,
progress=gr.Progress(track_tqdm=True),
):
"""Generate per-frame alpha hints with multi-keyframe segmented processing."""
import base64
if video_file is None:
raise gr.Error("Upload a video file first.")
video_path = video_file if isinstance(video_file, str) else video_file.name if hasattr(video_file, "name") else str(video_file)
# Parse keyframes
keyframes = json.loads(keyframes_json) if keyframes_json else {}
# If no keyframes, fall back to current mask at frame 0 (backward compatible)
if not keyframes:
combined = combine_masks(saved_masks_json, current_mask)
if combined is None:
raise gr.Error("Create a mask first by clicking on the frame.")
mask_u8 = (combined > 0.5).astype(np.uint8) * 255
_, encoded = cv2.imencode(".png", mask_u8)
mask_b64 = base64.b64encode(encoded.tobytes()).decode("ascii")
keyframes = {"0": {"mask_b64": mask_b64}}
# Get video info
cap = cv2.VideoCapture(video_path)
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
fps = cap.get(cv2.CAP_PROP_FPS) or 24.0
cap.release()
if total_frames <= 0:
raise gr.Error("Failed to read video frame count.")
# Sort keyframes and build segments
sorted_kf = sorted(keyframes.keys(), key=int)
segments = []
for i, kf_str in enumerate(sorted_kf):
# First segment always starts at frame 0
seg_start = 0 if i == 0 else int(kf_str)
seg_end = int(sorted_kf[i + 1]) - 1 if i + 1 < len(sorted_kf) else total_frames - 1
segments.append((seg_start, seg_end, keyframes[kf_str]))
tmp_dir = _make_output_dir("hints")
unified_pha_dir = os.path.join(tmp_dir, "pha_unified")
os.makedirs(unified_pha_dir, exist_ok=True)
try:
processor = load_matanyone()
for seg_idx, (seg_start, seg_end, kf_data) in enumerate(segments):
progress_base = seg_idx / len(segments)
progress_range = 1.0 / len(segments)
progress(progress_base + 0.02, desc=f"Segment {seg_idx+1}/{len(segments)}: extracting frames {seg_start}–{seg_end}...")
# Decode keyframe mask
buf = np.frombuffer(base64.b64decode(kf_data["mask_b64"]), dtype=np.uint8)
mask = cv2.imdecode(buf, cv2.IMREAD_GRAYSCALE)
# Save mask to temp file
seg_tmp = tempfile.mkdtemp(prefix=f"ck_seg{seg_idx}_")
mask_file = os.path.join(seg_tmp, "mask.png")
cv2.imwrite(mask_file, mask)
# Extract video segment to MP4
seg_video = os.path.join(seg_tmp, "segment.mp4")
extract_video_segment(video_path, seg_start, seg_end, seg_video, fps)
# Clear temporal state between segments (keeps model weights loaded)
processor.clear_memory()
progress(progress_base + progress_range * 0.15, desc=f"Segment {seg_idx+1}/{len(segments)}: running MatAnyone...")
# Process segment
seg_out = os.path.join(seg_tmp, "output")
fgr_path, alpha_path = processor.process_video(
input_path=seg_video,
mask_path=mask_file,
output_path=seg_out,
n_warmup=int(n_warmup),
r_erode=int(r_erode),
r_dilate=int(r_dilate),
max_size=int(max_size),
save_image=True,
)
progress(progress_base + progress_range * 0.85, desc=f"Segment {seg_idx+1}/{len(segments)}: copying alpha frames...")
# Copy alpha frames to unified directory with global frame numbering
seg_video_name = Path(seg_video).stem
pha_dir = os.path.join(seg_out, seg_video_name, "pha")
if os.path.isdir(pha_dir):
pha_files = sorted([f for f in os.listdir(pha_dir) if f.endswith(".png")])
for fi, fname in enumerate(pha_files):
global_frame = seg_start + fi
src = os.path.join(pha_dir, fname)
dst = os.path.join(unified_pha_dir, f"{global_frame:06d}.png")
shutil.copy2(src, dst)
progress(progress_base + progress_range, desc=f"Segment {seg_idx+1}/{len(segments)} done.")
except RuntimeError as e:
unload_matanyone()
if "out of memory" in str(e).lower():
raise gr.Error("GPU OOM during hint generation. Try max_size=720.")
raise gr.Error(f"MatAnyone failed: {e}")
finally:
unload_matanyone()
# Check output
all_pha = sorted([f for f in os.listdir(unified_pha_dir) if f.endswith(".png")])
if not all_pha:
raise gr.Error("No alpha hint frames generated.")
# Post-process: expand every output frame if expansion requested
exp = int(expansion_px) if expansion_px else 0
if exp > 0:
kernel_size = exp * 2 + 1
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (kernel_size, kernel_size))
for fname in all_pha:
fpath = os.path.join(unified_pha_dir, fname)
img = cv2.imread(fpath, cv2.IMREAD_GRAYSCALE)
if img is not None:
dilated = cv2.dilate(img, kernel)
cv2.imwrite(fpath, dilated)
# Gallery previews
gallery = []
step_g = max(1, len(all_pha) // 20)
for i, fname in enumerate(all_pha):
if i % step_g == 0 or i == len(all_pha) - 1:
img = cv2.imread(os.path.join(unified_pha_dir, fname), cv2.IMREAD_GRAYSCALE)
if img is not None:
gallery.append((img, f"Frame {i}"))
# Compile unified alpha frames to MP4
alpha_mp4 = os.path.join(tmp_dir, "alpha_hints.mp4")
frames_to_mp4(unified_pha_dir, alpha_mp4, fps)
exp_note = f" (expanded {exp}px)" if exp > 0 else ""
status = f"Done — generated {len(all_pha)} alpha hint frames across {len(segments)} segment(s){exp_note}"
preview = gallery[0][0] if gallery else None
return preview, status, gallery, alpha_mp4, alpha_mp4
def process_pipeline(
video_file,
current_mask,
saved_masks_json,
keyframes_json,
expansion_px,
ma_max_size, ma_warmup, ma_erode, ma_dilate,
frame_start, frame_end,
input_is_linear, despill_strength, auto_despeckle, despeckle_size, refiner_scale,
progress=gr.Progress(track_tqdm=True),
):
"""Full pipeline: SAM mask -> MatAnyone hints -> CorridorKey keying."""
import base64
if video_file is None:
raise gr.Error("Upload a video file first.")
video_path = video_file if isinstance(video_file, str) else video_file.name if hasattr(video_file, "name") else str(video_file)
tmp_dir = _make_output_dir("pipeline")
# Parse keyframes for segmented approach
keyframes = json.loads(keyframes_json) if keyframes_json else {}
# If no keyframes, fall back to current mask at frame 0
if not keyframes:
combined = combine_masks(saved_masks_json, current_mask)
if combined is None:
raise gr.Error("Create a mask first by clicking on the frame.")
mask_u8 = (combined > 0.5).astype(np.uint8) * 255
_, encoded = cv2.imencode(".png", mask_u8)
mask_b64 = base64.b64encode(encoded.tobytes()).decode("ascii")
keyframes = {"0": {"mask_b64": mask_b64}}
# Get video info for segments
cap_info = cv2.VideoCapture(video_path)
vid_total = int(cap_info.get(cv2.CAP_PROP_FRAME_COUNT))
vid_fps = cap_info.get(cv2.CAP_PROP_FPS) or 24.0
cap_info.release()
# Build segments from keyframes
sorted_kf = sorted(keyframes.keys(), key=int)
segments = []
for i, kf_str in enumerate(sorted_kf):
seg_start = 0 if i == 0 else int(kf_str)
seg_end = int(sorted_kf[i + 1]) - 1 if i + 1 < len(sorted_kf) else vid_total - 1
segments.append((seg_start, seg_end, keyframes[kf_str]))
unified_pha_dir = os.path.join(tmp_dir, "pha_unified")
os.makedirs(unified_pha_dir, exist_ok=True)
# ── Stage 1: MatAnyone (segmented) ──
progress(0.0, desc="Stage 1/2: Loading MatAnyone...")
try:
processor = load_matanyone()
for seg_idx, (seg_start, seg_end, kf_data) in enumerate(segments):
seg_frac = (seg_idx + 1) / len(segments) * 0.35
progress(0.02 + seg_frac * 0.5, desc=f"Stage 1/2: Segment {seg_idx+1}/{len(segments)} (frames {seg_start}–{seg_end})...")
buf = np.frombuffer(base64.b64decode(kf_data["mask_b64"]), dtype=np.uint8)
mask = cv2.imdecode(buf, cv2.IMREAD_GRAYSCALE)
seg_tmp = tempfile.mkdtemp(prefix=f"ck_pipe_seg{seg_idx}_")
mask_file = os.path.join(seg_tmp, "mask.png")
cv2.imwrite(mask_file, mask)
seg_video = os.path.join(seg_tmp, "segment.mp4")
extract_video_segment(video_path, seg_start, seg_end, seg_video, vid_fps)
processor.clear_memory()
seg_out = os.path.join(seg_tmp, "output")
processor.process_video(
input_path=seg_video, mask_path=mask_file, output_path=seg_out,
n_warmup=int(ma_warmup), r_erode=int(ma_erode),
r_dilate=int(ma_dilate), max_size=int(ma_max_size), save_image=True,
)
seg_video_name = Path(seg_video).stem
pha_src = os.path.join(seg_out, seg_video_name, "pha")
if os.path.isdir(pha_src):
for fi, fname in enumerate(sorted(f for f in os.listdir(pha_src) if f.endswith(".png"))):
shutil.copy2(os.path.join(pha_src, fname),
os.path.join(unified_pha_dir, f"{seg_start + fi:06d}.png"))
except RuntimeError as e:
unload_matanyone()
if "out of memory" in str(e).lower():
raise gr.Error("GPU OOM during MatAnyone. Try max_size=720.")
raise gr.Error(f"MatAnyone failed: {e}")
finally:
unload_matanyone()
progress(0.4, desc="Stage 1/2: Hints generated. Loading CorridorKey...")
pha_files = sorted([f for f in os.listdir(unified_pha_dir) if f.endswith(".png")])
if not pha_files:
raise gr.Error("No alpha hint frames generated.")
# Post-process: expand every output frame if expansion requested
exp = int(expansion_px) if expansion_px else 0
if exp > 0:
kernel_size = exp * 2 + 1
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (kernel_size, kernel_size))
for fname in pha_files:
fpath = os.path.join(unified_pha_dir, fname)
img = cv2.imread(fpath, cv2.IMREAD_GRAYSCALE)
if img is not None:
cv2.imwrite(fpath, cv2.dilate(img, kernel))
# ── Stage 2: CorridorKey ──
cap = cv2.VideoCapture(video_path)
if not cap.isOpened():
raise gr.Error("Failed to open video.")
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
fps = cap.get(cv2.CAP_PROP_FPS) or 24.0
start = max(0, int(frame_start) if frame_start else 0)
end = min(total_frames - 1, int(frame_end) if frame_end and frame_end > 0 else total_frames - 1)
num_frames = end - start + 1
if num_frames <= 0:
cap.release()
raise gr.Error(f"Invalid frame range.")
out_base = os.path.join(tmp_dir, "output")
alpha_dir_out = os.path.join(out_base, "alpha")
fg_dir = os.path.join(out_base, "foreground")
comp_dir = os.path.join(out_base, "composite")
processed_dir = os.path.join(out_base, "processed_rgba")
for d in [alpha_dir_out, fg_dir, comp_dir, processed_dir]:
os.makedirs(d, exist_ok=True)