-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathh1111.py
More file actions
10273 lines (9097 loc) · 464 KB
/
h1111.py
File metadata and controls
10273 lines (9097 loc) · 464 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 gradio as gr
from gradio import update as gr_update
import subprocess
import threading
import time
import re
import os
import random
import tiktoken
import sys
import ffmpeg
from typing import List, Tuple, Optional, Generator, Dict, Any
import json
from gradio import themes
from gradio.themes.utils import colors
import subprocess
from PIL import Image
import math
import cv2
import glob
import shutil
from pathlib import Path
import logging
from datetime import datetime
from tqdm import tqdm
from diffusers_helper.bucket_tools import find_nearest_bucket
import time
from gradio_image_annotation import image_annotator
# Add global stop event
stop_event = threading.Event()
skip_event = threading.Event()
logger = logging.getLogger(__name__)
UI_CONFIGS_DIR = "ui_configs"
FRAMEPROK_DEFAULTS_FILE = os.path.join(UI_CONFIGS_DIR, "framepack_defaults.json")
### Multitalk
def multitalk_batch_handler(
prompt: str,
negative_prompt: str,
cond_image_data: dict,
audio_person1: Optional[str],
audio_person2: Optional[str],
batch_size: int,
# Generation params
size: str,
mode: str,
frame_num: int,
motion_frame: int,
sample_steps: int,
sample_shift: float,
text_guide_scale: float,
audio_guide_scale: float,
seed: int,
# Advanced & Performance
audio_type: str,
num_persistent: float,
use_teacache: bool,
teacache_thresh: float,
use_apg: bool,
apg_momentum: float,
apg_norm_thresh: float,
use_full_video_preview: bool,
# Paths
ckpt_dir: str,
wav2vec_dir: str,
t5_tokenizer_path: str,
save_path: str,
# LoRAs
lora_folder: str,
lora1_str: str, lora2_str: str, lora3_str: str, lora4_str: str,
lora1_mult: float, lora2_mult: float, lora3_mult: float, lora4_mult: float,
) -> Generator[Tuple[List[Tuple[str, str]], List[str], str, str], None, None]:
global stop_event
stop_event.clear()
# --- Initial Checks ---
if not cond_image_data or not cond_image_data.get('image'):
yield [], None, "Error: Reference Image not provided.", ""
return
cond_image = cond_image_data['image']
if not cond_image or not os.path.exists(cond_image):
yield [], None, "Error: Reference Image not found.", ""
return
os.makedirs(save_path, exist_ok=True)
all_generated_videos = []
for i in range(int(batch_size)):
if stop_event.is_set():
yield all_generated_videos, None, "Generation stopped by user.", ""
return
current_seed = seed
if seed == -1:
current_seed = random.randint(0, 2**32 - 1)
elif int(batch_size) > 1:
current_seed = seed + i
status_text = f"Processing Item {i+1}/{batch_size} (Seed: {current_seed})"
yield all_generated_videos.copy(), None, status_text, "Starting item..."
# --- Prepare command for a single generation ---
run_id = f"{int(time.time())}_{random.randint(1000, 9999)}"
unique_preview_suffix = f"multitalk_{run_id}"
save_file_prefix = os.path.join(save_path, f"multitalk_{run_id}_s{current_seed}")
num_persistent_backend = int(num_persistent * 1_000_000_000)
command = [
sys.executable,
"generate_multitalk_video.py",
"--ckpt_dir", str(ckpt_dir),
"--wav2vec_dir", str(wav2vec_dir),
"--t5_tokenizer_path", str(t5_tokenizer_path),
"--prompt", str(prompt),
"--n_prompt", str(negative_prompt),
"--cond_image", str(cond_image),
"--cond_audio_person1", str(audio_person1),
"--base_seed", str(current_seed),
"--save_file", save_file_prefix,
"--size", str(size),
"--mode", str(mode),
"--frame_num", str(frame_num),
"--motion_frame", str(motion_frame),
"--sample_steps", str(sample_steps),
"--sample_shift", str(sample_shift),
"--sample_text_guide_scale", str(text_guide_scale),
"--sample_audio_guide_scale", str(audio_guide_scale),
"--audio_type", str(audio_type),
"--num_persistent_param_in_dit", str(num_persistent_backend),
]
if audio_person2 and os.path.exists(audio_person2):
command.extend(["--cond_audio_person2", str(audio_person2)])
boxes = cond_image_data.get('boxes', [])
bbox1_str = None
bbox2_str = None
if boxes:
for box_info in boxes:
label = box_info.get('label', '').strip().lower()
# The coordinates are directly in box_info, not in a nested 'box' dictionary.
if all(k in box_info for k in ["xmin", "ymin", "xmax", "ymax"]):
coords = ",".join(map(str, [
box_info["xmin"], box_info["ymin"],
box_info["xmax"], box_info["ymax"]
]))
if label == 'person 1' and not bbox1_str:
bbox1_str = coords
elif label == 'person 2' and not bbox2_str:
bbox2_str = coords
if bbox1_str:
command.extend(["--bbox_person1", bbox1_str])
if bbox2_str:
command.extend(["--bbox_person2", bbox2_str])
if use_teacache:
command.append("--use_teacache")
command.extend(["--teacache_thresh", str(teacache_thresh)])
if use_apg:
command.append("--use_apg")
command.extend(["--apg_momentum", str(apg_momentum)])
command.extend(["--apg_norm_threshold", str(apg_norm_thresh)])
if use_full_video_preview:
command.append("--full_preview")
# The generation script now requires the suffix to be passed for the full preview
command.extend(["--preview_suffix", unique_preview_suffix])
# LoRA Handling
lora_weights_paths = []
lora_multipliers_values = []
lora_inputs = [
(lora1_str, lora1_mult), (lora2_str, lora2_mult),
(lora3_str, lora3_mult), (lora4_str, lora4_mult)
]
if lora_folder and os.path.exists(lora_folder):
for name, mult in lora_inputs:
if name and name != "None":
path = os.path.join(lora_folder, name)
if os.path.exists(path):
lora_weights_paths.append(path)
lora_multipliers_values.append(str(mult))
else:
print(f"Warning: LoRA file not found: {path}")
if lora_weights_paths:
command.extend(["--lora_weight"] + lora_weights_paths)
command.extend(["--lora_multiplier"] + lora_multipliers_values)
# --- Execute Subprocess ---
print(f"Running MultiTalk Command: {' '.join(command)}")
process = subprocess.Popen(
command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
text=True, encoding='utf-8', errors='replace', bufsize=1
)
current_preview_yield_path = None
last_preview_mtime = 0
preview_base_dir = os.path.join(os.path.dirname(save_file_prefix), "previews")
preview_mp4_gen_path = os.path.join(preview_base_dir, f"latent_preview_{unique_preview_suffix}.mp4")
current_video_file_for_item = None
progress_text_update = "Subprocess started..."
for line in iter(process.stdout.readline, ''):
if stop_event.is_set():
try: process.terminate(); process.wait(timeout=5)
except: process.kill(); process.wait()
yield all_generated_videos, None, "Generation stopped by user.", ""
return
line_strip = line.strip()
if not line_strip: continue
print(f"MULTITALK_SUBPROCESS: {line_strip}")
tqdm_match = re.search(r"(\d+)\s*%\|.*?\|\s*(\d+/\d+)\s*\[([^\]]+)\]", line_strip)
clip_progress_match = re.search(r"Generating clip (\d+/\d+)", line_strip)
saving_video_match = re.search(r'Saving video:.*', line_strip)
final_save_match = re.search(r'Saving generated video to (.*\.mp4)', line_strip)
if final_save_match:
found_path = final_save_match.group(1).strip()
if os.path.exists(found_path):
current_video_file_for_item = found_path
progress_text_update = f"Finalized: {os.path.basename(current_video_file_for_item or found_path)}"
status_text = f"Item {i+1}/{batch_size} (Seed: {current_seed}) - Saved"
elif saving_video_match:
progress_text_update = "Saving final video..."
elif clip_progress_match:
status_text = f"Item {i+1}/{batch_size} (Seed: {current_seed}) - Clip {clip_progress_match.group(1)}"
tqdm_match_on_clip_line = re.search(r"(\d+)\s*%\|.*?\|\s*(\d+/\d+)\s*\[([^\]]+)\]", line_strip)
if tqdm_match_on_clip_line:
percentage = tqdm_match_on_clip_line.group(1)
steps_iter = tqdm_match_on_clip_line.group(2)
time_details = tqdm_match_on_clip_line.group(3)
time_elapsed = "??"
time_remaining = "??"
time_split = time_details.split('<')
if len(time_split) > 1:
time_elapsed = time_split[0].strip()
remaining_part = time_split[1]
time_remaining = remaining_part.split(',')[0].strip()
else:
time_elapsed = time_details.split(',')[0].strip().replace('?','')
progress_text_update = f"Step {steps_iter} ({percentage}%) | Elapsed: {time_elapsed} | ETA: {time_remaining}"
else:
progress_text_update = "Starting new clip generation..."
elif tqdm_match:
percentage = tqdm_match.group(1)
steps_iter = tqdm_match.group(2)
time_details = tqdm_match.group(3) # e.g., "00:01<00:09, 1.05it/s" or "00:00<?, ?it/s"
time_elapsed = "??"
time_remaining = "??"
time_split = time_details.split('<')
if len(time_split) > 1:
time_elapsed = time_split[0].strip()
remaining_part = time_split[1]
time_remaining = remaining_part.split(',')[0].strip()
else:
time_elapsed = time_details.split(',')[0].strip().replace('?','')
if "Clip" not in status_text: # Update status if not already showing clip info
status_text = f"Item {i+1}/{batch_size} (Seed: {current_seed}) - Denoising"
progress_text_update = f"Step {steps_iter} ({percentage}%) | Elapsed: {time_elapsed} | ETA: {time_remaining}"
else:
progress_text_update = line_strip
if use_full_video_preview:
found_preview_path = None
if os.path.exists(preview_mp4_gen_path):
current_mtime = os.path.getmtime(preview_mp4_gen_path)
if current_mtime > last_preview_mtime:
current_preview_yield_path = preview_mp4_gen_path
last_preview_mtime = current_mtime
yield all_generated_videos.copy(), current_preview_yield_path, status_text, progress_text_update
process.stdout.close()
return_code = process.wait()
# Check for the video file again after process completion
final_video_path = save_file_prefix + ".mp4"
if os.path.exists(final_video_path):
current_video_file_for_item = final_video_path
# After subprocess finishes for one item
if return_code == 0 and current_video_file_for_item:
# --- START METADATA SAVING ---
params_for_meta = {
"model_type": "MultiTalk",
"prompt": prompt,
"negative_prompt": negative_prompt,
"cond_image": os.path.basename(cond_image) if cond_image else None,
"audio_person1": os.path.basename(audio_person1) if audio_person1 else None,
"audio_person2": os.path.basename(audio_person2) if audio_person2 else None,
"batch_size": batch_size,
"seed": current_seed,
"size": size,
"mode": mode,
"frame_num": frame_num,
"motion_frame": motion_frame,
"sample_steps": sample_steps,
"sample_shift": sample_shift,
"text_guide_scale": text_guide_scale,
"audio_guide_scale": audio_guide_scale,
"audio_type": audio_type,
"num_persistent_param_in_dit": num_persistent,
"use_teacache": use_teacache,
"teacache_thresh": teacache_thresh,
"use_apg": use_apg,
"apg_momentum": apg_momentum,
"apg_norm_thresh": apg_norm_thresh,
"ckpt_dir": ckpt_dir,
"wav2vec_dir": wav2vec_dir,
"t5_tokenizer_path": t5_tokenizer_path,
"save_path": save_path,
"lora_folder": lora_folder,
"lora_weights": [lora1_str, lora2_str, lora3_str, lora4_str],
"lora_multipliers": [lora1_mult, lora2_mult, lora3_mult, lora4_mult],
}
try:
add_metadata_to_video(current_video_file_for_item, params_for_meta)
print(f"Added metadata to {current_video_file_for_item}")
except Exception as meta_err:
print(f"Warning: Failed to add metadata to {current_video_file_for_item}: {meta_err}")
# --- END METADATA SAVING ---
all_generated_videos.append((current_video_file_for_item, f"MultiTalk - Seed: {current_seed}"))
status_text = f"Item {i+1}/{batch_size} (Seed: {current_seed}) - Completed"
progress_text_update = f"Saved: {os.path.basename(current_video_file_for_item)}"
else:
status_text = f"Item {i+1}/{batch_size} (Seed: {current_seed}) - Failed (Code: {return_code})"
progress_text_update = "Subprocess failed. Check console."
yield all_generated_videos.copy(), None, status_text, progress_text_update
clear_cuda_cache()
time.sleep(0.2)
yield all_generated_videos, None, "MultiTalk Batch complete.", ""
def save_framepack_defaults(*values):
os.makedirs(UI_CONFIGS_DIR, exist_ok=True)
settings_to_save = {}
for i, key in enumerate(framepack_ui_default_keys):
settings_to_save[key] = values[i]
try:
with open(FRAMEPROK_DEFAULTS_FILE, 'w') as f:
json.dump(settings_to_save, f, indent=2)
return "FramePack defaults saved successfully."
except Exception as e:
return f"Error saving FramePack defaults: {e}"
def load_framepack_defaults(request: gr.Request): # request can be used to see if it's initial load
if not os.path.exists(FRAMEPROK_DEFAULTS_FILE):
if request: # If it's not an initial load (i.e., button click)
return [gr.update()] * len(framepack_ui_default_keys) + ["No defaults file found."]
else: # Initial load, let Gradio use its defined values
return [gr.update()] * len(framepack_ui_default_keys) + [""]
try:
with open(FRAMEPROK_DEFAULTS_FILE, 'r') as f:
loaded_settings = json.load(f)
except Exception as e:
return [gr.update()] * len(framepack_ui_default_keys) + [f"Error loading defaults: {e}"]
updates = []
for i, key in enumerate(framepack_ui_default_keys):
component = framepack_ui_default_components_ORDERED_LIST[i]
default_value_from_component = None
# Try to get the 'value' attribute from the component definition
if hasattr(component, 'value'):
default_value_from_component = component.value
elif isinstance(component, gr.State): # gr.State has value in its init
pass # For gr.State, default is often None or handled by its initial value
# Use loaded setting if available, otherwise the component's initial value
value_to_set = loaded_settings.get(key, default_value_from_component)
# Special handling for LoRA dropdowns to ensure 'None' is a valid choice
if "lora_weight" in key: # This covers framepack_lora_weight_1 to framepack_lora_weight_4
lora_choices = get_lora_options(loaded_settings.get("framepack_lora_folder", "lora"))
if value_to_set not in lora_choices:
value_to_set = "None" # Default to "None" if saved value is invalid
updates.append(gr.update(choices=lora_choices, value=value_to_set))
else:
updates.append(gr.update(value=value_to_set))
return updates + ["FramePack defaults loaded successfully."]
def refresh_lora_dropdowns_simple(lora_folder: str) -> List[gr.update]:
"""Refreshes LoRA choices, always defaulting the selection to 'None'."""
new_choices = get_lora_options(lora_folder)
results = []
print(f"Refreshing LoRA dropdowns. Found choices: {new_choices}") # Debug print
for i in range(4): # Update all 4 slots
results.extend([
gr.update(choices=new_choices, value="None"), # Always reset value to None
gr.update(value=1.0) # Reset multiplier
])
return results
def _extract_path_from_gallery_item(item: Any) -> Optional[str]:
"""
Helper to extract a string file path from various Gradio component item formats.
Verifies that the extracted path exists.
"""
path_to_check = None
if isinstance(item, str):
path_to_check = item
elif isinstance(item, Path):
path_to_check = str(item)
elif isinstance(item, tuple) and len(item) > 0:
path_obj_in_tuple = item[0]
if isinstance(path_obj_in_tuple, str):
path_to_check = path_obj_in_tuple
elif isinstance(path_obj_in_tuple, Path):
path_to_check = str(path_obj_in_tuple)
elif hasattr(item, 'name'):
name_attr = getattr(item, 'name', None)
if isinstance(name_attr, str):
path_to_check = name_attr
elif isinstance(name_attr, Path):
path_to_check = str(name_attr)
if path_to_check and os.path.exists(path_to_check):
return os.path.abspath(path_to_check)
else:
print(f"DEBUG _extract_path_from_gallery_item: Could not get valid path from {repr(item)} or path '{path_to_check}' does not exist.")
return None
def combine_image_sets(current_gallery_value: Optional[List[Any]],
newly_uploaded_paths_from_button: Optional[List[str]]) -> List[str]:
all_valid_paths = []
if current_gallery_value:
for item in current_gallery_value:
path = _extract_path_from_gallery_item(item)
if path:
all_valid_paths.append(path)
if newly_uploaded_paths_from_button:
for path_str in newly_uploaded_paths_from_button:
if isinstance(path_str, str) and os.path.exists(path_str):
all_valid_paths.append(os.path.abspath(path_str))
unique_final_paths = []
seen_paths = set()
for path in all_valid_paths:
if path not in seen_paths:
unique_final_paths.append(path)
seen_paths.add(path)
return unique_final_paths
def phantom_generate_video(
prompt_text: str,
negative_prompt_text: str,
input_images_list: List[str], # List of file paths
width_val: int,
height_val: int,
video_length_frames: int,
fps_val: int,
infer_steps_val: int,
flow_shift_val: float,
# S2V specific guidance scales for Phantom
guide_scale_img_val: float,
guide_scale_text_val: float,
# Main CFG scale (might not be used by S2V if its CFG is hardcoded or different)
cfg_scale_main_val: float,
seed_val: int,
task_str: str, # Should be an S2V task
dit_folder_str: str, # Folder for DiT
phantom_dit_model_path: str, # Specific Phantom DiT path (--phantom_ckpt in script)
vae_path_str: str,
t5_path_str: str,
# clip_path_str: str, # CLIP not directly used for S2V image features
save_path_str: str,
output_type_str: str,
sample_solver_str: str,
attn_mode_str: str,
block_swap_val: int,
fp8_val: bool,
fp8_scaled_val: bool,
fp8_t5_val: bool,
lora_folder_str: str,
slg_layers_str: str,
slg_start_val: float,
slg_end_val: float,
lora1_str: str, lora2_str: str, lora3_str: str, lora4_str: str,
lora1_mult: float, lora2_mult: float, lora3_mult: float, lora4_mult: float,
enable_cfg_skip_val: bool,
cfg_skip_mode_str: str,
cfg_apply_ratio_val: float,
enable_preview_val: bool,
preview_steps_val: int
) -> Generator[Tuple[List[Tuple[str, str]], List[str], str, str], None, None]:
global stop_event
stop_event.clear()
videos_gallery = []
previews_gallery = []
status_text_update = "Preparing Phantom generation..."
progress_text_update = ""
yield videos_gallery, previews_gallery, status_text_update, progress_text_update
if not input_images_list:
yield [], [], "Error: No input images provided for Phantom.", "Please select reference images."
return
ref_images_arg_str = ",".join(input_images_list) # Join paths with comma for --ref_images
current_seed = seed_val
if seed_val == -1:
current_seed = random.randint(0, 2**32 - 1)
# Construct path to the Phantom DiT model
# The `phantom_dit_model_path` is already the full path or filename from the dropdown
# If it's just a filename, `dit_folder_str` is used to prefix it.
actual_phantom_dit_path = os.path.join(dit_folder_str, phantom_dit_model_path) \
if not os.path.isabs(phantom_dit_model_path) and dit_folder_str \
else phantom_dit_model_path
if not os.path.exists(actual_phantom_dit_path):
yield [], [], f"Error: Phantom DiT model not found at {actual_phantom_dit_path}", ""
return
# Prepare environment and command
env = os.environ.copy()
env["PATH"] = os.path.dirname(sys.executable) + os.pathsep + env.get("PATH", "")
env["PYTHONIOENCODING"] = "utf-8"
clear_cuda_cache()
run_id = f"{int(time.time())}_{random.randint(1000, 9999)}"
unique_preview_suffix = f"phantom_{run_id}"
command = [
sys.executable,
"phantom_generate_video.py", # We're using the multi-purpose script
"--task", str(task_str), # e.g., "s2v-14B"
"--prompt", str(prompt_text),
"--video_size", str(height_val), str(width_val),
"--video_length", str(video_length_frames),
"--fps", str(fps_val),
"--infer_steps", str(infer_steps_val),
"--save_path", str(save_path_str),
"--seed", str(current_seed),
"--flow_shift", str(flow_shift_val),
# S2V uses specific guidance scales
"--guide_scale_img", str(guide_scale_img_val),
"--guide_scale_text", str(guide_scale_text_val),
# Pass the main CFG scale (script might use it or S2V logic might override)
"--guidance_scale", str(cfg_scale_main_val),
"--output_type", str(output_type_str),
"--sample_solver", str(sample_solver_str),
"--attn_mode", str(attn_mode_str),
"--blocks_to_swap", str(block_swap_val),
# Model paths
"--phantom_ckpt", str(actual_phantom_dit_path), # Pass Phantom DiT here
"--vae", str(vae_path_str),
"--t5", str(t5_path_str),
# "--clip", str(clip_path_str), # CLIP not typically used for S2V image features
# Reference images for S2V
"--ref_images", ref_images_arg_str,
]
if negative_prompt_text:
command.extend(["--negative_prompt", str(negative_prompt_text)])
if fp8_val: command.append("--fp8")
if fp8_scaled_val: command.append("--fp8_scaled")
if fp8_t5_val: command.append("--fp8_t5")
if slg_layers_str and str(slg_layers_str).strip() and str(slg_layers_str).lower() != "none":
command.extend(["--slg_layers", str(slg_layers_str).strip()])
if slg_start_val is not None: command.extend(["--slg_start", str(slg_start_val)])
if slg_end_val is not None: command.extend(["--slg_end", str(slg_end_val)])
# LoRAs
valid_loras_paths = []
valid_loras_mults_str = []
lora_inputs = [
(lora1_str, lora1_mult), (lora2_str, lora2_mult),
(lora3_str, lora3_mult), (lora4_str, lora4_mult)
]
if lora_folder_str and os.path.exists(lora_folder_str):
for name, mult in lora_inputs:
if name and name != "None":
path = os.path.join(lora_folder_str, name)
if os.path.exists(path):
valid_loras_paths.append(path)
valid_loras_mults_str.append(str(mult))
else:
print(f"Warning: LoRA file not found: {path}")
if valid_loras_paths:
command.extend(["--lora_weight"] + valid_loras_paths)
command.extend(["--lora_multiplier"] + valid_loras_mults_str)
if enable_cfg_skip_val and cfg_skip_mode_str != "none":
command.extend(["--cfg_skip_mode", str(cfg_skip_mode_str)])
command.extend(["--cfg_apply_ratio", str(cfg_apply_ratio_val)])
if enable_preview_val and preview_steps_val > 0:
command.extend(["--preview", str(preview_steps_val)])
command.extend(["--preview_suffix", unique_preview_suffix])
command_str_list = [str(item) for item in command]
print(f"Running Phantom Command: {' '.join(command_str_list)}")
process = subprocess.Popen(
command_str_list, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
env=env, text=True, encoding='utf-8', errors='replace', bufsize=1
)
# --- Preview file paths based on unique_preview_suffix ---
preview_base_dir = os.path.join(save_path_str, "previews") # Script saves previews here
preview_mp4_gen_path = os.path.join(preview_base_dir, f"latent_preview_{unique_preview_suffix}.mp4")
preview_png_glob_pattern = os.path.join(preview_base_dir, f"latent_preview_step_*_{unique_preview_suffix}.png")
last_preview_mtime = 0
current_preview_yield_list = [] # Store paths of previews to yield
current_video_file_for_item = None
status_text_update = f"Processing Phantom (Seed: {current_seed})"
for line in iter(process.stdout.readline, ''):
if stop_event.is_set():
try: process.terminate(); process.wait(timeout=5)
except: process.kill(); process.wait()
yield videos_gallery, [], "Generation stopped by user.", ""
return
line_strip = line.strip()
if not line_strip: continue
print(f"PHANTOM_SUBPROCESS: {line_strip}")
progress_text_update = line_strip
tqdm_match = re.search(r'(\d+)\%\|.+\| (\d+/\d+) \[(\d{2}:\d{2})<(\d{2}:\d{2})', line_strip)
video_saved_match = re.search(r"Video saved to:\s*(.*\.mp4)", line_strip) # Common save message
if tqdm_match:
percentage = tqdm_match.group(1)
steps_iter = tqdm_match.group(2)
time_elapsed = tqdm_match.group(3)
time_remaining = tqdm_match.group(4)
progress_text_update = f"Step {steps_iter} ({percentage}%) | ETA: {time_remaining}"
status_text_update = f"Phantom Denoising (Seed: {current_seed})"
elif video_saved_match:
found_path = video_saved_match.group(1).strip()
if os.path.exists(found_path):
current_video_file_for_item = found_path
progress_text_update = f"Finalizing: {os.path.basename(found_path)}"
status_text_update = f"Phantom Saved (Seed: {current_seed})"
else:
print(f"Warning: Video path from log not found: {found_path}")
# Preview handling (similar to WanX-i2v)
preview_updated_this_line = False
if enable_preview_val:
# Check MP4 (full video preview from script)
if os.path.exists(preview_mp4_gen_path):
current_mtime_mp4 = os.path.getmtime(preview_mp4_gen_path)
if current_mtime_mp4 > last_preview_mtime:
current_preview_yield_list = [preview_mp4_gen_path] # Replace list with MP4
last_preview_mtime = current_mtime_mp4
preview_updated_this_line = True
print(f"DEBUG Phantom: MP4 Preview updated - {preview_mp4_gen_path}")
# Check PNGs (step previews) - only if MP4 wasn't updated this line
if not preview_updated_this_line:
# This part is tricky because many PNGs can be generated.
# We want to show the *latest* set of step previews.
# A simpler approach for Gradio Gallery is to show the MP4 if available,
# or a single latest PNG. Let's stick to the MP4 from wan_generate_video.py for now
# as it's more straightforward. If the script only outputs PNGs, this needs rework.
# Assuming `--preview` in wan_generate_video.py generates an MP4.
# If it generates PNGs, we might need to glob and sort them.
# For now, `current_preview_yield_list` is primarily for the MP4.
pass
yield videos_gallery, current_preview_yield_list, status_text_update, progress_text_update
process.stdout.close()
return_code = process.wait()
clear_cuda_cache()
if return_code == 0 and current_video_file_for_item and os.path.exists(current_video_file_for_item):
videos_gallery.append((current_video_file_for_item, f"Phantom - Seed: {current_seed}"))
status_text_update = f"Phantom (Seed: {current_seed}) - Completed"
progress_text_update = f"Saved: {os.path.basename(current_video_file_for_item)}"
# Metadata parameters
params_for_meta = {
"prompt": prompt_text, "negative_prompt": negative_prompt_text,
"ref_images": [os.path.basename(p) for p in input_images_list],
"width": width_val, "height": height_val, "video_length": video_length_frames, "fps": fps_val,
"infer_steps": infer_steps_val, "flow_shift": flow_shift_val,
"guide_scale_img": guide_scale_img_val, "guide_scale_text": guide_scale_text_val,
"cfg_scale_main": cfg_scale_main_val,
"seed": current_seed, "task": task_str, "dit_path": actual_phantom_dit_path,
"vae_path": vae_path_str, "t5_path": t5_path_str,
"save_path": save_path_str, "output_type": output_type_str, "sample_solver": sample_solver_str,
"attn_mode": attn_mode_str, "block_swap": block_swap_val,
"fp8": fp8_val, "fp8_scaled": fp8_scaled_val, "fp8_t5": fp8_t5_val,
"lora_weights": [lora1_str, lora2_str, lora3_str, lora4_str],
"lora_multipliers": [lora1_mult, lora2_mult, lora3_mult, lora4_mult],
"slg_layers": slg_layers_str, "slg_start": slg_start_val, "slg_end": slg_end_val,
}
try:
add_metadata_to_video(current_video_file_for_item, params_for_meta)
except Exception as meta_err:
print(f"Warning: Failed to add metadata to {current_video_file_for_item}: {meta_err}")
yield videos_gallery.copy(), [], status_text_update, progress_text_update # Clear previews on success
else:
status_text_update = f"Phantom (Seed: {current_seed}) - Failed (Code: {return_code})"
progress_text_update = "Subprocess failed. Check console."
yield videos_gallery.copy(), [], status_text_update, progress_text_update
def phantom_batch_handler(
prompt_text: str,
negative_prompt_text: str,
input_images_list_files: List[Any], # This is the value from phantom_input_images gallery
width_val: int,
height_val: int,
video_length_frames: int,
fps_val: int,
infer_steps_val: int,
flow_shift_val: float,
guide_scale_img_val: float,
guide_scale_text_val: float,
cfg_scale_main_val: float,
seed_val: int,
batch_size_val: int,
task_str: str,
dit_folder_str: str,
phantom_dit_model_path_str: str,
vae_path_str: str,
t5_path_str: str,
save_path_str: str,
output_type_str: str,
sample_solver_str: str,
attn_mode_str: str,
block_swap_val: int,
fp8_val: bool,
fp8_scaled_val: bool,
fp8_t5_val: bool,
lora_folder_str: str,
slg_layers_str: str,
slg_start_val: float,
slg_end_val: float,
enable_cfg_skip_val: bool,
cfg_skip_mode_str: str,
cfg_apply_ratio_val: float,
enable_preview_val: bool,
preview_steps_val: int,
lora1_str: str, lora2_str: str, lora3_str: str, lora4_str: str,
lora1_mult: float, lora2_mult: float, lora3_mult: float, lora4_mult: float
):
global stop_event
stop_event.clear()
actual_input_image_paths = []
if input_images_list_files:
# print(f"DEBUG phantom_batch_handler - Received input_images_list_files: {input_images_list_files}")
for item_data in input_images_list_files:
# Use the same robust extraction logic here
path_str = _extract_path_from_gallery_item(item_data)
if path_str:
actual_input_image_paths.append(path_str)
else:
# This is where your warning was originating
print(f"Warning: Could not resolve path for file data (in phantom_batch_handler): {item_data}")
# print(f"DEBUG phantom_batch_handler - Extracted actual_input_image_paths: {actual_input_image_paths}")
if not actual_input_image_paths:
yield [], [], "Error: No valid input image paths provided for Phantom.", "Please ensure selected reference images exist on the server."
return
all_generated_videos = []
all_previews = []
status_text = "Preparing Phantom batch..."
progress_text = ""
yield all_generated_videos, all_previews, status_text, progress_text
for i in range(int(batch_size_val)):
if stop_event.is_set():
yield all_generated_videos, all_previews, "Phantom Batch stopped by user.", ""
return
current_seed_for_item = seed_val
if seed_val == -1:
current_seed_for_item = random.randint(0, 2**32 - 1)
elif int(batch_size_val) > 1:
current_seed_for_item = seed_val + i
status_text = f"Processing Phantom Item {i+1}/{batch_size_val} (Seed: {current_seed_for_item})"
yield all_generated_videos.copy(), [], status_text, "Starting item..."
item_videos = []
item_previews_temp = []
last_status_for_item = status_text
last_progress_for_item = "Generating..."
single_gen = phantom_generate_video(
prompt_text, negative_prompt_text, actual_input_image_paths, # Use the processed list
width_val, height_val, video_length_frames, fps_val, infer_steps_val,
flow_shift_val, guide_scale_img_val, guide_scale_text_val, cfg_scale_main_val,
current_seed_for_item, task_str, dit_folder_str, phantom_dit_model_path_str,
vae_path_str, t5_path_str, save_path_str, output_type_str,
sample_solver_str, attn_mode_str, block_swap_val,
fp8_val, fp8_scaled_val, fp8_t5_val, lora_folder_str,
slg_layers_str, slg_start_val, slg_end_val,
lora1_str, lora2_str, lora3_str, lora4_str,
lora1_mult, lora2_mult, lora3_mult, lora4_mult,
enable_cfg_skip_val, cfg_skip_mode_str, cfg_apply_ratio_val,
enable_preview_val, preview_steps_val
)
for videos_update, previews_update, status_upd, progress_upd in single_gen:
item_videos = videos_update
item_previews_temp = previews_update
last_status_for_item = f"Item {i+1}/{batch_size_val}: {status_upd}"
last_progress_for_item = progress_upd
yield all_generated_videos + ([item_videos[-1]] if item_videos and item_videos[-1] not in all_generated_videos else []), \
item_previews_temp, last_status_for_item, last_progress_for_item
if item_videos and item_videos[-1] not in all_generated_videos:
all_generated_videos.append(item_videos[-1])
clear_cuda_cache()
time.sleep(0.2)
yield all_generated_videos, [], "Phantom Batch complete.", ""
def process_framepack_extension_video(
input_video: str,
prompt: str,
negative_prompt: str,
seed: int,
batch_count: int,
fpe_use_normal_framepack: bool,
fpe_end_frame: Optional[str],
fpe_end_frame_weight: float,
resolution_max_dim: int,
total_second_length: float,
latent_window_size: int,
steps: int,
cfg_scale: float, # Maps to --cfg
distilled_guidance_scale: float, # Maps to --gs
# rs_scale: float, # --rs, usually 0.0, can be fixed or advanced option
gpu_memory_preservation: float,
use_teacache: bool,
no_resize: bool,
mp4_crf: int,
num_clean_frames: int,
vae_batch_size: int,
save_path: str, # Maps to --output_dir
# Model Paths
fpe_transformer_path: str, # DiT
fpe_vae_path: str,
fpe_text_encoder_path: str, # TE1
fpe_text_encoder_2_path: str, # TE2
fpe_image_encoder_path: str,
# Advanced performance
fpe_attn_mode: str,
fpe_fp8_llm: bool,
fpe_vae_chunk_size: Optional[int],
fpe_vae_spatial_tile_sample_min_size: Optional[int],
# LoRAs
fpe_lora_folder: str,
fpe_lora_weight_1: str, fpe_lora_mult_1: float,
fpe_lora_weight_2: str, fpe_lora_mult_2: float,
fpe_lora_weight_3: str, fpe_lora_mult_3: float,
fpe_lora_weight_4: str, fpe_lora_mult_4: float,
# Preview
fpe_enable_preview: bool,
fpe_preview_interval: int, # This arg is not used by f1_video_cli_local.py
fpe_extension_only: bool,
fpe_start_guidance_image: Optional[str],
fpe_start_guidance_image_clip_weight: float,
fpe_use_guidance_image_as_first_latent: bool,
*args: Any # For future expansion or unmapped params, not strictly needed here
) -> Generator[Tuple[List[Tuple[str, str]], Optional[str], str, str], None, None]:
global stop_event, skip_event
stop_event.clear()
skip_event.clear() # Assuming skip_event might be used for batch items
if not input_video or not os.path.exists(input_video):
yield [], None, "Error: Input video for extension not found.", ""
return
if not save_path or not save_path.strip():
save_path = "outputs/framepack_extensions" # Default save path for extensions
os.makedirs(save_path, exist_ok=True)
# Prepare LoRA arguments
lora_weights_paths = []
lora_multipliers_values = []
lora_params_ui = [
(fpe_lora_weight_1, fpe_lora_mult_1), (fpe_lora_weight_2, fpe_lora_mult_2),
(fpe_lora_weight_3, fpe_lora_mult_3), (fpe_lora_weight_4, fpe_lora_mult_4)
]
if fpe_lora_folder and os.path.exists(fpe_lora_folder):
for weight_name, mult_val in lora_params_ui:
if weight_name and weight_name != "None":
lora_path = os.path.join(fpe_lora_folder, weight_name)
if os.path.exists(lora_path):
lora_weights_paths.append(lora_path)
lora_multipliers_values.append(str(mult_val))
else:
print(f"Warning: LoRA file not found: {lora_path}")
all_generated_videos = []
script_to_use = "f_video_end_cli_local.py" if fpe_use_normal_framepack else "f1_video_cli_local.py"
model_type_str = "Normal FramePack" if fpe_use_normal_framepack else "FramePack F1"
print(f"Using {model_type_str} model for extension via script: {script_to_use}")
for i in range(batch_count):
if stop_event.is_set():
yield all_generated_videos, None, "Generation stopped by user.", ""
return
skip_event.clear()
current_seed_val = seed
if seed == -1:
current_seed_val = random.randint(0, 2**32 - 1)
elif batch_count > 1:
current_seed_val = seed + i
# This run_id is not directly used for preview file naming by f1_video_cli_local.py
# as it constructs its own job_id based filenames for section previews.
# run_id = f"{int(time.time())}_{random.randint(1000, 9999)}_ext_s{current_seed_val}"
current_preview_yield_path = None
last_preview_section_processed = -1
status_text = f"Processing Extension {i + 1}/{batch_count} (Seed: {current_seed_val})"
progress_text = "Preparing extension subprocess..."
yield all_generated_videos, current_preview_yield_path, status_text, progress_text
command = [
sys.executable, script_to_use,
"--input_video", str(input_video),
"--prompt", str(prompt),
"--n_prompt", str(negative_prompt),
"--seed", str(current_seed_val),
"--resolution_max_dim", str(resolution_max_dim),
"--total_second_length", str(total_second_length), # Script uses this for *additional* length
"--latent_window_size", str(latent_window_size),
"--steps", str(steps),
"--cfg", str(cfg_scale),
"--gs", str(distilled_guidance_scale),
"--rs", "0.0",
"--gpu_memory_preservation", str(gpu_memory_preservation),
"--mp4_crf", str(mp4_crf),
"--num_clean_frames", str(num_clean_frames),
"--vae_batch_size", str(vae_batch_size),
"--output_dir", str(save_path),
"--dit", str(fpe_transformer_path), "--vae", str(fpe_vae_path),
"--text_encoder1", str(fpe_text_encoder_path), "--text_encoder2", str(fpe_text_encoder_2_path),
"--image_encoder", str(fpe_image_encoder_path),
"--attn_mode", str(fpe_attn_mode),
]
if use_teacache: command.append("--use_teacache")
if no_resize: command.append("--no_resize")
if fpe_fp8_llm: command.append("--fp8_llm") # Though F1 script might not use this
if fpe_vae_chunk_size is not None and fpe_vae_chunk_size > 0:
command.extend(["--vae_chunk_size", str(fpe_vae_chunk_size)])
if fpe_vae_spatial_tile_sample_min_size is not None and fpe_vae_spatial_tile_sample_min_size > 0:
command.extend(["--vae_spatial_tile_sample_min_size", str(fpe_vae_spatial_tile_sample_min_size)])
if lora_weights_paths:
command.extend(["--lora_weight"] + lora_weights_paths)
command.extend(["--lora_multiplier"] + lora_multipliers_values)
if fpe_extension_only:
command.append("--extension_only")
# Script-specific arguments
if fpe_use_normal_framepack:
if fpe_fp8_llm: # Normal FP script uses this
command.append("--fp8_llm")
if fpe_end_frame and os.path.exists(fpe_end_frame):
command.extend(["--end_frame", str(fpe_end_frame)])
command.extend(["--end_frame_weight", str(fpe_end_frame_weight)])
else:
if fpe_start_guidance_image and os.path.exists(fpe_start_guidance_image):
command.extend(["--start_guidance_image", str(fpe_start_guidance_image)])
command.extend(["--start_guidance_image_clip_weight", str(fpe_start_guidance_image_clip_weight)])
if fpe_use_guidance_image_as_first_latent:
command.append("--use_guidance_image_as_first_latent")
env = os.environ.copy()