-
Notifications
You must be signed in to change notification settings - Fork 244
Expand file tree
/
Copy pathgradio_demo.py
More file actions
executable file
·3604 lines (3138 loc) · 169 KB
/
Copy pathgradio_demo.py
File metadata and controls
executable file
·3604 lines (3138 loc) · 169 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 argparse
import gc
import glob
import importlib.util
import json
import logging
import os
import warnings
# Suppress network retry warnings during Hugging Face downloads (normal retry behavior)
warnings.filterwarnings("ignore", category=UserWarning, module="huggingface_hub")
warnings.filterwarnings("ignore", category=UserWarning, module="huggingface_hub.utils")
# Suppress reqwest retry warnings (JSON log outputs, not real errors)
logging.getLogger("httpx").setLevel(logging.ERROR)
logging.getLogger("httpcore").setLevel(logging.ERROR)
logging.getLogger("urllib3").setLevel(logging.ERROR)
os.environ["PROFILING_DEBUG_LEVEL"] = "2"
os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "expandable_segments:True"
os.environ["DTYPE"] = "BF16"
import random # noqa E402
from datetime import datetime # noqa E402
import gradio as gr # noqa E402
import psutil # noqa E402
import torch # noqa E402
from loguru import logger # noqa E402
from lightx2v.utils.input_info import set_input_info # noqa E402
from lightx2v.utils.set_config import get_default_config # noqa E402
try:
from flashinfer.rope import apply_rope_with_cos_sin_cache_inplace # noqa E402
except ImportError:
apply_rope_with_cos_sin_cache_inplace = None # noqa E402
from huggingface_hub import HfApi, hf_hub_download, list_repo_files # noqa E402
from huggingface_hub import snapshot_download as hf_snapshot_download # noqa E402
HF_AVAILABLE = True
from modelscope.hub.api import HubApi # noqa E402
from modelscope.hub.snapshot_download import snapshot_download as ms_snapshot_download # noqa E402
MS_AVAILABLE = True
logger.add(
"inference_logs.log",
rotation="100 MB",
encoding="utf-8",
enqueue=True,
backtrace=True,
diagnose=True,
)
MAX_NUMPY_SEED = 2**32 - 1
MODEL_CONFIG = {
"Wan_14b": {
"_class_name": "WanModel",
"_diffusers_version": "0.33.0",
"dim": 5120,
"eps": 1e-06,
"ffn_dim": 13824,
"freq_dim": 256,
"in_dim": 36,
"num_heads": 40,
"num_layers": 40,
"out_dim": 16,
"text_len": 512,
},
"Qwen_Image_Edit_2511": {
"_class_name": "QwenImageTransformer2DModel",
"_diffusers_version": "0.36.0.dev0",
"attention_head_dim": 128,
"axes_dims_rope": [16, 56, 56],
"guidance_embeds": False,
"in_channels": 64,
"joint_attention_dim": 3584,
"num_attention_heads": 24,
"num_layers": 60,
"out_channels": 16,
"patch_size": 2,
"zero_cond_t": True,
},
}
# Model list cache (avoid fetching from HF every time)
HF_MODELS_CACHE = {
"lightx2v/wan2.1-Distill-Models": [],
"lightx2v/wan2.1-Official-Models": [],
"lightx2v/wan2.2-Distill-Models": [],
"lightx2v/wan2.2-Official-Models": [],
"lightx2v/Encoders": [],
"lightx2v/Autoencoders": [],
"lightx2v/Qwen-Image-Edit-2511-Lightning": [],
"Qwen/Qwen-Image-Edit-2511": [],
}
def scan_model_path_contents(model_path):
"""Scan model_path directory, return available files and subdirectories"""
if not model_path or not os.path.exists(model_path):
return {"dirs": [], "files": [], "safetensors_dirs": [], "pth_files": []}
dirs = []
files = []
safetensors_dirs = []
pth_files = []
for item in os.listdir(model_path):
item_path = os.path.join(model_path, item)
if os.path.isdir(item_path):
dirs.append(item)
if glob.glob(os.path.join(item_path, "*.safetensors")):
safetensors_dirs.append(item)
elif os.path.isfile(item_path):
files.append(item)
if item.endswith(".pth"):
pth_files.append(item)
return {
"dirs": sorted(dirs),
"files": sorted(files),
"safetensors_dirs": sorted(safetensors_dirs),
"pth_files": sorted(pth_files),
}
def load_hf_models_cache():
"""Load model list from Hugging Face and cache, if HF times out or fails, try ModelScope"""
import concurrent.futures
def process_files(files, repo_id=None):
"""Process file list, extract model names"""
model_names = []
seen_dirs = set()
# For Qwen/Qwen-Image-Edit-2511 repository, keep vae and scheduler directories
is_qwen_image_repo = repo_id == "Qwen/Qwen-Image-Edit-2511"
for file in files:
# Exclude files containing comfyui
if "comfyui" in file.lower():
continue
# If it's a top-level file (no path separator)
if "/" not in file:
# Only keep safetensors files
if file.endswith(".safetensors"):
model_names.append(file)
else:
# Extract top-level directory name (supports _split directories)
top_dir = file.split("/")[0]
if top_dir not in seen_dirs:
seen_dirs.add(top_dir)
# For Qwen repository, keep vae and scheduler directories
if is_qwen_image_repo and top_dir.lower() in ["vae", "scheduler"]:
model_names.append(top_dir)
# Support safetensors file directories and _split block storage directories
elif "_split" in top_dir or any(f.startswith(f"{top_dir}/") and f.endswith(".safetensors") for f in files):
model_names.append(top_dir)
return sorted(set(model_names))
# Timeout (seconds)
HF_TIMEOUT = 30
for repo_id in HF_MODELS_CACHE.keys():
files = None
source = None
# First try to get from ModelScope
try:
if MS_AVAILABLE:
logger.info(f"Loading models from ModelScope {repo_id}...")
api = HubApi()
# ModelScope API get file list
model_files = api.get_model_files(model_id=repo_id, recursive=True)
# Extract file paths
files = [file["Path"] for file in model_files if file.get("Type") == "blob"]
source = "ModelScope"
logger.info(f"Successfully loaded models from ModelScope {repo_id}")
except: # noqa E722
# If ModelScope fails, try to get from Hugging Face (with timeout)
if files is None and HF_AVAILABLE:
logger.info(f"Loading models from Hugging Face {repo_id}...")
api = HfApi()
# Use thread pool executor with timeout
with concurrent.futures.ThreadPoolExecutor() as executor:
future = executor.submit(list_repo_files, repo_id=repo_id, repo_type="model")
files = future.result(timeout=HF_TIMEOUT)
source = "Hugging Face"
# Process file list
if files:
model_names = process_files(files, repo_id)
HF_MODELS_CACHE[repo_id] = model_names
logger.info(f"Loaded {len(HF_MODELS_CACHE[repo_id])} models from {source} {repo_id}")
else:
logger.warning(f"No files retrieved from {repo_id}, setting empty cache")
HF_MODELS_CACHE[repo_id] = []
def get_hf_models(repo_id, prefix_filter=None, keyword_filter=None):
"""Get models from cached model list (no longer fetching from HF in real-time)"""
if repo_id not in HF_MODELS_CACHE:
return []
models = HF_MODELS_CACHE[repo_id]
if prefix_filter:
models = [m for m in models if m.lower().startswith(prefix_filter.lower())]
if keyword_filter:
models = [m for m in models if keyword_filter.lower() in m.lower()]
return models
def check_model_exists(model_path, model_name):
"""Check if model is already downloaded"""
if not model_path or not os.path.exists(model_path):
return False
model_path_full = os.path.join(model_path, model_name)
# Check if exists (file or directory)
if os.path.exists(model_path_full):
return True
# Additional check: if it's a safetensors file, also check for same-name directory (_split directory)
if model_name.endswith(".safetensors"):
# Check for same-name directory (may be stored in chunks)
base_name = model_name.replace(".safetensors", "")
split_dir = os.path.join(model_path, base_name + "_split")
if os.path.exists(split_dir):
return True
return False
def format_model_choice(model_name, model_path, status_emoji=None):
"""Format model option, add download status indicator"""
if not model_name:
return ""
# If status emoji is provided, use it directly
if status_emoji is not None:
return f"{status_emoji} {model_name}"
# Otherwise check if it exists locally
exists = check_model_exists(model_path, model_name)
emoji = "✅" if exists else "❌"
return f"{emoji} {model_name}"
def extract_model_name(formatted_name):
"""Extract original model name from formatted option name"""
if not formatted_name:
return ""
# Remove leading emoji and space
if formatted_name.startswith("✅ ") or formatted_name.startswith("❌ "):
return formatted_name[2:].strip()
return formatted_name.strip()
def sort_model_choices(models):
"""Sort model list based on device capability and model type
Sort rules:
- If device supports fp8: fp8+split > int8+split > fp8 > int8 > others
- If device doesn't support fp8: int8+split > int8 > others
"""
fp8_supported = is_fp8_supported_gpu()
def get_priority(name):
name_lower = name.lower()
if fp8_supported:
# fp8 device: fp8+split > int8+split > fp8 > int8 > others
if "fp8" in name_lower and "_split" in name_lower:
return 0 # Highest priority
elif "int8" in name_lower and "_split" in name_lower:
return 1
elif "fp8" in name_lower:
return 2
elif "int8" in name_lower:
return 3
else:
return 4 # Others
else:
# Non-fp8 device: int8+split > int8 > others
if "int8" in name_lower and "_split" in name_lower:
return 0 # Highest priority
elif "int8" in name_lower:
return 1
else:
return 2 # Others (fp8 already filtered out)
return sorted(models, key=lambda x: (get_priority(x), x.lower()))
def get_dit_choices(model_path, model_type="wan2.1", task_type=None, is_distill=None):
"""Get Diffusion model options (from Hugging Face and local)
Args:
model_path: Local model path
model_type: "wan2.1" or "wan2.2"
task_type: "i2v" or "t2v", None means no task type filtering
is_distill: Whether it's a distill model, None means get both distill and non-distill
"""
excluded_keywords = ["vae", "tae", "clip", "t5", "high_noise", "low_noise"]
fp8_supported = is_fp8_supported_gpu()
# Select repository based on model type and whether distill
if model_type == "wan2.1":
if is_distill is True:
repo_id = "lightx2v/wan2.1-Distill-Models"
elif is_distill is False:
repo_id = "lightx2v/wan2.1-Official-Models"
else:
# Get models from both repositories
repo_id_distill = "lightx2v/wan2.1-Distill-Models"
repo_id_official = "lightx2v/wan2.1-Official-Models"
hf_models_distill = get_hf_models(repo_id_distill, prefix_filter="wan2.1") if HF_AVAILABLE else []
hf_models_official = get_hf_models(repo_id_official, prefix_filter="wan2.1") if HF_AVAILABLE else []
hf_models = list(set(hf_models_distill + hf_models_official))
repo_id = None # Mark as already fetched
else: # wan2.2
if is_distill is True:
repo_id = "lightx2v/wan2.2-Distill-Models"
elif is_distill is False:
repo_id = "lightx2v/wan2.2-Official-Models"
else:
# Get models from both repositories
repo_id_distill = "lightx2v/wan2.2-Distill-Models"
repo_id_official = "lightx2v/wan2.2-Official-Models"
hf_models_distill = get_hf_models(repo_id_distill, prefix_filter="wan2.2") if HF_AVAILABLE else []
hf_models_official = get_hf_models(repo_id_official, prefix_filter="wan2.2") if HF_AVAILABLE else []
hf_models = list(set(hf_models_distill + hf_models_official))
repo_id = None # Mark as already fetched
if repo_id:
hf_models = get_hf_models(repo_id, prefix_filter=model_type) if HF_AVAILABLE else []
# Filter models that meet criteria
def is_valid(name):
name_lower = name.lower()
# Filter out files containing comfyui
if "comfyui" in name_lower:
return False
# Check model type
if model_type == "wan2.1":
if "wan2.1" not in name_lower:
return False
else:
if "wan2.2" not in name_lower:
return False
# Check task type (if specified)
if task_type:
if task_type.lower() not in name_lower:
return False
if not fp8_supported and "fp8" in name_lower:
return False
return not any(kw in name_lower for kw in excluded_keywords)
# Filter HF models: only keep safetensors files or _split directories
valid_hf_models = []
for m in hf_models:
if not is_valid(m):
continue
# Keep if it's a safetensors file or contains _split directory
if m.endswith(".safetensors") or "_split" in m.lower():
valid_hf_models.append(m)
# Check locally existing models (only search safetensors files and directories, including _split directories)
contents = scan_model_path_contents(model_path)
dir_choices = [d for d in contents["dirs"] if is_valid(d) and ("_split" in d.lower() or d in contents["safetensors_dirs"])]
safetensors_choices = [f for f in contents["files"] if f.endswith(".safetensors") and is_valid(f)]
safetensors_dir_choices = [d for d in contents["safetensors_dirs"] if is_valid(d)]
local_models = dir_choices + safetensors_choices + safetensors_dir_choices
# Merge HF and local models, deduplicate, and sort by priority
all_models = sort_model_choices(list(set(valid_hf_models + local_models)))
# Format options, add download status (✅ downloaded, ❌ not downloaded)
formatted_choices = [format_model_choice(m, model_path) for m in all_models]
return formatted_choices if formatted_choices else [""]
def get_high_noise_choices(model_path, model_type="wan2.2", task_type=None, is_distill=None):
"""Get high noise model options (from Hugging Face and local, files/directories containing high_noise)
Args:
model_path: Local model path
model_type: "wan2.2" (high noise model only for wan2.2)
task_type: "i2v" or "t2v", None means no task type filtering
is_distill: Whether it's a distill model, None means get both distill and non-distill
"""
fp8_supported = is_fp8_supported_gpu()
# Select repository based on whether distill
if is_distill is True:
repo_id = "lightx2v/wan2.2-Distill-Models"
elif is_distill is False:
repo_id = "lightx2v/wan2.2-Official-Models"
else:
# Get models from both repositories
repo_id_distill = "lightx2v/wan2.2-Distill-Models"
repo_id_official = "lightx2v/wan2.2-Official-Models"
hf_models_distill = get_hf_models(repo_id_distill, keyword_filter="high_noise") if HF_AVAILABLE else []
hf_models_official = get_hf_models(repo_id_official, keyword_filter="high_noise") if HF_AVAILABLE else []
hf_models = list(set(hf_models_distill + hf_models_official))
repo_id = None
if repo_id:
hf_models = get_hf_models(repo_id, keyword_filter="high_noise") if HF_AVAILABLE else []
def is_valid(name):
name_lower = name.lower()
# Filter out files containing comfyui
if "comfyui" in name_lower:
return False
# Check model type
if model_type.lower() not in name_lower:
return False
# Check task type (if specified)
if task_type:
if task_type.lower() not in name_lower:
return False
if not fp8_supported and "fp8" in name_lower:
return False
return "high_noise" in name_lower or "high-noise" in name_lower
# Filter HF models: only keep safetensors files or _split directories
valid_hf_models = []
for m in hf_models:
if not is_valid(m):
continue
# Keep if it's a safetensors file or contains _split directory
if m.endswith(".safetensors") or "_split" in m.lower():
valid_hf_models.append(m)
# Check locally existing models (only search safetensors files and directories, including _split directories)
contents = scan_model_path_contents(model_path)
dir_choices = [d for d in contents["dirs"] if is_valid(d) and ("_split" in d.lower() or d in contents["safetensors_dirs"])]
safetensors_choices = [f for f in contents["files"] if f.endswith(".safetensors") and is_valid(f)]
safetensors_dir_choices = [d for d in contents["safetensors_dirs"] if is_valid(d)]
local_models = dir_choices + safetensors_choices + safetensors_dir_choices
# Merge HF and local models, deduplicate, and sort by priority
all_models = sort_model_choices(list(set(valid_hf_models + local_models)))
# Format options, add download status (✅ downloaded, ❌ not downloaded)
formatted_choices = [format_model_choice(m, model_path) for m in all_models]
return formatted_choices if formatted_choices else [""]
def get_low_noise_choices(model_path, model_type="wan2.2", task_type=None, is_distill=None):
"""Get low noise model options (from Hugging Face and local, files/directories containing low_noise)
Args:
model_path: Local model path
model_type: "wan2.2" (low noise model only for wan2.2)
task_type: "i2v" or "t2v", None means no task type filtering
is_distill: Whether it's a distill model, None means get both distill and non-distill
"""
fp8_supported = is_fp8_supported_gpu()
# Select repository based on whether distill
if is_distill is True:
repo_id = "lightx2v/wan2.2-Distill-Models"
elif is_distill is False:
repo_id = "lightx2v/wan2.2-Official-Models"
else:
# Get models from both repositories
repo_id_distill = "lightx2v/wan2.2-Distill-Models"
repo_id_official = "lightx2v/wan2.2-Official-Models"
hf_models_distill = get_hf_models(repo_id_distill, keyword_filter="low_noise") if HF_AVAILABLE else []
hf_models_official = get_hf_models(repo_id_official, keyword_filter="low_noise") if HF_AVAILABLE else []
hf_models = list(set(hf_models_distill + hf_models_official))
repo_id = None
if repo_id:
hf_models = get_hf_models(repo_id, keyword_filter="low_noise") if HF_AVAILABLE else []
def is_valid(name):
name_lower = name.lower()
# Filter out files containing comfyui
if "comfyui" in name_lower:
return False
# Check model type
if model_type.lower() not in name_lower:
return False
# Check task type (if specified)
if task_type:
if task_type.lower() not in name_lower:
return False
if not fp8_supported and "fp8" in name_lower:
return False
return "low_noise" in name_lower or "low-noise" in name_lower
# Filter HF models: only keep safetensors files or _split directories
valid_hf_models = []
for m in hf_models:
if not is_valid(m):
continue
# Keep if it's a safetensors file or contains _split directory
if m.endswith(".safetensors") or "_split" in m.lower():
valid_hf_models.append(m)
# Check locally existing models (only search safetensors files and directories, including _split directories)
contents = scan_model_path_contents(model_path)
dir_choices = [d for d in contents["dirs"] if is_valid(d) and ("_split" in d.lower() or d in contents["safetensors_dirs"])]
safetensors_choices = [f for f in contents["files"] if f.endswith(".safetensors") and is_valid(f)]
safetensors_dir_choices = [d for d in contents["safetensors_dirs"] if is_valid(d)]
local_models = dir_choices + safetensors_choices + safetensors_dir_choices
# Merge HF and local models, deduplicate, and sort by priority
all_models = sort_model_choices(list(set(valid_hf_models + local_models)))
# Format options, add download status (✅ downloaded, ❌ not downloaded)
formatted_choices = [format_model_choice(m, model_path) for m in all_models]
return formatted_choices if formatted_choices else [""]
def get_t5_model_choices(model_path):
"""Get T5 model options (from Hugging Face Encoders repository and local, containing t5 keyword, only safetensors, excluding google)"""
fp8_supported = is_fp8_supported_gpu()
# Get from Hugging Face Encoders repository
repo_id = "lightx2v/Encoders"
hf_models = get_hf_models(repo_id) if HF_AVAILABLE else []
# Filter files containing t5, only safetensors, excluding google
def is_valid_hf(name):
name_lower = name.lower()
# Filter out files containing comfyui and google directory
if "comfyui" in name_lower or name == "google":
return False
if not fp8_supported and "fp8" in name_lower:
return False
# Only show safetensors files
return ("t5" in name_lower) and name.endswith(".safetensors")
valid_hf_models = [m for m in hf_models if is_valid_hf(m)]
# Check locally existing models
contents = scan_model_path_contents(model_path)
def is_valid_local(name):
name_lower = name.lower()
# Filter out files containing comfyui and google directory
if "comfyui" in name_lower or name == "google":
return False
if not fp8_supported and "fp8" in name_lower:
return False
# Only show safetensors files
return ("t5" in name_lower) and name.endswith(".safetensors")
# Only filter from .safetensors files
safetensors_choices = [f for f in contents["files"] if f.endswith(".safetensors") and is_valid_local(f)]
local_models = safetensors_choices
# Merge HF and local models, deduplicate, and sort by priority
all_models = sort_model_choices(list(set(valid_hf_models + local_models)))
# Format options, add download status (✅ downloaded, ❌ not downloaded)
formatted_choices = [format_model_choice(m, model_path) for m in all_models]
return formatted_choices if formatted_choices else [""]
def get_t5_tokenizer_choices(model_path):
"""Get T5 Tokenizer options (google directory)"""
# Only return google directory
contents = scan_model_path_contents(model_path)
dir_choices = ["google"] if "google" in contents["dirs"] else []
# Get from HF
repo_id = "lightx2v/Encoders"
hf_models = get_hf_models(repo_id) if HF_AVAILABLE else []
hf_google = ["google"] if "google" in hf_models else []
all_models = sorted(set(hf_google + dir_choices))
formatted_choices = [format_model_choice(m, model_path) for m in all_models]
return formatted_choices if formatted_choices else [""]
def get_clip_model_choices(model_path):
"""Get CLIP model options (from Hugging Face Encoders repository and local, containing clip keyword, only safetensors, excluding xlm-roberta-large)"""
fp8_supported = is_fp8_supported_gpu()
# Get from Hugging Face Encoders repository
repo_id = "lightx2v/Encoders"
hf_models = get_hf_models(repo_id) if HF_AVAILABLE else []
# Filter files containing clip, only safetensors, excluding xlm-roberta-large
def is_valid_hf(name):
name_lower = name.lower()
# Filter out files containing comfyui and xlm-roberta-large directory
if "comfyui" in name_lower or name == "xlm-roberta-large":
return False
if not fp8_supported and "fp8" in name_lower:
return False
# Only show safetensors files
return ("clip" in name_lower) and name.endswith(".safetensors")
valid_hf_models = [m for m in hf_models if is_valid_hf(m)]
# Check locally existing models
contents = scan_model_path_contents(model_path)
def is_valid_local(name):
name_lower = name.lower()
# Filter out files containing comfyui and xlm-roberta-large directory
if "comfyui" in name_lower or name == "xlm-roberta-large":
return False
if not fp8_supported and "fp8" in name_lower:
return False
# Only show safetensors files
return ("clip" in name_lower) and name.endswith(".safetensors")
# Only filter from .safetensors files
safetensors_choices = [f for f in contents["files"] if f.endswith(".safetensors") and is_valid_local(f)]
local_models = safetensors_choices
# Merge HF and local models, deduplicate, and sort by priority
all_models = sort_model_choices(list(set(valid_hf_models + local_models)))
# Format options, add download status (✅ downloaded, ❌ not downloaded)
formatted_choices = [format_model_choice(m, model_path) for m in all_models]
return formatted_choices if formatted_choices else [""]
def get_clip_tokenizer_choices(model_path):
"""Get CLIP Tokenizer options (xlm-roberta-large directory)"""
# Only return xlm-roberta-large directory
contents = scan_model_path_contents(model_path)
dir_choices = ["xlm-roberta-large"] if "xlm-roberta-large" in contents["dirs"] else []
# Get from HF
repo_id = "lightx2v/Encoders"
hf_models = get_hf_models(repo_id) if HF_AVAILABLE else []
hf_xlm = ["xlm-roberta-large"] if "xlm-roberta-large" in hf_models else []
all_models = sorted(set(hf_xlm + dir_choices))
formatted_choices = [format_model_choice(m, model_path) for m in all_models]
return formatted_choices if formatted_choices else [""]
def get_vae_encoder_choices(model_path):
"""Get VAE encoder options, only return wan2.1_VAE.safetensors"""
encoder_name = "wan2.1_VAE.safetensors"
# Get from Hugging Face Autoencoders repository
repo_id = "lightx2v/Autoencoders"
hf_models = get_hf_models(repo_id) if HF_AVAILABLE else []
# Check if the file exists in HF
hf_has = encoder_name in hf_models
# Check if it exists locally
local_has = check_model_exists(model_path, encoder_name)
# If HF or local has it, return
if hf_has or local_has:
return [format_model_choice(encoder_name, model_path)]
else:
return [format_model_choice(encoder_name, model_path)]
def get_vae_decoder_choices(model_path):
"""Get VAE decoder options (from Hugging Face Autoencoders repository and local, containing vae/VAE/tae keyword, only safetensors)"""
fp8_supported = is_fp8_supported_gpu()
# Get from Hugging Face Autoencoders repository
repo_id = "lightx2v/Autoencoders"
hf_models = get_hf_models(repo_id) if HF_AVAILABLE else []
# Filter files containing vae or tae, only safetensors files or _split directories
def is_valid_hf(name):
name_lower = name.lower()
# Filter out files containing comfyui
if "comfyui" in name_lower:
return False
if not fp8_supported and "fp8" in name_lower:
return False
# Only show safetensors files or _split directories, must contain vae or tae
return any(kw in name_lower for kw in ["vae", "tae", "lightvae", "lighttae"]) and (name.endswith(".safetensors") or "_split" in name_lower)
valid_hf_models = [m for m in hf_models if is_valid_hf(m)]
# Check locally existing models
contents = scan_model_path_contents(model_path)
def is_valid_local(name):
name_lower = name.lower()
# Filter out files containing comfyui
if "comfyui" in name_lower:
return False
if not fp8_supported and "fp8" in name_lower:
return False
# Only show safetensors files or _split directories, must contain vae or tae
if not any(kw in name_lower for kw in ["vae", "tae", "lightvae", "lighttae"]):
return False
# If it's a file, must be safetensors
if os.path.isfile(os.path.join(model_path, name)):
return name.endswith(".safetensors")
# If it's a directory, must be a directory containing safetensors or _split directory
return name in contents["safetensors_dirs"] or "_split" in name_lower
# Filter from .safetensors files
safetensors_choices = [f for f in contents["files"] if f.endswith(".safetensors") and is_valid_local(f)]
# Filter from directories containing safetensors (including _split directories)
dir_choices = [d for d in contents["dirs"] if is_valid_local(d)]
local_models = safetensors_choices + dir_choices
# Merge HF and local models, deduplicate
all_models = list(set(valid_hf_models + local_models))
# For VAE decoder, only show options containing "2_1" or "2.1"
all_models = [m for m in all_models if "2_1" in m or "2.1" in m]
# Sort by priority
all_models = sort_model_choices(all_models)
# Format options, add download status (✅ downloaded, ❌ not downloaded)
formatted_choices = [format_model_choice(m, model_path) for m in all_models]
return formatted_choices if formatted_choices else [""]
def get_qwen_image_dit_choices(model_path):
"""Get Qwen Image Edit Diffusion model options
From lightx2v/Qwen-Image-Edit-2511-Lightning repository
Only list models containing qwen_image_edit_2511 and ending with lightning.safetensors or lightning_split
"""
fp8_supported = is_fp8_supported_gpu()
# Get from Hugging Face repository
repo_id = "lightx2v/Qwen-Image-Edit-2511-Lightning"
hf_models = get_hf_models(repo_id) if HF_AVAILABLE else []
def is_valid(name):
name_lower = name.lower()
# Filter out files containing comfyui
if "comfyui" in name_lower:
return False
if not fp8_supported and "fp8" in name_lower:
return False
# Must contain qwen_image_edit_2511
if "qwen_image_edit_2511" not in name_lower:
return False
# Only keep those ending with lightning.safetensors or lightning_split
return name.endswith("lightning.safetensors") or name.endswith("_split") or "lightning_split" in name_lower
# Filter HF models
valid_hf_models = [m for m in hf_models if is_valid(m)]
# Check locally existing models
contents = scan_model_path_contents(model_path)
local_models = []
for item in contents["dirs"] + contents["files"]:
if is_valid(item):
local_models.append(item)
# Merge HF and local models, deduplicate, and sort by priority
all_models = sort_model_choices(list(set(valid_hf_models + local_models)))
# Format options, add download status
formatted_choices = [format_model_choice(m, model_path) for m in all_models]
return formatted_choices if formatted_choices else [""]
def get_qwen_image_vae_choices(model_path):
"""Get Qwen Image Edit VAE options
Get vae directory from Qwen/Qwen-Image-Edit-2511 repository
"""
# Get from Hugging Face repository
repo_id = "Qwen/Qwen-Image-Edit-2511"
hf_models = get_hf_models(repo_id) if HF_AVAILABLE else []
# Only keep vae directory
valid_hf_models = [m for m in hf_models if m.lower() == "vae"]
# Check locally existing models
contents = scan_model_path_contents(model_path)
local_models = [d for d in contents["dirs"] if d.lower() == "vae"]
# Merge HF and local models, deduplicate
all_models = sorted(set(valid_hf_models + local_models))
# If not found, add default value "vae"
if not all_models:
all_models = ["vae"]
# Format options, add download status
formatted_choices = [format_model_choice(m, model_path) for m in all_models]
return formatted_choices
def get_qwen_image_scheduler_choices(model_path):
"""Get Qwen Image Edit Scheduler options
Get scheduler directory from Qwen/Qwen-Image-Edit-2511 repository
"""
# Get from Hugging Face repository
repo_id = "Qwen/Qwen-Image-Edit-2511"
hf_models = get_hf_models(repo_id) if HF_AVAILABLE else []
# Only keep scheduler directory
valid_hf_models = [m for m in hf_models if m.lower() == "scheduler"]
# Check locally existing models
contents = scan_model_path_contents(model_path)
local_models = [d for d in contents["dirs"] if d.lower() == "scheduler"]
# Merge HF and local models, deduplicate
all_models = sorted(set(valid_hf_models + local_models))
# If not found, add default value "scheduler"
if not all_models:
all_models = ["scheduler"]
# Format options, add download status
formatted_choices = [format_model_choice(m, model_path) for m in all_models]
return formatted_choices
def get_qwen25vl_encoder_choices(model_path):
"""Get Qwen25-VL encoder options
From lightx2v/Encoders repository, only need Qwen25-VL-4bit-GPTQ
"""
# Get from Hugging Face Encoders repository
repo_id = "lightx2v/Encoders"
hf_models = get_hf_models(repo_id) if HF_AVAILABLE else []
# Only keep Qwen25-VL-4bit-GPTQ
valid_hf_models = [m for m in hf_models if "qwen25-vl-4bit-gptq" in m.lower() or "qwen25_vl_4bit_gptq" in m.lower()]
# Check locally existing models
contents = scan_model_path_contents(model_path)
local_models = [d for d in contents["dirs"] if "qwen25-vl-4bit-gptq" in d.lower() or "qwen25_vl_4bit_gptq" in d.lower()]
# Merge HF and local models, deduplicate
all_models = sorted(set(valid_hf_models + local_models))
# Format options, add download status
formatted_choices = [format_model_choice(m, model_path) for m in all_models]
return formatted_choices if formatted_choices else [""]
def detect_quant_scheme(model_name):
"""Automatically detect quantization precision based on model name
- If model name contains "int8" → "int8"
- If model name contains "fp8" and device supports it → "fp8"
- Otherwise return None (no quantization)
"""
if not model_name:
return None
name_lower = model_name.lower()
if "int8" in name_lower:
return "int8"
elif "fp8" in name_lower:
if is_fp8_supported_gpu():
return "fp8"
else:
# Device doesn't support fp8, return None (use default precision)
return None
return None
def download_model_from_hf(repo_id, model_name, model_path, progress=gr.Progress()):
"""Download model from Hugging Face (supports files and directories)"""
if not HF_AVAILABLE:
return f"❌ huggingface_hub not installed, cannot download model"
progress(0, desc=f"Starting to download {model_name} from Hugging Face...")
logger.info(f"Starting to download {model_name} from Hugging Face {repo_id} to {model_path}")
target_path = os.path.join(model_path, model_name)
os.makedirs(model_path, exist_ok=True)
import shutil
# Determine if it's a file or directory: if name doesn't end with .safetensors or .pth, it's a directory
is_directory = not (model_name.endswith(".safetensors") or model_name.endswith(".pth"))
if is_directory:
# Download directory
progress(0.1, desc=f"Downloading directory {model_name}...")
logger.info(f"Detected {model_name} is a directory, using snapshot_download")
if os.path.exists(target_path):
shutil.rmtree(target_path)
with warnings.catch_warnings():
warnings.simplefilter("ignore")
hf_snapshot_download(
repo_id=repo_id,
allow_patterns=[f"{model_name}/**"],
local_dir=model_path,
local_dir_use_symlinks=False,
repo_type="model",
)
# Move files to correct location
repo_name = repo_id.split("/")[-1]
source_dir = os.path.join(model_path, repo_name, model_name)
if os.path.exists(source_dir):
shutil.move(source_dir, target_path)
repo_dir = os.path.join(model_path, repo_name)
if os.path.exists(repo_dir) and not os.listdir(repo_dir):
os.rmdir(repo_dir)
else:
source_dir = os.path.join(model_path, model_name)
if os.path.exists(source_dir) and source_dir != target_path:
shutil.move(source_dir, target_path)
logger.info(f"Directory {model_name} download complete, moved to {target_path}")
else:
# Download file
progress(0.1, desc=f"Downloading file {model_name}...")
logger.info(f"Detected {model_name} is a file, using hf_hub_download")
if os.path.exists(target_path):
os.remove(target_path)
with warnings.catch_warnings():
warnings.simplefilter("ignore")
downloaded_path = hf_hub_download(
repo_id=repo_id,
filename=model_name,
local_dir=model_path,
local_dir_use_symlinks=False,
repo_type="model",
)
logger.info(f"File {model_name} download complete, saved to {downloaded_path}")
progress(1.0, desc=f"✅ {model_name} download complete")
return f"✅ {model_name} download complete"
def download_model_from_ms(repo_id, model_name, model_path, progress=gr.Progress()):
"""Download model from ModelScope (supports files and directories)"""
if not MS_AVAILABLE:
return f"❌ modelscope not installed, cannot download model"
progress(0, desc=f"Starting to download {model_name} from ModelScope...")
logger.info(f"Starting to download {model_name} from ModelScope {repo_id} to {model_path}")
target_path = os.path.join(model_path, model_name)
os.makedirs(model_path, exist_ok=True)
import shutil
# Determine if it's a file or directory: if name doesn't end with .safetensors or .pth, it's a directory
is_directory = not (model_name.endswith(".safetensors") or model_name.endswith(".pth"))
is_file = not is_directory
# Temporary directory for download
temp_dir = os.path.join(model_path, f".temp_{model_name}")
if os.path.exists(temp_dir):
shutil.rmtree(temp_dir)
# Handle directory download
if is_directory:
progress(0.1, desc=f"Downloading directory {model_name}...")
logger.info(f"Detected {model_name} is a directory, using snapshot_download")
if os.path.exists(target_path):
shutil.rmtree(target_path)
# Use snapshot_download to download directory
with warnings.catch_warnings():
warnings.simplefilter("ignore")
downloaded_path = ms_snapshot_download(
model_id=repo_id,
cache_dir=temp_dir,
allow_patterns=[f"{model_name}/**"],
)
# Move files to target location
source_dir = os.path.join(downloaded_path, model_name)
if not os.path.exists(source_dir) and os.path.exists(downloaded_path):
# If not found, try to find from download path
for item in os.listdir(downloaded_path):
item_path = os.path.join(downloaded_path, item)
if model_name in item or os.path.isdir(item_path):