-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathapi.py
More file actions
1566 lines (1306 loc) · 60.1 KB
/
Copy pathapi.py
File metadata and controls
1566 lines (1306 loc) · 60.1 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 FastAPI Service
RESTful API for video generation with preset support and real-time SSE streaming.
Features:
- Generate videos using presets or custom settings
- Real-time progress streaming via Server-Sent Events (SSE)
- Preset management (CRUD operations)
- Health check and status endpoints
Usage:
uvicorn api:app --host 0.0.0.0 --port 8000
# Or with auto-reload for development
uvicorn api:app --host 0.0.0.0 --port 8000 --reload
"""
import os
import sys
import time
import uuid
import base64
import asyncio
import threading
import json
import io
from pathlib import Path
from typing import Optional, List, Dict, Any
from contextlib import asynccontextmanager
from concurrent.futures import ThreadPoolExecutor
import torch
from fastapi import FastAPI, HTTPException, BackgroundTasks
from fastapi.responses import FileResponse, HTMLResponse, StreamingResponse
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel, Field
from huggingface_hub import hf_hub_download
from presets import (
get_preset_manager,
PresetManager,
GenerationPreset,
DEFAULT_PRESET_NAME,
)
# Constants
MODELS_DIR = Path("./models")
OUTPUTS_DIR = Path("./outputs")
TEMPLATES_DIR = Path("./templates")
HF_REPO_ID = "Lightricks/LTX-2"
# ============================================================================
# Progress Callback System for SSE Streaming
# ============================================================================
# Thread-local storage for progress callbacks
_progress_callbacks = threading.local()
def get_progress_callback():
"""Get the current thread's progress callback."""
return getattr(_progress_callbacks, 'callback', None)
def set_progress_callback(callback):
"""Set the current thread's progress callback."""
_progress_callbacks.callback = callback
import re
import sys
class OutputCapture:
"""Capture stdout/stderr and parse tqdm progress for SSE streaming.
Stage detection is based on step count patterns, NOT sequence position:
- Distilled: Stage 1 (8 steps), Stage 2 (3 steps), Encoding (variable)
- Two-stage: Stage 1 (num_inference_steps), Stage 2 (3 steps), Encoding (variable)
- One-stage: Stage 1 (num_inference_steps), Encoding (variable)
Loading bars from safetensors may or may not appear depending on model caching.
"""
# Shared state across stdout/stderr captures
_shared_state = {}
# Known step counts for specific stages
DISTILLED_STAGE1_STEPS = 8 # DISTILLED_SIGMA_VALUES has 9 values, tqdm uses sigmas[:-1]
STAGE2_REFINEMENT_STEPS = 3 # STAGE_2_DISTILLED_SIGMA_VALUES has 4 values, tqdm uses sigmas[:-1]
def __init__(self, progress_callback, original_stream, capture_id, pipeline_type=None, num_inference_steps=None):
self.progress_callback = progress_callback
self.original_stream = original_stream
self.capture_id = capture_id
# Initialize shared state for this capture session
if capture_id not in OutputCapture._shared_state:
OutputCapture._shared_state[capture_id] = {
"pipeline_type": pipeline_type,
"num_inference_steps": num_inference_steps,
# Track completed stages by step count (to distinguish loading vs stage 2)
"stage1_completed": False, # Have we completed Stage 1?
"stage2_completed": False, # Have we completed Stage 2?
"current_stage_total": None, # Current bar's step count
"current_stage_name": None, # Current stage name
"current_bar_completed": False, # Has current bar hit 100%?
}
# tqdm patterns - matches progress like " 5%|███ | 1/8 [00:01<00:05, 1.25it/s]"
# Extended pattern to capture time info: [elapsed<remaining, rate]
self.tqdm_pattern = re.compile(r'^\s*(\d+)%\|.*?\|\s*(\d+)/(\d+)\s*\[([^\]]+)\]')
# Fallback without time info
self.tqdm_pattern_simple = re.compile(r'^\s*(\d+)%\|.*?\|\s*(\d+)/(\d+)')
# Alternative pattern for simpler tqdm output
self.tqdm_simple = re.compile(r'(\d+)/(\d+)\s+\[([^\]]+)\]')
@property
def state(self):
return OutputCapture._shared_state[self.capture_id]
def _determine_stage(self, total, percentage):
"""Determine stage name based on step count patterns and pipeline type.
Detection logic:
1. For distilled pipeline: Stage 1 = 8 steps, Stage 2 = 3 steps
2. For other pipelines: Stage 1 = num_inference_steps, Stage 2 = 3 steps
3. 3 steps BEFORE Stage 1 completes = Loading Models
4. 3 steps AFTER Stage 1 completes = Stage 2 Refinement (for two-stage)
5. Any steps after Stage 2 (or Stage 1 for one-stage) = Video Encoding
"""
pipeline_type = self.state.get("pipeline_type")
num_inference_steps = self.state.get("num_inference_steps")
stage1_completed = self.state.get("stage1_completed", False)
stage2_completed = self.state.get("stage2_completed", False)
current_stage_total = self.state.get("current_stage_total")
current_stage_name = self.state.get("current_stage_name")
current_bar_completed = self.state.get("current_bar_completed", False)
is_one_stage = pipeline_type == "ti2vid_one_stage"
is_distilled = pipeline_type == "distilled"
# If still in the same bar (same total and bar not completed), return cached name
if current_stage_total == total and current_stage_name and not current_bar_completed:
# Check if bar just completed
if percentage >= 100:
self.state["current_bar_completed"] = True
self._mark_stage_completed(current_stage_name)
return current_stage_name
# New bar detected (different total or previous bar completed) - determine stage
stage_name = self._identify_stage_by_steps(
total, stage1_completed, stage2_completed,
is_one_stage, is_distilled, num_inference_steps
)
# Update state for new bar
self.state["current_stage_total"] = total
self.state["current_stage_name"] = stage_name
self.state["current_bar_completed"] = (percentage >= 100)
if percentage >= 100:
self._mark_stage_completed(stage_name)
return stage_name
def _identify_stage_by_steps(self, total, stage1_completed, stage2_completed,
is_one_stage, is_distilled, num_inference_steps):
"""Identify stage based on step count and pipeline state."""
# Determine expected Stage 1 step count
expected_stage1_steps = self.DISTILLED_STAGE1_STEPS if is_distilled else num_inference_steps
# Stage 1 detection: matches expected step count
if total == expected_stage1_steps and not stage1_completed:
return "Stage 1: Denoising"
# Stage 2 detection (3 steps, only for two-stage pipelines)
if total == self.STAGE2_REFINEMENT_STEPS:
if not stage1_completed:
# 3 steps before Stage 1 = Loading (from safetensors)
return "Loading Models"
elif not stage2_completed and not is_one_stage:
# 3 steps after Stage 1 = Stage 2 Refinement
return "Stage 2: Refinement"
# After main stages complete, it's encoding
if is_one_stage:
if stage1_completed:
return "Video Encoding"
else:
if stage1_completed and stage2_completed:
return "Video Encoding"
elif stage1_completed:
# Still waiting for Stage 2, but got unexpected step count
# Could be encoding if Stage 2 was skipped or has different steps
return "Video Encoding"
# Fallback for unexpected step counts
if not stage1_completed:
return "Loading Models"
return "Video Encoding"
def _mark_stage_completed(self, stage_name):
"""Mark a stage as completed based on its name."""
if "Stage 1" in stage_name:
self.state["stage1_completed"] = True
elif "Stage 2" in stage_name:
self.state["stage2_completed"] = True
def write(self, text):
# Also write to original stream
self.original_stream.write(text)
# Try to parse tqdm progress
if text.strip():
self._parse_progress(text)
def _parse_time_info(self, time_str):
"""Parse tqdm time info like '00:08<00:00, 1.04s/it' into structured data."""
time_info = {"elapsed": None, "remaining": None, "rate": None}
try:
# Split by comma to get elapsed<remaining and rate
parts = time_str.split(',')
if parts:
# Parse elapsed<remaining
time_part = parts[0].strip()
if '<' in time_part:
elapsed, remaining = time_part.split('<')
time_info["elapsed"] = elapsed.strip()
time_info["remaining"] = remaining.strip()
# Parse rate (e.g., "1.04s/it" or "1.25it/s")
if len(parts) > 1:
time_info["rate"] = parts[1].strip()
except Exception:
pass
return time_info
def _parse_progress(self, text):
# Check for tqdm progress pattern with time info
match = self.tqdm_pattern.search(text)
if match:
percentage = int(match.group(1))
current = int(match.group(2))
total = int(match.group(3))
time_str = match.group(4)
time_info = self._parse_time_info(time_str)
stage = self._determine_stage(total, percentage)
self.progress_callback({
"type": "step",
"stage": stage,
"step": current,
"total": total,
"percentage": percentage,
"elapsed": time_info.get("elapsed"),
"remaining": time_info.get("remaining"),
"rate": time_info.get("rate")
})
return
# Try fallback pattern without time
match = self.tqdm_pattern_simple.search(text)
if match:
percentage = int(match.group(1))
current = int(match.group(2))
total = int(match.group(3))
stage = self._determine_stage(total, percentage)
self.progress_callback({
"type": "step",
"stage": stage,
"step": current,
"total": total,
"percentage": percentage
})
return
# Try simple pattern with time
match = self.tqdm_simple.search(text)
if match:
current = int(match.group(1))
total = int(match.group(2))
time_str = match.group(3)
time_info = self._parse_time_info(time_str)
percentage = round(current / total * 100, 1) if total > 0 else 0
stage = self._determine_stage(total, percentage)
self.progress_callback({
"type": "step",
"stage": stage,
"step": current,
"total": total,
"percentage": percentage,
"elapsed": time_info.get("elapsed"),
"remaining": time_info.get("remaining"),
"rate": time_info.get("rate")
})
def flush(self):
self.original_stream.flush()
def isatty(self):
return self.original_stream.isatty()
class OutputCaptureContext:
"""Context manager to capture stdout/stderr during generation."""
def __init__(self, progress_callback, pipeline_type=None, num_inference_steps=None):
self.progress_callback = progress_callback
self.original_stdout = None
self.original_stderr = None
# Unique capture ID for this context (shared between stdout/stderr)
self.capture_id = id(self)
self.pipeline_type = pipeline_type
self.num_inference_steps = num_inference_steps
def __enter__(self):
self.original_stdout = sys.stdout
self.original_stderr = sys.stderr
sys.stdout = OutputCapture(self.progress_callback, self.original_stdout, self.capture_id, self.pipeline_type, self.num_inference_steps)
sys.stderr = OutputCapture(self.progress_callback, self.original_stderr, self.capture_id, self.pipeline_type, self.num_inference_steps)
return self
def __exit__(self, exc_type, exc_val, exc_tb):
sys.stdout = self.original_stdout
sys.stderr = self.original_stderr
# Clean up shared state
if self.capture_id in OutputCapture._shared_state:
del OutputCapture._shared_state[self.capture_id]
return False
# 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"
},
}
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)
TEMPLATES_DIR.mkdir(parents=True, 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:
"""Check if a model is downloaded. Returns (status, path)."""
path = get_model_path(model_key)
if path and path.exists():
# Always use forward slashes for cross-platform consistency
return "ready", str(path).replace("\\", "/")
return "missing", None
def download_model_file(model_key: str) -> str:
"""Download a model from HuggingFace. Returns the path."""
if model_key not in CHECKPOINTS:
raise ValueError(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 str(target_path)
downloaded_path = hf_hub_download(
repo_id=HF_REPO_ID,
filename=filename,
local_dir=target_dir,
)
return downloaded_path
def get_default_checkpoint() -> Optional[str]:
"""Get the default checkpoint path (prefer distilled-fp8)."""
checkpoint_dir = MODELS_DIR / "checkpoints"
if checkpoint_dir.exists():
# Prefer distilled-fp8
for name in ["ltx-2-19b-distilled-fp8.safetensors", "ltx-2-19b-distilled.safetensors"]:
path = checkpoint_dir / name
if path.exists():
return str(path)
# Return any available checkpoint
checkpoints = list(checkpoint_dir.glob("*.safetensors"))
if checkpoints:
return str(checkpoints[0])
return None
def get_default_upsampler() -> Optional[str]:
"""Get the default spatial upsampler path."""
upsampler_dir = MODELS_DIR / "upsamplers"
if upsampler_dir.exists():
upsamplers = list(upsampler_dir.glob("*.safetensors"))
if upsamplers:
return str(upsamplers[0])
return None
def auto_download_required_models(preset) -> tuple:
"""
Auto-download required models if not present.
Returns (checkpoint_path, upsampler_path) or raises error.
"""
checkpoint_path = preset.checkpoint_path
upsampler_path = preset.spatial_upsampler_path
# Check and download checkpoint
if not checkpoint_path or not Path(checkpoint_path).exists():
# Try to find existing checkpoint
existing = get_default_checkpoint()
if existing:
checkpoint_path = existing
else:
# Download default checkpoint (distilled-fp8)
print("Auto-downloading default checkpoint: ltx-2-19b-distilled-fp8")
checkpoint_path = download_model_file("ltx-2-19b-distilled-fp8")
# Check and download upsampler for pipelines that need it
if preset.pipeline_type in ["distilled", "ic_lora", "ti2vid_two_stages", "keyframe_interpolation"]:
if not upsampler_path or not Path(upsampler_path).exists():
existing = get_default_upsampler()
if existing:
upsampler_path = existing
else:
# Download spatial upscaler
print("Auto-downloading spatial upscaler")
upsampler_path = download_model_file("ltx-2-spatial-upscaler-x2")
return checkpoint_path, upsampler_path
# ============================================================================
# Pydantic Models for API
# ============================================================================
class ImageInput(BaseModel):
"""Single image input with frame index and strength."""
image_base64: str = Field(..., description="Base64 encoded image")
frame_index: int = Field(default=0, ge=0, description="Frame index where this image applies")
strength: float = Field(default=1.0, ge=0.0, le=1.0, description="Conditioning strength")
class VideoConditioningInput(BaseModel):
"""Video conditioning input for IC-LoRA pipeline."""
video_base64: str = Field(..., description="Base64 encoded video file")
strength: float = Field(default=1.0, ge=0.0, le=1.0, description="Conditioning strength")
class GenerationRequest(BaseModel):
"""Request model for video generation."""
preset_name: Optional[str] = Field(
default=None,
description="Preset name to use. If not provided, uses default preset."
)
# Required generation input
prompt: str = Field(..., description="Prompt for video generation (required)")
negative_prompt: Optional[str] = Field(default="", description="Negative prompt")
# Pipeline settings (override preset values)
pipeline_type: Optional[str] = Field(default=None, description="Override pipeline type")
checkpoint_path: Optional[str] = Field(default=None, description="Override checkpoint path")
spatial_upsampler_path: Optional[str] = Field(default=None, description="Override upsampler path")
distilled_lora_path: Optional[str] = Field(default=None, description="Override distilled LoRA path")
gemma_path: Optional[str] = Field(default=None, description="Override Gemma path")
enable_fp8: Optional[bool] = Field(default=None, description="Override FP8 setting")
# Generation settings (override preset values)
height: Optional[int] = Field(default=None, ge=256, le=2048, description="Override height")
width: Optional[int] = Field(default=None, ge=256, le=2048, description="Override width")
num_frames: Optional[int] = Field(default=None, ge=9, le=257, description="Override frame count")
frame_rate: Optional[float] = Field(default=None, ge=8, le=60, description="Override FPS")
num_inference_steps: Optional[int] = Field(default=None, ge=4, le=100, description="Override steps")
cfg_guidance_scale: Optional[float] = Field(default=None, ge=1.0, le=15.0, description="Override CFG")
seed: Optional[int] = Field(default=None, description="Override seed (-1 for random)")
image_strength: Optional[float] = Field(default=None, ge=0.0, le=1.0, description="Image strength")
# Multiple images support (new format)
images: Optional[List[ImageInput]] = Field(default=None, description="List of image inputs with frame indices")
# Video conditioning for IC-LoRA pipeline
video_conditioning: Optional[List[VideoConditioningInput]] = Field(
default=None,
description="Video conditioning inputs for IC-LoRA (depth maps, pose, edges)"
)
# Legacy single image support (backward compatible)
input_image_base64: Optional[str] = Field(default=None, description="Base64 encoded input image (legacy)")
class PresetCreate(BaseModel):
"""Model for creating/updating a preset (no prompt - that's a generation input)."""
name: str = Field(..., min_length=1, max_length=100)
description: str = Field(default="", max_length=500)
# Pipeline settings
pipeline_type: str = Field(default="distilled")
checkpoint_path: Optional[str] = None
distilled_lora_path: str = Field(default="None")
spatial_upsampler_path: Optional[str] = None
gemma_path: str = Field(default="./models/gemma")
# Generation parameters (NO prompt/negative_prompt - those are generation inputs)
height: int = Field(default=1024, ge=256, le=2048)
width: int = Field(default=1536, ge=256, le=2048)
num_frames: int = Field(default=121, ge=9, le=257)
frame_rate: float = Field(default=24.0, ge=8, le=60)
num_inference_steps: int = Field(default=40, ge=4, le=100)
cfg_guidance_scale: float = Field(default=4.0, ge=1.0, le=15.0)
seed: int = Field(default=-1)
enable_fp8: bool = Field(default=True)
image_strength: float = Field(default=1.0, ge=0.0, le=1.0)
class PresetResponse(BaseModel):
"""Response model for preset data (no prompt - that's a generation input)."""
name: str
description: str
is_default: bool
created_at: str
updated_at: str
pipeline_type: str
height: int
width: int
num_frames: int
frame_rate: float
num_inference_steps: int
cfg_guidance_scale: float
seed: int
enable_fp8: bool
image_strength: float
# Model paths
checkpoint_path: Optional[str] = None
spatial_upsampler_path: Optional[str] = None
distilled_lora_path: Optional[str] = None
gemma_path: Optional[str] = None
class HealthResponse(BaseModel):
"""Health check response."""
status: str
cuda_available: bool
gpu_name: Optional[str]
gpu_memory_gb: Optional[float]
pipeline_loaded: bool
is_generating: bool
# ============================================================================
# Pipeline Manager (handles caching)
# ============================================================================
class PipelineManager:
"""
Manages pipeline loading and caching.
Keeps models in VRAM for faster subsequent generations.
"""
def __init__(self):
self._lock = threading.Lock()
self._is_generating = False
self._current_job_id: Optional[str] = None
self._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 is_pipeline_loaded(self) -> bool:
"""Check if a pipeline is currently cached."""
return self._pipeline_cache["pipeline"] is not None
def is_generating(self) -> bool:
"""Check if currently generating."""
return self._is_generating
def set_generating(self, is_generating: bool, job_id: Optional[str] = None):
"""Set the generating state."""
with self._lock:
self._is_generating = is_generating
self._current_job_id = job_id
def get_cached_pipeline(self, preset: GenerationPreset):
"""Get or create cached pipeline."""
cache = self._pipeline_cache
cache_valid = (
cache["pipeline"] is not None
and cache["pipeline_type"] == preset.pipeline_type
and cache["checkpoint_path"] == preset.checkpoint_path
and cache["spatial_upsampler_path"] == preset.spatial_upsampler_path
and cache["gemma_path"] == preset.gemma_path
and cache["distilled_lora_path"] == preset.distilled_lora_path
and cache["enable_fp8"] == preset.enable_fp8
)
if cache_valid:
return cache["pipeline"], None
# Clear old pipeline
if cache["pipeline"] is not None:
del cache["pipeline"]
cache["pipeline"] = None
torch.cuda.empty_cache()
try:
if preset.pipeline_type == "distilled":
from ltx_pipelines.distilled import DistilledPipeline
if not preset.spatial_upsampler_path or not Path(preset.spatial_upsampler_path).exists():
return None, "Spatial upsampler is required for distilled pipeline."
pipeline = DistilledPipeline(
checkpoint_path=preset.checkpoint_path,
spatial_upsampler_path=preset.spatial_upsampler_path,
gemma_root=preset.gemma_path,
loras=[],
fp8transformer=preset.enable_fp8,
)
elif preset.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 preset.distilled_lora_path or preset.distilled_lora_path == "None":
return None, "Two-Stage Pipeline requires a distilled LoRA."
distilled_lora_list = [
LoraPathStrengthAndSDOps(preset.distilled_lora_path, 1.0, LTXV_LORA_COMFY_RENAMING_MAP)
]
pipeline = TI2VidTwoStagesPipeline(
checkpoint_path=preset.checkpoint_path,
distilled_lora=distilled_lora_list,
spatial_upsampler_path=preset.spatial_upsampler_path if preset.spatial_upsampler_path else None,
gemma_root=preset.gemma_path,
loras=[],
fp8transformer=preset.enable_fp8,
)
elif preset.pipeline_type == "ti2vid_one_stage":
from ltx_pipelines.ti2vid_one_stage import TI2VidOneStagePipeline
pipeline = TI2VidOneStagePipeline(
checkpoint_path=preset.checkpoint_path,
gemma_root=preset.gemma_path,
loras=[],
fp8transformer=preset.enable_fp8,
)
elif preset.pipeline_type == "ic_lora":
from ltx_pipelines.ic_lora import ICLoraPipeline
if not preset.spatial_upsampler_path or not Path(preset.spatial_upsampler_path).exists():
return None, "Spatial upsampler is required for IC-LoRA pipeline."
loras = []
if preset.distilled_lora_path and preset.distilled_lora_path != "None" and Path(preset.distilled_lora_path).exists():
from ltx_core.loader import LoraPathStrengthAndSDOps, LTXV_LORA_COMFY_RENAMING_MAP
loras = [LoraPathStrengthAndSDOps(preset.distilled_lora_path, 1.0, LTXV_LORA_COMFY_RENAMING_MAP)]
pipeline = ICLoraPipeline(
checkpoint_path=preset.checkpoint_path,
spatial_upsampler_path=preset.spatial_upsampler_path,
gemma_root=preset.gemma_path,
loras=loras,
fp8transformer=preset.enable_fp8,
)
elif preset.pipeline_type == "keyframe_interpolation":
from ltx_pipelines.keyframe_interpolation import KeyframeInterpolationPipeline
from ltx_core.loader import LoraPathStrengthAndSDOps, LTXV_LORA_COMFY_RENAMING_MAP
if not preset.distilled_lora_path or preset.distilled_lora_path == "None":
return None, "Keyframe Interpolation Pipeline requires a distilled LoRA."
distilled_lora_list = [
LoraPathStrengthAndSDOps(preset.distilled_lora_path, 1.0, LTXV_LORA_COMFY_RENAMING_MAP)
]
pipeline = KeyframeInterpolationPipeline(
checkpoint_path=preset.checkpoint_path,
distilled_lora=distilled_lora_list,
spatial_upsampler_path=preset.spatial_upsampler_path if preset.spatial_upsampler_path else None,
gemma_root=preset.gemma_path,
loras=[],
fp8transformer=preset.enable_fp8,
)
else:
return None, f"Unknown pipeline type: {preset.pipeline_type}"
# Cache the pipeline
cache["pipeline"] = pipeline
cache["pipeline_type"] = preset.pipeline_type
cache["checkpoint_path"] = preset.checkpoint_path
cache["spatial_upsampler_path"] = preset.spatial_upsampler_path
cache["gemma_path"] = preset.gemma_path
cache["distilled_lora_path"] = preset.distilled_lora_path
cache["enable_fp8"] = preset.enable_fp8
return pipeline, None
except ImportError as e:
return None, f"LTX Pipelines not installed: {e}"
except Exception as e:
import traceback
return None, f"Failed to load pipeline: {e}\n{traceback.format_exc()}"
# ============================================================================
# FastAPI Application
# ============================================================================
# Global pipeline manager
_pipeline_manager: Optional[PipelineManager] = None
@asynccontextmanager
async def lifespan(app: FastAPI):
"""Application lifespan - initialize pipeline manager."""
global _pipeline_manager
# Startup
ensure_directories()
_pipeline_manager = PipelineManager()
print("✅ LTX-2 API started. Streaming generation enabled.")
print(f"📂 Models directory: {MODELS_DIR.absolute()}")
print(f"📂 Outputs directory: {OUTPUTS_DIR.absolute()}")
print(f"🌐 Web UI: http://localhost:8000/")
print(f"📚 API Docs: http://localhost:8000/docs")
yield
# Shutdown
print("🛑 LTX-2 API stopped.")
app = FastAPI(
title="LTX-2 Video Generation API",
description="RESTful API for AI video generation using LTX-2 models",
version="1.0.0",
lifespan=lifespan,
)
# CORS middleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# ============================================================================
# API Endpoints
# ============================================================================
@app.get("/", response_class=HTMLResponse)
async def root():
"""Serve the web UI."""
html_path = TEMPLATES_DIR / "index.html"
if html_path.exists():
with open(html_path, 'r', encoding='utf-8') as f:
return HTMLResponse(content=f.read())
else:
return HTMLResponse(content="""
<html>
<head><title>LTX-2 API</title></head>
<body style="background: #0a0a0f; color: #f0f0f5; font-family: sans-serif; padding: 2rem;">
<h1>🎬 LTX-2 Video Generation API</h1>
<p>Web UI template not found. Please ensure templates/index.html exists.</p>
<p><a href="/docs" style="color: #a855f7;">📚 View API Documentation</a></p>
</body>
</html>
""")
@app.get("/health", response_model=HealthResponse)
async def health_check():
"""Health check endpoint."""
gpu_name = None
gpu_memory = None
if torch.cuda.is_available():
gpu_name = torch.cuda.get_device_name(0)
gpu_memory = round(torch.cuda.get_device_properties(0).total_memory / (1024**3), 2)
pipeline_loaded = _pipeline_manager.is_pipeline_loaded() if _pipeline_manager else False
is_generating = _pipeline_manager.is_generating() if _pipeline_manager else False
return HealthResponse(
status="healthy",
cuda_available=torch.cuda.is_available(),
gpu_name=gpu_name,
gpu_memory_gb=gpu_memory,
pipeline_loaded=pipeline_loaded,
is_generating=is_generating,
)
# ============================================================================
# Model Endpoints
# ============================================================================
@app.get("/models")
async def list_models():
"""List all available models and their download status."""
result = {}
for key, info in CHECKPOINTS.items():
status, path = check_model_status(key)
result[key] = {
"filename": info["filename"],
"size": info["size"],
"description": info["description"],
"type": info["type"],
"status": status,
"path": path,
}
return result
@app.get("/models/{model_key}")
async def get_model_info(model_key: str):
"""Get information about a specific model."""
if model_key not in CHECKPOINTS:
raise HTTPException(status_code=404, detail=f"Model '{model_key}' not found")
info = CHECKPOINTS[model_key]
status, path = check_model_status(model_key)
return {
"key": model_key,
"filename": info["filename"],
"size": info["size"],
"description": info["description"],
"type": info["type"],
"status": status,
"path": path,
}
@app.post("/models/{model_key}/download")
async def download_model(model_key: str, background_tasks: BackgroundTasks):
"""Download a model from HuggingFace."""
if model_key not in CHECKPOINTS:
raise HTTPException(status_code=404, detail=f"Model '{model_key}' not found")
# Check if already downloaded
status, path = check_model_status(model_key)
if status == "ready":
return {"message": f"Model '{model_key}' is already downloaded", "path": path}
try:
# Download synchronously (could be made async with background task for large files)
downloaded_path = download_model_file(model_key)
return {"message": f"Model '{model_key}' downloaded successfully", "path": downloaded_path}
except Exception as e:
raise HTTPException(status_code=500, detail=f"Download failed: {str(e)}")
# ============================================================================
# Generation Endpoints (Streaming Only)
# ============================================================================
@app.post("/generate")
async def generate_video_stream(request: GenerationRequest):
"""
Generate a video with real-time progress streaming via SSE.
This endpoint streams progress updates during generation, eliminating
the need for polling. Events include:
- init: Job initialized with job_id
- stage: Current generation stage (loading models, stage 1, stage 2, encoding)
- step: Denoising step progress within a stage
- complete: Generation finished with download URL
- error: Generation failed with error message
"""
if not _pipeline_manager:
raise HTTPException(status_code=503, detail="Generation service not ready")
# Get preset (optional - if not specified, use default as base for any missing values)
preset_manager = get_preset_manager()
if request.preset_name:
preset = preset_manager.get_preset(request.preset_name)
if not preset:
raise HTTPException(status_code=404, detail=f"Preset '{request.preset_name}' not found")
else:
# Use default preset as base for any missing values
preset = preset_manager.get_default_preset()
# Handle input images (multiple images with frame indices)
image_inputs = [] # List of (path, frame_index, strength)
video_conditioning_inputs = [] # List of (path, strength)
temp_dir = OUTPUTS_DIR / "temp"
temp_dir.mkdir(exist_ok=True)
try:
from PIL import Image
# Handle new multiple images format
if request.images:
for i, img_input in enumerate(request.images):
image_data = base64.b64decode(img_input.image_base64)
image = Image.open(io.BytesIO(image_data))