multimodalart HF Staff commited on
Commit
6d4f737
·
verified ·
1 Parent(s): 4e8c568

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +214 -0
app.py ADDED
@@ -0,0 +1,214 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import subprocess
3
+ import sys
4
+
5
+ # Disable torch.compile / dynamo before any torch import
6
+ os.environ["TORCH_COMPILE_DISABLE"] = "1"
7
+ os.environ["TORCHDYNAMO_DISABLE"] = "1"
8
+
9
+ # Clone LTX-2 repo and install packages
10
+ LTX_REPO_URL = "https://github.com/Lightricks/LTX-2.git"
11
+ LTX_REPO_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "LTX-2")
12
+
13
+ if not os.path.exists(LTX_REPO_DIR):
14
+ print(f"Cloning {LTX_REPO_URL}...")
15
+ subprocess.run(["git", "clone", "--depth", "1", LTX_REPO_URL, LTX_REPO_DIR], check=True)
16
+
17
+ # Install ltx-core and ltx-pipelines if not already installed
18
+ try:
19
+ import ltx_pipelines # noqa: F401
20
+ except ImportError:
21
+ print("Installing ltx-core and ltx-pipelines...")
22
+ subprocess.run(
23
+ [sys.executable, "-m", "pip", "install", "-e",
24
+ os.path.join(LTX_REPO_DIR, "packages", "ltx-core"),
25
+ "-e", os.path.join(LTX_REPO_DIR, "packages", "ltx-pipelines")],
26
+ check=True,
27
+ )
28
+
29
+ sys.path.insert(0, os.path.join(LTX_REPO_DIR, "packages", "ltx-pipelines", "src"))
30
+ sys.path.insert(0, os.path.join(LTX_REPO_DIR, "packages", "ltx-core", "src"))
31
+
32
+ import logging
33
+ import random
34
+ import tempfile
35
+
36
+ import torch
37
+ torch._dynamo.config.suppress_errors = True
38
+ torch._dynamo.config.disable = True
39
+
40
+ import spaces
41
+ import gradio as gr
42
+ import numpy as np
43
+ from huggingface_hub import hf_hub_download, snapshot_download
44
+
45
+ from ltx_core.model.video_vae import TilingConfig, get_video_chunks_number
46
+ from ltx_core.quantization import QuantizationPolicy
47
+ from ltx_pipelines.distilled import DistilledPipeline
48
+ from ltx_pipelines.utils.args import ImageConditioningInput
49
+ from ltx_pipelines.utils.media_io import encode_video
50
+
51
+ logging.getLogger().setLevel(logging.INFO)
52
+
53
+ MAX_SEED = np.iinfo(np.int32).max
54
+ DEFAULT_PROMPT = (
55
+ "An astronaut hatches from a fragile egg on the surface of the Moon, "
56
+ "the shell cracking and peeling apart in gentle low-gravity motion."
57
+ )
58
+ DEFAULT_HEIGHT = 1024
59
+ DEFAULT_WIDTH = 1536
60
+ DEFAULT_FRAME_RATE = 24.0
61
+
62
+ # Download models from Hugging Face
63
+ LTX_MODEL_REPO = "diffusers-internal-dev/ltx-23"
64
+ GEMMA_MODEL_REPO = "google/gemma-3-12b-it-qat-q4_0-unquantized"
65
+
66
+ print("=" * 80)
67
+ print("Downloading models from Hugging Face...")
68
+ print("=" * 80)
69
+
70
+ DISTILLED_CHECKPOINT = hf_hub_download(repo_id=LTX_MODEL_REPO, filename="ltx-2.3-22b-distilled.safetensors")
71
+ SPATIAL_UPSAMPLER = hf_hub_download(repo_id=LTX_MODEL_REPO, filename="ltx-2.3-spatial-upscaler-x2-1.0.safetensors")
72
+ GEMMA_ROOT = snapshot_download(repo_id=GEMMA_MODEL_REPO)
73
+
74
+ print(f"Distilled checkpoint: {DISTILLED_CHECKPOINT}")
75
+ print(f"Spatial upsampler: {SPATIAL_UPSAMPLER}")
76
+ print(f"Gemma root: {GEMMA_ROOT}")
77
+
78
+ # Initialize pipeline
79
+ print("=" * 80)
80
+ print("Loading LTX-2.3 Distilled pipeline...")
81
+ print("=" * 80)
82
+
83
+ pipeline = DistilledPipeline(
84
+ distilled_checkpoint_path=DISTILLED_CHECKPOINT,
85
+ spatial_upsampler_path=SPATIAL_UPSAMPLER,
86
+ gemma_root=GEMMA_ROOT,
87
+ loras=[],
88
+ quantization=QuantizationPolicy.fp8_cast(),
89
+ )
90
+
91
+ # Preload all models so first request is fast.
92
+ # On ZeroGPU, .to('cuda') is intercepted and actual GPU allocation
93
+ # happens inside the @spaces.GPU decorated function.
94
+ print("Preloading models...")
95
+ ledger = pipeline.model_ledger
96
+ _text_encoder = ledger.text_encoder()
97
+ _transformer = ledger.transformer()
98
+ _video_encoder = ledger.video_encoder()
99
+ _video_decoder = ledger.video_decoder()
100
+ _audio_decoder = ledger.audio_decoder()
101
+ _vocoder = ledger.vocoder()
102
+ _spatial_upsampler = ledger.spatial_upsampler()
103
+
104
+ ledger.text_encoder = lambda: _text_encoder
105
+ ledger.transformer = lambda: _transformer
106
+ ledger.video_encoder = lambda: _video_encoder
107
+ ledger.video_decoder = lambda: _video_decoder
108
+ ledger.audio_decoder = lambda: _audio_decoder
109
+ ledger.vocoder = lambda: _vocoder
110
+ ledger.spatial_upsampler = lambda: _spatial_upsampler
111
+
112
+ print("All models preloaded!")
113
+
114
+
115
+ @spaces.GPU(duration=300)
116
+ @torch.inference_mode()
117
+ def generate_video(
118
+ input_image,
119
+ prompt: str,
120
+ duration: float,
121
+ enhance_prompt: bool,
122
+ seed: int,
123
+ randomize_seed: bool,
124
+ height: int,
125
+ width: int,
126
+ progress=gr.Progress(track_tqdm=True),
127
+ ):
128
+ current_seed = random.randint(0, MAX_SEED) if randomize_seed else int(seed)
129
+ num_frames = int(duration * DEFAULT_FRAME_RATE) + 1
130
+ num_frames = ((num_frames - 1 + 7) // 8) * 8 + 1
131
+
132
+ images = []
133
+ if input_image is not None:
134
+ with tempfile.NamedTemporaryFile(suffix=".jpg", delete=False) as f:
135
+ temp_path = f.name
136
+ if hasattr(input_image, "save"):
137
+ input_image.save(temp_path)
138
+ else:
139
+ from shutil import copy2
140
+ copy2(str(input_image), temp_path)
141
+ images = [ImageConditioningInput(path=temp_path, frame_idx=0, strength=1.0)]
142
+
143
+ tiling_config = TilingConfig.default()
144
+ video_chunks_number = get_video_chunks_number(num_frames, tiling_config)
145
+
146
+ video, audio = pipeline(
147
+ prompt=prompt,
148
+ seed=current_seed,
149
+ height=int(height),
150
+ width=int(width),
151
+ num_frames=num_frames,
152
+ frame_rate=DEFAULT_FRAME_RATE,
153
+ images=images,
154
+ tiling_config=tiling_config,
155
+ enhance_prompt=enhance_prompt,
156
+ )
157
+
158
+ output_path = tempfile.mktemp(suffix=".mp4")
159
+ encode_video(
160
+ video=video,
161
+ fps=DEFAULT_FRAME_RATE,
162
+ audio=audio,
163
+ output_path=output_path,
164
+ video_chunks_number=video_chunks_number,
165
+ )
166
+
167
+ return output_path, current_seed
168
+
169
+
170
+ with gr.Blocks(title="LTX-2.3 Distilled") as demo:
171
+ gr.Markdown("# LTX-2.3 Distilled (22B): Fast Audio-Video Generation")
172
+ gr.Markdown(
173
+ "Fast video + audio generation using the distilled model (8 steps stage 1, 4 steps stage 2). "
174
+ "[[model]](https://huggingface.co/Lightricks/LTX-2) "
175
+ "[[code]](https://github.com/Lightricks/LTX-2)"
176
+ )
177
+
178
+ with gr.Row():
179
+ with gr.Column():
180
+ input_image = gr.Image(label="Input Image (Optional)", type="pil")
181
+ prompt = gr.Textbox(
182
+ label="Prompt",
183
+ value=DEFAULT_PROMPT,
184
+ lines=3,
185
+ placeholder="Describe the video you want to generate...",
186
+ )
187
+ with gr.Row():
188
+ duration = gr.Slider(label="Duration (seconds)", minimum=1.0, maximum=10.0, value=5.0, step=0.5)
189
+ enhance_prompt = gr.Checkbox(label="Enhance Prompt", value=True)
190
+
191
+ generate_btn = gr.Button("Generate Video", variant="primary")
192
+
193
+ with gr.Accordion("Advanced Settings", open=False):
194
+ seed = gr.Slider(label="Seed", minimum=0, maximum=MAX_SEED, value=10, step=1)
195
+ randomize_seed = gr.Checkbox(label="Randomize Seed", value=True)
196
+ with gr.Row():
197
+ width = gr.Number(label="Width", value=DEFAULT_WIDTH, precision=0)
198
+ height = gr.Number(label="Height", value=DEFAULT_HEIGHT, precision=0)
199
+
200
+ with gr.Column():
201
+ output_video = gr.Video(label="Generated Video", autoplay=True)
202
+
203
+ generate_btn.click(
204
+ fn=generate_video,
205
+ inputs=[
206
+ input_image, prompt, duration, enhance_prompt,
207
+ seed, randomize_seed, height, width,
208
+ ],
209
+ outputs=[output_video, seed],
210
+ )
211
+
212
+
213
+ if __name__ == "__main__":
214
+ demo.launch(share=True)