Fabrice-TIERCELIN commited on
Commit
2f97780
·
verified ·
1 Parent(s): 8788929

Upload 8 files

Browse files
Files changed (9) hide show
  1. .gitattributes +4 -0
  2. README.md +13 -0
  3. app.py +296 -273
  4. astronaut.jpg +3 -0
  5. cat_selfie.JPG +3 -0
  6. kill_bill.jpeg +3 -0
  7. ltx2_two_stage.py +84 -0
  8. requirements.txt +10 -3
  9. wednesday.png +3 -0
.gitattributes CHANGED
@@ -71,3 +71,7 @@ squatting_sonic.png filter=lfs diff=lfs merge=lfs -text
71
  tower_takes_off.png filter=lfs diff=lfs merge=lfs -text
72
  ugly_sonic.jpeg filter=lfs diff=lfs merge=lfs -text
73
  bird.webp filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
71
  tower_takes_off.png filter=lfs diff=lfs merge=lfs -text
72
  ugly_sonic.jpeg filter=lfs diff=lfs merge=lfs -text
73
  bird.webp filter=lfs diff=lfs merge=lfs -text
74
+ 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
README.md CHANGED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: LTX-2 Video Fast
3
+ emoji: 🎥💨
4
+ colorFrom: yellow
5
+ colorTo: indigo
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
11
+ ---
12
+
13
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py CHANGED
@@ -1,299 +1,322 @@
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
  try:
143
- for i in range(number):
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
 
4
+ # Add packages to Python path
5
+ current_dir = Path(__file__).parent
6
+ sys.path.insert(0, str(current_dir / "packages" / "ltx-pipelines" / "src"))
7
+ sys.path.insert(0, str(current_dir / "packages" / "ltx-core" / "src"))
 
 
 
 
 
8
 
9
+ import spaces
10
  import gradio as gr
11
+ from gradio_client import Client, handle_file
12
  import numpy as np
 
13
  import random
14
+ import torch
15
+ from typing import Optional
 
 
 
 
 
16
  from pathlib import Path
17
+ from huggingface_hub import hf_hub_download
18
+ from gradio_client import Client
19
+ from ltx_pipelines.distilled import DistilledPipeline
20
+ from ltx_core.tiling import TilingConfig
21
+ from ltx_core.loader.primitives import LoraPathStrengthAndSDOps
22
+ from ltx_core.loader.sd_ops import LTXV_LORA_COMFY_RENAMING_MAP
23
+ from ltx_pipelines.constants import (
24
+ DEFAULT_SEED,
25
+ DEFAULT_HEIGHT,
26
+ DEFAULT_WIDTH,
27
+ DEFAULT_NUM_FRAMES,
28
+ DEFAULT_FRAME_RATE,
29
+ DEFAULT_LORA_STRENGTH,
30
+ )
31
 
32
+ MAX_SEED = np.iinfo(np.int32).max
33
+ # Default prompt from docstring example
34
+ 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."
35
 
36
+ # HuggingFace Hub defaults
37
+ DEFAULT_REPO_ID = "Lightricks/LTX-2"
38
+ DEFAULT_CHECKPOINT_FILENAME = "ltx-2-19b-dev-fp8.safetensors"
39
+ DEFAULT_DISTILLED_LORA_FILENAME = "ltx-2-19b-distilled-lora-384.safetensors"
40
+ DEFAULT_SPATIAL_UPSAMPLER_FILENAME = "ltx-2-spatial-upscaler-x2-1.0.safetensors"
41
 
42
+ # Text encoder space URL
43
+ TEXT_ENCODER_SPACE = "linoyts/gemma-text-encoder"
44
 
