-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnodes.py
More file actions
3222 lines (2880 loc) · 126 KB
/
nodes.py
File metadata and controls
3222 lines (2880 loc) · 126 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
import json
import os
import hashlib
import subprocess
import shutil
import sys
import time
import tempfile
import wave
from contextlib import nullcontext
from urllib.parse import urlparse
from fractions import Fraction
import numpy as np
import torch
import torch.nn.functional as F
from torch.hub import download_url_to_file
from PIL import Image
import comfy.model_management as mm
from comfy.utils import ProgressBar, common_upscale
import folder_paths
from hydra import initialize_config_dir
from hydra.core.global_hydra import GlobalHydra
try:
import sam2.build_sam as sam2_build
from sam2.build_sam import build_sam2
from sam2.sam2_image_predictor import SAM2ImagePredictor
except Exception as ex: # pragma: no cover - runtime env specific
sam2_build = None
build_sam2 = None
SAM2ImagePredictor = None
_sam2_import_error = ex
else:
_sam2_import_error = None
try:
from transformers import AutoModelForZeroShotObjectDetection, AutoProcessor
except Exception as ex: # pragma: no cover - runtime env specific
AutoModelForZeroShotObjectDetection = None
AutoProcessor = None
_groundingdino_import_error = ex
else:
_groundingdino_import_error = None
try:
from transnetv2_pytorch import TransNetV2 as _TransNetV2
except Exception as ex: # pragma: no cover - runtime env specific
_TransNetV2 = None
_transnet_import_error = ex
else:
_transnet_import_error = None
try:
import torchaudio
except Exception as ex: # pragma: no cover - runtime env specific
torchaudio = None
_deepfilternet_import_error = ex
else:
_deepfilternet_import_error = None
SAM2_MODEL_DIR = "sam2"
OPENSHOT_NODEPACK_VERSION = "v1.1.2-track-object-keyframes"
GROUNDING_DINO_MODEL_IDS = (
"IDEA-Research/grounding-dino-tiny",
"IDEA-Research/grounding-dino-base",
)
GROUNDING_DINO_CACHE = {}
def _openshot_log(message):
print("[OpenShot-ComfyUI] {}".format(message), flush=True)
def _sam2_debug_enabled():
# Temporary: always-on debug while we diagnose chunk/carry drift.
return True
def _sam2_debug(*parts):
if _sam2_debug_enabled():
try:
print("[OpenShot-SAM2-DEBUG]", *parts)
except Exception:
pass
SAM2_MODELS = {
"sam2.1_hiera_tiny.safetensors": {
"url": "https://dl.fbaipublicfiles.com/segment_anything_2/092824/sam2.1_hiera_tiny.pt",
"config": "sam2.1_hiera_t.yaml",
},
"sam2.1_hiera_small.safetensors": {
"url": "https://dl.fbaipublicfiles.com/segment_anything_2/092824/sam2.1_hiera_small.pt",
"config": "sam2.1_hiera_s.yaml",
},
"sam2.1_hiera_base_plus.safetensors": {
"url": "https://dl.fbaipublicfiles.com/segment_anything_2/092824/sam2.1_hiera_base_plus.pt",
"config": "sam2.1_hiera_b+.yaml",
},
"sam2.1_hiera_large.safetensors": {
"url": "https://dl.fbaipublicfiles.com/segment_anything_2/092824/sam2.1_hiera_large.pt",
"config": "sam2.1_hiera_l.yaml",
},
}
def _require_sam2():
if build_sam2 is None or SAM2ImagePredictor is None:
raise RuntimeError(
"SAM2 imports failed. Ensure `sam2` is available in Comfy runtime. Error: {}".format(_sam2_import_error)
)
def _require_groundingdino():
if AutoModelForZeroShotObjectDetection is None or AutoProcessor is None:
raise RuntimeError(
"GroundingDINO imports failed. Install requirements and restart ComfyUI. Error: {}".format(
_groundingdino_import_error
)
)
def _require_transnet():
if _TransNetV2 is None:
raise RuntimeError(
"TransNetV2 imports failed. Install `transnetv2-pytorch` and restart ComfyUI. Error: {}".format(
_transnet_import_error
)
)
def _require_deepfilternet():
if torchaudio is None:
raise RuntimeError(
"DeepFilterNet imports failed. Install requirements and restart ComfyUI. Error: {}".format(
_deepfilternet_import_error
)
)
def _require_lavasr_bootstrap():
if torchaudio is None:
raise RuntimeError("LavaSR requires torchaudio in the main Comfy environment")
try:
from LavaSR.model import LavaEnhance2 # noqa: F401
except Exception as ex:
raise RuntimeError("LavaSR imports failed. Install requirements and restart ComfyUI. Error: {}".format(ex))
def _model_storage_dir():
path = os.path.join(folder_paths.models_dir, SAM2_MODEL_DIR)
os.makedirs(path, exist_ok=True)
return path
def _safe_get_filename_list(model_dir_name):
try:
return list(folder_paths.get_filename_list(model_dir_name) or [])
except Exception:
# Folder key may not be registered in some Comfy installs.
path = os.path.join(folder_paths.models_dir, model_dir_name)
if not os.path.isdir(path):
return []
return sorted(
name
for name in os.listdir(path)
if os.path.isfile(os.path.join(path, name))
)
def _safe_get_full_path(model_dir_name, name):
try:
full = folder_paths.get_full_path(model_dir_name, name)
if full:
return full
except Exception:
pass
fallback = os.path.join(folder_paths.models_dir, model_dir_name, name)
if os.path.exists(fallback):
return fallback
return ""
def _model_options():
available = set(_safe_get_filename_list(SAM2_MODEL_DIR))
merged = list(SAM2_MODELS.keys())
for name in sorted(available):
if name not in merged:
merged.append(name)
return merged
def _download_if_needed(model_name):
model_name = str(model_name or "").strip()
if not model_name:
raise ValueError("Model name is required")
full_path = _safe_get_full_path(SAM2_MODEL_DIR, model_name)
if full_path and os.path.exists(full_path):
return full_path
if model_name not in SAM2_MODELS:
raise ValueError("Model not found locally and no download mapping for '{}'".format(model_name))
url = SAM2_MODELS[model_name]["url"]
parsed = urlparse(url)
src_name = os.path.basename(parsed.path)
target = os.path.join(_model_storage_dir(), src_name)
if not os.path.exists(target):
_openshot_log("Downloading SAM2 checkpoint '{}' from {}".format(model_name, url))
download_url_to_file(url, target)
_openshot_log("Downloaded SAM2 checkpoint to {}".format(target))
return target
def _resolve_config_candidates(model_name, checkpoint_path):
candidates = []
info = SAM2_MODELS.get(model_name)
if info and info.get("config"):
candidates.append(str(info["config"]))
base = os.path.basename(checkpoint_path).replace(".pt", "")
variants = {
base,
base.replace("2.1", "2_1"),
base.replace("2.1", "2"),
base.replace("sam2.1", "sam2"),
base.replace("sam2_1", "sam2"),
}
for variant in sorted(variants):
candidates.append("{}.yaml".format(variant))
# De-duplicate while preserving order.
seen = set()
ordered = []
for name in candidates:
if name in seen:
continue
seen.add(name)
ordered.append(name)
return ordered
def _pack_config_dir():
return os.path.join(os.path.dirname(os.path.abspath(__file__)), "sam2_configs")
def _init_hydra_for_local_configs():
cfg_dir = _pack_config_dir()
if not os.path.isdir(cfg_dir):
raise RuntimeError("OpenShot SAM2 config directory not found: {}".format(cfg_dir))
if GlobalHydra.instance().is_initialized():
GlobalHydra.instance().clear()
initialize_config_dir(config_dir=cfg_dir, version_base=None)
def _to_device_dtype(device_name, precision):
device_name = str(device_name or "").strip().lower()
if device_name in ("", "auto"):
device = mm.get_torch_device()
elif device_name == "cpu":
device = torch.device("cpu")
elif device_name == "cuda":
device = torch.device("cuda")
elif device_name == "mps":
device = torch.device("mps")
else:
device = mm.get_torch_device()
precision = str(precision or "fp16").strip().lower()
if precision == "bf16":
dtype = torch.bfloat16
elif precision == "fp32":
dtype = torch.float32
else:
dtype = torch.float16
return device, dtype
def _parse_points(text):
text = str(text or "").strip()
if not text:
return []
try:
parsed = json.loads(text.replace("'", '"'))
except Exception:
return []
if not isinstance(parsed, list):
return []
pts = []
for item in parsed:
if not isinstance(item, dict):
continue
try:
pts.append((float(item["x"]), float(item["y"])))
except Exception:
continue
return pts
def _parse_rects(text):
text = str(text or "").strip()
if not text:
return []
try:
parsed = json.loads(text.replace("'", '"'))
except Exception:
return []
if not isinstance(parsed, list):
return []
out = []
for item in parsed:
if not isinstance(item, dict):
continue
if all(k in item for k in ("x1", "y1", "x2", "y2")):
try:
x1 = float(item["x1"])
y1 = float(item["y1"])
x2 = float(item["x2"])
y2 = float(item["y2"])
except Exception:
continue
elif all(k in item for k in ("x", "y", "w", "h")):
try:
x1 = float(item["x"])
y1 = float(item["y"])
x2 = x1 + float(item["w"])
y2 = y1 + float(item["h"])
except Exception:
continue
else:
continue
out.append((x1, y1, x2, y2))
return out
def _parse_tracking_selection(text):
text = str(text or "").strip()
if not text:
return {"seed_frame_idx": 0, "schedule": {}}
try:
parsed = json.loads(text.replace("'", '"'))
except Exception:
return {"seed_frame_idx": 0, "schedule": {}}
if not isinstance(parsed, dict):
return {"seed_frame_idx": 0, "schedule": {}}
try:
seed_frame_idx = max(0, int(parsed.get("seed_frame", 1)) - 1)
except Exception:
seed_frame_idx = 0
frames = parsed.get("frames", {})
if not isinstance(frames, dict):
frames = {}
schedule = {}
for frame_key, frame_data in frames.items():
if not isinstance(frame_data, dict):
continue
try:
frame_idx = int(frame_key)
except Exception:
continue
frame_idx = max(0, frame_idx - 1)
pos = []
neg = []
for item in frame_data.get("positive_points", []) or []:
if not isinstance(item, dict):
continue
try:
pos.append((float(item["x"]), float(item["y"])))
except Exception:
continue
for item in frame_data.get("negative_points", []) or []:
if not isinstance(item, dict):
continue
try:
neg.append((float(item["x"]), float(item["y"])))
except Exception:
continue
pos_rects = []
neg_rects = []
for item in frame_data.get("positive_rects", []) or []:
if not isinstance(item, dict):
continue
try:
pos_rects.append(
(
float(item["x1"]),
float(item["y1"]),
float(item["x2"]),
float(item["y2"]),
)
)
except Exception:
continue
for item in frame_data.get("negative_rects", []) or []:
if not isinstance(item, dict):
continue
try:
neg_rects.append(
(
float(item["x1"]),
float(item["y1"]),
float(item["x2"]),
float(item["y2"]),
)
)
except Exception:
continue
points = []
labels = []
object_prompts = []
for idx, (x, y) in enumerate(pos):
obj_id = int(idx)
points.append((x, y))
labels.append(1)
object_prompts.append(
{
"obj_id": obj_id,
"points": [(x, y)],
"labels": [1],
"positive_rects": [],
}
)
for x, y in neg:
points.append((x, y))
labels.append(0)
for extra_idx, rect in enumerate(pos_rects):
obj_id = int(len(object_prompts) + extra_idx)
object_prompts.append(
{
"obj_id": obj_id,
"points": [],
"labels": [],
"positive_rects": [rect],
}
)
if points or pos_rects or neg_rects:
schedule[int(frame_idx)] = {
"points": points,
"labels": labels,
"positive_rects": pos_rects,
"negative_rects": neg_rects,
"object_prompts": object_prompts,
}
return {"seed_frame_idx": int(seed_frame_idx), "schedule": schedule}
def _clip_rect(rect, width, height):
x1, y1, x2, y2 = [float(v) for v in rect]
left = max(0, min(int(np.floor(min(x1, x2))), int(width)))
top = max(0, min(int(np.floor(min(y1, y2))), int(height)))
right = max(0, min(int(np.ceil(max(x1, x2))), int(width)))
bottom = max(0, min(int(np.ceil(max(y1, y2))), int(height)))
if right <= left or bottom <= top:
return None
return (left, top, right, bottom)
def _rect_center_points(rects):
out = []
for x1, y1, x2, y2 in rects:
out.append(((float(x1) + float(x2)) * 0.5, (float(y1) + float(y2)) * 0.5))
return out
def _mask_stack_like(base_mask, image):
if base_mask is None:
return None
mask = base_mask.float()
if mask.ndim == 2:
mask = mask.unsqueeze(0)
if mask.ndim == 4:
mask = mask.squeeze(-1)
if mask.ndim != 3:
return None
b = int(image.shape[0])
h = int(image.shape[1])
w = int(image.shape[2])
if int(mask.shape[0]) == 1 and b > 1:
mask = mask.repeat(b, 1, 1)
if int(mask.shape[0]) != b:
return None
if int(mask.shape[1]) != h or int(mask.shape[2]) != w:
mask = F.interpolate(mask.unsqueeze(1), size=(h, w), mode="nearest").squeeze(1)
return torch.clamp(mask, 0.0, 1.0)
def _apply_negative_rects(mask_tensor, negative_rects):
if mask_tensor is None or not negative_rects:
return mask_tensor
if mask_tensor.ndim != 3:
return mask_tensor
h = int(mask_tensor.shape[1])
w = int(mask_tensor.shape[2])
out = mask_tensor.clone()
for rect in negative_rects:
clipped = _clip_rect(rect, w, h)
if not clipped:
continue
left, top, right, bottom = clipped
out[:, top:bottom, left:right] = 0.0
return out
def _tensor_to_pil_image(img):
arr = torch.clamp(img, 0.0, 1.0).mul(255.0).byte().cpu().numpy()
return Image.fromarray(arr)
def _resolve_dino_device(device_name):
device_name = str(device_name or "auto").strip().lower()
if device_name == "auto":
return mm.get_torch_device()
return torch.device(device_name)
def _get_groundingdino_model_and_processor(model_id, device):
key = "{}::{}".format(str(model_id), str(device))
if key in GROUNDING_DINO_CACHE:
return GROUNDING_DINO_CACHE[key]
_openshot_log("Loading GroundingDINO processor '{}'".format(model_id))
processor = AutoProcessor.from_pretrained(model_id)
_openshot_log("Loading GroundingDINO model '{}'".format(model_id))
model = AutoModelForZeroShotObjectDetection.from_pretrained(model_id)
model.to(device)
model.eval()
_openshot_log("GroundingDINO ready on {}".format(device))
GROUNDING_DINO_CACHE[key] = (processor, model)
return processor, model
def _detect_groundingdino_boxes(image_tensor, prompt, model_id, box_threshold, text_threshold, device_name):
prompt = str(prompt or "").strip()
if not prompt:
return []
_require_groundingdino()
if not prompt.endswith("."):
prompt = "{}.".format(prompt)
if image_tensor is None or int(image_tensor.shape[0]) <= 0:
return []
device = _resolve_dino_device(device_name)
processor, model = _get_groundingdino_model_and_processor(model_id, device)
pil = _tensor_to_pil_image(image_tensor[0])
h = int(image_tensor.shape[1])
w = int(image_tensor.shape[2])
with torch.inference_mode():
inputs = processor(images=pil, text=prompt, return_tensors="pt")
inputs = {k: v.to(device) for k, v in inputs.items()}
outputs = model(**inputs)
post_kwargs = {
"target_sizes": [(h, w)],
"text_threshold": float(text_threshold),
}
try:
result = processor.post_process_grounded_object_detection(
outputs,
inputs["input_ids"],
box_threshold=float(box_threshold),
**post_kwargs,
)[0]
except TypeError:
try:
result = processor.post_process_grounded_object_detection(
outputs,
inputs["input_ids"],
threshold=float(box_threshold),
**post_kwargs,
)[0]
except TypeError:
result = processor.post_process_grounded_object_detection(
outputs,
inputs["input_ids"],
threshold=float(box_threshold),
target_sizes=[(h, w)],
)[0]
boxes = result.get("boxes")
labels = result.get("labels")
scores = result.get("scores")
if boxes is None or boxes.numel() == 0:
_sam2_debug("dino-detect", "prompt=", prompt, "detections=0")
return []
boxes_cpu = boxes.detach().cpu()
out_boxes = [tuple(float(v) for v in boxes_cpu[i].tolist()) for i in range(int(boxes_cpu.shape[0]))]
# Detailed detection diagnostics for prompt-quality debugging.
details = []
for i in range(int(boxes_cpu.shape[0])):
try:
lbl = str(labels[i]) if labels is not None else ""
except Exception:
lbl = ""
try:
score = float(scores[i].item()) if scores is not None else 0.0
except Exception:
score = 0.0
b = out_boxes[i]
details.append({
"i": i,
"label": lbl,
"score": round(score, 4),
"box": [round(float(b[0]), 1), round(float(b[1]), 1), round(float(b[2]), 1), round(float(b[3]), 1)],
})
_sam2_debug(
"dino-detect",
"prompt=", prompt,
"detections=", len(out_boxes),
"details=", json.dumps(details[:12]),
)
return out_boxes
def _sam2_add_prompts(model, state, frame_idx, obj_id, coords, labels, positive_rects):
errors = []
if coords is not None and labels is not None and len(coords) > 0 and len(labels) > 0:
for call in (
lambda: model.add_new_points(
inference_state=state,
frame_idx=int(frame_idx),
obj_id=int(obj_id),
points=coords,
labels=labels,
),
lambda: model.add_new_points_or_box(
inference_state=state,
frame_idx=int(frame_idx),
obj_id=int(obj_id),
points=coords,
labels=labels,
),
):
try:
call()
break
except Exception as ex:
errors.append(str(ex))
else:
raise RuntimeError("Failed SAM2 add points across API variants: {}".format(errors))
for rect in positive_rects or []:
box = np.array([float(rect[0]), float(rect[1]), float(rect[2]), float(rect[3])], dtype=np.float32)
rect_errors = []
for call in (
lambda: model.add_new_points_or_box(
inference_state=state,
frame_idx=int(frame_idx),
obj_id=int(obj_id),
box=box,
),
lambda: model.add_new_points_or_box(
inference_state=state,
frame_idx=int(frame_idx),
obj_id=int(obj_id),
points=np.empty((0, 2), dtype=np.float32),
labels=np.empty((0,), dtype=np.int32),
box=box,
),
):
try:
call()
rect_errors = []
break
except Exception as ex:
rect_errors.append(str(ex))
if rect_errors:
errors.extend(rect_errors)
return errors
def _resolve_video_path_for_sam2(path_text):
"""Resolve Comfy-style path text to an absolute local file path for SAM2 video predictor."""
path_text = str(path_text or "").strip()
if not path_text:
return ""
# Strip Comfy annotation suffixes if present.
if path_text.endswith("]") and " [" in path_text:
path_text = path_text.rsplit(" [", 1)[0].strip()
if os.path.isabs(path_text) and os.path.exists(path_text):
return path_text
# Handles plain names and annotated names like "clip.mp4 [input]".
try:
resolved = folder_paths.get_annotated_filepath(path_text)
if resolved and os.path.exists(resolved):
return resolved
except Exception:
pass
# Fallback to Comfy input directory.
try:
candidate = os.path.join(folder_paths.get_input_directory(), path_text)
if os.path.exists(candidate):
return candidate
# fallback to basename if caller passed nested/odd relative path tokens
candidate2 = os.path.join(folder_paths.get_input_directory(), os.path.basename(path_text))
if os.path.exists(candidate2):
return candidate2
except Exception:
pass
return path_text
def _resolve_local_media_path(path_text):
path_text = str(path_text or "").strip()
if not path_text:
return ""
if path_text.endswith("]") and " [" in path_text:
path_text = path_text.rsplit(" [", 1)[0].strip()
if os.path.isabs(path_text) and os.path.exists(path_text):
return path_text
try:
resolved = folder_paths.get_annotated_filepath(path_text)
if resolved and os.path.exists(resolved):
return resolved
except Exception:
pass
for getter in (
getattr(folder_paths, "get_input_directory", None),
getattr(folder_paths, "get_output_directory", None),
getattr(folder_paths, "get_temp_directory", None),
):
if not callable(getter):
continue
try:
root = getter()
except Exception:
continue
for candidate in (
os.path.join(root, path_text),
os.path.join(root, os.path.basename(path_text)),
):
if os.path.exists(candidate):
return candidate
return path_text
def _ensure_mp4_for_sam2(video_path):
"""Convert non-MP4 input videos to MP4 for SAM2VideoPredictor compatibility."""
video_path = str(video_path or "").strip()
if not video_path:
return video_path
ext = os.path.splitext(video_path)[1].lower()
if ext == ".mp4":
return video_path
if not os.path.isfile(video_path):
return video_path
cache_dir = os.path.join(folder_paths.get_temp_directory(), "openshot_sam2_mp4_cache")
os.makedirs(cache_dir, exist_ok=True)
st = os.stat(video_path)
key = "{}|{}|{}".format(video_path, int(st.st_mtime_ns), int(st.st_size))
digest = hashlib.sha256(key.encode("utf-8")).hexdigest()[:16]
out_path = os.path.join(cache_dir, "{}.mp4".format(digest))
if os.path.exists(out_path):
return out_path
cmd = [
"ffmpeg",
"-y",
"-i",
video_path,
"-an",
"-c:v",
"libx264",
"-pix_fmt",
"yuv420p",
"-crf",
"18",
out_path,
]
try:
subprocess.run(cmd, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, text=True)
except FileNotFoundError:
raise RuntimeError("ffmpeg not found; required to convert '{}' to MP4".format(video_path))
except subprocess.CalledProcessError as ex:
err = (ex.stderr or "").strip()
if len(err) > 500:
err = err[:500] + "...(truncated)"
raise RuntimeError("ffmpeg conversion to MP4 failed: {}".format(err))
return out_path
def _load_video_frame_tensor_for_dino(video_path, frame_index=0):
"""Load one RGB frame from video as IMAGE tensor shape [1,H,W,C] in 0..1."""
vp = _resolve_video_path_for_sam2(video_path)
vp = _ensure_mp4_for_sam2(vp)
if not vp or (not os.path.isfile(vp)):
return None
try:
frame_index = int(max(0, frame_index))
except Exception:
frame_index = 0
tmp_dir = tempfile.mkdtemp(prefix="openshot_dino_frame_", dir=folder_paths.get_temp_directory())
out_png = os.path.join(tmp_dir, "seed.png")
filter_expr = r"select=eq(n\,{})".format(frame_index)
cmd = [
"ffmpeg",
"-y",
"-i",
vp,
"-vf",
filter_expr,
"-vframes",
"1",
out_png,
]
try:
subprocess.run(cmd, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, text=True)
if not os.path.isfile(out_png):
return None
pil = Image.open(out_png).convert("RGB")
arr = np.asarray(pil, dtype=np.float32) / 255.0
return torch.from_numpy(arr).unsqueeze(0)
except Exception:
return None
finally:
shutil.rmtree(tmp_dir, ignore_errors=True)
def _build_sam2_video_predictor(config_name, checkpoint, torch_device):
"""Build a SAM2 video predictor across package variants."""
if sam2_build is None:
raise RuntimeError("sam2.build_sam module unavailable")
candidate_names = (
"build_sam2_video_predictor",
"build_video_predictor",
"build_sam_video_predictor",
)
found = []
last_error = None
for name in candidate_names:
fn = getattr(sam2_build, name, None)
if not callable(fn):
continue
found.append(name)
for kwargs in (
{"device": torch_device},
{},
):
try:
return fn(config_name, checkpoint, **kwargs)
except TypeError:
continue
except Exception as ex:
last_error = ex
continue
raise RuntimeError(
"Could not build SAM2 video predictor. Found builders={} last_error={}".format(found, last_error)
)
class OpenShotTransNetSceneDetect:
@classmethod
def IS_CHANGED(cls, **kwargs):
return ""
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"source_video_path": ("STRING", {"default": ""}),
"threshold": ("FLOAT", {"default": 0.50, "min": 0.01, "max": 0.99, "step": 0.01}),
"min_scene_length_frames": ("INT", {"default": 30, "min": 1, "max": 10000}),
"device": (["auto", "cuda", "cpu", "mps"], {"default": "auto"}),
},
}
RETURN_TYPES = ("STRING",)
RETURN_NAMES = ("scene_ranges_json",)
FUNCTION = "detect"
CATEGORY = "OpenShot/Video"
def _resolve_device_name(self, device_name):
value = str(device_name or "auto").strip().lower()
if value != "auto":
return value
if torch.cuda.is_available():
return "cuda"
if getattr(torch.backends, "mps", None) and torch.backends.mps.is_available():
return "mps"
return "cpu"
def _build_model(self, device_name):
errors = []
for kwargs in (
{"device": device_name},
{},
):
try:
return _TransNetV2(**kwargs)
except Exception as ex:
errors.append(str(ex))
raise RuntimeError("Failed to initialize TransNetV2 model: {}".format(errors[:2]))
def _extract_scenes(self, raw):
fps = None
scenes = None
if isinstance(raw, dict):
scenes = raw.get("scenes")
fps_value = raw.get("fps")
try:
if fps_value is not None:
fps = float(fps_value)
except Exception:
fps = None
else:
scenes = raw
normalized = []
if isinstance(scenes, np.ndarray):
scenes = scenes.tolist()
if isinstance(scenes, list):
for entry in scenes:
start = end = None
if isinstance(entry, dict):
start = entry.get("start_seconds", entry.get("start_time", entry.get("start")))
end = entry.get("end_seconds", entry.get("end_time", entry.get("end")))
elif isinstance(entry, (list, tuple)) and len(entry) >= 2:
start, end = entry[0], entry[1]
try:
start_f = float(start)
end_f = float(end)
except Exception:
continue
if end_f <= start_f:
continue
normalized.append((start_f, end_f))
return normalized, fps
def _run_inference(self, model, video_path, threshold):
errors = []
for fn_name in ("detect_scenes", "analyze_video", "predict_video"):
fn = getattr(model, fn_name, None)
if not callable(fn):
continue
for kwargs in (
{"threshold": float(threshold)},
{},
):
try:
return fn(video_path, **kwargs)
except TypeError:
continue
except Exception as ex:
errors.append("{}: {}".format(fn_name, ex))
break
raise RuntimeError("TransNetV2 inference failed: {}".format(errors[:2]))
def _apply_min_scene_length(self, scenes, fps, min_scene_length_frames):
if not scenes:
return []
if not fps or fps <= 0:
return scenes
min_seconds = float(min_scene_length_frames) / float(fps)
if min_seconds <= 0:
return scenes
out = []
for start_sec, end_sec in scenes:
if not out:
out.append([start_sec, end_sec])
continue
duration = end_sec - start_sec
if duration < min_seconds:
out[-1][1] = max(out[-1][1], end_sec)
continue
out.append([start_sec, end_sec])
return [(float(s), float(e)) for s, e in out if e > s]
def detect(self, source_video_path, threshold, min_scene_length_frames, device):
_require_transnet()
video_path = _resolve_video_path_for_sam2(source_video_path)
if not video_path or not os.path.exists(video_path):
raise ValueError("Video path not found: {}".format(source_video_path))
device_name = self._resolve_device_name(device)