-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathapp.py
More file actions
1740 lines (1464 loc) · 71 KB
/
Copy pathapp.py
File metadata and controls
1740 lines (1464 loc) · 71 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
"""
LTX-2 WebUI - Video Generation Interface
A beautiful web interface for Lightricks LTX-2 video generation models.
LTX-2 supports:
- Synchronized audio-video generation
- Native 4K resolution at up to 50 FPS
- Clips up to 20 seconds long
- Text-to-video, image-to-video, video-to-video, keyframe interpolation
Requires: Python >= 3.12, CUDA >= 12.7, PyTorch ~= 2.7
"""
import os
import sys
import json
import time
import torch
import gradio as gr
from pathlib import Path
from typing import Optional, List, Tuple
from dataclasses import dataclass
from huggingface_hub import hf_hub_download, snapshot_download
from PIL import Image
import tempfile
import shutil
from presets import get_preset_manager, GenerationPreset, DEFAULT_PRESET_NAME
# Constants
MODELS_DIR = Path("./models")
OUTPUTS_DIR = Path("./outputs")
HF_REPO_ID = "Lightricks/LTX-2"
# Available checkpoints from HuggingFace
CHECKPOINTS = {
"ltx-2-19b-dev": {
"filename": "ltx-2-19b-dev.safetensors",
"size": "43.3 GB",
"description": "Full precision development model",
"type": "checkpoint"
},
"ltx-2-19b-dev-fp8": {
"filename": "ltx-2-19b-dev-fp8.safetensors",
"size": "27.1 GB",
"description": "FP8 quantized development model (recommended)",
"type": "checkpoint"
},
"ltx-2-19b-dev-fp4": {
"filename": "ltx-2-19b-dev-fp4.safetensors",
"size": "20 GB",
"description": "FP4 quantized development model (smallest)",
"type": "checkpoint"
},
"ltx-2-19b-distilled": {
"filename": "ltx-2-19b-distilled.safetensors",
"size": "43.3 GB",
"description": "Full precision distilled model",
"type": "checkpoint"
},
"ltx-2-19b-distilled-fp8": {
"filename": "ltx-2-19b-distilled-fp8.safetensors",
"size": "27.1 GB",
"description": "FP8 distilled model (fast inference)",
"type": "checkpoint"
},
"ltx-2-19b-distilled-lora-384": {
"filename": "ltx-2-19b-distilled-lora-384.safetensors",
"size": "7.67 GB",
"description": "Distilled LoRA adapter",
"type": "lora"
},
"ltx-2-spatial-upscaler-x2": {
"filename": "ltx-2-spatial-upscaler-x2-1.0.safetensors",
"size": "996 MB",
"description": "2x spatial upscaler",
"type": "upscaler"
},
"ltx-2-temporal-upscaler-x2": {
"filename": "ltx-2-temporal-upscaler-x2-1.0.safetensors",
"size": "262 MB",
"description": "2x temporal upscaler",
"type": "upscaler"
},
}
# Pipeline types - based on README Pipeline Selection Guide
# Decision Tree:
# - Text-to-video only:
# - Fastest inference → DistilledPipeline (8 sigmas, no CFG)
# - Best quality → TI2VidTwoStagesPipeline (production recommended)
# - Image/Video conditioning:
# - Reference videos → ICLoraPipeline
# - Keyframe interpolation → KeyframeInterpolationPipeline
# - Image-to-video → Any pipeline supports this
# Note: TI2VidOneStagePipeline is primarily for educational purposes
PIPELINE_TYPES = {
"distilled": {
"name": "⚡ Distilled Pipeline (Fastest)",
"description": "🚀 Fastest inference with 8 predefined sigmas, no CFG needed. Best for: quick iterations, batch processing. Uses distilled checkpoint.",
"recommended": True,
"requires": ["distilled checkpoint", "spatial_upsampler", "gemma"],
"features": {"stages": 2, "cfg": False, "upsampling": True, "conditioning": "Image"}
},
"ti2vid_two_stages": {
"name": "🎬 Two-Stage Pipeline (Best Quality)",
"description": "Production quality - Stage 1 with CFG guidance, Stage 2 upsamples 2x with distilled LoRA refinement. Best for: final renders, highest quality.",
"recommended": False,
"requires": ["checkpoint", "distilled_lora", "spatial_upsampler", "gemma"],
"features": {"stages": 2, "cfg": True, "upsampling": True, "conditioning": "Image"}
},
"ti2vid_one_stage": {
"name": "📚 One-Stage Pipeline (Educational)",
"description": "⚠️ For learning/prototyping only. Single stage, no upsampling, lower resolution (512×768). NOT recommended for production.",
"recommended": False,
"requires": ["checkpoint", "gemma"],
"features": {"stages": 1, "cfg": True, "upsampling": False, "conditioning": "Image"}
},
"ic_lora": {
"name": "🎞️ IC-LoRA Pipeline (Video-to-Video)",
"description": "Video-to-video transformations with reference video/image conditioning. Best for: style transfer, pose/depth control, video editing.",
"recommended": False,
"requires": ["checkpoint", "ic_lora", "spatial_upsampler", "gemma"],
"features": {"stages": 2, "cfg": False, "upsampling": True, "conditioning": "Image + Video"}
},
"keyframe_interpolation": {
"name": "🎨 Keyframe Interpolation Pipeline",
"description": "Interpolate between keyframe images for smooth animations. Uses guiding latents for smoother transitions. Best for: animation, motion graphics.",
"recommended": False,
"requires": ["checkpoint", "distilled_lora", "spatial_upsampler", "gemma"],
"features": {"stages": 2, "cfg": True, "upsampling": True, "conditioning": "Keyframes"}
},
}
# Custom CSS for a stunning dark theme
CUSTOM_CSS = """
@import url('https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;500;700&family=Outfit:wght@300;400;500;600;700&display=swap');
:root {
--primary-hue: 265;
--accent-hue: 340;
--bg-dark: #0a0a0f;
--bg-card: #12121a;
--bg-hover: #1a1a25;
--border-color: #2a2a3a;
--text-primary: #f0f0f5;
--text-secondary: #9090a5;
--accent-purple: #a855f7;
--accent-pink: #ec4899;
--accent-gradient: linear-gradient(135deg, #a855f7 0%, #ec4899 50%, #f97316 100%);
--glow-purple: 0 0 30px rgba(168, 85, 247, 0.3);
--glow-pink: 0 0 30px rgba(236, 72, 153, 0.3);
}
body, .gradio-container {
background: var(--bg-dark) !important;
font-family: 'Outfit', sans-serif !important;
}
.gradio-container {
max-width: 1400px !important;
}
/* Header styling */
.header-container {
text-align: center;
padding: 2rem 0;
margin-bottom: 1rem;
position: relative;
}
.header-container::before {
content: '';
position: absolute;
top: 0;
left: 50%;
transform: translateX(-50%);
width: 80%;
height: 100%;
background: radial-gradient(ellipse at center, rgba(168, 85, 247, 0.15) 0%, transparent 70%);
pointer-events: none;
}
.header-title {
font-size: 3.5rem;
font-weight: 700;
background: var(--accent-gradient);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
margin: 0;
letter-spacing: -0.02em;
}
.header-subtitle {
font-size: 1.1rem;
color: var(--text-secondary);
margin-top: 0.5rem;
}
/* Card styling */
.gr-panel, .gr-box, .gr-form {
background: var(--bg-card) !important;
border: 1px solid var(--border-color) !important;
border-radius: 16px !important;
}
/* Tab styling */
.tab-nav {
background: var(--bg-card) !important;
border-radius: 12px !important;
padding: 0.5rem !important;
border: 1px solid var(--border-color) !important;
}
.tab-nav button {
font-family: 'Outfit', sans-serif !important;
font-weight: 500 !important;
border-radius: 8px !important;
transition: all 0.3s ease !important;
}
.tab-nav button.selected {
background: var(--accent-gradient) !important;
color: white !important;
}
/* Input styling */
input, textarea, select {
background: var(--bg-dark) !important;
border: 1px solid var(--border-color) !important;
border-radius: 10px !important;
color: var(--text-primary) !important;
font-family: 'Outfit', sans-serif !important;
transition: all 0.3s ease !important;
}
input:focus, textarea:focus, select:focus {
border-color: var(--accent-purple) !important;
box-shadow: var(--glow-purple) !important;
}
/* Button styling */
.gr-button {
font-family: 'Outfit', sans-serif !important;
font-weight: 600 !important;
border-radius: 10px !important;
transition: all 0.3s ease !important;
text-transform: uppercase;
letter-spacing: 0.05em;
}
.gr-button-primary {
background: var(--accent-gradient) !important;
border: none !important;
color: white !important;
}
.gr-button-primary:hover {
box-shadow: var(--glow-purple), var(--glow-pink) !important;
transform: translateY(-2px);
}
.gr-button-secondary {
background: var(--bg-hover) !important;
border: 1px solid var(--border-color) !important;
color: var(--text-primary) !important;
}
/* Slider styling */
.gr-slider input[type="range"] {
accent-color: var(--accent-purple) !important;
}
/* Label styling */
label {
color: var(--text-primary) !important;
font-weight: 500 !important;
}
/* Accordion styling */
.gr-accordion {
border: 1px solid var(--border-color) !important;
border-radius: 12px !important;
overflow: hidden;
}
/* Progress bar */
.progress-bar {
background: var(--accent-gradient) !important;
}
/* Model card styling */
.model-card {
background: var(--bg-card);
border: 1px solid var(--border-color);
border-radius: 12px;
padding: 1rem;
margin: 0.5rem 0;
transition: all 0.3s ease;
}
.model-card:hover {
border-color: var(--accent-purple);
box-shadow: var(--glow-purple);
}
/* Status indicators */
.status-ready {
color: #22c55e;
}
.status-downloading {
color: #f59e0b;
}
.status-missing {
color: #ef4444;
}
/* Code blocks */
code {
font-family: 'JetBrains Mono', monospace !important;
background: var(--bg-dark) !important;
padding: 0.2rem 0.5rem;
border-radius: 6px;
font-size: 0.9em;
}
/* Video output */
video {
border-radius: 12px !important;
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.5) !important;
}
/* Gallery */
.gr-gallery {
border-radius: 12px !important;
overflow: hidden;
}
/* Markdown */
.gr-markdown {
color: var(--text-secondary) !important;
}
.gr-markdown h1, .gr-markdown h2, .gr-markdown h3 {
color: var(--text-primary) !important;
}
/* Scrollbar */
::-webkit-scrollbar {
width: 8px;
height: 8px;
}
::-webkit-scrollbar-track {
background: var(--bg-dark);
}
::-webkit-scrollbar-thumb {
background: var(--border-color);
border-radius: 4px;
}
::-webkit-scrollbar-thumb:hover {
background: var(--accent-purple);
}
/* Animation */
@keyframes pulse-glow {
0%, 100% { box-shadow: 0 0 20px rgba(168, 85, 247, 0.3); }
50% { box-shadow: 0 0 40px rgba(236, 72, 153, 0.5); }
}
.generating {
animation: pulse-glow 2s ease-in-out infinite;
}
"""
def ensure_directories():
"""Create necessary directories."""
MODELS_DIR.mkdir(parents=True, exist_ok=True)
OUTPUTS_DIR.mkdir(parents=True, exist_ok=True)
(MODELS_DIR / "checkpoints").mkdir(exist_ok=True)
(MODELS_DIR / "loras").mkdir(exist_ok=True)
(MODELS_DIR / "upsamplers").mkdir(exist_ok=True)
(MODELS_DIR / "gemma").mkdir(exist_ok=True)
def get_model_path(model_key: str) -> Optional[Path]:
"""Get local path for a model if it exists."""
if model_key not in CHECKPOINTS:
return None
model_info = CHECKPOINTS[model_key]
model_type = model_info["type"]
if model_type == "checkpoint":
path = MODELS_DIR / "checkpoints" / model_info["filename"]
elif model_type == "lora":
path = MODELS_DIR / "loras" / model_info["filename"]
elif model_type == "upscaler":
path = MODELS_DIR / "upsamplers" / model_info["filename"]
else:
path = MODELS_DIR / model_info["filename"]
return path if path.exists() else None
def check_model_status(model_key: str) -> Tuple[str, str]:
"""Check if a model is downloaded. Returns (status, status_text)."""
path = get_model_path(model_key)
if path and path.exists():
size = path.stat().st_size / (1024 ** 3) # GB
return "ready", f"✅ Downloaded ({size:.2f} GB)"
return "missing", "❌ Not downloaded"
def download_model(model_key: str, progress=gr.Progress()) -> str:
"""Download a model from HuggingFace."""
if model_key not in CHECKPOINTS:
return f"❌ Unknown model: {model_key}"
model_info = CHECKPOINTS[model_key]
model_type = model_info["type"]
filename = model_info["filename"]
# Determine target directory
if model_type == "checkpoint":
target_dir = MODELS_DIR / "checkpoints"
elif model_type == "lora":
target_dir = MODELS_DIR / "loras"
elif model_type == "upscaler":
target_dir = MODELS_DIR / "upsamplers"
else:
target_dir = MODELS_DIR
target_dir.mkdir(parents=True, exist_ok=True)
target_path = target_dir / filename
if target_path.exists():
return f"✅ Model already exists: {target_path}"
try:
progress(0, desc=f"Downloading {filename}...")
downloaded_path = hf_hub_download(
repo_id=HF_REPO_ID,
filename=filename,
local_dir=target_dir,
)
progress(1, desc="Download complete!")
return f"✅ Successfully downloaded to: {downloaded_path}\n\n📋 Click 'Refresh Model Lists' in the Generate tab to see the new model."
except Exception as e:
return f"❌ Download failed: {str(e)}"
def get_available_models() -> dict:
"""Get status of all available models."""
statuses = {}
for key in CHECKPOINTS:
status, text = check_model_status(key)
statuses[key] = {
"status": status,
"text": text,
"info": CHECKPOINTS[key]
}
return statuses
def refresh_model_status() -> str:
"""Generate HTML for model status display."""
statuses = get_available_models()
html = "<div style='display: grid; gap: 0.75rem;'>"
for key, data in statuses.items():
info = data["info"]
status_class = "status-ready" if data["status"] == "ready" else "status-missing"
html += f"""
<div class="model-card">
<div style="display: flex; justify-content: space-between; align-items: center;">
<div>
<strong style="color: var(--text-primary);">{key}</strong>
<span style="color: var(--text-secondary); font-size: 0.9em;"> ({info['size']})</span>
</div>
<span class="{status_class}" style="font-size: 0.9em;">{data['text']}</span>
</div>
<div style="color: var(--text-secondary); font-size: 0.85em; margin-top: 0.25rem;">
{info['description']}
</div>
</div>
"""
html += "</div>"
return html
def get_checkpoint_choices() -> List[str]:
"""Get list of available checkpoint files."""
choices = []
checkpoint_dir = MODELS_DIR / "checkpoints"
if checkpoint_dir.exists():
for f in checkpoint_dir.glob("*.safetensors"):
choices.append(str(f))
# Sort with distilled-fp8 first (most memory efficient), then distilled, then others
def sort_key(x):
x_lower = x.lower()
if "distilled-fp8" in x_lower:
return (0, x) # FP8 first (most memory efficient)
elif "distilled" in x_lower and "lora" not in x_lower:
return (1, x) # Then full distilled
elif "fp8" in x_lower:
return (2, x) # Then other FP8
elif "fp4" in x_lower:
return (3, x) # Then FP4
else:
return (4, x) # Then everything else
choices.sort(key=sort_key)
return choices if choices else ["No checkpoints found - download from Models tab"]
def get_default_checkpoint() -> str:
"""Get the default checkpoint path (prefer distilled-fp8 for memory efficiency)."""
choices = get_checkpoint_choices()
if choices and "No checkpoints" not in choices[0]:
# Return first choice (distilled-fp8 is sorted first)
return choices[0]
# Fall back to expected default paths (prefer FP8)
fp8_path = MODELS_DIR / "checkpoints" / "ltx-2-19b-distilled-fp8.safetensors"
full_path = MODELS_DIR / "checkpoints" / "ltx-2-19b-distilled.safetensors"
if fp8_path.exists():
return str(fp8_path)
return str(full_path)
def get_default_upsampler() -> str:
"""Get the default spatial upsampler path."""
choices = get_upscaler_choices()
if choices and "No upsamplers" not in choices[0]:
return choices[0]
# Fall back to expected default path
default_path = str(MODELS_DIR / "upsamplers" / "ltx-2-spatial-upscaler-x2-1.0.safetensors")
return default_path
def get_lora_choices() -> List[str]:
"""Get list of available LoRA files."""
choices = ["None"]
lora_dir = MODELS_DIR / "loras"
if lora_dir.exists():
for f in lora_dir.glob("*.safetensors"):
choices.append(str(f))
return choices
def get_upscaler_choices() -> List[str]:
"""Get list of available upscaler files."""
choices = []
upscaler_dir = MODELS_DIR / "upsamplers"
if upscaler_dir.exists():
for f in upscaler_dir.glob("*.safetensors"):
choices.append(str(f))
return choices if choices else ["No upsamplers found - download from Models tab"]
# Global pipeline cache - keeps models in VRAM between generations
# The underlying ModelLedger also caches individual models (transformer, VAE, etc.)
# for even faster subsequent runs within the same pipeline configuration
_pipeline_cache = {
"pipeline": None,
"pipeline_type": None,
"checkpoint_path": None,
"spatial_upsampler_path": None,
"gemma_path": None,
"distilled_lora_path": None,
"enable_fp8": None,
}
def clear_vram_cache() -> str:
"""Clear all cached models from VRAM."""
global _pipeline_cache
try:
# Get VRAM usage before clearing
if torch.cuda.is_available():
vram_before = torch.cuda.memory_allocated() / (1024 ** 3)
else:
vram_before = 0
# Clear the pipeline cache
if _pipeline_cache["pipeline"] is not None:
# Clear ModelLedger cache(s) if the pipeline has them
pipeline = _pipeline_cache["pipeline"]
if hasattr(pipeline, 'model_ledger'):
pipeline.model_ledger.clear_cache()
# For two-stage pipelines with multiple ledgers
if hasattr(pipeline, 'stage_1_model_ledger'):
pipeline.stage_1_model_ledger.clear_cache()
if hasattr(pipeline, 'stage_2_model_ledger'):
pipeline.stage_2_model_ledger.clear_cache()
# Clear the pipeline reference
_pipeline_cache["pipeline"] = None
_pipeline_cache["pipeline_type"] = None
_pipeline_cache["checkpoint_path"] = None
_pipeline_cache["spatial_upsampler_path"] = None
_pipeline_cache["gemma_path"] = None
_pipeline_cache["distilled_lora_path"] = None
_pipeline_cache["enable_fp8"] = None
# Force garbage collection
import gc
gc.collect()
# Clear CUDA cache
if torch.cuda.is_available():
torch.cuda.empty_cache()
torch.cuda.synchronize()
vram_after = torch.cuda.memory_allocated() / (1024 ** 3)
freed = vram_before - vram_after
return f"✅ VRAM cache cleared!\n\n📊 Freed: {freed:.2f} GB\n💾 Current usage: {vram_after:.2f} GB"
else:
return "✅ Cache cleared (no CUDA device detected)"
except Exception as e:
return f"❌ Error clearing cache: {str(e)}"
def get_vram_status() -> str:
"""Get current VRAM usage status."""
if not torch.cuda.is_available():
return "No CUDA device detected"
allocated = torch.cuda.memory_allocated() / (1024 ** 3)
reserved = torch.cuda.memory_reserved() / (1024 ** 3)
total = torch.cuda.get_device_properties(0).total_memory / (1024 ** 3)
# Check if pipeline is cached
pipeline_status = "🟢 Pipeline cached" if _pipeline_cache["pipeline"] is not None else "⚪ No pipeline loaded"
return f"""**VRAM Status:**
- Allocated: {allocated:.2f} GB
- Reserved: {reserved:.2f} GB
- Total: {total:.1f} GB
- {pipeline_status}"""
def get_cached_pipeline(
pipeline_type: str,
checkpoint_path: str,
spatial_upsampler_path: str,
gemma_path: str,
distilled_lora_path: str,
enable_fp8: bool,
progress=gr.Progress()
):
"""
Get or create a cached pipeline. Keeps models in VRAM for faster subsequent generations.
Only recreates pipeline if configuration changes.
"""
global _pipeline_cache
# Check if we can reuse the cached pipeline
cache_valid = (
_pipeline_cache["pipeline"] is not None
and _pipeline_cache["pipeline_type"] == pipeline_type
and _pipeline_cache["checkpoint_path"] == checkpoint_path
and _pipeline_cache["spatial_upsampler_path"] == spatial_upsampler_path
and _pipeline_cache["gemma_path"] == gemma_path
and _pipeline_cache["distilled_lora_path"] == distilled_lora_path
and _pipeline_cache["enable_fp8"] == enable_fp8
)
if cache_valid:
progress(0.1, desc="Using cached pipeline (models already in VRAM)...")
# Models are also cached in ModelLedger, making repeated generations instant
return _pipeline_cache["pipeline"], None
# Clear old pipeline to free VRAM before loading new one
if _pipeline_cache["pipeline"] is not None:
progress(0.1, desc="Clearing old pipeline from VRAM...")
del _pipeline_cache["pipeline"]
_pipeline_cache["pipeline"] = None
torch.cuda.empty_cache()
# Create new pipeline
progress(0.15, desc=f"Loading {pipeline_type} pipeline (first run is slower)...")
try:
if pipeline_type == "distilled":
from ltx_pipelines.distilled import DistilledPipeline
if not spatial_upsampler_path or not Path(spatial_upsampler_path).exists():
return None, "❌ Spatial upsampler is required for distilled pipeline.\n\nPlease download from the Models tab."
pipeline = DistilledPipeline(
checkpoint_path=checkpoint_path,
spatial_upsampler_path=spatial_upsampler_path,
gemma_root=gemma_path,
loras=[],
fp8transformer=enable_fp8,
)
elif pipeline_type == "ti2vid_two_stages":
from ltx_pipelines.ti2vid_two_stages import TI2VidTwoStagesPipeline
from ltx_core.loader import LoraPathStrengthAndSDOps, LTXV_LORA_COMFY_RENAMING_MAP
if not distilled_lora_path or distilled_lora_path == "None" or not Path(distilled_lora_path).exists():
return None, "❌ Two-Stage Pipeline requires a distilled LoRA.\n\nPlease download 'ltx-2-19b-distilled-lora-384' from the Models tab."
distilled_lora_list = [
LoraPathStrengthAndSDOps(distilled_lora_path, 1.0, LTXV_LORA_COMFY_RENAMING_MAP)
]
pipeline = TI2VidTwoStagesPipeline(
checkpoint_path=checkpoint_path,
distilled_lora=distilled_lora_list,
spatial_upsampler_path=spatial_upsampler_path if spatial_upsampler_path else None,
gemma_root=gemma_path,
loras=[],
fp8transformer=enable_fp8,
)
elif pipeline_type == "ti2vid_one_stage":
from ltx_pipelines.ti2vid_one_stage import TI2VidOneStagePipeline
pipeline = TI2VidOneStagePipeline(
checkpoint_path=checkpoint_path,
gemma_root=gemma_path,
loras=[],
fp8transformer=enable_fp8,
)
elif pipeline_type == "ic_lora":
from ltx_pipelines.ic_lora import ICLoraPipeline
if not spatial_upsampler_path or not Path(spatial_upsampler_path).exists():
return None, "❌ Spatial upsampler is required for IC-LoRA pipeline.\n\nPlease download from the Models tab."
# IC-LoRA uses loras parameter, not distilled_lora
# The user should provide the IC-LoRA model via the distilled_lora_path field
loras = []
if distilled_lora_path and distilled_lora_path != "None" and Path(distilled_lora_path).exists():
from ltx_core.loader import LoraPathStrengthAndSDOps, LTXV_LORA_COMFY_RENAMING_MAP
loras = [LoraPathStrengthAndSDOps(distilled_lora_path, 1.0, LTXV_LORA_COMFY_RENAMING_MAP)]
pipeline = ICLoraPipeline(
checkpoint_path=checkpoint_path,
spatial_upsampler_path=spatial_upsampler_path,
gemma_root=gemma_path,
loras=loras,
fp8transformer=enable_fp8,
)
elif pipeline_type == "keyframe_interpolation":
from ltx_pipelines.keyframe_interpolation import KeyframeInterpolationPipeline
from ltx_core.loader import LoraPathStrengthAndSDOps, LTXV_LORA_COMFY_RENAMING_MAP
if not distilled_lora_path or distilled_lora_path == "None" or not Path(distilled_lora_path).exists():
return None, "❌ Keyframe Interpolation Pipeline requires a distilled LoRA.\n\nPlease download 'ltx-2-19b-distilled-lora-384' from the Models tab."
distilled_lora_list = [
LoraPathStrengthAndSDOps(distilled_lora_path, 1.0, LTXV_LORA_COMFY_RENAMING_MAP)
]
pipeline = KeyframeInterpolationPipeline(
checkpoint_path=checkpoint_path,
distilled_lora=distilled_lora_list,
spatial_upsampler_path=spatial_upsampler_path if spatial_upsampler_path else None,
gemma_root=gemma_path,
loras=[],
fp8transformer=enable_fp8,
)
else:
return None, f"❌ Unknown pipeline type: {pipeline_type}"
# Cache the pipeline
_pipeline_cache["pipeline"] = pipeline
_pipeline_cache["pipeline_type"] = pipeline_type
_pipeline_cache["checkpoint_path"] = checkpoint_path
_pipeline_cache["spatial_upsampler_path"] = spatial_upsampler_path
_pipeline_cache["gemma_path"] = gemma_path
_pipeline_cache["distilled_lora_path"] = distilled_lora_path
_pipeline_cache["enable_fp8"] = enable_fp8
return pipeline, None
except ImportError as e:
return None, f"""❌ LTX Pipelines not installed.
Please install from the LTX-2 repository:
```
cd LTX-2
pip install -e packages/ltx-core
pip install -e packages/ltx-pipelines
```
Error: {str(e)}"""
except Exception as e:
import traceback
return None, f"❌ Failed to load pipeline:\n{str(e)}\n{traceback.format_exc()}"
def generate_video(
pipeline_type: str,
checkpoint_path: str,
distilled_lora_path: str,
spatial_upsampler_path: str,
gemma_path: str,
prompt: str,
negative_prompt: str,
height: int,
width: int,
num_frames: int,
frame_rate: float,
num_inference_steps: int,
cfg_guidance_scale: float,
seed: int,
enable_fp8: bool,
input_image: Optional[Image.Image],
image_strength: float,
reference_video: Optional[str],
keyframe_images: Optional[List[Image.Image]],
progress=gr.Progress()
) -> Tuple[Optional[str], str]:
"""Generate video using the selected pipeline. Keeps models in VRAM for faster subsequent runs."""
# Validate inputs
if not prompt:
return None, "❌ Please enter a prompt"
if not checkpoint_path or "No checkpoints" in checkpoint_path:
return None, "❌ Please download and select a checkpoint from the Models tab"
if not Path(checkpoint_path).exists():
return None, f"❌ Checkpoint not found: {checkpoint_path}"
# Check Gemma path
if not gemma_path or not Path(gemma_path).exists():
return None, """❌ Gemma text encoder not configured!
The Gemma 3 **12B** text encoder is **required** for all LTX-2 pipelines.
**To download Gemma 3 12B FP8 (no HF token required):**
```bash
huggingface-cli download pytorch/gemma-3-12b-it-FP8 --local-dir ./models/gemma
```
Then set the "Gemma Path" to `./models/gemma` in the Generate tab.
> ⚠️ **Important:** You must use Gemma 3 12B. Gemma 2 and Gemma 3 4B will NOT work!"""
# Generate output filename
timestamp = time.strftime("%Y%m%d_%H%M%S")
output_path = OUTPUTS_DIR / f"ltx2_{timestamp}.mp4"
# Handle seed - generate random if -1 or None
import random
if seed is None or seed < 0:
seed = random.randint(0, 2**32 - 1)
seed = int(seed) # Ensure it's an integer
# Set environment variable for FP8 optimization
if enable_fp8:
os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "expandable_segments:True"
try:
# Get or create cached pipeline (keeps models in VRAM)
pipeline, error = get_cached_pipeline(
pipeline_type=pipeline_type,
checkpoint_path=checkpoint_path,
spatial_upsampler_path=spatial_upsampler_path,
gemma_path=gemma_path,
distilled_lora_path=distilled_lora_path,
enable_fp8=enable_fp8,
progress=progress,
)
if error:
return None, error
progress(0.3, desc="Generating video...")
# Prepare image conditioning
images = []
if input_image is not None:
temp_img_path = OUTPUTS_DIR / f"temp_input_{timestamp}.png"
input_image.save(temp_img_path)
images = [(str(temp_img_path), 0, image_strength)]
# Prepare keyframes for keyframe_interpolation pipeline
if pipeline_type == "keyframe_interpolation" and keyframe_images:
images = [] # Replace with keyframes
for i, img in enumerate(keyframe_images):
temp_path = OUTPUTS_DIR / f"temp_keyframe_{timestamp}_{i}.png"
img.save(temp_path)
frame_idx = int(i * (num_frames - 1) / max(1, len(keyframe_images) - 1))
images.append((str(temp_path), frame_idx, 1.0))
# Import utilities needed for video encoding
from ltx_core.model.video_vae import TilingConfig, get_video_chunks_number
from ltx_pipelines.utils.media_io import encode_video
from ltx_pipelines.utils.constants import AUDIO_SAMPLE_RATE
# TilingConfig and video_chunks_number for two-stage pipelines
# One-stage uses video_chunks_number=1 (no chunking)
tiling_config = TilingConfig.default()
if pipeline_type == "ti2vid_one_stage":
video_chunks_number = 1
else:
video_chunks_number = get_video_chunks_number(num_frames, tiling_config)
# Generate video using the cached pipeline
# Each pipeline has a different API - match the source code exactly
with torch.no_grad():
if pipeline_type == "distilled":
# DistilledPipeline: no CFG, no negative prompt, has tiling_config
video, audio = pipeline(
prompt=prompt,
seed=seed,
height=int(height),
width=int(width),
num_frames=int(num_frames),
frame_rate=float(frame_rate),
images=images,
tiling_config=tiling_config,
enhance_prompt=False,
)
elif pipeline_type == "ic_lora":
# ICLoraPipeline: video conditioning support, has tiling_config
video_conditioning = []
if reference_video and Path(reference_video).exists():
video_conditioning = [(reference_video, 1.0)]
video, audio = pipeline(
prompt=prompt,
seed=seed,
height=int(height),
width=int(width),
num_frames=int(num_frames),
frame_rate=float(frame_rate),
images=images,
video_conditioning=video_conditioning,
tiling_config=tiling_config,
enhance_prompt=False,
)
elif pipeline_type == "ti2vid_one_stage":
# TI2VidOneStagePipeline: CFG + negative prompt, NO tiling_config
video, audio = pipeline(
prompt=prompt,
negative_prompt=negative_prompt if negative_prompt else "",
seed=seed,
height=int(height),
width=int(width),
num_frames=int(num_frames),
frame_rate=float(frame_rate),
num_inference_steps=int(num_inference_steps),
cfg_guidance_scale=float(cfg_guidance_scale),
images=images,
enhance_prompt=False,
)
else:
# TI2VidTwoStagesPipeline, KeyframeInterpolationPipeline: CFG + negative prompt, has tiling_config
video, audio = pipeline(
prompt=prompt,
negative_prompt=negative_prompt if negative_prompt else "",
seed=seed,
height=int(height),
width=int(width),
num_frames=int(num_frames),
frame_rate=float(frame_rate),
num_inference_steps=int(num_inference_steps),
cfg_guidance_scale=float(cfg_guidance_scale),
images=images,
tiling_config=tiling_config,
enhance_prompt=False,
)
# Encode and save video
progress(0.9, desc="Encoding video...")
encode_video(
video=video,
fps=float(frame_rate),
audio=audio,
audio_sample_rate=AUDIO_SAMPLE_RATE,
output_path=str(output_path),
video_chunks_number=video_chunks_number,
)
progress(1.0, desc="Complete!")
if output_path.exists():