45
+ def get_hub_or_local_checkpoint(repo_id: Optional[str] = None, filename: Optional[str] = None):
46
+ """Download from HuggingFace Hub or use local checkpoint."""
47
+ if repo_id is None and filename is None:
48
+ raise ValueError("Please supply at least one of `repo_id` or `filename`")
49
+
50
+ if repo_id is not None:
51
+ if filename is None:
52
+ raise ValueError("If repo_id is specified, filename must also be specified.")
53
+ print(f"Downloading {filename} from {repo_id}...")
54
+ ckpt_path = hf_hub_download(repo_id=repo_id, filename=filename)
55
+ print(f"Downloaded to {ckpt_path}")
56
+ else:
57
+ ckpt_path = filename
58
+
59
+ return ckpt_path
60
+
61
+
62
+ # Initialize pipeline at startup
63
+ print("=" * 80)
64
+ print("Loading LTX-2 Distilled pipeline...")
65
+ print("=" * 80)
66
+
67
+ checkpoint_path = get_hub_or_local_checkpoint(DEFAULT_REPO_ID, DEFAULT_CHECKPOINT_FILENAME)
68
+ distilled_lora_path = get_hub_or_local_checkpoint(DEFAULT_REPO_ID, DEFAULT_DISTILLED_LORA_FILENAME)
69
+ spatial_upsampler_path = get_hub_or_local_checkpoint(DEFAULT_REPO_ID, DEFAULT_SPATIAL_UPSAMPLER_FILENAME)
70
+
71
+ print(f"Initializing pipeline with:")
72
+ print(f" checkpoint_path={checkpoint_path}")
73
+ print(f" distilled_lora_path={distilled_lora_path}")
74
+ print(f" spatial_upsampler_path={spatial_upsampler_path}")
75
+ print(f" text_encoder_space={TEXT_ENCODER_SPACE}")
76
 
77
+ # Load distilled LoRA as a regular LoRA
78
+ loras = [
79
+ LoraPathStrengthAndSDOps(
80
+ path=distilled_lora_path,
81
+ strength=DEFAULT_LORA_STRENGTH,
82
+ sd_ops=LTXV_LORA_COMFY_RENAMING_MAP,
83
+ )
84
+ ]
85
+
86
+ # Initialize pipeline WITHOUT text encoder (gemma_root=None)
87
+ # Text encoding will be done by external space
88
+ pipeline = DistilledPipeline(
89
+ checkpoint_path=checkpoint_path,
90
+ spatial_upsampler_path=spatial_upsampler_path,
91
+ gemma_root=None, # No text encoder in this space
92
+ loras=loras,
93
+ fp8transformer=True,
94
+ local_files_only=False,
95
+ )
96
+
97
+ # Initialize text encoder client
98
+ print(f"Connecting to text encoder space: {TEXT_ENCODER_SPACE}")
99
+ try:
100
+ text_encoder_client = Client(TEXT_ENCODER_SPACE)
101
+ print("✓ Text encoder client connected!")
102
+ except Exception as e:
103
+ print(f"⚠ Warning: Could not connect to text encoder space: {e}")
104
+ text_encoder_client = None
105
+
106
+ print("=" * 80)
107
+ print("Pipeline fully loaded and ready!")
108
+ print("=" * 80)
109
+
110
+ @spaces.GPU(duration=300)
111
+ def generate_video(
112
  input_image,
113
+ prompt: str,
114
+ duration: float,
115
+ enhance_prompt: bool = True,
116
+ seed: int = 42,
117
+ randomize_seed: bool = True,
118
+ height: int = DEFAULT_HEIGHT,
119
+ width: int = DEFAULT_WIDTH,
120
  progress=gr.Progress(track_tqdm=True)
121
  ):
