Fabrice-TIERCELIN commited on
Commit
5534554
·
verified ·
1 Parent(s): 8519d3d

Upload 16 files

Browse files
Files changed (12) hide show
  1. .gitattributes +8 -0
  2. README.md +7 -8
  3. app.py +2326 -299
  4. astronaut.png +3 -0
  5. clay.png +3 -0
  6. highland.png +3 -0
  7. paint.png +3 -0
  8. requirements.txt +19 -3
  9. supergirl-2.png +3 -0
  10. supergirl.m4a +3 -0
  11. supergirl.png +3 -0
  12. tiktok.mp4 +3 -0
.gitattributes CHANGED
@@ -75,3 +75,11 @@ astronaut.jpg filter=lfs diff=lfs merge=lfs -text
75
  cat_selfie.JPG filter=lfs diff=lfs merge=lfs -text
76
  kill_bill.jpeg filter=lfs diff=lfs merge=lfs -text
77
  wednesday.png filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
75
  cat_selfie.JPG filter=lfs diff=lfs merge=lfs -text
76
  kill_bill.jpeg filter=lfs diff=lfs merge=lfs -text
77
  wednesday.png filter=lfs diff=lfs merge=lfs -text
78
+ astronaut.png filter=lfs diff=lfs merge=lfs -text
79
+ clay.png filter=lfs diff=lfs merge=lfs -text
80
+ highland.png filter=lfs diff=lfs merge=lfs -text
81
+ paint.png filter=lfs diff=lfs merge=lfs -text
82
+ supergirl-2.png filter=lfs diff=lfs merge=lfs -text
83
+ supergirl.m4a filter=lfs diff=lfs merge=lfs -text
84
+ supergirl.png filter=lfs diff=lfs merge=lfs -text
85
+ tiktok.mp4 filter=lfs diff=lfs merge=lfs -text
README.md CHANGED
@@ -1,14 +1,13 @@
1
  ---
2
- title: FLUX.1 Kontext
3
- emoji:
4
- colorFrom: green
5
- colorTo: gray
6
  sdk: gradio
7
- sdk_version: 5.29.1
8
  app_file: app.py
9
- pinned: true
10
- license: mit
11
- short_description: 'Kontext image editing on FLUX[dev] '
12
  ---
13
 
14
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
  ---
2
+ title: LTX-2 Video [Turbo]
3
+ emoji: 🔥
4
+ colorFrom: yellow
5
+ colorTo: yellow
6
  sdk: gradio
7
+ sdk_version: 6.2.0
8
  app_file: app.py
9
+ pinned: false
10
+ short_description: Fast high quality video with audio generation with FA3
 
11
  ---
12
 
