forked from vrgamegirl19/comfyui-vrgamedevgirl
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHumoAutomation.py
More file actions
3377 lines (2797 loc) · 132 KB
/
HumoAutomation.py
File metadata and controls
3377 lines (2797 loc) · 132 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 os, gc
import torch
import numpy as np
import imageio
import torchaudio
import random
import re
from transformers import WhisperProcessor, WhisperForConditionalGeneration
import folder_paths
import json
from typing import TypedDict, Tuple
from torch import Tensor
from server import PromptServer
from torchaudio.transforms import Vad
#########################
import subprocess
def find_ffmpeg_path():
"""
Checks if system ffmpeg is available;
if not, falls back to imageio-ffmpeg bundled binary.
"""
try:
# Try to call system ffmpeg
subprocess.run(["ffmpeg", "-version"], capture_output=True, check=True)
return "ffmpeg" # System ffmpeg is available
except (subprocess.CalledProcessError, FileNotFoundError):
try:
import imageio_ffmpeg
ffmpeg_path = imageio_ffmpeg.get_ffmpeg_exe()
print(f"[VRGDG] Using fallback ffmpeg from imageio: {ffmpeg_path}")
return ffmpeg_path
except Exception as e:
print(f"[VRGDG] ⚠️ No FFmpeg found. Error: {e}")
return None
####################
class AUDIO(TypedDict):
"""
Required Fields:
waveform (torch.Tensor): Audio data [Batch, Channels, Frames]
sample_rate (int): Sample rate of the audio.
"""
waveform: Tensor
sample_rate: int
class VRGDG_CombinevideosV2:
RETURN_TYPES = ("IMAGE",)
RETURN_NAMES = ("blended_video_frames",)
FUNCTION = "blend_videos"
CATEGORY = "Video"
@classmethod
def INPUT_TYPES(cls):
# Hardcode exactly 16 video inputs
opt_videos = {f"video_{i}": ("IMAGE",) for i in range(1, 17)}
return {
"required": {
"fps": ("FLOAT", {"default": 25.0, "min": 1.0}),
"audio_meta": ("DICT",), # required to drive durations
},
"optional": {
**opt_videos,
},
}
# --- helpers -------------------------------------------------------------
def _target_frames_for_index(self, durations, idx_zero_based, fps, current_frames):
"""durations[idx] seconds * fps -> target frames. If duration <= 0, use current_frames."""
try:
dur_sec = float(durations[idx_zero_based])
except Exception:
dur_sec = 0.0
if dur_sec > 0.0:
tgt = int(round(dur_sec * float(fps)))
return max(1, tgt)
return int(current_frames)
def _trim_or_pad(self, video, target_frames, pad_short=False):
if video is None:
return None
if video.ndim != 4:
raise ValueError(f"Expected video tensor with 4 dims (frames,H,W,C), got {tuple(video.shape)}")
cur = int(video.shape[0])
if cur > target_frames:
return video[:target_frames]
if cur < target_frames and pad_short:
need = target_frames - cur
last = video[-1:].clone()
pad = last.repeat(need, 1, 1, 1)
return torch.cat([video, pad], dim=0)
return video
# --- main op -------------------------------------------------------------
def blend_videos(self, fps, audio_meta, **kwargs):
pad_short_videos = True
effective_scene_count = 16 # hardcoded
# ✅ Always use durations from audio_meta
durations = []
if isinstance(audio_meta, dict) and "durations" in audio_meta and isinstance(audio_meta["durations"], (list, tuple)):
meta_durations = list(audio_meta.get("durations", []))
if len(meta_durations) < effective_scene_count:
meta_durations += [0.0] * (effective_scene_count - len(meta_durations))
durations = meta_durations[:effective_scene_count]
else:
durations = [0.0] * effective_scene_count
# Collect videos (up to 16, some may be None)
vids = []
for i in range(1, effective_scene_count + 1):
v = kwargs.get(f"video_{i}")
if v is not None:
vids.append((i, v))
if len(vids) < 1:
raise ValueError("Provide at least one videos (e.g., video_1).")
trimmed = []
for slot_idx, vid in vids:
if vid.ndim != 4:
raise ValueError(f"video_{slot_idx} must have shape (frames,H,W,C), got {tuple(vid.shape)}")
tgt = self._target_frames_for_index(durations, slot_idx - 1, fps, vid.shape[0])
trimmed.append(self._trim_or_pad(vid, tgt, pad_short=pad_short_videos))
final = torch.cat([t.to(dtype=torch.float32) for t in trimmed], dim=0).cpu()
return (final,)
class VRGDG_PromptSplitter:
RETURN_TYPES = tuple(["STRING"] * 50)
RETURN_NAMES = tuple([f"text_output_{i}" for i in range(1, 51)])
FUNCTION = "split_prompt"
CATEGORY = "VRGDG"
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"prompt_text": ("STRING", {"multiline": True, "default": ""}),
"scene_count": ("INT", {"default": 2, "min": 1, "max": 50}),
}
}
@classmethod
def IS_DYNAMIC(cls):
return True
@classmethod
def get_output_types(cls, **kwargs):
count = int(kwargs.get("scene_count", 2))
count = max(1, min(50, count))
return tuple(["STRING"] * count)
@classmethod
def get_output_names(cls, **kwargs):
count = int(kwargs.get("scene_count", 2))
count = max(1, min(50, count))
return [f"text_output_{i+1}" for i in range(count)]
def split_prompt(self, prompt_text, scene_count=2, **kwargs):
scene_count = max(1, min(50, scene_count))
parts = [p.strip() for p in prompt_text.strip().split("|") if p.strip()]
outputs = [parts[i] if i < len(parts) else "" for i in range(scene_count)]
return tuple(outputs)
class VRGDG_TimecodeFromIndex:
# one set = 16 groups × 97 frames @ 25 fps
_FRAMES_PER_GROUP = 97
_FPS = 25
_GROUPS_PER_SET = 16
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"index": ("INT", {"default": 0, "min": 0}),
}
}
RETURN_TYPES = ("STRING",)
RETURN_NAMES = ("start_time",)
FUNCTION = "format_timecode"
CATEGORY = "utils"
def format_timecode(self, index):
# compute exact duration per set
set_duration = (self._FRAMES_PER_GROUP * self._GROUPS_PER_SET) / self._FPS # 62.08
start_seconds = index * set_duration
minutes = int(start_seconds // 60)
seconds = start_seconds % 60
return (f"{minutes}:{seconds:05.2f}",)
class VRGDG_ConditionalLoadVideos:
RETURN_TYPES = ("IMAGE",)
RETURN_NAMES = ("video",)
FUNCTION = "load_videos"
CATEGORY = "Video"
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"trigger": ("VHS_FILENAMES", {}),
"threshold": ("INT", {"default": 3}),
"video_folder": ("STRING", {"default": "./videos", "multiline": False}),
"batch_size": ("INT", {"default": 100, "min": 1, "max": 1000}), # 🔧 new option
}
}
def load_videos(self, trigger, threshold, video_folder, batch_size=100):
video_folder = video_folder.strip()
# ensure folder exists
if not os.path.exists(video_folder):
os.makedirs(video_folder, exist_ok=True)
print(f"[VRGDG_ConditionalLoadVideos] Created folder: {video_folder}")
print(f"[VRGDG_ConditionalLoadVideos] No videos yet, skipping.")
return (None,)
# collect only -audio.mp4 (final videos)
videos = sorted(
[f for f in os.listdir(video_folder)
if f.lower().endswith(".mp4") and "-audio" in f.lower()]
)
video_count = len(videos)
print(f"[VRGDG_ConditionalLoadVideos] Found {video_count} -audio.mp4 videos in {video_folder}")
if video_count < threshold:
print(f"[VRGDG_ConditionalLoadVideos] Threshold not met ({video_count}/{threshold}), skipping.")
return (None,)
all_frames = []
for vid in videos:
path = os.path.join(video_folder, vid)
print(f"[VRGDG_ConditionalLoadVideos] Loading {path}")
reader = imageio.get_reader(path, "ffmpeg")
frames = []
batch = []
frame_count = 0
for frame in reader:
# normalize to float32 RGB tensor
frame = frame.astype(np.float32) / 255.0
tensor = torch.from_numpy(frame).unsqueeze(0) # (1,H,W,C)
batch.append(tensor)
frame_count += 1
# flush in batches
if len(batch) >= batch_size:
frames.append(torch.cat(batch, dim=0))
batch = []
if frame_count % 500 == 0:
print(f"[VRGDG_ConditionalLoadVideos] {vid}: loaded {frame_count} frames...")
# add any leftovers
if batch:
frames.append(torch.cat(batch, dim=0))
reader.close()
if not frames:
print(f"[VRGDG_ConditionalLoadVideos] Skipped {vid}, no frames read.")
continue
video_tensor = torch.cat(frames, dim=0) # (F,H,W,C)
all_frames.append(video_tensor)
print(f"[VRGDG_ConditionalLoadVideos] Finished {vid} with {video_tensor.shape[0]} frames")
# cleanup per video
del frames, batch
gc.collect()
if not all_frames:
print("[VRGDG_ConditionalLoadVideos] No valid videos loaded, returning None.")
return (None,)
# final concat + cleanup
final_video = torch.cat(all_frames, dim=0) # (ΣF,H,W,C)
print(f"[VRGDG_ConditionalLoadVideos] Returning tensor with {final_video.shape[0]} frames")
del all_frames
gc.collect()
# move to CPU (important for downstream save nodes)
final_video = final_video.cpu()
return (final_video,)
class VRGDG_CalculateSetsFromAudio:
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"audio": ("AUDIO",),
"index": ("INT", {"default": 0, "min": 0}),
}
}
RETURN_TYPES = ("STRING", "STRING", "INT",)
RETURN_NAMES = ("instructions", "end_time", "total_sets",)
FUNCTION = "calculate"
CATEGORY = "utils/audio"
def calculate(self, audio, index):
set_duration = 62.0
group_duration = 3.88
groups_per_set = 16
try:
waveform = audio["waveform"]
sample_rate = audio["sample_rate"]
except Exception:
return ("❌ Expected audio to be a dict with 'waveform' and 'sample_rate'.", "0:00", 0)
try:
num_samples = waveform.shape[-1]
audio_duration = num_samples / sample_rate
except Exception:
return ("❌ Failed to compute audio duration from waveform.", "0:00", 0)
# Convert duration to MM:SS
minutes = int(audio_duration // 60)
seconds = int(audio_duration % 60)
end_time_str = f"{minutes}:{seconds:02d}"
# Compute sets
full_sets = int(audio_duration // set_duration)
remainder = audio_duration - (full_sets * set_duration)
import math
if remainder > 0:
total_sets = full_sets + 1
groups_in_last_set = min(math.ceil(remainder / group_duration), groups_per_set)
else:
total_sets = full_sets
groups_in_last_set = groups_per_set
# ---------------------
# Instructions section
# ---------------------
if index == 0:
run_num = 1
header = f"▶️ Run {run_num} of {total_sets} in progress…\n"
if audio_duration < set_duration:
instructions = (
header +
f"Audio is shorter than one set (62s). "
f"Cancel this run and disable groups {groups_in_last_set+1}–16 "
f"so only groups 1–{groups_in_last_set} are enabled then run again."
)
elif total_sets == 1:
instructions = (
header +
"Audio is exactly one full set (62s) so you’re good to go! "
"You don’t need to run again."
)
elif remainder > 0:
middle_runs = max(total_sets - 2, 0)
if groups_in_last_set == 0:
# Remainder doesn’t even cover one group
instructions = (
header +
f"This audio requires {total_sets-1} full runs in total.\n"
"You don’t need to run again after the last full set."
)
elif middle_runs > 0:
instructions = (
header +
f"This audio requires {total_sets} runs in total.\n"
f"➡️ Click 'Run' {middle_runs} more times with all 16 groups enabled.\n"
f"➡️ Then, disable groups {groups_in_last_set+1}–16 so only groups 1–{groups_in_last_set} are enabled, "
f"➡️ and click 'Run' once more."
)
else:
# Only 2 runs total — no "Then"
instructions = (
header +
f"This audio requires {total_sets} runs in total.\n"
f"➡️ Disable groups {groups_in_last_set+1}–16 so only groups 1–{groups_in_last_set} are enabled, "
f"➡️ and click 'Run' once more."
)
else:
instructions = (
header +
f"This audio requires {total_sets} runs in total.\n"
f"Click 'Run' {total_sets - 1} more times. "
"Keep all 16 groups enabled for every run."
)
elif index < total_sets - 1:
# 🎬 Middle runs
run_num = index + 1
instructions = (
f"🎬 Video creation in progress…\n"
f"➡️ Run {run_num} of {total_sets}"
)
else:
# 🏁 Final run
run_num = index + 1
instructions = (
f"🏁 Final run in progress…\n"
f"➡️ Run {run_num} of {total_sets}"
)
return (instructions, end_time_str, total_sets)
class VRGDG_GetFilenamePrefix:
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"folder_path": ("STRING", {"multiline": False}),
}
}
RETURN_TYPES = ("STRING",)
RETURN_NAMES = ("Filename_Prefix",)
FUNCTION = "get_prefix"
CATEGORY = "utils/files"
def get_prefix(self, folder_path):
# Clean up any accidental whitespace or newline characters
folder_path = folder_path.strip()
# Ensure the folder exists (create it if missing)
os.makedirs(folder_path, exist_ok=True)
# Normalize and extract last folder name
base_name = os.path.basename(os.path.normpath(folder_path))
# Build result in an OS-safe way
result = os.path.join(base_name, "video")
return (result,)
class VRGDG_TriggerCounter:
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"seed": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff}),
},
"hidden": {"id": "UNIQUE_ID"}
}
RETURN_TYPES = ("INT",)
RETURN_NAMES = ("index",)
FUNCTION = "generate"
CATEGORY = "utils/control"
def generate(self, seed, id=None):
# Just return the seed, ComfyUI handles incrementing via control_after_generate
return (seed,)
class VRGDG_LoadAudioSplit_HUMO_TranscribeV2:
RETURN_TYPES = ("DICT", "FLOAT", "STRING") + tuple(["AUDIO"] * 16)
RETURN_NAMES = ("meta", "total_duration", "lyrics_string") + tuple([f"audio_{i}" for i in range(1, 17)])
FUNCTION = "split_audio"
CATEGORY = "VRGDG"
fallback_words = ["standing", "sitting", "laying", "resting", "waiting",
"walking", "dancing", "looking", "thinking"]
@classmethod
def INPUT_TYPES(cls):
optional = {}
hidden = {}
for i in range(1, 17):
optional[f"context_{i}"] = ("STRING", {"default": "", "multiline": True})
hidden[f"play_{i}"] = ("BUTTON", {"label": f"▶️ Play {i}"})
return {
"required": {
"audio": ("AUDIO",),
"set_index": ("INT", {"default": 0, "min": 0}),
"language": (
[
"auto", "english", "chinese", "german", "spanish", "russian", "korean", "french",
"japanese", "portuguese", "turkish", "polish", "catalan", "dutch", "arabic", "swedish",
"italian", "indonesian", "hindi", "finnish", "vietnamese", "hebrew", "ukrainian", "greek",
"malay", "czech", "romanian", "danish", "hungarian", "tamil", "norwegian", "thai", "urdu",
"croatian", "bulgarian", "lithuanian", "latin", "maori", "malayalam", "welsh", "slovak",
"telugu", "persian", "latvian", "bengali", "serbian", "azerbaijani", "slovenian", "kannada",
"estonian", "macedonian", "breton", "basque", "icelandic", "armenian", "nepali", "mongolian",
"bosnian", "kazakh", "albanian", "swahili", "galician", "marathi", "punjabi", "sinhala",
"khmer", "shona", "yoruba", "somali", "afrikaans", "occitan", "georgian", "belarusian",
"tajik", "sindhi", "gujarati", "amharic", "yiddish", "lao", "uzbek", "faroese", "haitian creole",
"pashto", "turkmen", "nynorsk", "maltese", "sanskrit", "luxembourgish", "myanmar", "tibetan",
"tagalog", "malagasy", "assamese", "tatar", "hawaiian", "lingala", "hausa", "bashkir",
"javanese", "sundanese", "cantonese", "burmese", "valencian", "flemish", "haitian",
"letzeburgesch", "pushto", "panjabi", "moldavian", "moldovan", "sinhalese", "castilian", "mandarin"
],
{"default": "english"}
),
"enable_lyrics": ("BOOLEAN", {"default": True}),
"overlap_lyric_seconds": ("FLOAT", {"default": 0.0, "min": 0.0}),
"fallback_words": ("STRING", {"default": "thinking,walking,sitting"}),
},
"optional": optional,
"hidden": hidden,
}
def split_audio(
self,
audio,
set_index=0,
language="english",
enable_lyrics=True,
overlap_lyric_seconds=0.0,
fallback_words="",
**kwargs
):
waveform = audio["waveform"]
src_sample_rate = int(audio.get("sample_rate", 44100))
if waveform.ndim == 2:
waveform = waveform.unsqueeze(0)
total_samples = waveform.shape[-1]
total_duration = float(total_samples) / float(src_sample_rate)
scene_count = 16
fps = 25
frames_per_scene = 97
samples_per_frame = int(round(src_sample_rate / fps))
samples_per_scene = frames_per_scene * samples_per_frame
# NEW: offset per set
offset_samples = set_index * scene_count * samples_per_scene
print(f"[Split] set_index={set_index}, offset_samples={offset_samples}")
durations = [frames_per_scene / fps] * scene_count
starts = [offset_samples + i * samples_per_scene for i in range(scene_count)] # integer sample indices
# ---- Split precisely on integer sample boundaries ----
segments = []
total_len_samples = scene_count * samples_per_scene
# Always try to make `scene_count` groups, even if audio runs short
for idx in range(scene_count):
start_samp = offset_samples + idx * samples_per_scene
end_samp = start_samp + samples_per_scene
# If we're entirely past end of file, fill full silence
if start_samp >= total_samples:
seg = torch.zeros((1, 1, samples_per_scene), dtype=waveform.dtype)
print(f"[Split] idx={idx} filled with silence (no audio left)")
else:
# Clamp end within the file
end_samp = min(total_samples, end_samp)
seg = waveform[..., start_samp:end_samp].contiguous().clone()
cur_len = seg.shape[-1]
# Pad with silence if short
if cur_len < samples_per_scene:
pad = samples_per_scene - cur_len
seg = torch.nn.functional.pad(seg, (0, pad))
print(f"[Split] idx={idx} padded {pad} samples")
segments.append({"waveform": seg, "sample_rate": src_sample_rate})
print(f"[Split] Created {len(segments)} segments (scene_count={scene_count})")
# Never return None — always at least silence
if not segments:
empty_audio = {"waveform": torch.zeros((1, 1, samples_per_scene)), "sample_rate": src_sample_rate}
return (empty_audio, total_duration, "")
# -----------------------------------------------------------
# The rest of your existing transcription and saving logic
# -----------------------------------------------------------
if enable_lyrics:
device = "cuda" if torch.cuda.is_available() else "cpu"
processor = WhisperProcessor.from_pretrained("openai/whisper-large-v3")
model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-large-v3").to(device).eval()
else:
processor = model = device = None
output_dir = folder_paths.get_input_directory()
os.makedirs(output_dir, exist_ok=True)
# Clear out old audio files in the audiochunks folder
for filename in os.listdir(output_dir):
file_path = os.path.join(output_dir, filename)
if filename.startswith("audio_") and filename.endswith(".wav"):
try:
os.remove(file_path)
except Exception as e:
print(f"Failed to delete {file_path}: {e}")
fb_words = [w.strip() for w in fallback_words.split(",") if w.strip()] or self.fallback_words
overlap_samples = int(overlap_lyric_seconds * src_sample_rate)
transcriptions = []
for idx, start_samp in enumerate(starts):
end_samp = min(total_samples, start_samp + samples_per_scene)
filepath = os.path.join(output_dir, f"audio_{idx+1}.wav")
torchaudio.save(filepath, segments[idx]["waveform"].squeeze(0).cpu(), src_sample_rate)
if not enable_lyrics:
transcriptions.append("")
continue
# --- segment for transcription (extended with overlap) ---
trans_start = max(0, start_samp - overlap_samples)
trans_end = min(total_samples, end_samp + overlap_samples)
seg_for_transcribe = waveform[..., trans_start:trans_end].contiguous().clone()
try:
flat_seg = seg_for_transcribe.mean(dim=1).squeeze()
if src_sample_rate != 16000:
flat_seg = torchaudio.functional.resample(flat_seg, src_sample_rate, 16000)
inputs = processor(flat_seg, sampling_rate=16000, return_tensors="pt", padding="longest")
input_features = inputs["input_features"].to(device)
if language == "auto":
generated_ids = model.generate(input_features)
else:
decoder_ids = processor.get_decoder_prompt_ids(language=language)
generated_ids = model.generate(input_features, forced_decoder_ids=decoder_ids)
text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0].strip()
if not text:
text = random.choice(fb_words)
except Exception:
text = random.choice(fb_words)
transcriptions.append(text)
safe_transcriptions = [t if t else random.choice(fb_words) for t in transcriptions]
enriched = []
for i in range(scene_count):
lyric_line = safe_transcriptions[i]
context = kwargs.get(f"context_{i+1}", "").strip()
if context:
lyric_line = f"{context}, {lyric_line}"
enriched.append(lyric_line)
lyrics_text = " | ".join(enriched)
meta = {
"durations": durations,
"offset_seconds": 0.0,
"starts": starts,
"sample_rate": src_sample_rate,
"audio_total_duration": total_duration,
"outputs_count": len(segments),
"used_padding": False,
}
return (meta, total_duration, lyrics_text, *tuple(segments))
class VRGDG_StringConcat:
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"instructions": ("STRING", {
"multiline": True,
"default": "",
}),
"song_theme_style": ("STRING", {
"multiline": True,
"default": "",
}),
"pipe_separated_lyrics": ("STRING", {
"multiline": True,
"default": "",
}),
}
}
RETURN_TYPES = ("STRING",)
RETURN_NAMES = ("concatenated_string",)
FUNCTION = "concat_strings"
CATEGORY = "VRGDG/Prompt Tools"
def concat_strings(self, instructions, song_theme_style, pipe_separated_lyrics):
full_string = (
"Instructions:\n" + instructions.strip() + "\n\n"
"Song theme/style:\n" + song_theme_style.strip() + "\n\n"
"Pipe separated lyrics:\n" + pipe_separated_lyrics.strip()
)
return (full_string,)
class VRGDG_AudioCrop:
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"audio": ("AUDIO",),
"start_time": (
"STRING",
{
"default": "0:00",
},
),
"end_time": (
"STRING",
{
"default": "1:00",
},
),
},
}
FUNCTION = "main"
RETURN_TYPES = ("AUDIO",)
CATEGORY = "audio"
DESCRIPTION = "Crop (trim) audio to a specific start and end time."
def main(
self,
audio: "AUDIO",
start_time: str = "0:00",
end_time: str = "1:00",
):
waveform: torch.Tensor = audio["waveform"]
sample_rate: int = audio["sample_rate"]
if ":" not in start_time:
start_time = f"00:{start_time}"
if ":" not in end_time:
end_time = f"00:{end_time}"
# --- UPDATED PARSING (accepts mm:ss or mm:ss.xx) ---
start_min, start_sec = start_time.split(":")
start_seconds_time = 60 * int(start_min) + float(start_sec)
start_frame = int(start_seconds_time * sample_rate)
if start_frame >= waveform.shape[-1]:
start_frame = waveform.shape[-1] - 1
end_min, end_sec = end_time.split(":")
end_seconds_time = 60 * int(end_min) + float(end_sec)
end_frame = int(end_seconds_time * sample_rate)
if end_frame >= waveform.shape[-1]:
end_frame = waveform.shape[-1] - 1
# --- END UPDATED SECTION ---
if start_frame < 0:
start_frame = 0
if end_frame < 0:
end_frame = 0
if start_frame > end_frame:
total_duration_sec = waveform.shape[-1] / sample_rate
raise ValueError(
f"Invalid crop range:\n"
f"- Start time: {start_seconds_time} sec\n"
f"- End time: {end_seconds_time} sec\n"
f"- Total duration: {total_duration_sec:.2f} sec\n"
f"Start time must come before end time, and both must be within the audio duration.\n"
f"If this is your first run, double-check that the index or batch position is set to 0 or not set higher than the total number of sets in the read-me note."
)
return (
{
"waveform": waveform[..., start_frame:end_frame],
"sample_rate": sample_rate,
},
)
class VRGDG_GetIndexNumber:
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"trigger": ("INT",), # ✅ forces execution each run
"folder_path": ("STRING", {"multiline": True, "default": ""}),
}
}
RETURN_TYPES = ("INT",)
RETURN_NAMES = ("index",)
FUNCTION = "count_videos"
CATEGORY = "utils"
def count_videos(self, trigger, folder_path):
import os
# 🔹 Always run — trigger is just here to ensure ComfyUI re-executes on queue
if not os.path.isdir(folder_path):
return (0,)
mp4_count = len([
f for f in os.listdir(folder_path)
if f.lower().endswith(".mp4") and "-audio" in f.lower()
])
return (mp4_count,)
class VRGDG_DisplayIndex:
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"index": ("INT", {"default": 0, "min": 0}),
}
}
# We output a STRING so ComfyUI will actually render it in the node UI
RETURN_TYPES = ("STRING",)
RETURN_NAMES = ("index_display",)
FUNCTION = "show"
OUTPUT_NODE = True # makes this a "display-only" node
CATEGORY = "utils"
def show(self, index):
# Convert int to string for UI preview
return (f"Current index: {index}",)
class VRGDG_PromptSplitterV2:
RETURN_TYPES = tuple(["STRING"] * 16)
RETURN_NAMES = tuple([f"text_output_{i}" for i in range(1, 17)])
FUNCTION = "split_prompt"
CATEGORY = "VRGDG"
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"prompt_text": ("STRING", {"multiline": True, "default": ""}),
}
}
def split_prompt(self, prompt_text, **kwargs):
parts = [p.strip() for p in prompt_text.strip().split("|") if p.strip()]
outputs = [parts[i] if i < len(parts) else "" for i in range(16)]
return tuple(outputs)
class VRGDG_CombinevideosV3:
VERSION = "v3.1_fixed"
RETURN_TYPES = ("IMAGE",)
RETURN_NAMES = ("blended_video_frames",)
FUNCTION = "blend_videos"
CATEGORY = "Video"
@classmethod
def INPUT_TYPES(cls):
# fixed 16 video inputs
opt_videos = {f"video_{i}": ("IMAGE",) for i in range(1, 17)}
return {
"required": {
"fps": ("FLOAT", {"default": 25.0, "min": 1.0}),
"duration": ("FLOAT", {"default": 4.0, "min": 0.01}), # 👈 per-group duration in seconds
"audio_meta": ("DICT",), # always use meta for durations
"index": ("INT", {"default": 0, "min": 0}),
"total_sets": ("INT", {"default": 1, "min": 1}),
"groups_in_last_set": ("INT", {"default": 16, "min": 0, "max": 16}),
},
"optional": {**opt_videos},
}
# --- helpers -------------------------------------------------------------
def _target_frames_for_index(self, durations, idx_zero_based, fps, is_frames=False):
"""
Decide target frame count from audio_meta.
durations can be in seconds OR frames depending on the key.
"""
value = float(durations[idx_zero_based])
if is_frames:
# Already in frames
return max(1, int(round(value)))
else:
# In seconds, convert to frames
frames_per_scene = int(round(fps * value))
return max(1, frames_per_scene)
def _trim_or_pad(self, video, target_frames):
if video is None:
return None
if video.ndim != 4:
raise ValueError(f"Expected video tensor with 4 dims (frames,H,W,C), got {tuple(video.shape)}")
cur = int(video.shape[0])
if cur > target_frames:
# Trim if too long
return video[:target_frames]
if cur < target_frames:
# Warn if too short (video generation issue)
#print(f"⚠️ WARNING: Video has {cur} frames but needs {target_frames} (short by {target_frames - cur})")
return video # Return as-is, don't pad
return video
# --- main op -------------------------------------------------------------
def blend_videos(self, fps, duration, audio_meta=None, index=0, total_sets=1, groups_in_last_set=16, **kwargs):
print(f"[CombineV3 {self.VERSION}] index={index}, ...") # Update this line
effective_scene_count = 16
is_last_run = (index == total_sets - 1)
print(f"[CombineV3] index={index}, total_sets={total_sets}, last_run={is_last_run}")
# ✅ Always use durations from audio_meta
if not isinstance(audio_meta, dict):
raise ValueError("[CombineV3] audio_meta must be a dict")
# Accept either key: "durations" (seconds) or "durations_frames" (frames)
durations_seconds = audio_meta.get("durations")
durations_frames = audio_meta.get("durations_frames")
if durations_frames is not None:
durations = list(durations_frames)
is_frames = True
print(f"[CombineV3] Using durations_frames (already in frames)")
elif durations_seconds is not None:
durations = list(durations_seconds)
is_frames = False
print(f"[CombineV3] Using durations (in seconds)")
else:
raise ValueError("[CombineV3] audio_meta missing 'durations' or 'durations_frames' list")
# Pad or trim durations list
if len(durations) < effective_scene_count:
durations += [0.0] * (effective_scene_count - len(durations))
else:
durations = durations[:effective_scene_count]
# Determine how many videos to process this run
limit_videos = effective_scene_count
if is_last_run:
limit_videos = max(1, min(groups_in_last_set, effective_scene_count))
# Collect videos
vids = []
for i in range(1, limit_videos + 1):
v = kwargs.get(f"video_{i}")
if v is not None:
vids.append((i, v))
if len(vids) < 1:
raise ValueError("[CombineV3] No video inputs detected. Connect at least one video_x input.")