122
+ """Generate a video based on the given parameters."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
123
  try:
124
+ # Randomize seed if checkbox is enabled
125
+ current_seed = random.randint(0, MAX_SEED) if randomize_seed else int(seed)
126
+
127
+ # Calculate num_frames from duration (using fixed 24 fps)
128
+ frame_rate = 24.0
129
+ num_frames = int(duration * frame_rate) + 1 # +1 to ensure we meet the duration
130
+
131
+ # Create output directory if it doesn't exist
132
+ output_dir = Path("outputs")
133
+ output_dir.mkdir(exist_ok=True)
134
+ output_path = output_dir / f"video_{current_seed}.mp4"
135
+
136
+ # Handle image input
137
+ images = []
138
+ temp_image_path = None # Initialize to None
139
+
140
+ if input_image is not None:
141
+ # Save uploaded image temporarily
142
+ temp_image_path = output_dir / f"temp_input_{current_seed}.jpg"
143
+ if hasattr(input_image, 'save'):
144
+ input_image.save(temp_image_path)
145
+ else:
146
+ # If it's a file path already
147
+ temp_image_path = Path(input_image)
148
+ # Format: (image_path, frame_idx, strength)
149
+ images = [(str(temp_image_path), 0, 1.0)]
150
+
151
+ # Get embeddings from text encoder space
152
+ print(f"Encoding prompt: {prompt}")
153
+
154
+ if text_encoder_client is None:
155
+ raise RuntimeError(
156
+ f"Text encoder client not connected. Please ensure the text encoder space "
157
+ f"({TEXT_ENCODER_SPACE}) is running and accessible."
158
+ )
159
+
160
+ try:
161
+ # Prepare image for upload if it exists
162
+ image_input = None
163
+ if temp_image_path is not None:
164
+ image_input = handle_file(str(temp_image_path))
165
+
166
+ result = text_encoder_client.predict(
167
+ prompt=prompt,
168
+ enhance_prompt=enhance_prompt,
169
+ input_image=image_input,
170
+ seed=current_seed,
171
+ negative_prompt="",
172
+ api_name="/encode_prompt"
173
+ )
174
+ embedding_path = result[0] # Path to .pt file
175
+ print(f"Embeddings received from: {embedding_path}")
176
 
177
+ # Load embeddings
178
+ embeddings = torch.load(embedding_path)
179
+ video_context = embeddings['video_context']
180
+ audio_context = embeddings['audio_context']
181
+ print("✓ Embeddings loaded successfully")
182
+ except Exception as e:
183
+ raise RuntimeError(
184
+ f"Failed to get embeddings from text encoder space: {e}\n"
185
+ f"Please ensure {TEXT_ENCODER_SPACE} is running properly."
186
+ )
187
+
188
+ # Run inference - progress automatically tracks tqdm from pipeline
189
+ pipeline(
190
+ prompt=prompt,
191
+ output_path=str(output_path),
192
+ seed=current_seed,
193
+ height=height,
194
+ width=width,
195
+ num_frames=num_frames,
196
+ frame_rate=frame_rate,
197
+ images=images,
198
+ tiling_config=TilingConfig.default(),
199
+ video_context=video_context,
200
+ audio_context=audio_context,
201
+ )
202
+
203
+ return str(output_path), current_seed
204
+
205
+ except Exception as e:
206
+ import traceback
207
+ error_msg = f"Error: {str(e)}\n{traceback.format_exc()}"
208
+ print(error_msg)
209
+ return None
210
+
211
+
212
+ # Create Gradio interface
213
+ with gr.Blocks(title="LTX-2 Video Distilled 🎥🔈") as demo:
214
+ gr.Markdown("# LTX-2 Distilled 🎥🔈: The First Open Source Audio-Video Model")
215
+ gr.Markdown("Fast, state-of-the-art video & audio generation with [Lightricks LTX-2 TI2V model](https://huggingface.co/Lightricks/LTX-2) and [distillation LoRA](https://huggingface.co/Lightricks/LTX-2/blob/main/ltx-2-19b-distilled-lora-384.safetensors) for accelerated inference. Read more: [[model]](https://huggingface.co/Lightricks/LTX-2), [[code]](https://github.com/Lightricks/LTX-2)")
216
+ with gr.Row():
217
+ with gr.Column():
218
+ input_image = gr.Image(
219
+ label="Input Image (Optional)",
220
+ type="pil"
221
+ )
222
+
223
+ prompt = gr.Textbox(
224
+ label="Prompt",
225
+ info="for best results - make it as elaborate as possible",
226
+ value="Make this image come alive with cinematic motion, smooth animation",
227
+ lines=3,
228
+ placeholder="Describe the motion and animation you want..."
229
+ )
230
+ with gr.Row():
231
+ duration = gr.Slider(
232
+ label="Duration (seconds)",
233
+ minimum=1.0,
234
+ maximum=10.0,
235
+ value=3.0,
236
+ step=0.1
237
+ )
238
+ enhance_prompt = gr.Checkbox(
239
+ label="Enhance Prompt",
240
+ value=True
241
  )
242
+
243
+ generate_btn = gr.Button("Generate Video", variant="primary", size="lg")
244
+
245
+ with gr.Accordion("Advanced Settings", open=False):
246
+ seed = gr.Slider(
247
+ label="Seed",
248
+ minimum=0,
249
+ maximum=MAX_SEED,
250
+ value=DEFAULT_SEED,
251
+ step=1
252
+ )
253
+
254
+ randomize_seed = gr.Checkbox(
255
+ label="Randomize Seed",
256
+ value=True
257
+ )
258
+
259
+ with gr.Row():
260
+ width = gr.Number(
261
+ label="Width",
262
+ value=DEFAULT_WIDTH,
263
+ precision=0
264
  )
265
+ height = gr.Number(
266
+ label="Height",
267
+ value=DEFAULT_HEIGHT,
268
+ precision=0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
269
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
270
 
271
+ with gr.Column():
272
+ output_video = gr.Video(label="Generated Video", autoplay=True)
273
+
274
+ generate_btn.click(
275
+ fn=generate_video,
276
+ inputs=[
277
+ input_image,
278
+ prompt,
279
+ duration,
280
+ enhance_prompt,
281
+ seed,
282
+ randomize_seed,
283
+ height,
284
+ width,
285
  ],
286
+ outputs=[output_video,seed]
 
 
287
  )
288
 
289
+ # Add example
290
+ gr.Examples(
291
+ examples=[
292
+ [
293
+ "kill_bill.jpeg",
294
+ "A low, subsonic drone pulses as Uma Thurman's character, Beatrix Kiddo, holds her razor-sharp katana blade steady in the cinematic lighting. A faint electrical hum fills the silence. Suddenly, accompanied by a deep metallic groan, the polished steel begins to soften and distort, like heated metal starting to lose its structural integrity. Discordant strings swell as the blade's perfect edge slowly warps and droops, molten steel beginning to flow downward in silvery rivulets while maintaining its metallic sheen—each drip producing a wet, viscous stretching sound. The transformation starts subtly at first—a slight bend in the blade—then accelerates as the metal becomes increasingly fluid, the groaning intensifying. The camera holds steady on her face as her piercing eyes gradually narrow, not with lethal focus, but with confusion and growing alarm as she watches her weapon dissolve before her eyes. She whispers under her breath, voice flat with disbelief: 'Wait, what?' Her heartbeat rises in the mix—thump... thump-thump—as her breathing quickens slightly while she witnesses this impossible transformation. Sharp violin stabs punctuate each breath. The melting intensifies, the katana's perfect form becoming increasingly abstract, dripping like liquid mercury from her grip. Molten droplets fall to the ground with soft, bell-like pings. Unintelligible whispers fade in and out as her expression shifts from calm readiness to bewilderment and concern, her heartbeat now pounding like a war drum, as her legendary instrument of vengeance literally liquefies in her hands, leaving her defenseless and disoriented. All sound cuts to silence—then a single devastating bass drop as the final droplet falls, leaving only her unsteady breathing in the dark.",
295
+ 5.0,
296
+ ],
297
+ [
298
+ "wednesday.png",
299
+ "A cinematic close-up 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.",
300
+ 5.0,
301
+ ],
302
+ [
303
+ "astronaut.jpg",
304
+ "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.",
305
+ 3.0,
306
+ ]
307
 
308
+ ],
309
+ fn=generate_video,
310
+ inputs=[input_image, prompt, duration],
311
+ outputs = [output_video, seed],
312
+ label="Example",
313
+ cache_examples=True,
314
+ cache_mode="lazy",
 
 
 
315
  )
316
 
317
+
318
+ css = '''
319
+ .gradio-container .contain{max-width: 1200px !important; margin: 0 auto !important}
320
+ '''
321
+ if __name__ == "__main__":
322
+ demo.launch(theme=gr.themes.Citrus(), css=css)
astronaut.jpg ADDED

Git LFS Details

  • SHA256: b1257de01d8440baea06865ea35ce557d885b6dda700281ba25202193c58285c
  • Pointer size: 131 Bytes
  • Size of remote file: 958 kB
cat_selfie.JPG ADDED

Git LFS Details

  • SHA256: 077e3d965090c9028c69c00931675f42e1acc815c6eb450ab291b3b72d211a8e
  • Pointer size: 131 Bytes
  • Size of remote file: 251 kB
kill_bill.jpeg ADDED

Git LFS Details

  • SHA256: d1db15fcc022a6c639d14d4b246c40729af2873ca81d4acf7b48d36d62b8d864
  • Pointer size: 131 Bytes
  • Size of remote file: 240 kB
ltx2_two_stage.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ python ltx2_two_stage.py \
3
+ --image "astronaut.jpg" 0 1.0 \
4
+ --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." \
5
+ --output_path="t2v_2.mp4" \
6
+ --gemma_root="google/gemma-3-12b-it-qat-q4_0-unquantized" \
7
+ --checkpoint_path="rc1/ltx-2-19b-dev-rc1.safetensors" \
8
+ --distilled_lora_path "rc1/ltx-2-19b-distilled-lora-384-rc1.safetensors" \
9
+ --spatial_upsampler_path "rc1/ltx-2-spatial-upscaler-x2-1.0-rc1.safetensors"
10
+
11
+ """
12
+
13
+ from huggingface_hub import hf_hub_download
14
+ from typing import Optional
15
+ from ltx_pipelines import utils
16
+ from ltx_pipelines.constants import DEFAULT_LORA_STRENGTH
17
+ from ltx_core.loader.primitives import LoraPathStrengthAndSDOps
18
+ from ltx_core.loader.sd_ops import LTXV_LORA_COMFY_RENAMING_MAP
19
+ from ltx_pipelines.ti2vid_two_stages import TI2VidTwoStagesPipeline
20
+ from ltx_core.tiling import TilingConfig
21
+
22
+
23
+ def get_hub_or_local_checkpoint(repo_id: Optional[str] = None, filename: Optional[str] = None):
24
+ if repo_id is None and filename is None:
25
+ raise ValueError("Please supply at least one of `repo_id` or `filename`")
26
+
27
+ if repo_id is not None:
28
+ if filename is None:
29
+ raise ValueError("If repo_id is specified, filename must also be specified.")
30
+ ckpt_path = hf_hub_download(repo_id=repo_id, filename=filename)
31
+ else:
32
+ ckpt_path = filename
33
+
34
+ return ckpt_path
35
+
36
+
37
+ def default_2_stage_arg_parser_mod():
38
+ parser = utils.default_2_stage_arg_parser()
39
+ parser.add_argument("--local_files_only", action="store_true")
40
+ parser.add_argument("--checkpoint_id", type=str, default="diffusers-internal-dev/new-ltx-model")
41
+ return parser
42
+
43
+
44
+ def main() -> None:
45
+ parser = default_2_stage_arg_parser_mod()
46
+ args = parser.parse_args()
47
+
48
+ checkpoint_path = get_hub_or_local_checkpoint(args.checkpoint_id, args.checkpoint_path)
49
+ distilled_lora_path = get_hub_or_local_checkpoint(args.checkpoint_id, args.distilled_lora_path)
50
+ spatial_upsampler_path = get_hub_or_local_checkpoint(args.checkpoint_id, args.spatial_upsampler_path)
51
+
52
+ lora_strengths = (args.lora_strength + [DEFAULT_LORA_STRENGTH] * len(args.lora))[: len(args.lora)]
53
+ loras = [
54
+ LoraPathStrengthAndSDOps(lora, strength, LTXV_LORA_COMFY_RENAMING_MAP)
55
+ for lora, strength in zip(args.lora, lora_strengths, strict=True)
56
+ ]
57
+ pipeline = TI2VidTwoStagesPipeline(
58
+ checkpoint_path=checkpoint_path,
59
+ distilled_lora_path=distilled_lora_path,
60
+ distilled_lora_strength=args.distilled_lora_strength,
61
+ spatial_upsampler_path=spatial_upsampler_path,
62
+ gemma_root=args.gemma_root,
63
+ loras=loras,
64
+ fp8transformer=args.enable_fp8,
65
+ local_files_only=args.local_files_only
66
+ )
67
+ pipeline(
68
+ prompt=args.prompt,
69
+ negative_prompt=args.negative_prompt,
70
+ output_path=args.output_path,
71
+ seed=args.seed,
72
+ height=args.height,
73
+ width=args.width,
74
+ num_frames=args.num_frames,
75
+ frame_rate=args.frame_rate,
76
+ num_inference_steps=args.num_inference_steps,
77
+ cfg_guidance_scale=args.cfg_guidance_scale,
78
+ images=args.images,
79
+ tiling_config=TilingConfig.default(),
80
+ )
81
+
82
+
83
+ if __name__ == "__main__":
84
+ main()
requirements.txt CHANGED
@@ -1,5 +1,12 @@
 
 
 
1
  transformers
2
- git+https://github.com/huggingface/diffusers.git
3
- accelerate
4
  safetensors
5
- sentencepiece
 
 
 
 
 
 
 
1
+ einops
2
+ numpy
3
+ torchaudio
4
  transformers
 
 
5
  safetensors
6
+ accelerate
7
+ flashpack==0.1.2
8
+ scikit-image>=0.25.2
9
+ av
10
+ tqdm
11
+ pillow
12
+ scipy>=1.14
wednesday.png ADDED

Git LFS Details

  • SHA256: 27193cae97c24a31ab574a21fc3c598627c28ab60edb0c60209acdb8071cf1ea
  • Pointer size: 132 Bytes
  • Size of remote file: 1.36 MB