13
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py CHANGED
@@ -1,299 +1,2326 @@
1
- # PyTorch 2.8 (temporary hack)
2
- import os
3
- os.system('pip install --upgrade --pre --extra-index-url https://download.pytorch.org/whl/nightly/cu126 "torch<2.9" spaces')
4
-
5
- # Actual demo code
6
- try:
7
- import spaces
8
- except:
9
- class spaces():
10
- def GPU(*args, **kwargs):
11
- def decorator(function):
12
- return lambda *dummy_args, **dummy_kwargs: function(*dummy_args, **dummy_kwargs)
13
- return decorator
14
-
15
- import gradio as gr
16
- import numpy as np
17
- import torch
18
- import random
19
- import os
20
- from datetime import datetime
21
-
22
- from PIL import Image
23
- import tempfile
24
- import zipfile
25
- import shutil
26
- from pathlib import Path
27
-
28
- from diffusers import FluxKontextPipeline
29
- from diffusers.utils import load_image
30
-
31
- from optimization import optimize_pipeline_
32
-
33
- MAX_SEED = np.iinfo(np.int32).max
34
-
35
- pipe = FluxKontextPipeline.from_pretrained("yuvraj108c/FLUX.1-Kontext-dev", torch_dtype=torch.bfloat16).to("cuda")
36
- optimize_pipeline_(pipe, image=Image.new("RGB", (512, 512)), prompt='prompt')
37
-
38
- input_image_debug_value = [None]
39
- prompt_debug_value = [None]
40
- number_debug_value = [None]
41
- def save_on_path(img: Image, filename: str, format_: str = None) -> Path:
42
- """
43
- Save `img` in a unique temporary folder under the given `filename`
44
- and return its absolute path.
45
- """
46
- # 1) unique temporary folder
47
- tmp_dir = Path(tempfile.mkdtemp(prefix="pil_tmp_"))
48
-
49
- # 2) full path of the future file
50
- file_path = tmp_dir / filename
51
-
52
- # 3) save
53
- img.save(file_path, format=format_ or img.format)
54
-
55
- return file_path
56
-
57
- @spaces.GPU(duration=40)
58
- def infer(
59
- input_image,
60
- prompt,
61
- seed = 42,
62
- randomize_seed = False,
63
- guidance_scale = 2.5,
64
- steps = 28,
65
- width = -1,
66
- height = -1,
67
- progress=gr.Progress(track_tqdm=True)
68
- ):
69
- """
70
- Perform image editing using the FLUX.1 Kontext pipeline.
71
-
72
- This function takes an input image and a text prompt to generate a modified version
73
- of the image based on the provided instructions. It uses the FLUX.1 Kontext model
74
- for contextual image editing tasks.
75
-
76
- Args:
77
- input_image (PIL.Image.Image): The input image to be edited. Will be converted
78
- to RGB format if not already in that format.
79
- prompt (str): Text description of the desired edit to apply to the image.
80
- Examples: "Remove glasses", "Add a hat", "Change background to beach".
81
- seed (int, optional): Random seed for reproducible generation. Defaults to 42.
82
- Must be between 0 and MAX_SEED (2^31 - 1).
83
- randomize_seed (bool, optional): If True, generates a random seed instead of
84
- using the provided seed value. Defaults to False.
85
- guidance_scale (float, optional): Controls how closely the model follows the
86
- prompt. Higher values mean stronger adherence to the prompt but may reduce
87
- image quality. Range: 1.0-10.0. Defaults to 2.5.
88
- steps (int, optional): Controls how many steps to run the diffusion model for.
89
- Range: 1-30. Defaults to 28.
90
- progress (gr.Progress, optional): Gradio progress tracker for monitoring
91
- generation progress. Defaults to gr.Progress(track_tqdm=True).
92
-
93
- Returns:
94
- tuple: A 3-tuple containing:
95
- - PIL.Image.Image: The generated/edited image
96
- - int: The seed value used for generation (useful when randomize_seed=True)
97
- - gr.update: Gradio update object to make the reuse button visible
98
-
99
- Example:
100
- >>> edited_image, used_seed, button_update = infer(
101
- ... input_image=my_image,
102
- ... prompt="Add sunglasses",
103
- ... seed=123,
104
- ... randomize_seed=False,
105
- ... guidance_scale=2.5
106
- ... )
107
- """
108
- if randomize_seed:
109
- seed = random.randint(0, MAX_SEED)
110
-
111
- if input_image:
112
- input_image = input_image.convert("RGB")
113
- image = pipe(
114
- image=input_image,
115
- prompt=prompt,
116
- guidance_scale=guidance_scale,
117
- width = input_image.size[0] if width == -1 else width,
118
- height = input_image.size[1] if height == -1 else height,
119
- num_inference_steps=steps,
120
- generator=torch.Generator().manual_seed(seed),
121
- ).images[0]
122
- else:
123
- image = pipe(
124
- prompt=prompt,
125
- guidance_scale=guidance_scale,
126
- num_inference_steps=steps,
127
- generator=torch.Generator().manual_seed(seed),
128
- ).images[0]
129
-
130
- image_filename = datetime.now().strftime("%Y-%m-%d_%H-%M-%S.%f") + '.webp'
131
- path = save_on_path(image, image_filename, format_="WEBP")
132
- return path, gr.update(value=path, visible=True), seed, gr.update(visible=True)
133
-
134
- def infer_example(input_image, prompt):
135
- number=1
136
- if input_image_debug_value[0] is not None or prompt_debug_value[0] is not None or number_debug_value[0] is not None:
137
- input_image=input_image_debug_value[0]
138
- prompt=prompt_debug_value[0]
139
- number=number_debug_value[0]
140
- #input_image_debug_value[0]=prompt_debug_value[0]=prompt_debug_value[0]=None
141
- gallery = []
142
- for i in range(number):
143
- try:
144
- print("Generating #" + str(i + 1) + " image...")
145
- seed = random.randint(0, MAX_SEED)
146
- image, download_button, seed, _ = infer(input_image, prompt, seed, True)
147
- gallery.append(image)
148
- except:
149
- print("Error")
150
- zip_path = export_images_to_zip(gallery)
151
- return gallery, seed, zip_path
152
-
153
- def export_images_to_zip(gallery) -> str:
154
- """
155
- Bundle compiled_transformer_1 and compiled_transformer_2 into a zip file and return the file path.
156
- """
157
-
158
- tmp_zip = tempfile.NamedTemporaryFile(suffix=".zip", delete=False)
159
- tmp_zip.close()
160
-
161
- with zipfile.ZipFile(tmp_zip.name, "w", compression=zipfile.ZIP_DEFLATED) as zf:
162
- for i in range(len(gallery)):
163
- image_path = gallery[i]
164
- zf.write(image_path, arcname=os.path.basename(image_path))
165
-
166
- print(str(len(gallery)) + " images zipped")
167
- return tmp_zip.name
168
-
169
- css="""
170
- #col-container {
171
- margin: 0 auto;
172
- max-width: 960px;
173
- }
174
- """
175
-
176
- with gr.Blocks(css=css) as demo:
177
-
178
- with gr.Column(elem_id="col-container"):
179
- gr.Markdown(f"""# FLUX.1 Kontext [dev]
180
- Image editing and manipulation model guidance-distilled from FLUX.1 Kontext [pro], [[blog]](https://bfl.ai/announcements/flux-1-kontext-dev) [[model]](https://huggingface.co/black-forest-labs/FLUX.1-Kontext-dev)
181
- """)
182
- with gr.Row():
183
- with gr.Column():
184
- input_image = gr.Image(label="Upload the image for editing", type="pil")
185
- with gr.Row():
186
- prompt = gr.Text(
187
- label="Prompt",
188
- show_label=False,
189
- max_lines=1,
190
- placeholder="Enter your prompt for editing (e.g., 'Remove glasses', 'Add a hat')",
191
- container=False,
192
- )
193
- run_button = gr.Button(value="🚀 Edit", variant = "primary", scale=0)
194
- with gr.Accordion("Advanced Settings", open=False):
195
-
196
- seed = gr.Slider(
197
- label="Seed",
198
- minimum=0,
199
- maximum=MAX_SEED,
200
- step=1,
201
- value=0,
202
- )
203
-
204
- randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
205
-
206
- guidance_scale = gr.Slider(
207
- label="Guidance Scale",
208
- minimum=1,
209
- maximum=10,
210
- step=0.1,
211
- value=2.5,
212
- )
213
-
214
- steps = gr.Slider(
215
- label="Steps",
216
- minimum=1,
217
- maximum=30,
218
- value=30,
219
- step=1
220
- )
221
-
222
- width = gr.Slider(
223
- label="Output width",
224
- info="-1 = original width",
225
- minimum=-1,
226
- maximum=1024,
227
- value=-1,
228
- step=1
229
- )
230
-
231
- height = gr.Slider(
232
- label="Output height",
233
- info="-1 = original height",
234
- minimum=-1,
235
- maximum=1024,
236
- value=-1,
237
- step=1
238
- )
239
-
240
- with gr.Column():
241
- result = gr.Image(label="Result", show_label=False, interactive=False)
242
- download_button = gr.DownloadButton(elem_id="download_btn", visible=False)
243
- reuse_button = gr.Button("Reuse this image", visible=False)
244
-
245
- with gr.Row(visible=False):
246
- download_button = gr.DownloadButton(elem_id="download_btn", interactive = True)
247
- result_gallery = gr.Gallery(interactive = False, elem_id = "gallery1")
248
- gr.Examples(
249
- examples=[
250
- ["monster.png", "Make this monster ride a skateboard on the beach"]
251
- ],
252
- inputs=[input_image, prompt],
253
- outputs=[result_gallery, seed, download_button],
254
- fn=infer_example,
255
- run_on_click=True,
256
- cache_examples=True,
257
- cache_mode='lazy'
258
- )
259
- prompt_debug=gr.Textbox()
260
- input_image_debug=gr.Image(type="pil")
261
- number_debug=gr.Slider(minimum=1, maximum=50, step=1, value=50)
262
-
263
- gr.Examples(
264
- label = "Examples from demo",
265
- examples=[
266
- ["flowers.png", "turn the flowers into sunflowers"],
267
- ["monster.png", "make this monster ride a skateboard on the beach"],
268
- ["cat.png", "make this cat happy"]
269
- ],
270
- inputs=[input_image, prompt],
271
- outputs=[result, download_button, seed],
272
- fn=infer
273
- )
274
-
275
- def handle_field_debug_change(input_image_debug_data, prompt_debug_data, number_debug_data):
276
- prompt_debug_value[0] = prompt_debug_data
277
- input_image_debug_value[0] = input_image_debug_data
278
- number_debug_value[0] = number_debug_data
279
- return []
280
-
281
- inputs_debug=[input_image_debug, prompt_debug, number_debug]
282
-
283
- input_image_debug.upload(fn=handle_field_debug_change, inputs=inputs_debug, outputs=[])
284
- prompt_debug.change(fn=handle_field_debug_change, inputs=inputs_debug, outputs=[])
285
- number_debug.change(fn=handle_field_debug_change, inputs=inputs_debug, outputs=[])
286
-
287
- gr.on(
288
- triggers=[run_button.click, prompt.submit],
289
- fn = infer,
290
- inputs = [input_image, prompt, seed, randomize_seed, guidance_scale, steps, width, height],
291
- outputs = [result, download_button, seed, reuse_button]
292
- )
293
- reuse_button.click(
294
- fn = lambda image: image,
295
- inputs = [result],
296
- outputs = [input_image]
297
- )
298
-
299
- demo.launch(mcp_server=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ from pathlib import Path
3
+ import uuid
4
+ import tempfile
5
+ import subprocess
6
+ import torch
7
+ import torch.nn.functional as F
8
+ import torchaudio
9
+ import os
10
+ from typing import Any
11
+ import time
12
+ from contextlib import contextmanager
13
+
14
+ @contextmanager
15
+ def timer(name: str):
16
+ start = time.time()
17
+ print(f"{name}...")
18
+ yield
19
+ print(f" -> {name} completed in {time.time() - start:.2f} sec")
20
+
21
+ def _coerce_audio_path(audio_path: Any) -> str:
22
+ # Common Gradio case: tuple where first item is the filepath
23
+ if isinstance(audio_path, tuple) and len(audio_path) > 0:
24
+ audio_path = audio_path[0]
25
+
26
+ # Some gradio versions pass a dict-like object
27
+ if isinstance(audio_path, dict):
28
+ # common keys: "name", "path"
29
+ audio_path = audio_path.get("name") or audio_path.get("path")
30
+
31
+ # pathlib.Path etc.
32
+ if not isinstance(audio_path, (str, bytes, os.PathLike)):
33
+ raise TypeError(f"audio_path must be a path-like, got {type(audio_path)}: {audio_path}")
34
+
35
+ return os.fspath(audio_path)
36
+
37
+ def extract_audio_wav_ffmpeg(video_path: str, target_sr: int = 48000) -> str | None:
38
+ """
39
+ Extract audio from a video into a temp WAV (mono, target_sr).
40
+ Returns path, or None if the video has no audio stream.
41
+ """
42
+ out_path = tempfile.NamedTemporaryFile(suffix=".wav", delete=False).name
43
+
44
+ # Check if there's an audio stream
45
+ probe_cmd = [
46
+ "ffprobe", "-v", "error",
47
+ "-select_streams", "a:0",
48
+ "-show_entries", "stream=codec_type",
49
+ "-of", "default=nw=1:nk=1",
50
+ video_path,
51
+ ]
52
+ try:
53
+ out = subprocess.check_output(probe_cmd).decode("utf-8").strip()
54
+ if not out:
55
+ return None
56
+ except subprocess.CalledProcessError:
57
+ return None
58
+
59
+ # Extract + resample + mono
60
+ cmd = [
61
+ "ffmpeg", "-y", "-v", "error",
62
+ "-i", video_path,
63
+ "-vn",
64
+ "-ac", "1",
65
+ "-ar", str(int(target_sr)),
66
+ "-c:a", "pcm_s16le",
67
+ out_path
68
+ ]
69
+ subprocess.check_call(cmd)
70
+ return out_path
71
+
72
+
73
+
74
+ def match_audio_to_duration(
75
+ audio_path: str,
76
+ target_seconds: float,
77
+ target_sr: int = 48000,
78
+ to_mono: bool = True,
79
+ pad_mode: str = "silence", # "silence" | "repeat"
80
+ device: str = "cuda",
81
+ ):
82
+ """
83
+ Load audio, resample, (optionally) mono, then trim/pad to exactly target_seconds.
84
+ Returns: (waveform[T] or [1,T], sr)
85
+ """
86
+ audio_path = _coerce_audio_path(audio_path)
87
+
88
+ wav, sr = torchaudio.load(audio_path) # [C, T] float32 CPU
89
+
90
+ # Resample to target_sr (recommended so duration math is stable)
91
+ if sr != target_sr:
92
+ wav = torchaudio.functional.resample(wav, sr, target_sr)
93
+ sr = target_sr
94
+
95
+ # Mono (common expectation; if your model supports stereo, set to_mono=False)
96
+ if to_mono and wav.shape[0] > 1:
97
+ wav = wav.mean(dim=0, keepdim=True) # [1, T]
98
+
99
+ # Exact target length in samples
100
+ target_len = int(round(target_seconds * sr))
101
+ cur_len = wav.shape[-1]
102
+
103
+ if cur_len > target_len:
104
+ wav = wav[..., :target_len]
105
+ elif cur_len < target_len:
106
+ pad_len = target_len - cur_len
107
+ if pad_mode == "repeat" and cur_len > 0:
108
+ # Repeat then cut to exact length
109
+ reps = (target_len + cur_len - 1) // cur_len
110
+ wav = wav.repeat(1, reps)[..., :target_len]
111
+ else:
112
+ # Silence pad
113
+ wav = F.pad(wav, (0, pad_len))
114
+
115
+ # move to device
116
+ wav = wav.to(device, non_blocking=True)
117
+ return wav, sr
118
+
119
+
120
+ def sh(cmd): subprocess.check_call(cmd, shell=True)
121
+
122
+ # Add packages to Python path
123
+ current_dir = Path(__file__).parent
124
+ sys.path.insert(0, str(current_dir / "packages" / "ltx-pipelines" / "src"))
125
+ sys.path.insert(0, str(current_dir / "packages" / "ltx-core" / "src"))
126
+
127
+ import spaces
128
+ import flash_attn_interface
129
+ import time
130
+ import gradio as gr
131
+ import numpy as np
132
+ import random
133
+ import torch
134
+ from typing import Optional
135
+ from pathlib import Path
136
+ import torchaudio
137
+ from huggingface_hub import hf_hub_download, snapshot_download
138
+ from ltx_pipelines.distilled import DistilledPipeline
139
+ from ltx_core.model.video_vae import TilingConfig
140
+ from ltx_core.model.audio_vae.ops import AudioProcessor
141
+ from ltx_core.loader.primitives import LoraPathStrengthAndSDOps
142
+ from ltx_core.loader.sd_ops import LTXV_LORA_COMFY_RENAMING_MAP
143
+ from ltx_pipelines.utils.constants import (
144
+ DEFAULT_SEED,
145
+ DEFAULT_1_STAGE_HEIGHT,
146
+ DEFAULT_1_STAGE_WIDTH ,
147
+ DEFAULT_NUM_FRAMES,
148
+ DEFAULT_FRAME_RATE,
149
+ DEFAULT_LORA_STRENGTH,
150
+ )
151
+ from ltx_core.loader.single_gpu_model_builder import enable_only_lora
152
+ from ltx_core.model.audio_vae import decode_audio
153
+ from ltx_core.model.audio_vae import encode_audio
154
+ from PIL import Image
155
+
156
+ MAX_SEED = np.iinfo(np.int32).max
157
+ # Import from public LTX-2 package
158
+ # Install with: pip install git+https://github.com/Lightricks/LTX-2.git
159
+ from ltx_pipelines.utils import ModelLedger
160
+ from ltx_pipelines.utils.helpers import generate_enhanced_prompt
161
+ import imageio
162
+ import cv2
163
+ from controlnet_aux import CannyDetector, MidasDetector
164
+ from dwpose import DwposeDetector
165
+
166
+
167
+ # HuggingFace Hub defaults
168
+ DEFAULT_REPO_ID = "Lightricks/LTX-2"
169
+ DEFAULT_GEMMA_REPO_ID = "unsloth/gemma-3-12b-it-qat-bnb-4bit"
170
+ DEFAULT_CHECKPOINT_FILENAME = "ltx-2-19b-dev.safetensors"
171
+
172
+
173
+ def get_hub_or_local_checkpoint(repo_id: str, filename: str):
174
+ """Download from HuggingFace Hub."""
175
+ print(f"Downloading {filename} from {repo_id}...")
176
+ ckpt_path = hf_hub_download(repo_id=repo_id, filename=filename)
177
+ print(f"Downloaded to {ckpt_path}")
178
+ return ckpt_path
179
+
180
+ def download_gemma_model(repo_id: str):
181
+ """Download the full Gemma model directory."""
182
+ print(f"Downloading Gemma model from {repo_id}...")
183
+ local_dir = snapshot_download(repo_id=repo_id)
184
+ print(f"Gemma model downloaded to {local_dir}")
185
+ return local_dir
186
+
187
+ # Initialize model ledger and text encoder at startup (load once, keep in memory)
188
+ print("=" * 80)
189
+ print("Loading Gemma Text Encoder...")
190
+ print("=" * 80)
191
+
192
+ checkpoint_path = get_hub_or_local_checkpoint(DEFAULT_REPO_ID, DEFAULT_CHECKPOINT_FILENAME)
193
+ gemma_local_path = download_gemma_model(DEFAULT_GEMMA_REPO_ID)
194
+ device = "cuda"
195
+
196
+ print(f"Initializing text encoder with:")
197
+ print(f" checkpoint_path={checkpoint_path}")
198
+ print(f" gemma_root={gemma_local_path}")
199
+ print(f" device={device}")
200
+
201
+
202
+ model_ledger = ModelLedger(
203
+ dtype=torch.bfloat16,
204
+ device=device,
205
+ checkpoint_path=checkpoint_path,
206
+ gemma_root_path=DEFAULT_GEMMA_REPO_ID,
207
+ local_files_only=False
208
+ )
209
+
210
+ canny_processor = CannyDetector()
211
+ # Depth (MiDaS) processor
212
+ # Downloads annotator weights automatically the first time.
213
+ depth_processor = MidasDetector.from_pretrained("lllyasviel/Annotators").to("cuda")
214
+
215
+
216
+ # Load text encoder once and keep it in memory
217
+ text_encoder = model_ledger.text_encoder()
218
+
219
+ print("=" * 80)
220
+ print("Text encoder loaded and ready!")
221
+ print("=" * 80)
222
+
223
+ def on_lora_change(selected: str):
224
+ needs_video = selected in {"Pose", "Canny", "Detailer"}
225
+ return (
226
+ selected,
227
+ gr.update(visible=not needs_video, value=None if needs_video else None),
228
+ gr.update(visible=needs_video, value=None if not needs_video else None),
229
+ )
230
+
231
+
232
+ def process_video_for_pose(frames, width: int, height: int):
233
+
234
+ pose_processor = DwposeDetector.from_pretrained_default()
235
+
236
+ if not frames:
237
+ return []
238
+
239
+ pose_frames = []
240
+ for frame in frames:
241
+ # imageio frame -> PIL
242
+ pil = Image.fromarray(frame.astype(np.uint8)).convert("RGB")
243
+
244
+ # ✅ do NOT pass width/height here (easy_dwpose will handle drawing sizes internally)
245
+ pose_img = pose_processor(pil, include_body=True, include_hand=True, include_face=True)
246
+
247
+ # Ensure it's PIL then resize to your conditioning size
248
+ if not isinstance(pose_img, Image.Image):
249
+ # some versions might return np array
250
+ pose_img = Image.fromarray(pose_img.astype(np.uint8))
251
+
252
+ pose_img = pose_img.convert("RGB").resize((width, height), Image.BILINEAR)
253
+
254
+ pose_np = np.array(pose_img).astype(np.float32) / 255.0
255
+ pose_frames.append(pose_np)
256
+
257
+ return pose_frames
258
+
259
+
260
+ def preprocess_video_to_pose_mp4(video_path: str, width: int, height: int, fps: float):
261
+ frames = load_video_frames(video_path)
262
+ pose_frames = process_video_for_pose(frames, width=width, height=height)
263
+ tmp = tempfile.NamedTemporaryFile(suffix=".mp4", delete=False)
264
+ tmp.close()
265
+ return write_video_mp4(pose_frames, fps=fps, out_path=tmp.name)
266
+
267
+ def process_video_for_depth(frames, width: int, height: int):
268
+ """
269
+ Convert RGB frames -> depth map frames.
270
+ Returns list of np arrays (H,W,3) float in [0..1] (controlnet-style).
271
+ """
272
+ if not frames:
273
+ return []
274
+
275
+ detect_resolution = max(frames[0].shape[0], frames[0].shape[1])
276
+ image_resolution = max(width, height)
277
+
278
+ depth_frames = []
279
+ for frame in frames:
280
+ # controlnet_aux MidasDetector returns float [0..1] when output_type="np"
281
+ depth = depth_processor(
282
+ frame,
283
+ detect_resolution=detect_resolution,
284
+ image_resolution=image_resolution,
285
+ output_type="np",
286
+ )
287
+
288
+ # Safety: ensure HWC and 3 channels (some versions may output 1ch)
289
+ if depth.ndim == 2:
290
+ depth = np.stack([depth, depth, depth], axis=-1)
291
+ elif depth.shape[-1] == 1:
292
+ depth = np.repeat(depth, 3, axis=-1)
293
+
294
+ depth_frames.append(depth)
295
+
296
+ return depth_frames
297
+
298
+
299
+ def preprocess_video_to_depth_mp4(video_path: str, width: int, height: int, fps: float):
300
+ """End-to-end: read video -> depth -> write temp mp4 -> return path."""
301
+ frames = load_video_frames(video_path)
302
+ depth_frames = process_video_for_depth(frames, width=width, height=height)
303
+ tmp = tempfile.NamedTemporaryFile(suffix=".mp4", delete=False)
304
+ tmp.close()
305
+ return write_video_mp4(depth_frames, fps=fps, out_path=tmp.name)
306
+
307
+
308
+ def load_video_frames(video_path: str):
309
+ """Return list of frames as numpy arrays (H,W,3) uint8."""
310
+ frames = []
311
+ with imageio.get_reader(video_path) as reader:
312
+ for frame in reader:
313
+ frames.append(frame)
314
+ return frames
315
+
316
+
317
+ def process_video_for_canny(frames, width: int, height: int,
318
+ low_threshold=20, high_threshold=60):
319
+ """
320
+ Convert RGB frames -> canny edge frames.
321
+ Returns list of np arrays (H,W,3) in float [0..1] (like controlnet_aux output).
322
+ """
323
+ if not frames:
324
+ return []
325
+
326
+ detect_resolution = max(frames[0].shape[0], frames[0].shape[1])
327
+ image_resolution = max(width, height)
328
+
329
+ canny_frames = []
330
+ for frame in frames:
331
+ # controlnet_aux CannyDetector returns float image in [0..1] if output_type="np"
332
+ # frame_blur = cv2.GaussianBlur(frame, (3, 3), 0)
333
+
334
+ canny = canny_processor(
335
+ frame,
336
+ low_threshold=low_threshold,
337
+ high_threshold=high_threshold,
338
+ detect_resolution=detect_resolution,
339
+ image_resolution=image_resolution,
340
+ output_type="np",
341
+ )
342
+ canny_frames.append(canny)
343
+
344
+ return canny_frames
345
+
346
+
347
+ def write_video_mp4(frames_float_01, fps: float, out_path: str):
348
+ """Write frames in float [0..1] to mp4 as uint8."""
349
+ frames_uint8 = [(f * 255).astype(np.uint8) for f in frames_float_01]
350
+
351
+ # PyAV backend doesn't support `quality=...`
352
+ with imageio.get_writer(out_path, fps=fps, macro_block_size=1) as writer:
353
+ for fr in frames_uint8:
354
+ writer.append_data(fr)
355
+ return out_path
356
+
357
+
358
+
359
+ def preprocess_video_to_canny_mp4(video_path: str, width: int, height: int, fps: float):
360
+ """End-to-end: read video -> canny -> write temp mp4 -> return path."""
361
+ frames = load_video_frames(video_path)
362
+ canny_frames = process_video_for_canny(frames, width=width, height=height)
363
+ tmp = tempfile.NamedTemporaryFile(suffix=".mp4", delete=False)
364
+ tmp.close()
365
+ return write_video_mp4(canny_frames, fps=fps, out_path=tmp.name)
366
+
367
+ import json
368
+
369
+ def probe_video_duration_seconds(video_path: str) -> float:
370
+ """Return duration in seconds using ffprobe."""
371
+ cmd = [
372
+ "ffprobe", "-v", "error",
373
+ "-select_streams", "v:0",
374
+ "-show_entries", "format=duration",
375
+ "-of", "json",
376
+ video_path,
377
+ ]
378
+ out = subprocess.check_output(cmd).decode("utf-8")
379
+ data = json.loads(out)
380
+ dur = float(data["format"]["duration"])
381
+ return dur
382
+
383
+ def trim_video_to_seconds_ffmpeg(video_path: str, target_seconds: float, fps: float = None) -> str:
384
+ """
385
+ Trim video to [0, target_seconds]. Re-encode for accuracy & compatibility.
386
+ If fps is provided, also normalize fps.
387
+ Returns new temp mp4 path.
388
+ """
389
+ target_seconds = max(0.01, float(target_seconds))
390
+
391
+ out_path = tempfile.NamedTemporaryFile(suffix=".mp4", delete=False).name
392
+
393
+ vf = []
394
+ if fps is not None:
395
+ vf.append(f"fps={float(fps)}")
396
+ vf_str = ",".join(vf) if vf else None
397
+
398
+ cmd = ["ffmpeg", "-y", "-v", "error"]
399
+
400
+ # Accurate trim: use -t and re-encode.
401
+ cmd += ["-i", video_path, "-t", f"{target_seconds:.6f}"]
402
+
403
+ if vf_str:
404
+ cmd += ["-vf", vf_str]
405
+
406
+ # Safe default encode
407
+ cmd += [
408
+ "-c:v", "libx264", "-pix_fmt", "yuv420p", "-preset", "veryfast", "-crf", "18",
409
+ "-an", # conditioning video doesn't need audio
410
+ out_path
411
+ ]
412
+
413
+ subprocess.check_call(cmd)
414
+ return out_path
415
+
416
+ def extract_first_frame_png(video_path: str) -> str:
417
+ """Extract first frame as png; returns png path."""
418
+ out_path = tempfile.NamedTemporaryFile(suffix=".png", delete=False).name
419
+ cmd = [
420
+ "ffmpeg", "-y", "-v", "error",
421
+ "-i", video_path,
422
+ "-frames:v", "1",
423
+ out_path
424
+ ]
425
+ subprocess.check_call(cmd)
426
+ return out_path
427
+
428
+ def _coerce_video_path(video_path: Any) -> str:
429
+ if isinstance(video_path, tuple) and len(video_path) > 0:
430
+ video_path = video_path[0]
431
+ if isinstance(video_path, dict):
432
+ video_path = video_path.get("name") or video_path.get("path")
433
+ if not isinstance(video_path, (str, bytes, os.PathLike)):
434
+ raise TypeError(f"video_path must be a path-like, got {type(video_path)}: {video_path}")
435
+ return os.fspath(video_path)
436
+
437
+
438
+ def prepare_conditioning_video_mp4(
439
+ video_path: Any,
440
+ target_num_frames: int,
441
+ target_fps: float,
442
+ ) -> tuple[str, str]:
443
+ """
444
+ Returns (conditioning_mp4_path, first_frame_png_path).
445
+
446
+ Makes an mp4 with exactly target_num_frames frames:
447
+ - if source has more -> truncate
448
+ - if source has fewer -> pad by repeating last frame
449
+ """
450
+ video_path = _coerce_video_path(video_path)
451
+
452
+ # Decode frames (robust / deterministic)
453
+ frames = load_video_frames(video_path) # list of HWC uint8 frames
454
+ if not frames:
455
+ raise ValueError("No frames decoded from input video")
456
+
457
+ # Truncate or pad to exact length
458
+ if len(frames) >= target_num_frames:
459
+ frames = frames[:target_num_frames]
460
+ else:
461
+ last = frames[-1]
462
+ frames = frames + [last] * (target_num_frames - len(frames))
463
+
464
+ # Save first frame as PNG (for input_image)
465
+ first_png = tempfile.NamedTemporaryFile(suffix=".png", delete=False).name
466
+ Image.fromarray(frames[0]).save(first_png)
467
+
468
+ # Write conditioning mp4
469
+ # write_video_mp4 expects float [0..1]
470
+ frames_float = [f.astype(np.float32) / 255.0 for f in frames]
471
+ cond_mp4 = tempfile.NamedTemporaryFile(suffix=".mp4", delete=False).name
472
+ write_video_mp4(frames_float, fps=target_fps, out_path=cond_mp4)
473
+
474
+ return cond_mp4, first_png
475
+
476
+ def valid_1_plus_8k(n: int) -> int:
477
+ """Largest integer <= n that is of the form 1 + 8*k (k>=0)."""
478
+ if n <= 0:
479
+ return 0
480
+ return 1 + 8 * ((n - 1) // 8)
481
+
482
+ def prepare_conditioning_video_mp4_no_pad(
483
+ video_path: Any,
484
+ duration_frames: int,
485
+ target_fps: float,
486
+ ) -> tuple[str, str, int]:
487
+ """
488
+ Returns (conditioning_mp4_path, first_frame_png_path, used_num_frames)
489
+
490
+ - Decodes source frames
491
+ - Trims to the largest valid length (1 + 8*k) <= source length
492
+ - NEVER pads / loops / repeats last frame
493
+ """
494
+ video_path = _coerce_video_path(video_path)
495
+
496
+ frames = load_video_frames(video_path) # list of HWC uint8
497
+ if not frames:
498
+ raise ValueError("No frames decoded from input video")
499
+
500
+ n_src = len(frames)
501
+ n_src = min(n_src, duration_frames)
502
+ n_used = valid_1_plus_8k(n_src)
503
+
504
+ # If the video is extremely short (e.g. 1 frame), n_used can be 1 which is valid.
505
+ if n_used == 0:
506
+ raise ValueError(f"Video too short: {n_src} frames")
507
+
508
+ frames = frames[:n_used]
509
+
510
+ first_png = tempfile.NamedTemporaryFile(suffix=".png", delete=False).name
511
+ Image.fromarray(frames[0]).save(first_png)
512
+
513
+ frames_float = [f.astype(np.float32) / 255.0 for f in frames]
514
+ cond_mp4 = tempfile.NamedTemporaryFile(suffix=".mp4", delete=False).name
515
+ write_video_mp4(frames_float, fps=target_fps, out_path=cond_mp4)
516
+
517
+ return cond_mp4, first_png, n_used
518
+
519
+
520
+ def encode_text_simple(text_encoder, prompt: str):
521
+ """Simple text encoding without using pipeline_utils."""
522
+ v_context, a_context, _ = text_encoder(prompt)
523
+ return v_context, a_context
524
+
525
+ @spaces.GPU()
526
+ def encode_prompt(
527
+ prompt: str,
528
+ enhance_prompt: bool = True,
529
+ input_image=None, # this is now filepath (string) or None
530
+ seed: int = 42,
531
+ negative_prompt: str = ""
532
+ ):
533
+ start_time = time.time()
534
+ try:
535
+ final_prompt = prompt
536
+ if enhance_prompt:
537
+ final_prompt = generate_enhanced_prompt(
538
+ text_encoder=text_encoder,
539
+ prompt=prompt,
540
+ image_path=input_image if input_image is not None else None,
541
+ seed=seed,
542
+ )
543
+
544
+ with torch.inference_mode():
545
+ video_context, audio_context = encode_text_simple(text_encoder, final_prompt)
546
+
547
+ video_context_negative = None
548
+ audio_context_negative = None
549
+ if negative_prompt:
550
+ video_context_negative, audio_context_negative = encode_text_simple(text_encoder, negative_prompt)
551
+
552
+ # IMPORTANT: return tensors directly (no torch.save)
553
+ embedding_data = {
554
+ "video_context": video_context.detach().cpu(),
555
+ "audio_context": audio_context.detach().cpu(),
556
+ "prompt": final_prompt,
557
+ "original_prompt": prompt,
558
+ }
559
+ if video_context_negative is not None:
560
+ embedding_data["video_context_negative"] = video_context_negative
561
+ embedding_data["audio_context_negative"] = audio_context_negative
562
+ embedding_data["negative_prompt"] = negative_prompt
563
+
564
+ elapsed_time = time.time() - start_time
565
+ if torch.cuda.is_available():
566
+ allocated = torch.cuda.memory_allocated() / 1024**3
567
+ peak = torch.cuda.max_memory_allocated() / 1024**3
568
+ status = f"✓ Encoded in {elapsed_time:.2f}s | VRAM: {allocated:.2f}GB allocated, {peak:.2f}GB peak"
569
+ else:
570
+ status = f"✓ Encoded in {elapsed_time:.2f}s (CPU mode)"
571
+
572
+ return embedding_data, final_prompt, status
573
+
574
+ except Exception as e:
575
+ import traceback
576
+ error_msg = f"Error: {str(e)}\n{traceback.format_exc()}"
577
+ print(error_msg)
578
+ return None, prompt, error_msg
579
+
580
+
581
+ # Default prompt from docstring example
582
+ DEFAULT_PROMPT = "An astronaut hatches from a fragile egg on the surface of the Moon, the shell cracking and peeling apart in gentle low-gravity motion. Fine lunar dust lifts and drifts outward with each movement, floating in slow arcs before settling back onto the ground. The astronaut pushes free in a deliberate, weightless motion, small fragments of the egg tumbling and spinning through the air. In the background, the deep darkness of space subtly shifts as stars glide with the camera's movement, emphasizing vast depth and scale. The camera performs a smooth, cinematic slow push-in, with natural parallax between the foreground dust, the astronaut, and the distant starfield. Ultra-realistic detail, physically accurate low-gravity motion, cinematic lighting, and a breath-taking, movie-like shot."
583
+
584
+ # HuggingFace Hub defaults
585
+ DEFAULT_REPO_ID = "Lightricks/LTX-2"
586
+ DEFAULT_CHECKPOINT_FILENAME = "ltx-2-19b-dev.safetensors"
587
+ DEFAULT_DISTILLED_LORA_FILENAME = "ltx-2-19b-distilled-lora-384.safetensors"
588
+ DEFAULT_SPATIAL_UPSAMPLER_FILENAME = "ltx-2-spatial-upscaler-x2-1.0.safetensors"
589
+
590
+ def get_hub_or_local_checkpoint(repo_id: Optional[str] = None, filename: Optional[str] = None):
591
+ """Download from HuggingFace Hub or use local checkpoint."""
592
+ if repo_id is None and filename is None:
593
+ raise ValueError("Please supply at least one of `repo_id` or `filename`")
594
+
595
+ if repo_id is not None:
596
+ if filename is None:
597
+ raise ValueError("If repo_id is specified, filename must also be specified.")
598
+ print(f"Downloading {filename} from {repo_id}...")
599
+ ckpt_path = hf_hub_download(repo_id=repo_id, filename=filename)
600
+ print(f"Downloaded to {ckpt_path}")
601
+ else:
602
+ ckpt_path = filename
603
+
604
+ return ckpt_path
605
+
606
+
607
+ # Initialize pipeline at startup
608
+ print("=" * 80)
609
+ print("Loading LTX-2 Distilled pipeline...")
610
+ print("=" * 80)
611
+
612
+ checkpoint_path = get_hub_or_local_checkpoint(DEFAULT_REPO_ID, DEFAULT_CHECKPOINT_FILENAME)
613
+ spatial_upsampler_path = get_hub_or_local_checkpoint(DEFAULT_REPO_ID, DEFAULT_SPATIAL_UPSAMPLER_FILENAME)
614
+
615
+ print(f"Initializing pipeline with:")
616
+ print(f" checkpoint_path={checkpoint_path}")
617
+ print(f" spatial_upsampler_path={spatial_upsampler_path}")
618
+
619
+ distilled_lora_path = get_hub_or_local_checkpoint(
620
+ DEFAULT_REPO_ID,
621
+ DEFAULT_DISTILLED_LORA_FILENAME,
622
+ )
623
+
624
+ distilled_lora_path = get_hub_or_local_checkpoint(
625
+ DEFAULT_REPO_ID,
626
+ DEFAULT_DISTILLED_LORA_FILENAME,
627
+ )
628
+ static_lora_path = get_hub_or_local_checkpoint(
629
+ "Lightricks/LTX-2-19b-LoRA-Camera-Control-Static",
630
+ "ltx-2-19b-lora-camera-control-static.safetensors",
631
+ )
632
+ dolly_in_lora_path = get_hub_or_local_checkpoint(
633
+ "Lightricks/LTX-2-19b-LoRA-Camera-Control-Dolly-In",
634
+ "ltx-2-19b-lora-camera-control-dolly-in.safetensors",
635
+ )
636
+ dolly_out_lora_path = get_hub_or_local_checkpoint(
637
+ "Lightricks/LTX-2-19b-LoRA-Camera-Control-Dolly-Out",
638
+ "ltx-2-19b-lora-camera-control-dolly-out.safetensors",
639
+ )
640
+ dolly_left_lora_path = get_hub_or_local_checkpoint(
641
+ "Lightricks/LTX-2-19b-LoRA-Camera-Control-Dolly-Left",
642
+ "ltx-2-19b-lora-camera-control-dolly-left.safetensors",
643
+ )
644
+ dolly_right_lora_path = get_hub_or_local_checkpoint(
645
+ "Lightricks/LTX-2-19b-LoRA-Camera-Control-Dolly-Right",
646
+ "ltx-2-19b-lora-camera-control-dolly-right.safetensors",
647
+ )
648
+ jib_down_lora_path = get_hub_or_local_checkpoint(
649
+ "Lightricks/LTX-2-19b-LoRA-Camera-Control-Jib-Down",
650
+ "ltx-2-19b-lora-camera-control-jib-down.safetensors",
651
+ )
652
+ jib_up_lora_path = get_hub_or_local_checkpoint(
653
+ "Lightricks/LTX-2-19b-LoRA-Camera-Control-Jib-Up",
654
+ "ltx-2-19b-lora-camera-control-jib-up.safetensors",
655
+ )
656
+
657
+ detailer_lora_path = get_hub_or_local_checkpoint(
658
+ "Lightricks/LTX-2-19b-IC-LoRA-Detailer",
659
+ "ltx-2-19b-ic-lora-detailer.safetensors",
660
+ )
661
+
662
+ pose_lora_path = get_hub_or_local_checkpoint(
663
+ "Lightricks/LTX-2-19b-IC-LoRA-Pose-Control",
664
+ "ltx-2-19b-ic-lora-pose-control.safetensors",
665
+ )
666
+
667
+
668
+
669
+ # Load distilled LoRA as a regular LoRA
670
+ loras = [
671
+ # --- fused / base behavior ---
672
+ LoraPathStrengthAndSDOps(
673
+ path=distilled_lora_path,
674
+ strength=0.6,
675
+ sd_ops=LTXV_LORA_COMFY_RENAMING_MAP,
676
+ ),
677
+ LoraPathStrengthAndSDOps(static_lora_path, DEFAULT_LORA_STRENGTH, LTXV_LORA_COMFY_RENAMING_MAP),
678
+ LoraPathStrengthAndSDOps(detailer_lora_path, DEFAULT_LORA_STRENGTH, LTXV_LORA_COMFY_RENAMING_MAP),
679
+ LoraPathStrengthAndSDOps(dolly_in_lora_path, DEFAULT_LORA_STRENGTH, LTXV_LORA_COMFY_RENAMING_MAP),
680
+ LoraPathStrengthAndSDOps(dolly_out_lora_path, DEFAULT_LORA_STRENGTH, LTXV_LORA_COMFY_RENAMING_MAP),
681
+ LoraPathStrengthAndSDOps(dolly_left_lora_path, DEFAULT_LORA_STRENGTH, LTXV_LORA_COMFY_RENAMING_MAP),
682
+ LoraPathStrengthAndSDOps(dolly_right_lora_path, DEFAULT_LORA_STRENGTH, LTXV_LORA_COMFY_RENAMING_MAP),
683
+ LoraPathStrengthAndSDOps(jib_down_lora_path, DEFAULT_LORA_STRENGTH, LTXV_LORA_COMFY_RENAMING_MAP),
684
+ LoraPathStrengthAndSDOps(jib_up_lora_path, DEFAULT_LORA_STRENGTH, LTXV_LORA_COMFY_RENAMING_MAP),
685
+ LoraPathStrengthAndSDOps(pose_lora_path, DEFAULT_LORA_STRENGTH, LTXV_LORA_COMFY_RENAMING_MAP),
686
+ ]
687
+
688
+ # Runtime-toggle LoRAs (exclude fused distilled at index 0)
689
+ VISIBLE_RUNTIME_LORA_CHOICES = [
690
+ ("No LoRA", -1),
691
+ ("Static", 0),
692
+ ("Detailer", 1),
693
+ ("Zoom In", 2),
694
+ ("Zoom Out", 3),
695
+ ("Slide Left", 4),
696
+ ("Slide Right", 5),
697
+ ("Slide Down", 6),
698
+ ("Slide Up", 7),
699
+ ]
700
+
701
+ RUNTIME_LORA_CHOICES = [
702
+ ("No LoRA", -1),
703
+ ("Static", 0),
704
+ ("Detailer", 1),
705
+ ("Zoom In", 2),
706
+ ("Zoom Out", 3),
707
+ ("Slide Left", 4),
708
+ ("Slide Right", 5),
709
+ ("Slide Down", 6),
710
+ ("Slide Up", 7),
711
+ ("Pose", 8),
712
+ ]
713
+
714
+ # Initialize pipeline WITHOUT text encoder (gemma_root=None)
715
+ # Text encoding will be done by external space
716
+ pipeline = DistilledPipeline(
717
+ device=torch.device("cuda"),
718
+ checkpoint_path=checkpoint_path,
719
+ spatial_upsampler_path=spatial_upsampler_path,
720
+ gemma_root=None, # No text encoder in this space
721
+ loras=loras,
722
+ fp8transformer=False,
723
+ local_files_only=False,
724
+ )
725
+
726
+ pipeline._video_encoder = pipeline.model_ledger.video_encoder()
727
+ pipeline._transformer = pipeline.model_ledger.transformer()
728
+
729
+ print("=" * 80)
730
+ print("Pipeline fully loaded and ready!")
731
+ print("=" * 80)
732
+
733
+ class RadioAnimated(gr.HTML):
734
+ """
735
+ Animated segmented radio (like iOS pill selector).
736
+ Outputs: selected option string, e.g. "768x512"
737
+ """
738
+ def __init__(self, choices, value=None, **kwargs):
739
+ if not choices or len(choices) < 2:
740
+ raise ValueError("RadioAnimated requires at least 2 choices.")
741
+ if value is None:
742
+ value = choices[0]
743
+
744
+ uid = uuid.uuid4().hex[:8] # unique per instance
745
+ group_name = f"ra-{uid}"
746
+
747
+ inputs_html = "\n".join(
748
+ f"""
749
+ <input class="ra-input" type="radio" name="{group_name}" id="{group_name}-{i}" value="{c}">
750
+ <label class="ra-label" for="{group_name}-{i}">{c}</label>
751
+ """
752
+ for i, c in enumerate(choices)
753
+ )
754
+
755
+ # NOTE: use classes instead of duplicate IDs
756
+ html_template = f"""
757
+ <div class="ra-wrap" data-ra="{uid}">
758
+ <div class="ra-inner">
759
+ <div class="ra-highlight"></div>
760
+ {inputs_html}
761
+ </div>
762
+ </div>
763
+ """
764
+
765
+ js_on_load = r"""
766
+ (() => {
767
+ const wrap = element.querySelector('.ra-wrap');
768
+ const inner = element.querySelector('.ra-inner');
769
+ const highlight = element.querySelector('.ra-highlight');
770
+ const inputs = Array.from(element.querySelectorAll('.ra-input'));
771
+ const labels = Array.from(element.querySelectorAll('.ra-label'));
772
+
773
+ if (!inputs.length || !labels.length) return;
774
+
775
+ const choices = inputs.map(i => i.value);
776
+ const PAD = 6; // must match .ra-inner padding and .ra-highlight top/left
777
+
778
+ let currentIdx = 0;
779
+
780
+ function setHighlightByIndex(idx) {
781
+ currentIdx = idx;
782
+
783
+ const lbl = labels[idx];
784
+ if (!lbl) return;
785
+
786
+ const innerRect = inner.getBoundingClientRect();
787
+ const lblRect = lbl.getBoundingClientRect();
788
+
789
+ // width matches the label exactly
790
+ highlight.style.width = `${lblRect.width}px`;
791
+
792
+ // highlight has left: 6px, so subtract PAD to align
793
+ const x = (lblRect.left - innerRect.left - PAD);
794
+ highlight.style.transform = `translateX(${x}px)`;
795
+ }
796
+
797
+ function setCheckedByValue(val, shouldTrigger=false) {
798
+ const idx = Math.max(0, choices.indexOf(val));
799
+ inputs.forEach((inp, i) => { inp.checked = (i === idx); });
800
+
801
+ // Wait a frame in case fonts/layout settle (prevents rare drift)
802
+ requestAnimationFrame(() => setHighlightByIndex(idx));
803
+
804
+ props.value = choices[idx];
805
+ if (shouldTrigger) trigger('change', props.value);
806
+ }
807
+
808
+ // Init
809
+ setCheckedByValue(props.value ?? choices[0], false);
810
+
811
+ // Input handlers
812
+ inputs.forEach((inp) => {
813
+ inp.addEventListener('change', () => setCheckedByValue(inp.value, true));
814
+ });
815
+
816
+ // Recalc on resize (important in Gradio layouts)
817
+ window.addEventListener('resize', () => setHighlightByIndex(currentIdx));
818
+
819
+ // sync from Python (Examples / backend updates)
820
+ let last = props.value;
821
+ const syncFromProps = () => {
822
+ if (props.value !== last) {
823
+ last = props.value;
824
+ setCheckedByValue(last, false);
825
+ }
826
+ requestAnimationFrame(syncFromProps);
827
+ };
828
+ requestAnimationFrame(syncFromProps);
829
+
830
+ })();
831
+
832
+ """
833
+
834
+ super().__init__(
835
+ value=value,
836
+ html_template=html_template,
837
+ js_on_load=js_on_load,
838
+ **kwargs
839
+ )
840
+
841
+
842
+ class PromptBox(gr.HTML):
843
+ """
844
+ Prompt textarea with an internal footer slot (.ds-footer) where we can inject dropdowns.
845
+ """
846
+ def __init__(self, value="", placeholder="Describe what you want...", **kwargs):
847
+ uid = uuid.uuid4().hex[:8]
848
+
849
+ html_template = f"""
850
+ <div class="ds-card" data-ds="{uid}">
851
+ <div class="ds-top">
852
+ <textarea class="ds-textarea" rows="3" placeholder="{placeholder}"></textarea>
853
+
854
+ <!-- footer slot -->
855
+ <div class="ds-footer" aria-label="prompt-footer"></div>
856
+ </div>
857
+ </div>
858
+ """
859
+
860
+ js_on_load = r"""
861
+ (() => {
862
+ const textarea = element.querySelector(".ds-textarea");
863
+ if (!textarea) return;
864
+
865
+ const autosize = () => {
866
+ textarea.style.height = "0px";
867
+ textarea.style.height = Math.min(textarea.scrollHeight, 240) + "px";
868
+ };
869
+
870
+ const setValue = (v, triggerChange=false) => {
871
+ const val = (v ?? "");
872
+ if (textarea.value !== val) textarea.value = val;
873
+ autosize();
874
+ props.value = textarea.value;
875
+ if (triggerChange) trigger("change", props.value);
876
+ };
877
+
878
+ setValue(props.value, false);
879
+
880
+ textarea.addEventListener("input", () => {
881
+ autosize();
882
+ props.value = textarea.value;
883
+ trigger("change", props.value);
884
+ });
885
+
886
+ // ✅ Focus-on-load (robust)
887
+ const shouldAutoFocus = () => {
888
+ // don’t steal focus if user already clicked/typed somewhere
889
+ const ae = document.activeElement;
890
+ if (ae && ae !== document.body && ae !== document.documentElement) return false;
891
+ // don’t auto-focus on small screens (optional; avoids mobile keyboard pop)
892
+ if (window.matchMedia && window.matchMedia("(max-width: 768px)").matches) return false;
893
+ return true;
894
+ };
895
+
896
+ const focusWithRetry = (tries = 30) => {
897
+ if (!shouldAutoFocus()) return;
898
+ // only focus if still not focused
899
+ if (document.activeElement !== textarea) textarea.focus({ preventScroll: true });
900
+ if (document.activeElement === textarea) return;
901
+ if (tries > 0) requestAnimationFrame(() => focusWithRetry(tries - 1));
902
+ };
903
+
904
+ // wait a tick so Gradio/layout settles
905
+ requestAnimationFrame(() => focusWithRetry());
906
+
907
+ // keep your sync loop
908
+ let last = props.value;
909
+ const syncFromProps = () => {
910
+ if (props.value !== last) {
911
+ last = props.value;
912
+ setValue(last, false);
913
+ }
914
+ requestAnimationFrame(syncFromProps);
915
+ };
916
+ requestAnimationFrame(syncFromProps);
917
+ })();
918
+
919
+ """
920
+
921
+ super().__init__(value=value, html_template=html_template, js_on_load=js_on_load, **kwargs)
922
+
923
+
924
+ class CameraDropdown(gr.HTML):
925
+ """
926
+ Custom dropdown (More-style) with optional icons per item.
927
+ Outputs: selected option string, e.g. "16:9"
928
+
929
+ choices can be:
930
+ - ["16:9", "1:1", "9:16"] (text only)
931
+ - [{"label":"16:9","value":"16:9","icon":"…"}, ...] (icon+text)
932
+
933
+ icon can be emoji or inline SVG/HTML.
934
+ """
935
+ def __init__(self, choices, value="None", title="Dropdown", **kwargs):
936
+ if not choices:
937
+ raise ValueError("CameraDropdown requires choices.")
938
+
939
+ # Normalize choices -> list of dicts: {label, value, icon(optional)}
940
+ norm = []
941
+ for c in choices:
942
+ if isinstance(c, dict):
943
+ label = str(c.get("label", c.get("value", "")))
944
+ val = str(c.get("value", label))
945
+ icon = c.get("icon", None) # emoji or svg/html
946
+ norm.append({"label": label, "value": val, "icon": icon})
947
+ else:
948
+ s = str(c)
949
+ norm.append({"label": s, "value": s, "icon": None})
950
+
951
+ uid = uuid.uuid4().hex[:8]
952
+
953
+ def render_item(item):
954
+ icon_html = ""
955
+ if item["icon"]:
956
+ icon_html = f'<span class="cd-icn">{item["icon"]}</span>'
957
+ return (
958
+ f'<button type="button" class="cd-item" '
959
+ f'data-value="{item["value"]}">'
960
+ f'{icon_html}<span class="cd-label">{item["label"]}</span>'
961
+ f'</button>'
962
+ )
963
+
964
+ items_html = "\n".join(render_item(item) for item in norm)
965
+
966
+ html_template = f"""
967
+ <div class="cd-wrap" data-cd="{uid}">
968
+ <button type="button" class="cd-trigger" aria-haspopup="menu" aria-expanded="false">
969
+ <span class="cd-trigger-icon"></span>
970
+ <span class="cd-trigger-text"></span>
971
+ <span class="cd-caret">▾</span>
972
+ </button>
973
+
974
+ <div class="cd-menu" role="menu" aria-hidden="true">
975
+ <div class="cd-title">{title}</div>
976
+ <div class="cd-items">
977
+ {items_html}
978
+ </div>
979
+ </div>
980
+ </div>
981
+ """
982
+
983
+ # Pass a mapping value->label so the trigger can show label text
984
+ # (and still output value to Python)
985
+ value_to_label = {it["value"]: it["label"] for it in norm}
986
+ value_to_icon = {it["value"]: (it["icon"] or "") for it in norm}
987
+
988
+ js_on_load = r"""
989
+ (() => {
990
+ const wrap = element.querySelector(".cd-wrap");
991
+ const trigger = element.querySelector(".cd-trigger");
992
+ const triggerIcon = element.querySelector(".cd-trigger-icon");
993
+ const triggerText = element.querySelector(".cd-trigger-text");
994
+ const menu = element.querySelector(".cd-menu");
995
+ const items = Array.from(element.querySelectorAll(".cd-item"));
996
+ if (!wrap || !trigger || !menu || !items.length) return;
997
+
998
+ const valueToLabel = __VALUE_TO_LABEL__;
999
+ const valueToIcon = __VALUE_TO_ICON__;
1000
+
1001
+ const safeLabel = (v) => (valueToLabel && valueToLabel[v]) ? valueToLabel[v] : (v ?? "None");
1002
+ const safeIcon = (v) => (valueToIcon && valueToIcon[v]) ? valueToIcon[v] : "";
1003
+
1004
+
1005
+ function closeMenu() {
1006
+ menu.classList.remove("open");
1007
+ trigger.setAttribute("aria-expanded", "false");
1008
+ menu.setAttribute("aria-hidden", "true");
1009
+ }
1010
+
1011
+ function openMenu() {
1012
+ menu.classList.add("open");
1013
+ trigger.setAttribute("aria-expanded", "true");
1014
+ menu.setAttribute("aria-hidden", "false");
1015
+ }
1016
+
1017
+ function setValue(val, shouldTrigger = false) {
1018
+ const v = (val ?? "None");
1019
+ props.value = v;
1020
+
1021
+ // Trigger shows LABEL only (icons stay in menu)
1022
+ triggerText.textContent = safeLabel(v);
1023
+ if (triggerIcon) {
1024
+ triggerIcon.innerHTML = safeIcon(v);
1025
+ triggerIcon.style.display = safeIcon(v) ? "inline-flex" : "none";
1026
+ }
1027
+
1028
+
1029
+ items.forEach(btn => {
1030
+ btn.dataset.selected = (btn.dataset.value === v) ? "true" : "false";
1031
+ });
1032
+
1033
+ if (shouldTrigger) trigger("change", props.value);
1034
+ }
1035
+
1036
+ trigger.addEventListener("pointerdown", (e) => {
1037
+ e.preventDefault();
1038
+ e.stopPropagation();
1039
+ if (menu.classList.contains("open")) closeMenu();
1040
+ else openMenu();
1041
+ });
1042
+
1043
+ document.addEventListener("pointerdown", (e) => {
1044
+ if (!wrap.contains(e.target)) closeMenu();
1045
+ }, true);
1046
+
1047
+ document.addEventListener("keydown", (e) => {
1048
+ if (e.key === "Escape") closeMenu();
1049
+ });
1050
+
1051
+ wrap.addEventListener("focusout", (e) => {
1052
+ if (!wrap.contains(e.relatedTarget)) closeMenu();
1053
+ });
1054
+
1055
+ items.forEach((btn) => {
1056
+ btn.addEventListener("pointerdown", (e) => {
1057
+ e.preventDefault();
1058
+ e.stopPropagation();
1059
+ closeMenu();
1060
+ setValue(btn.dataset.value, true);
1061
+ });
1062
+ });
1063
+
1064
+ // init
1065
+ setValue((props.value ?? "None"), false);
1066
+
1067
+ // sync from Python
1068
+ let last = props.value;
1069
+ const syncFromProps = () => {
1070
+ if (props.value !== last) {
1071
+ last = props.value;
1072
+ setValue(last, false);
1073
+ }
1074
+ requestAnimationFrame(syncFromProps);
1075
+ };
1076
+ requestAnimationFrame(syncFromProps);
1077
+ })();
1078
+ """
1079
+
1080
+ # Inject mapping into JS safely
1081
+ import json
1082
+ js_on_load = js_on_load.replace("__VALUE_TO_LABEL__", json.dumps(value_to_label))
1083
+ js_on_load = js_on_load.replace("__VALUE_TO_ICON__", json.dumps(value_to_icon))
1084
+
1085
+ super().__init__(
1086
+ value=value,
1087
+ html_template=html_template,
1088
+ js_on_load=js_on_load,
1089
+ **kwargs
1090
+ )
1091
+
1092
+ def generate_video_example(input_image, prompt, camera_lora, resolution, radioanimated_mode, input_video, input_audio, progress=gr.Progress(track_tqdm=True)):
1093
+
1094
+ w, h = apply_resolution(resolution)
1095
+
1096
+ with timer(f'generating with video path:{input_video} with duration:{duration} and LoRA:{camera_lora} in {w}x{h}'):
1097
+ output_video = generate_video(
1098
+ input_image,
1099
+ prompt,
1100
+ 10,
1101
+ input_video,
1102
+ radioanimated_mode,
1103
+ True,
1104
+ 42,
1105
+ True,
1106
+ h,
1107
+ w,
1108
+ camera_lora,
1109
+ input_audio,
1110
+ progress
1111
+ )
1112
+ return output_video
1113
+
1114
+ def get_duration(
1115
+ input_image,
1116
+ prompt,
1117
+ duration,
1118
+ input_video,
1119
+ radioanimated_mode,
1120
+ enhance_prompt,
1121
+ seed,
1122
+ randomize_seed,
1123
+ height,
1124
+ width,
1125
+ camera_lora,
1126
+ audio_path,
1127
+ progress
1128
+ ):
1129
+ extra_time = 0
1130
+
1131
+ if audio_path is not None:
1132
+ extra_time += 10
1133
+
1134
+ if input_video is not None:
1135
+ extra_time += 60
1136
+
1137
+ if duration <= 3:
1138
+ return 60 + extra_time
1139
+ elif duration <= 5:
1140
+ return 80 + extra_time
1141
+ elif duration <= 10:
1142
+ return 120 + extra_time
1143
+ else:
1144
+ return 180 + extra_time
1145
+
1146
+
1147
+ @spaces.GPU(duration=get_duration)
1148
+ def generate_video(
1149
+ input_image,
1150
+ prompt: str,
1151
+ duration: float,
1152
+ input_video = None,
1153
+ generation_mode = "Image-to-Video",
1154
+ enhance_prompt: bool = True,
1155
+ seed: int = 42,
1156
+ randomize_seed: bool = True,
1157
+ height: int = DEFAULT_1_STAGE_HEIGHT,
1158
+ width: int = DEFAULT_1_STAGE_WIDTH,
1159
+ camera_lora: str = "No LoRA",
1160
+ audio_path = None,
1161
+ progress=gr.Progress(track_tqdm=True),
1162
+ ):
1163
+ """
1164
+ Generate a short cinematic video from a text prompt and optional input image using the LTX-2 distilled pipeline.
1165
+ Args:
1166
+ input_image: Optional input image for image-to-video. If provided, it is injected at frame 0 to guide motion.
1167
+ prompt: Text description of the scene, motion, and cinematic style to generate.
1168
+ duration: Desired video length in seconds. Converted to frames using a fixed 24 FPS rate.
1169
+ input_video: Optional conditioning video path (mp4). If provided, motion is guided by this video.
1170
+ enhance_prompt: Whether to enhance the prompt using the prompt enhancer before encoding.
1171
+ seed: Base random seed for reproducibility (ignored if randomize_seed is True).
1172
+ randomize_seed: If True, a random seed is generated for each run.
1173
+ height: Output video height in pixels.
1174
+ width: Output video width in pixels.
1175
+ camera_lora: Camera motion control LoRA to apply during generation (enables exactly one at runtime).
1176
+ audio_path: Optiona audio file for soundtrack. Could be a lipsync audio or a background music or a mixture of both guiding the image-to-vidoe motion process.
1177
+ progress: Gradio progress tracker.
1178
+ Returns:
1179
+
1180
+ A tuple of:
1181
+ - output_path: Path to the generated MP4 video file.
1182
+ - seed: The seed used for generation.
1183
+ Notes:
1184
+ - Uses a fixed frame rate of 24 FPS.
1185
+ - Prompt embeddings are generated externally to avoid reloading the text encoder.
1186
+ - GPU cache is cleared after generation to reduce VRAM pressure.
1187
+ - If an input image is provided, it is temporarily saved to disk for processing.
1188
+ """
1189
+
1190
+ if (camera_lora != "No LoRA" or audio_path is not None) and duration == 15:
1191
+ gr.Info("15s not avaiable when a LoRA or lipsync is activated, reducing to 10s for this generation")
1192
+ duration = 10
1193
+
1194
+ if audio_path is None:
1195
+ print(f'generating with duration:{duration} and LoRA:{camera_lora} in {width}x{height}')
1196
+ else:
1197
+ print(f'generating with duration:{duration} and audio in {width}x{height}')
1198
+
1199
+ # Randomize seed if checkbox is enabled
1200
+ current_seed = random.randint(0, MAX_SEED) if randomize_seed else int(seed)
1201
+
1202
+ # Calculate num_frames from duration (using fixed 24 fps)
1203
+ frame_rate = 24.0
1204
+ num_frames = int(duration * frame_rate) + 1 # +1 to ensure we meet the duration
1205
+ video_seconds = int(duration)
1206
+
1207
+ with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as tmpfile:
1208
+ output_path = tmpfile.name
1209
+
1210
+
1211
+ images = []
1212
+ videos = []
1213
+
1214
+ if generation_mode == "Motion Control":
1215
+ if input_video is not None:
1216
+ cond_mp4, first_png, used_frames = prepare_conditioning_video_mp4_no_pad(
1217
+ video_path=input_video,
1218
+ duration_frames=num_frames,
1219
+ target_fps=frame_rate,
1220
+ )
1221
+
1222
+ if input_image is None:
1223
+ images = [(first_png, 0, 1.0)]
1224
+
1225
+ if audio_path is None:
1226
+ src_video_path = _coerce_video_path(input_video)
1227
+ extracted_audio_tmp = extract_audio_wav_ffmpeg(src_video_path, target_sr=48000)
1228
+
1229
+ if extracted_audio_tmp is not None:
1230
+ audio_path = extracted_audio_tmp
1231
+
1232
+ with timer("Pose selected: preprocessing conditioning video to pose..."):
1233
+ cond_path = preprocess_video_to_pose_mp4(
1234
+ video_path=cond_mp4,
1235
+ width=width,
1236
+ height=height,
1237
+ fps=frame_rate,
1238
+ )
1239
+ videos = [(cond_path, 1.0)]
1240
+ camera_lora = "Pose"
1241
+
1242
+ if input_image is not None:
1243
+ images = [(input_image, 0, 1.0)]
1244
+
1245
+ embeddings, final_prompt, status = encode_prompt(
1246
+ prompt=prompt,
1247
+ enhance_prompt=enhance_prompt,
1248
+ input_image=input_image,
1249
+ seed=current_seed,
1250
+ negative_prompt="",
1251
+ )
1252
+
1253
+ video_context = embeddings["video_context"].to("cuda", non_blocking=True)
1254
+ audio_context = embeddings["audio_context"].to("cuda", non_blocking=True)
1255
+ print("✓ Embeddings loaded successfully")
1256
+
1257
+
1258
+ # free prompt enhancer / encoder temps ASAP
1259
+ del embeddings, final_prompt, status
1260
+ torch.cuda.empty_cache()
1261
+
1262
+ # ✅ if user provided audio, use a neutral audio_context
1263
+ n_audio_context = None
1264
+
1265
+ if audio_path is not None:
1266
+ with torch.inference_mode():
1267
+ _, n_audio_context = encode_text_simple(text_encoder, "") # returns tensors on GPU already
1268
+ del audio_context
1269
+ audio_context = n_audio_context
1270
+
1271
+ if len(videos) == 0:
1272
+ camera_lora = "Static"
1273
+
1274
+ torch.cuda.empty_cache()
1275
+
1276
+ # Map dropdown name -> adapter index
1277
+ name_to_idx = {name: idx for name, idx in RUNTIME_LORA_CHOICES}
1278
+ selected_idx = name_to_idx.get(camera_lora, -1)
1279
+
1280
+ enable_only_lora(pipeline._transformer, selected_idx)
1281
+ torch.cuda.empty_cache()
1282
+
1283
+ # True video duration in seconds based on your rounding
1284
+ video_seconds = (num_frames - 1) / frame_rate
1285
+
1286
+ if audio_path is not None:
1287
+ input_waveform, input_waveform_sample_rate = match_audio_to_duration(
1288
+ audio_path=audio_path,
1289
+ target_seconds=video_seconds,
1290
+ target_sr=48000, # pick what your model expects; 48k is common for AV models
1291
+ to_mono=True, # set False if your model wants stereo
1292
+ pad_mode="silence", # or "repeat" if you prefer looping over silence
1293
+ device="cuda",
1294
+ )
1295
+ else:
1296
+ input_waveform = None
1297
+ input_waveform_sample_rate = None
1298
+
1299
+ with timer(f'generating with video path:{input_video} and LoRA:{camera_lora} in {width}x{height}'):
1300
+ with torch.inference_mode():
1301
+ pipeline(
1302
+ prompt=prompt,
1303
+ output_path=str(output_path),
1304
+ seed=current_seed,
1305
+ height=height,
1306
+ width=width,
1307
+ num_frames=num_frames,
1308
+ frame_rate=frame_rate,
1309
+ images=images,
1310
+ video_conditioning=videos,
1311
+ tiling_config=TilingConfig.default(),
1312
+ video_context=video_context,
1313
+ audio_context=audio_context,
1314
+ input_waveform=input_waveform,
1315
+ input_waveform_sample_rate=input_waveform_sample_rate,
1316
+ )
1317
+ del video_context, audio_context
1318
+ torch.cuda.empty_cache()
1319
+ print("successful generation")
1320
+
1321
+ return str(output_path)
1322
+
1323
+
1324
+
1325
+ def apply_resolution(resolution: str):
1326
+
1327
+ if resolution == "16:9":
1328
+ w, h = 768, 512
1329
+ elif resolution == "1:1":
1330
+ w, h = 512, 512
1331
+ elif resolution == "9:16":
1332
+ w, h = 512, 768
1333
+
1334
+ return int(w), int(h)
1335
+
1336
+ def apply_duration(duration: str):
1337
+ duration_s = int(duration[:-1])
1338
+ return duration_s
1339
+
1340
+ def on_mode_change(selected: str):
1341
+ is_i2v = (selected == "Image-to-Video")
1342
+
1343
+ return gr.update(visible=not is_i2v)
1344
+
1345
+
1346
+
1347
+ css = """
1348
+
1349
+ /* Make the row behave nicely */
1350
+ #controls-row {
1351
+ display: none !important;
1352
+ align-items: center;
1353
+ gap: 12px;
1354
+ flex-wrap: nowrap; /* or wrap if you prefer on small screens */
1355
+ }
1356
+
1357
+ /* Stop these components from stretching */
1358
+ #controls-row > * {
1359
+ flex: 0 0 auto !important;
1360
+ width: auto !important;
1361
+ min-width: 0 !important;
1362
+ }
1363
+
1364
+
1365
+ #col-container {
1366
+ margin: 0 auto;
1367
+ max-width: 1600px;
1368
+ }
1369
+ #modal-container {
1370
+ width: 100vw; /* Take full viewport width */
1371
+ height: 100vh; /* Take full viewport height (optional) */
1372
+ display: flex;
1373
+ justify-content: center; /* Center content horizontally */
1374
+ align-items: center; /* Center content vertically if desired */
1375
+ }
1376
+ #modal-content {
1377
+ width: 100%;
1378
+ max-width: 700px; /* Limit content width */
1379
+ margin: 0 auto;
1380
+ border-radius: 8px;
1381
+ padding: 1.5rem;
1382
+ }
1383
+ #step-column {
1384
+ padding: 10px;
1385
+ border-radius: 8px;
1386
+ box-shadow: var(--card-shadow);
1387
+ margin: 10px;
1388
+ }
1389
+ #col-showcase {
1390
+ margin: 0 auto;
1391
+ max-width: 1100px;
1392
+ }
1393
+ .button-gradient {
1394
+ background: linear-gradient(45deg, rgb(255, 65, 108), rgb(255, 75, 43), rgb(255, 155, 0), rgb(255, 65, 108)) 0% 0% / 400% 400%;
1395
+ border: none;
1396
+ padding: 14px 28px;
1397
+ font-size: 16px;
1398
+ font-weight: bold;
1399
+ color: white;
1400
+ border-radius: 10px;
1401
+ cursor: pointer;
1402
+ transition: 0.3s ease-in-out;
1403
+ animation: 2s linear 0s infinite normal none running gradientAnimation;
1404
+ box-shadow: rgba(255, 65, 108, 0.6) 0px 4px 10px;
1405
+ }
1406
+ .toggle-container {
1407
+ display: inline-flex;
1408
+ background-color: #ffd6ff; /* light pink background */
1409
+ border-radius: 9999px;
1410
+ padding: 4px;
1411
+ position: relative;
1412
+ width: fit-content;
1413
+ font-family: sans-serif;
1414
+ }
1415
+ .toggle-container input[type="radio"] {
1416
+ display: none;
1417
+ }
1418
+ .toggle-container label {
1419
+ position: relative;
1420
+ z-index: 2;
1421
+ flex: 1;
1422
+ text-align: center;
1423
+ font-weight: 700;
1424
+ color: #4b2ab5; /* dark purple text for unselected */
1425
+ padding: 6px 22px;
1426
+ border-radius: 9999px;
1427
+ cursor: pointer;
1428
+ transition: color 0.25s ease;
1429
+ }
1430
+ /* Moving highlight */
1431
+ .toggle-highlight {
1432
+ position: absolute;
1433
+ top: 4px;
1434
+ left: 4px;
1435
+ width: calc(50% - 4px);
1436
+ height: calc(100% - 8px);
1437
+ background-color: #4b2ab5; /* dark purple background */
1438
+ border-radius: 9999px;
1439
+ transition: transform 0.25s ease;
1440
+ z-index: 1;
1441
+ }
1442
+ /* When "True" is checked */
1443
+ #true:checked ~ label[for="true"] {
1444
+ color: #ffd6ff; /* light pink text */
1445
+ }
1446
+ /* When "False" is checked */
1447
+ #false:checked ~ label[for="false"] {
1448
+ color: #ffd6ff; /* light pink text */
1449
+ }
1450
+ /* Move highlight to right side when False is checked */
1451
+ #false:checked ~ .toggle-highlight {
1452
+ transform: translateX(100%);
1453
+ }
1454
+
1455
+ /* Center items inside that row */
1456
+ #mode-row{
1457
+ justify-content: center !important;
1458
+ align-items: center !important;
1459
+ }
1460
+
1461
+ /* Center the mode row contents */
1462
+ #mode-row {
1463
+ display: flex !important;
1464
+ justify-content: center !important;
1465
+ align-items: center !important;
1466
+ width: 100% !important;
1467
+ }
1468
+
1469
+ /* Stop Gradio from making children stretch */
1470
+ #mode-row > * {
1471
+ flex: 0 0 auto !important;
1472
+ width: auto !important;
1473
+ min-width: 0 !important;
1474
+ }
1475
+
1476
+ /* Specifically ensure the HTML component wrapper doesn't take full width */
1477
+ #mode-row .gr-html,
1478
+ #mode-row .gradio-html,
1479
+ #mode-row .prose,
1480
+ #mode-row .block {
1481
+ width: auto !important;
1482
+ flex: 0 0 auto !important;
1483
+ display: inline-block !important;
1484
+ }
1485
+
1486
+ /* Center the pill itself */
1487
+ #radioanimated_mode {
1488
+ display: inline-flex !important;
1489
+ justify-content: center !important;
1490
+ width: auto !important;
1491
+ }
1492
+
1493
+ """
1494
+
1495
+ css += """
1496
+ .cd-trigger-icon{
1497
+ color: rgba(255,255,255,0.9);
1498
+ display: inline-flex;
1499
+ align-items: center;
1500
+ justify-content: center;
1501
+ width: 18px;
1502
+ height: 18px;
1503
+ }
1504
+ .cd-trigger-icon svg {
1505
+ width: 18px;
1506
+ height: 18px;
1507
+ display: block;
1508
+ }
1509
+ """
1510
+
1511
+
1512
+ css += """
1513
+ /* ---- radioanimated ---- */
1514
+ .ra-wrap{
1515
+ width: fit-content;
1516
+ }
1517
+ .ra-inner{
1518
+ position: relative;
1519
+ display: inline-flex;
1520
+ align-items: center;
1521
+ gap: 0;
1522
+ padding: 6px;
1523
+ background: #0b0b0b;
1524
+ border-radius: 9999px;
1525
+ overflow: hidden;
1526
+ user-select: none;
1527
+ }
1528
+ .ra-input{
1529
+ display: none;
1530
+ }
1531
+ .ra-label{
1532
+ position: relative;
1533
+ z-index: 2;
1534
+ padding: 10px 18px;
1535
+ font-family: ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, Arial;
1536
+ font-size: 14px;
1537
+ font-weight: 600;
1538
+ color: rgba(255,255,255,0.7);
1539
+ cursor: pointer;
1540
+ transition: color 180ms ease;
1541
+ white-space: nowrap;
1542
+ }
1543
+ .ra-highlight{
1544
+ position: absolute;
1545
+ z-index: 1;
1546
+ top: 6px;
1547
+ left: 6px;
1548
+ height: calc(100% - 12px);
1549
+ border-radius: 9999px;
1550
+ background: #8bff97; /* green knob */
1551
+ transition: transform 200ms ease, width 200ms ease;
1552
+ }
1553
+ /* selected label becomes darker like your screenshot */
1554
+ .ra-input:checked + .ra-label{
1555
+ color: rgba(0,0,0,0.75);
1556
+ }
1557
+ """
1558
+
1559
+ css += """
1560
+ .cd-icn svg{
1561
+ width: 18px;
1562
+ height: 18px;
1563
+ display: block;
1564
+ }
1565
+ .cd-icn svg *{
1566
+ stroke: rgba(255,255,255,0.9);
1567
+ }
1568
+ """
1569
+
1570
+
1571
+ css += """
1572
+ /* --- prompt box --- */
1573
+ .ds-prompt{
1574
+ width: 100%;
1575
+ max-width: 720px;
1576
+ margin-top: 3px;
1577
+ }
1578
+
1579
+ .ds-textarea{
1580
+ width: 100%;
1581
+ box-sizing: border-box;
1582
+ background: #2b2b2b;
1583
+ color: rgba(255,255,255,0.9);
1584
+ border: 1px solid rgba(255,255,255,0.12);
1585
+ border-radius: 14px;
1586
+ padding: 14px 16px;
1587
+ outline: none;
1588
+ font-family: ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, Arial;
1589
+ font-size: 15px;
1590
+ line-height: 1.35;
1591
+ resize: none;
1592
+ min-height: 210px;
1593
+ max-height: 210px;
1594
+ overflow-y: auto;
1595
+
1596
+ /* IMPORTANT: space for the footer controls */
1597
+ padding-bottom: 72px;
1598
+ }
1599
+
1600
+
1601
+ .ds-card{
1602
+ width: 100%;
1603
+ max-width: 720px;
1604
+ margin: 0 auto;
1605
+ }
1606
+ .ds-top{
1607
+ position: relative;
1608
+ }
1609
+
1610
+ /* Make room for footer inside textarea */
1611
+ .ds-textarea{
1612
+ padding-bottom: 72px;
1613
+ }
1614
+
1615
+ /* Footer positioning */
1616
+ .ds-footer{
1617
+ position: absolute;
1618
+ right: 12px;
1619
+ bottom: 10px;
1620
+ display: flex;
1621
+ gap: 8px;
1622
+ align-items: center;
1623
+ justify-content: flex-end;
1624
+ z-index: 3;
1625
+ }
1626
+
1627
+ /* Smaller pill buttons inside footer */
1628
+ .ds-footer .cd-trigger{
1629
+ min-height: 32px;
1630
+ padding: 6px 10px;
1631
+ font-size: 12px;
1632
+ gap: 6px;
1633
+ border-radius: 9999px;
1634
+ }
1635
+ .ds-footer .cd-trigger-icon,
1636
+ .ds-footer .cd-icn{
1637
+ width: 14px;
1638
+ height: 14px;
1639
+ }
1640
+ .ds-footer .cd-trigger-icon svg,
1641
+ .ds-footer .cd-icn svg{
1642
+ width: 14px;
1643
+ height: 14px;
1644
+ }
1645
+ .ds-footer .cd-caret{
1646
+ font-size: 11px;
1647
+ }
1648
+
1649
+ /* Bottom safe area bar (optional but looks nicer) */
1650
+ .ds-top::after{
1651
+ content: "";
1652
+ position: absolute;
1653
+ left: 1px;
1654
+ right: 1px;
1655
+ bottom: 1px;
1656
+ height: 56px;
1657
+ background: #2b2b2b;
1658
+ border-bottom-left-radius: 13px;
1659
+ border-bottom-right-radius: 13px;
1660
+ pointer-events: none;
1661
+ z-index: 2;
1662
+ }
1663
+
1664
+ """
1665
+
1666
+ css += """
1667
+ /* ---- camera dropdown ---- */
1668
+
1669
+ /* 1) Fix overlap: make the Gradio HTML block shrink-to-fit when it contains a CameraDropdown.
1670
+ Gradio uses .gr-html for HTML components in most versions; older themes sometimes use .gradio-html.
1671
+ This keeps your big header HTML unaffected because it doesn't contain .cd-wrap.
1672
+ */
1673
+
1674
+ /* 2) Actual dropdown layout */
1675
+ .cd-wrap{
1676
+ position: relative;
1677
+ display: inline-block;
1678
+ }
1679
+
1680
+ /* 3) Match RadioAnimated pill size/feel */
1681
+ .cd-trigger{
1682
+ margin-top: 2px;
1683
+ display: inline-flex;
1684
+ align-items: center;
1685
+ justify-content: center;
1686
+ gap: 10px;
1687
+
1688
+ border: none;
1689
+
1690
+ box-sizing: border-box;
1691
+ padding: 10px 18px;
1692
+ min-height: 52px;
1693
+ line-height: 1.2;
1694
+
1695
+ border-radius: 9999px;
1696
+ background: #0b0b0b;
1697
+
1698
+ font-family: ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, Arial;
1699
+ font-size: 14px;
1700
+
1701
+ /* ✅ match .ra-label exactly */
1702
+ color: rgba(255,255,255,0.7) !important;
1703
+ font-weight: 600 !important;
1704
+
1705
+ cursor: pointer;
1706
+ user-select: none;
1707
+ white-space: nowrap;
1708
+ }
1709
+
1710
+ /* Ensure inner spans match too */
1711
+ .cd-trigger .cd-trigger-text,
1712
+ .cd-trigger .cd-caret{
1713
+ color: rgba(255,255,255,0.7) !important;
1714
+ }
1715
+
1716
+ /* keep caret styling */
1717
+ .cd-caret{
1718
+ opacity: 0.8;
1719
+ font-weight: 900;
1720
+ }
1721
+
1722
+ /* 4) Ensure menu overlays neighbors and isn't clipped */
1723
+ /* Move dropdown a tiny bit up (closer to the trigger) */
1724
+ .cd-menu{
1725
+ position: absolute;
1726
+ top: calc(100% + 4px); /* was +10px */
1727
+ left: 0;
1728
+
1729
+ min-width: 240px;
1730
+ background: #2b2b2b;
1731
+ border: 1px solid rgba(255,255,255,0.14);
1732
+ border-radius: 14px;
1733
+ box-shadow: 0 18px 40px rgba(0,0,0,0.35);
1734
+ padding: 10px;
1735
+
1736
+ opacity: 0;
1737
+ transform: translateY(-6px);
1738
+ pointer-events: none;
1739
+ transition: opacity 160ms ease, transform 160ms ease;
1740
+
1741
+ z-index: 9999;
1742
+ }
1743
+
1744
+ .cd-title{
1745
+ font-size: 12px;
1746
+ font-weight: 600;
1747
+ text-transform: uppercase;
1748
+ letter-spacing: 0.04em;
1749
+
1750
+ color: rgba(255,255,255,0.45); /* 👈 muted grey */
1751
+ margin-bottom: 6px;
1752
+ padding: 0 6px;
1753
+ pointer-events: none; /* title is non-interactive */
1754
+ }
1755
+
1756
+
1757
+ .cd-menu.open{
1758
+ opacity: 1;
1759
+ transform: translateY(0);
1760
+ pointer-events: auto;
1761
+ }
1762
+
1763
+ .cd-items{
1764
+ display: flex;
1765
+ flex-direction: column;
1766
+ gap: 0px; /* tighter, more like a native menu */
1767
+ }
1768
+
1769
+ /* Items: NO "boxed" buttons by default */
1770
+ .cd-item{
1771
+ width: 100%;
1772
+ text-align: left;
1773
+ border: none;
1774
+ background: transparent; /* ✅ removes box look */
1775
+ color: rgba(255,255,255,0.92);
1776
+ padding: 8px 34px 8px 12px; /* right padding leaves room for tick */
1777
+ border-radius: 10px; /* only matters on hover */
1778
+ cursor: pointer;
1779
+
1780
+ font-size: 14px;
1781
+ font-weight: 700;
1782
+
1783
+ position: relative;
1784
+ transition: background 120ms ease;
1785
+ }
1786
+
1787
+ /* “Box effect” only on hover (not always) */
1788
+ .cd-item:hover{
1789
+ background: rgba(255,255,255,0.08);
1790
+ }
1791
+
1792
+ /* Tick on the right ONLY on hover */
1793
+ .cd-item::after{
1794
+ content: "✓";
1795
+ position: absolute;
1796
+ right: 12px;
1797
+ top: 50%;
1798
+ transform: translateY(-50%);
1799
+ opacity: 0; /* hidden by default */
1800
+ transition: opacity 120ms ease;
1801
+ color: rgba(255,255,255,0.9);
1802
+ font-weight: 900;
1803
+ }
1804
+
1805
+ /* show tick ONLY for selected item */
1806
+ .cd-item[data-selected="true"]::after{
1807
+ opacity: 1;
1808
+ }
1809
+
1810
+ /* keep hover box effect, but no tick change */
1811
+ .cd-item:hover{
1812
+ background: rgba(255,255,255,0.08);
1813
+ }
1814
+
1815
+
1816
+ /* Kill any old “selected” styling just in case */
1817
+ .cd-item.selected{
1818
+ background: transparent !important;
1819
+ border: none !important;
1820
+ }
1821
+
1822
+
1823
+ """
1824
+
1825
+ css += """
1826
+ /* icons in dropdown items */
1827
+ .cd-item{
1828
+ display: flex;
1829
+ align-items: center;
1830
+ gap: 10px;
1831
+ }
1832
+ .cd-icn{
1833
+ display: inline-flex;
1834
+ align-items: center;
1835
+ justify-content: center;
1836
+ width: 18px;
1837
+ height: 18px;
1838
+ flex: 0 0 18px;
1839
+ }
1840
+ .cd-label{
1841
+ flex: 1;
1842
+ }
1843
+
1844
+ /* =========================
1845
+ FIX: prompt border + scrollbar bleed
1846
+ ========================= */
1847
+
1848
+ /* Put the border + background on the wrapper, not the textarea */
1849
+ .ds-top{
1850
+ position: relative;
1851
+ background: #2b2b2b;
1852
+ border: 1px solid rgba(255,255,255,0.12);
1853
+ border-radius: 14px;
1854
+ overflow: hidden; /* ensures the footer bar is clipped to rounded corners */
1855
+ }
1856
+
1857
+ /* Make textarea "transparent" so wrapper owns the border/background */
1858
+ .ds-textarea{
1859
+ background: transparent !important;
1860
+ border: none !important;
1861
+ border-radius: 0 !important; /* wrapper handles radius */
1862
+ outline: none;
1863
+
1864
+ /* keep your spacing */
1865
+ padding: 14px 16px;
1866
+ padding-bottom: 72px; /* room for footer */
1867
+ width: 100%;
1868
+ box-sizing: border-box;
1869
+
1870
+ /* keep scroll behavior */
1871
+ overflow-y: auto;
1872
+
1873
+ /* prevent scrollbar bleed by hiding native scrollbar */
1874
+ scrollbar-width: none; /* Firefox */
1875
+ }
1876
+ .ds-textarea::-webkit-scrollbar{ /* Chrome/Safari */
1877
+ width: 0;
1878
+ height: 0;
1879
+ }
1880
+
1881
+ /* Safe-area bar: now it matches perfectly because it's inside the same bordered wrapper */
1882
+ .ds-top::after{
1883
+ content: "";
1884
+ position: absolute;
1885
+ left: 0;
1886
+ right: 0;
1887
+ bottom: 0;
1888
+ height: 56px;
1889
+ background: #2b2b2b;
1890
+ pointer-events: none;
1891
+ z-index: 2;
1892
+ }
1893
+
1894
+ /* Footer above the bar */
1895
+ .ds-footer{
1896
+ position: absolute;
1897
+ right: 12px;
1898
+ bottom: 10px;
1899
+ display: flex;
1900
+ gap: 8px;
1901
+ align-items: center;
1902
+ justify-content: flex-end;
1903
+ z-index: 3;
1904
+ }
1905
+
1906
+ /* Ensure textarea content sits below overlays */
1907
+ .ds-textarea{
1908
+ position: relative;
1909
+ z-index: 1;
1910
+ }
1911
+
1912
+ /* ===== FIX dropdown menu being clipped/behind ===== */
1913
+
1914
+ /* Let the dropdown menu escape the prompt wrapper */
1915
+ .ds-top{
1916
+ overflow: visible !important; /* IMPORTANT: do not clip the menu */
1917
+ }
1918
+
1919
+ /* Keep the rounded "safe area" look without clipping the menu */
1920
+ .ds-top::after{
1921
+ left: 0 !important;
1922
+ right: 0 !important;
1923
+ bottom: 0 !important;
1924
+ border-bottom-left-radius: 14px !important;
1925
+ border-bottom-right-radius: 14px !important;
1926
+ }
1927
+
1928
+ /* Ensure the footer stays above the safe-area bar */
1929
+ .ds-footer{
1930
+ z-index: 20 !important;
1931
+ }
1932
+
1933
+ /* Make sure the opened menu is above EVERYTHING */
1934
+ .ds-footer .cd-menu{
1935
+ z-index: 999999 !important;
1936
+ }
1937
+
1938
+ /* Sometimes Gradio/columns/cards create stacking contexts;
1939
+ force the whole prompt card above nearby panels */
1940
+ .ds-card{
1941
+ position: relative;
1942
+ z-index: 50;
1943
+ }
1944
+
1945
+ /* --- Fix focus highlight shape (make it match rounded container) --- */
1946
+
1947
+ /* Kill any theme focus ring on the textarea itself */
1948
+ .ds-textarea:focus,
1949
+ .ds-textarea:focus-visible{
1950
+ outline: none !important;
1951
+ box-shadow: none !important;
1952
+ }
1953
+
1954
+ /* Optional: if some themes apply it even when not focused */
1955
+ .ds-textarea{
1956
+ outline: none !important;
1957
+ }
1958
+
1959
+ /* Apply the focus ring to the rounded wrapper instead */
1960
+ .ds-top:focus-within{
1961
+ border-color: rgba(255,255,255,0.22) !important;
1962
+ box-shadow: 0 0 0 3px rgba(255,255,255,0.06) !important;
1963
+ border-radius: 14px !important;
1964
+ }
1965
+
1966
+ /* If you see any tiny square corners, ensure the wrapper clips its own shadow properly */
1967
+ .ds-top{
1968
+ border-radius: 14px !important;
1969
+ }
1970
+
1971
+ /* =========================
1972
+ CameraDropdown: force readable menu text in BOTH themes
1973
+ ========================= */
1974
+
1975
+ /* Menu surface */
1976
+ .cd-menu{
1977
+ background: #2b2b2b !important;
1978
+ border: 1px solid rgba(255,255,255,0.14) !important;
1979
+ }
1980
+
1981
+ /* Title */
1982
+ .cd-title{
1983
+ color: rgba(255,255,255,0.55) !important;
1984
+ }
1985
+
1986
+ /* Items + all descendants (fixes spans / inherited theme colors) */
1987
+ .cd-item,
1988
+ .cd-item *{
1989
+ color: rgba(255,255,255,0.92) !important;
1990
+ }
1991
+
1992
+ /* Hover state */
1993
+ .cd-item:hover{
1994
+ background: rgba(255,255,255,0.10) !important;
1995
+ }
1996
+
1997
+ /* Checkmark */
1998
+ .cd-item::after{
1999
+ color: rgba(255,255,255,0.92) !important;
2000
+ }
2001
+
2002
+ /* (Optional) make sure the trigger stays readable too */
2003
+ .cd-trigger,
2004
+ .cd-trigger *{
2005
+ color: rgba(255,255,255,0.75) !important;
2006
+ }
2007
+
2008
+
2009
+ """
2010
+
2011
+
2012
+
2013
+ with gr.Blocks(title="LTX-2 Video Distilled 🎥🔈") as demo:
2014
+ gr.HTML(
2015
+ """
2016
+ <div style="text-align: center;">
2017
+ <p style="font-size:16px; display: inline; margin: 0;">
2018
+ <strong>LTX-2 Distilled</strong> DiT-based audio-video foundation model
2019
+ </p>
2020
+ <a href="https://huggingface.co/Lightricks/LTX-2"
2021
+ target="_blank"
2022
+ rel="noopener noreferrer"
2023
+ style="display: inline-block; vertical-align: middle; margin-left: 0.5em;">
2024
+ [model]
2025
+ </a>
2026
+ </div>
2027
+ <div style="text-align: center;">
2028
+ <p style="font-size:16px; display: inline; margin: 0;">
2029
+ Using FA3 and Gemma 3 12B 4bit Quantisation for Faster Inference
2030
+ </p>
2031
+ </div>
2032
+ <div style="text-align: center;">
2033
+ <strong>HF Space by:</strong>
2034
+ <a href="https://huggingface.co/alexnasa" target="_blank" rel="noopener noreferrer" style="display: inline-block; vertical-align: middle; margin-left: 0.5em;">
2035
+ <img src="https://img.shields.io/badge/🤗-Follow Me-green.svg">
2036
+ </a>
2037
+ </div>
2038
+ """
2039
+ )
2040
+ with gr.Column(elem_id="col-container"):
2041
+ with gr.Row(elem_id="mode-row"):
2042
+ radioanimated_mode = RadioAnimated(
2043
+ choices=["Image-to-Video", "Motion Control"],
2044
+ value="Image-to-Video",
2045
+ elem_id="radioanimated_mode"
2046
+ )
2047
+ with gr.Row():
2048
+ with gr.Column(elem_id="step-column"):
2049
+
2050
+ input_image = gr.Image(
2051
+ label="First Frame (Optional)",
2052
+ type="filepath",
2053
+ height=256
2054
+ )
2055
+
2056
+ input_video = gr.Video(
2057
+ label="Motion Reference Video",
2058
+ height=256,
2059
+ visible=False,
2060
+ )
2061
+
2062
+ relocate = gr.HTML(
2063
+ value="",
2064
+ html_template="<div></div>",
2065
+ js_on_load=r"""
2066
+ (() => {
2067
+ function moveIntoFooter() {
2068
+ const promptRoot = document.querySelector("#prompt_ui");
2069
+ if (!promptRoot) return false;
2070
+
2071
+ const footer = promptRoot.querySelector(".ds-footer");
2072
+ if (!footer) return false;
2073
+
2074
+ const dur = document.querySelector("#duration_ui .cd-wrap");
2075
+ const res = document.querySelector("#resolution_ui .cd-wrap");
2076
+ const cam = document.querySelector("#camera_ui .cd-wrap");
2077
+
2078
+ if (!dur || !res || !cam) return false;
2079
+
2080
+ footer.appendChild(dur);
2081
+ footer.appendChild(res);
2082
+ footer.appendChild(cam);
2083
+
2084
+ return true;
2085
+ }
2086
+
2087
+ const tick = () => {
2088
+ if (!moveIntoFooter()) requestAnimationFrame(tick);
2089
+ };
2090
+ requestAnimationFrame(tick);
2091
+ })();
2092
+ """
2093
+ )
2094
+
2095
+
2096
+ prompt_ui = PromptBox(
2097
+ value="Make this image come alive with cinematic motion, smooth animation",
2098
+ elem_id="prompt_ui",
2099
+ )
2100
+
2101
+ audio_input = gr.Audio(label="Audio (Optional)", type="filepath")
2102
+
2103
+ prompt = gr.Textbox(
2104
+ label="Prompt",
2105
+ value="Make this image come alive with cinematic motion, smooth animation",
2106
+ lines=3,
2107
+ max_lines=3,
2108
+ placeholder="Describe the motion and animation you want...",
2109
+ visible=False
2110
+ )
2111
+
2112
+ enhance_prompt = gr.Checkbox(
2113
+ label="Enhance Prompt",
2114
+ value=True,
2115
+ visible=False
2116
+ )
2117
+
2118
+ with gr.Accordion("Advanced Settings", open=False, visible=False):
2119
+ seed = gr.Slider(
2120
+ label="Seed",
2121
+ minimum=0,
2122
+ maximum=MAX_SEED,
2123
+ value=DEFAULT_SEED,
2124
+ step=1
2125
+ )
2126
+
2127
+ randomize_seed = gr.Checkbox(label="Randomize Seed", value=True)
2128
+
2129
+
2130
+ with gr.Column(elem_id="step-column"):
2131
+ output_video = gr.Video(label="Generated Video", autoplay=True, height=512)
2132
+
2133
+ with gr.Row(elem_id="controls-row"):
2134
+
2135
+ duration_ui = CameraDropdown(
2136
+ choices=["3s", "5s", "10s", "15s"],
2137
+ value="5s",
2138
+ title="Clip Duration",
2139
+ elem_id="duration_ui"
2140
+ )
2141
+
2142
+ duration = gr.Slider(
2143
+ label="Duration (seconds)",
2144
+ minimum=1.0,
2145
+ maximum=15.0,
2146
+ value=5.0,
2147
+ step=0.1,
2148
+ visible=False
2149
+ )
2150
+
2151
+ ICON_16_9 = """<svg viewBox="0 0 24 24" fill="none" aria-hidden="true">
2152
+ <rect x="3" y="7" width="18" height="10" rx="2" stroke="currentColor" stroke-width="2"/>
2153
+ </svg>"""
2154
+
2155
+ ICON_1_1 = """<svg viewBox="0 0 24 24" fill="none" aria-hidden="true">
2156
+ <rect x="6" y="6" width="12" height="12" rx="2" stroke="currentColor" stroke-width="2"/>
2157
+ </svg>"""
2158
+
2159
+ ICON_9_16 = """<svg viewBox="0 0 24 24" fill="none" aria-hidden="true">
2160
+ <rect x="7" y="3" width="10" height="18" rx="2" stroke="currentColor" stroke-width="2"/>
2161
+ </svg>"""
2162
+
2163
+
2164
+ resolution_ui = CameraDropdown(
2165
+ choices=[
2166
+ {"label": "16:9", "value": "16:9", "icon": ICON_16_9},
2167
+ {"label": "1:1", "value": "1:1", "icon": ICON_1_1},
2168
+ {"label": "9:16", "value": "9:16", "icon": ICON_9_16},
2169
+ ],
2170
+ value="16:9",
2171
+ title="Resolution",
2172
+ elem_id="resolution_ui"
2173
+ )
2174
+
2175
+
2176
+ width = gr.Number(label="Width", value=DEFAULT_1_STAGE_WIDTH, precision=0, visible=False)
2177
+ height = gr.Number(label="Height", value=DEFAULT_1_STAGE_HEIGHT, precision=0, visible=False)
2178
+
2179
+ camera_ui = CameraDropdown(
2180
+ choices=[name for name, _ in VISIBLE_RUNTIME_LORA_CHOICES],
2181
+ value="No LoRA",
2182
+ title="Camera LoRA",
2183
+ elem_id="camera_ui",
2184
+ )
2185
+
2186
+ # Hidden real dropdown (backend value)
2187
+ camera_lora = gr.Dropdown(
2188
+ label="Camera Control LoRA",
2189
+ choices=[name for name, _ in VISIBLE_RUNTIME_LORA_CHOICES],
2190
+ value="No LoRA",
2191
+ visible=False
2192
+ )
2193
+
2194
+ generate_btn = gr.Button("🤩 Generate Video", variant="primary", elem_classes="button-gradient")
2195
+
2196
+ camera_ui.change(
2197
+ fn=lambda x: x,
2198
+ inputs=camera_ui,
2199
+ outputs=camera_lora,
2200
+ api_visibility="private"
2201
+ )
2202
+
2203
+ radioanimated_mode.change(
2204
+ fn=on_mode_change,
2205
+ inputs=radioanimated_mode,
2206
+ outputs=[input_video],
2207
+ api_visibility="private",
2208
+ )
2209
+
2210
+
2211
+ duration_ui.change(
2212
+ fn=apply_duration,
2213
+ inputs=duration_ui,
2214
+ outputs=[duration],
2215
+ api_visibility="private"
2216
+ )
2217
+ resolution_ui.change(
2218
+ fn=apply_resolution,
2219
+ inputs=resolution_ui,
2220
+ outputs=[width, height],
2221
+ api_visibility="private"
2222
+ )
2223
+ prompt_ui.change(
2224
+ fn=lambda x: x,
2225
+ inputs=prompt_ui,
2226
+ outputs=prompt,
2227
+ api_visibility="private"
2228
+ )
2229
+
2230
+
2231
+ generate_btn.click(
2232
+ fn=generate_video,
2233
+ inputs=[
2234
+ input_image,
2235
+ prompt,
2236
+ duration,
2237
+ input_video,
2238
+ radioanimated_mode,
2239
+ enhance_prompt,
2240
+ seed,
2241
+ randomize_seed,
2242
+ height,
2243
+ width,
2244
+ camera_lora,
2245
+ audio_input
2246
+ ],
2247
+ outputs=[output_video]
2248
+ )
2249
+
2250
+ # Add example
2251
+ gr.Examples(
2252
+ examples=[
2253
+ [
2254
+ "supergirl-2.png",
2255
+ "A fuzzy puppet superhero character resembling a female puppet with blonde hair and a blue superhero suit sleeping in bed and just waking up, she gradually gets up, rubbing her eyes and looking at her dog that just popped on the bed. the scene feels chaotic, comedic, and emotional with expressive puppet reactions, cinematic lighting, smooth camera motion, shallow depth of field, and high-quality puppet-style animation",
2256
+ "Static",
2257
+ "16:9",
2258
+ "Image-to-Video",
2259
+ None,
2260
+ "supergirl.m4a"
2261
+ ],
2262
+ [
2263
+ "supergirl.png",
2264
+ "A fuzzy puppet superhero character resembling a female puppet with blonde hair and a blue superhero suit stands inside an icy cave made of frozen walls and icicles, she looks panicked and frantic, rapidly turning her head left and right and scanning the cave while waving her arms and shouting angrily and desperately, mouthing the words “where the hell is my dog,” her movements exaggerated and puppet-like with high energy and urgency, suddenly a second puppet dog bursts into frame from the side, jumping up excitedly and tackling her affectionately while licking her face repeatedly, she freezes in surprise and then breaks into relief and laughter as the dog continues licking her, the scene feels chaotic, comedic, and emotional with expressive puppet reactions, cinematic lighting, smooth camera motion, shallow depth of field, and high-quality puppet-style animation",
2265
+ "No LoRA",
2266
+ "16:9",
2267
+ "Image-to-Video",
2268
+ None,
2269
+ None,
2270
+ ],
2271
+ [
2272
+ "clay.png",
2273
+ "a character doing a tiktok dance by moving their heads side to side with dramatic lighting and cinematic effects and singing",
2274
+ "No LoRA",
2275
+ "9:16",
2276
+ "Motion Control",
2277
+ "tiktok.mp4",
2278
+ None,
2279
+ ],
2280
+ [
2281
+ "paint.png",
2282
+ "a character doing a tiktok dance by moving their heads side to side with dramatic lighting and cinematic effects and singing",
2283
+ "No LoRA",
2284
+ "9:16",
2285
+ "Motion Control",
2286
+ "tiktok.mp4",
2287
+ None,
2288
+ ],
2289
+ [
2290
+ "highland.png",
2291
+ "Realistic POV selfie-style video in a snowy, foggy field. Two shaggy Highland cows with long curved horns stand ahead. The camera is handheld and slightly shaky. The woman filming talks nervously and excitedly in a vlog tone: \"Oh my god guys… look how big those horns are… I’m kinda scared.\" The cow on the left walks toward the camera in a cute, bouncy, hopping way, curious and gentle. Snow crunches under its hooves, breath visible in the cold air. The horns look massive from the POV. As the cow gets very close, its wet nose with slight dripping fills part of the frame. She laughs nervously but reaches out and pets the cow. The cow makes deep, soft, interesting mooing and snorting sounds, calm and friendly. Ultra-realistic, natural lighting, immersive audio, documentary-style realism.",
2292
+ "No LoRA",
2293
+ "16:9",
2294
+ "Image-to-Video",
2295
+ None,
2296
+ None,
2297
+ ],
2298
+ [
2299
+ "wednesday.png",
2300
+ "A cinematic dolly out of Wednesday Addams frozen mid-dance on a dark, blue-lit ballroom floor as students move indistinctly behind her, their footsteps and muffled music reduced to a distant, underwater thrum; the audio foregrounds her steady breathing and the faint rustle of fabric as she slowly raises one arm, never breaking eye contact with the camera, then after a deliberately long silence she speaks in a flat, dry, perfectly controlled voice, “I don’t dance… I vibe code,” each word crisp and unemotional, followed by an abrupt cutoff of her voice as the background sound swells slightly, reinforcing the deadpan humor, with precise lip sync, minimal facial movement, stark gothic lighting, and cinematic realism.",
2301
+ "Zoom Out",
2302
+ "16:9",
2303
+ "Image-to-Video",
2304
+ None,
2305
+ None,
2306
+ ],
2307
+ [
2308
+ "astronaut.png",
2309
+ "An astronaut hatches from a fragile egg on the surface of the Moon, the shell cracking and peeling apart in gentle low-gravity motion. Fine lunar dust lifts and drifts outward with each movement, floating in slow arcs before settling back onto the ground. The astronaut pushes free in a deliberate, weightless motion, small fragments of the egg tumbling and spinning through the air. In the background, the deep darkness of space subtly shifts as stars glide with the camera's movement, emphasizing vast depth and scale. The camera performs a smooth, cinematic slow push-in, with natural parallax between the foreground dust, the astronaut, and the distant starfield. Ultra-realistic detail, physically accurate low-gravity motion, cinematic lighting, and a breath-taking, movie-like shot.",
2310
+ "Static",
2311
+ "1:1",
2312
+ "Image-to-Video",
2313
+ None,
2314
+ None,
2315
+ ],
2316
+ ],
2317
+ fn=generate_video_example,
2318
+ inputs=[input_image, prompt_ui, camera_ui, resolution_ui, radioanimated_mode, input_video, audio_input],
2319
+ outputs = [output_video],
2320
+ label="Examples",
2321
+ cache_examples=True,
2322
+ )
2323
+
2324
+
2325
+ if __name__ == "__main__":
2326
+ demo.launch(ssr_mode=False, mcp_server=True, css=css)
astronaut.png ADDED

Git LFS Details

  • SHA256: 3fba12d552c8441df1253c58b29e6e0c3d3b29ca5f16825178d5761500bc64c7
  • Pointer size: 131 Bytes
  • Size of remote file: 663 kB
clay.png ADDED

Git LFS Details

  • SHA256: e7abbbe4419b768fff07d22770ee8eb4594e3be0ef54ec8ce7894cd12b1d4e1d
  • Pointer size: 131 Bytes
  • Size of remote file: 651 kB
highland.png ADDED

Git LFS Details

  • SHA256: eb44a723f305f7ce274d38bbc91c64c3a832f43ea29708b07dba36310751a8d0
  • Pointer size: 132 Bytes
  • Size of remote file: 3.4 MB
paint.png ADDED

Git LFS Details

  • SHA256: 28b97869fb0219d8a6688b441ba198cc1035574d00cdc8387296f69c4ee6de28
  • Pointer size: 132 Bytes
  • Size of remote file: 1.11 MB
requirements.txt CHANGED
@@ -1,5 +1,21 @@
 
 
 
1
  transformers
2
- git+https://github.com/huggingface/diffusers.git
3
- accelerate
4
  safetensors
5
- sentencepiece
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ einops
2
+ numpy
3
+ torchaudio==2.8.0
4
  transformers
 
 
5
  safetensors
6
+ accelerate
7
+ flashpack==0.1.2
8
+ scikit-image>=0.25.2
9
+ imageio
10
+ imageio-ffmpeg
11
+ av
12
+ tqdm
13
+ pillow
14
+ scipy>=1.14
15
+ flash-attn-3 @ https://huggingface.co/alexnasa/flash-attn-3/resolve/main/128/flash_attn_3-3.0.0b1-cp39-abi3-linux_x86_64.whl
16
+ bitsandbytes
17
+ opencv-python
18
+ controlnet_aux
19
+ onnxruntime-gpu
20
+ matplotlib
21
+ dwpose
supergirl-2.png ADDED

Git LFS Details

  • SHA256: 2e17b3169c2d27d2a96cfffd109da7ca47bffa7d7c71962f9c2bb8fb47051b2f
  • Pointer size: 131 Bytes
  • Size of remote file: 521 kB
supergirl.m4a ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bf84b27e65e876f20c966df21749f848615159a5e3eb971b7ce95cb75e3f49aa
3
+ size 113408
supergirl.png ADDED

Git LFS Details

  • SHA256: 997856aa10003e7fa635b364d77255355f91640ee0fef1dd5bb2e8c19f09535e
  • Pointer size: 131 Bytes
  • Size of remote file: 762 kB
tiktok.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:42e30ff54f52bf914a3e7279a4394217d06288302ef81b25b9f8c713399c0e3d
3
+ size 1419707