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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import torch
|
3 |
+
import numpy as np
|
4 |
+
import tempfile
|
5 |
+
import os
|
6 |
+
import spaces
|
7 |
+
from diffusers import LTXLatentUpsamplePipeline
|
8 |
+
from pipeline_ltx_condition_control import LTXConditionPipeline
|
9 |
+
from diffusers.utils import export_to_video, load_video
|
10 |
+
from torchvision import transforms
|
11 |
+
import random
|
12 |
+
|
13 |
+
|
14 |
+
dtype = torch.bfloat16
|
15 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
16 |
+
|
17 |
+
pipeline = LTXConditionPipeline.from_pretrained("Lightricks/LTX-Video-0.9.7-dev", torch_dtype=dtype)
|
18 |
+
pipe_upsample = LTXLatentUpsamplePipeline.from_pretrained("Lightricks/ltxv-spatial-upscaler-0.9.7", vae=pipeline.vae, torch_dtype=dtype)
|
19 |
+
pipeline.to(device)
|
20 |
+
pipe_upsample.to(device)
|
21 |
+
pipeline.vae.enable_tiling()
|
22 |
+
|
23 |
+
|
24 |
+
CONTROL_LORAS = {
|
25 |
+
"canny": {
|
26 |
+
"repo": "Lightricks/LTX-Video-ICLoRA-canny-13b-0.9.7",
|
27 |
+
"weight_name": "ltxv-097-ic-lora-canny-control-diffusers.safetensors",
|
28 |
+
"adapter_name": "canny_lora"
|
29 |
+
},
|
30 |
+
"depth": {
|
31 |
+
"repo": "Lightricks/LTX-Video-ICLoRA-depth-13b-0.9.7",
|
32 |
+
"weight_name": "ltxv-097-ic-lora-depth-control-diffusers.safetensors",
|
33 |
+
"adapter_name": "depth_lora"
|
34 |
+
},
|
35 |
+
"pose": {
|
36 |
+
"repo": "Lightricks/LTX-Video-ICLoRA-pose-13b-0.9.7",
|
37 |
+
"weight_name": "ltxv-097-ic-lora-pose-control-diffusers.safetensors",
|
38 |
+
"adapter_name": "pose_lora"
|
39 |
+
}
|
40 |
+
}
|
41 |
+
@spaces.GPU()
|
42 |
+
def read_video(video_path: str) -> torch.Tensor:
|
43 |
+
"""
|
44 |
+
Reads a video file and converts it into a torch.Tensor with the shape [F, C, H, W].
|
45 |
+
"""
|
46 |
+
pil_images = load_video(video_path)
|
47 |
+
to_tensor_transform = transforms.ToTensor()
|
48 |
+
video_tensor = torch.stack([to_tensor_transform(img) for img in pil_images])
|
49 |
+
return video_tensor
|
50 |
+
|
51 |
+
def round_to_nearest_resolution_acceptable_by_vae(height, width, vae_temporal_compression_ratio):
|
52 |
+
height = height - (height % vae_temporal_compression_ratio)
|
53 |
+
width = width - (width % vae_temporal_compression_ratio)
|
54 |
+
return height, width
|
55 |
+
|
56 |
+
@spaces.GPU()
|
57 |
+
def load_control_lora(control_type, current_lora_state):
|
58 |
+
"""Load the specified control LoRA, unloading any previous one"""
|
59 |
+
|
60 |
+
if control_type not in CONTROL_LORAS:
|
61 |
+
raise ValueError(f"Unknown control type: {control_type}")
|
62 |
+
|
63 |
+
# If same LoRA is already loaded, do nothing
|
64 |
+
if current_lora_state == control_type:
|
65 |
+
print(f"{control_type} LoRA already loaded")
|
66 |
+
return current_lora_state
|
67 |
+
|
68 |
+
# Unload current LoRA if any
|
69 |
+
if current_lora_state is not None:
|
70 |
+
try:
|
71 |
+
pipeline.unload_lora_weights()
|
72 |
+
print(f"Unloaded previous LoRA: {current_lora_state}")
|
73 |
+
except Exception as e:
|
74 |
+
print(f"Warning: Could not unload previous LoRA: {e}")
|
75 |
+
|
76 |
+
# Load new LoRA
|
77 |
+
lora_config = CONTROL_LORAS[control_type]
|
78 |
+
try:
|
79 |
+
pipeline.load_lora_weights(
|
80 |
+
lora_config["repo"],
|
81 |
+
weight_name=lora_config["weight_name"],
|
82 |
+
adapter_name=lora_config["adapter_name"]
|
83 |
+
)
|
84 |
+
pipeline.set_adapters([lora_config["adapter_name"]], adapter_weights=[1.0])
|
85 |
+
new_lora_state = control_type
|
86 |
+
print(f"Loaded {control_type} LoRA successfully")
|
87 |
+
return new_lora_state
|
88 |
+
except Exception as e:
|
89 |
+
print(f"Error loading {control_type} LoRA: {e}")
|
90 |
+
raise
|
91 |
+
|
92 |
+
def process_video_for_canny(video_tensor):
|
93 |
+
"""
|
94 |
+
Process video for canny control.
|
95 |
+
Placeholder function - will return video as-is for now.
|
96 |
+
TODO: Implement canny edge detection processing
|
97 |
+
"""
|
98 |
+
print("Processing video for canny control...")
|
99 |
+
|
100 |
+
return video_tensor
|
101 |
+
|
102 |
+
def process_video_for_depth(video_tensor):
|
103 |
+
"""
|
104 |
+
Process video for depth control.
|
105 |
+
Placeholder function - will return video as-is for now.
|
106 |
+
TODO: Implement depth estimation processing
|
107 |
+
"""
|
108 |
+
print("Processing video for depth control...")
|
109 |
+
|
110 |
+
return video_tensor
|
111 |
+
|
112 |
+
def process_video_for_pose(video_tensor):
|
113 |
+
"""
|
114 |
+
Process video for pose control.
|
115 |
+
Placeholder function - will return video as-is for now.
|
116 |
+
TODO: Implement pose estimation processing
|
117 |
+
"""
|
118 |
+
print("Processing video for pose control...")
|
119 |
+
|
120 |
+
return video_tensor
|
121 |
+
|
122 |
+
def process_video_for_control(video_tensor, control_type):
|
123 |
+
"""Process video based on the selected control type"""
|
124 |
+
if control_type == "canny":
|
125 |
+
return process_video_for_canny(video_tensor)
|
126 |
+
elif control_type == "depth":
|
127 |
+
return process_video_for_depth(video_tensor)
|
128 |
+
elif control_type == "pose":
|
129 |
+
return process_video_for_pose(video_tensor)
|
130 |
+
else:
|
131 |
+
return video_tensor
|
132 |
+
|
133 |
+
@spaces.GPU()
|
134 |
+
def generate_video(
|
135 |
+
reference_video,
|
136 |
+
prompt,
|
137 |
+
control_type,
|
138 |
+
current_lora_state,
|
139 |
+
duration=3.0,
|
140 |
+
negative_prompt="worst quality, inconsistent motion, blurry, jittery, distorted",
|
141 |
+
height=768,
|
142 |
+
width=1152,
|
143 |
+
num_inference_steps=30,
|
144 |
+
guidance_scale=5.0,
|
145 |
+
guidance_rescale=0.7,
|
146 |
+
decode_timestep=0.05,
|
147 |
+
decode_noise_scale=0.025,
|
148 |
+
image_cond_noise_scale=0.0,
|
149 |
+
seed=0,
|
150 |
+
randomize_seed=False,
|
151 |
+
progress=gr.Progress()
|
152 |
+
):
|
153 |
+
try:
|
154 |
+
# Initialize models if needed
|
155 |
+
# Models are already loaded at startup
|
156 |
+
|
157 |
+
if reference_video is None:
|
158 |
+
return None, "Please upload a reference video."
|
159 |
+
|
160 |
+
if not prompt.strip():
|
161 |
+
return None, "Please enter a prompt."
|
162 |
+
|
163 |
+
# Handle seed
|
164 |
+
if randomize_seed:
|
165 |
+
seed = random.randint(0, 2**32 - 1)
|
166 |
+
|
167 |
+
progress(0.05, desc="Loading control LoRA...")
|
168 |
+
|
169 |
+
# Load the appropriate control LoRA and update state
|
170 |
+
updated_lora_state = load_control_lora(control_type, current_lora_state)
|
171 |
+
|
172 |
+
progress(0.1, desc="Loading reference video...")
|
173 |
+
|
174 |
+
# Read the reference video
|
175 |
+
video = read_video(reference_video)
|
176 |
+
|
177 |
+
progress(0.15, desc="Processing video for control...")
|
178 |
+
|
179 |
+
# Process video based on control type
|
180 |
+
processed_video = process_video_for_control(video, control_type)
|
181 |
+
|
182 |
+
progress(0.2, desc="Preparing generation parameters...")
|
183 |
+
|
184 |
+
# Calculate number of frames from duration (24 fps)
|
185 |
+
fps = 24
|
186 |
+
num_frames = int(duration * fps) + 1 # +1 for proper frame count
|
187 |
+
# Ensure num_frames is valid for the model (multiple of temporal compression + 1)
|
188 |
+
temporal_compression = pipeline.vae_temporal_compression_ratio
|
189 |
+
num_frames = ((num_frames - 1) // temporal_compression) * temporal_compression + 1
|
190 |
+
|
191 |
+
# Calculate downscaled dimensions
|
192 |
+
downscale_factor = 2 / 3
|
193 |
+
downscaled_height = int(height * downscale_factor)
|
194 |
+
downscaled_width = int(width * downscale_factor)
|
195 |
+
downscaled_height, downscaled_width = round_to_nearest_resolution_acceptable_by_vae(
|
196 |
+
downscaled_height, downscaled_width, pipeline.vae_temporal_compression_ratio
|
197 |
+
)
|
198 |
+
|
199 |
+
progress(0.3, desc="Generating video at lower resolution...")
|
200 |
+
|
201 |
+
# 1. Generate video at smaller resolution
|
202 |
+
latents = pipeline(
|
203 |
+
reference_video=processed_video, # Use processed video
|
204 |
+
prompt=prompt,
|
205 |
+
negative_prompt=negative_prompt,
|
206 |
+
width=downscaled_width,
|
207 |
+
height=downscaled_height,
|
208 |
+
num_frames=num_frames,
|
209 |
+
num_inference_steps=num_inference_steps,
|
210 |
+
decode_timestep=decode_timestep,
|
211 |
+
decode_noise_scale=decode_noise_scale,
|
212 |
+
image_cond_noise_scale=image_cond_noise_scale,
|
213 |
+
guidance_scale=guidance_scale,
|
214 |
+
guidance_rescale=guidance_rescale,
|
215 |
+
generator=torch.Generator().manual_seed(seed),
|
216 |
+
output_type="latent",
|
217 |
+
).frames
|
218 |
+
|
219 |
+
progress(0.6, desc="Upscaling video...")
|
220 |
+
|
221 |
+
# 2. Upscale generated video
|
222 |
+
upscaled_height, upscaled_width = downscaled_height * 2, downscaled_width * 2
|
223 |
+
upscaled_latents = pipe_upsample(
|
224 |
+
latents=latents,
|
225 |
+
output_type="latent"
|
226 |
+
).frames
|
227 |
+
|
228 |
+
progress(0.8, desc="Final denoising and processing...")
|
229 |
+
|
230 |
+
# 3. Denoise the upscaled video
|
231 |
+
video_output = pipeline(
|
232 |
+
prompt=prompt,
|
233 |
+
negative_prompt=negative_prompt,
|
234 |
+
width=upscaled_width,
|
235 |
+
height=upscaled_height,
|
236 |
+
num_frames=num_frames,
|
237 |
+
denoise_strength=0.4,
|
238 |
+
num_inference_steps=10,
|
239 |
+
latents=upscaled_latents,
|
240 |
+
decode_timestep=decode_timestep,
|
241 |
+
decode_noise_scale=decode_noise_scale,
|
242 |
+
image_cond_noise_scale=image_cond_noise_scale,
|
243 |
+
guidance_scale=guidance_scale,
|
244 |
+
guidance_rescale=guidance_rescale,
|
245 |
+
generator=torch.Generator().manual_seed(seed),
|
246 |
+
output_type="pil",
|
247 |
+
).frames[0]
|
248 |
+
|
249 |
+
progress(0.9, desc="Finalizing output...")
|
250 |
+
|
251 |
+
# 4. Downscale to expected resolution
|
252 |
+
video_output = [frame.resize((width, height)) for frame in video_output]
|
253 |
+
|
254 |
+
# Export to temporary file
|
255 |
+
with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as tmp_file:
|
256 |
+
output_path = tmp_file.name
|
257 |
+
export_to_video(video_output, output_path, fps=fps)
|
258 |
+
|
259 |
+
progress(1.0, desc="Complete!")
|
260 |
+
|
261 |
+
return output_path, updated_lora_state
|
262 |
+
|
263 |
+
except Exception as e:
|
264 |
+
return None, current_lora_state
|
265 |
+
|
266 |
+
# Create Gradio interface
|
267 |
+
with gr.Blocks() as demo:
|
268 |
+
gr.Markdown(
|
269 |
+
"""
|
270 |
+
# LTX Video Control
|
271 |
+
"""
|
272 |
+
)
|
273 |
+
|
274 |
+
# State variable for tracking current LoRA
|
275 |
+
current_lora_state = gr.State(value=None)
|
276 |
+
|
277 |
+
with gr.Row():
|
278 |
+
with gr.Column(scale=1):
|
279 |
+
|
280 |
+
reference_video = gr.Video(
|
281 |
+
label="Reference Video",
|
282 |
+
height=300
|
283 |
+
)
|
284 |
+
|
285 |
+
prompt = gr.Textbox(
|
286 |
+
label="Prompt",
|
287 |
+
placeholder="Describe the video you want to generate...",
|
288 |
+
lines=3,
|
289 |
+
value="A graceful pink swan gliding smoothly across a serene lake, its elegant neck curved as it moves through the calm water. The swan's soft pink feathers shimmer in the gentle sunlight, creating ripples that spread outward in concentric circles. The lake is surrounded by lush green trees reflected in the still water. Shot from a side angle, the camera slowly follows the swan's peaceful movement across the frame. Cinematic lighting, 4K quality, smooth motion."
|
290 |
+
)
|
291 |
+
|
292 |
+
# Control Type Selection
|
293 |
+
control_type = gr.Radio(
|
294 |
+
label="Control Type",
|
295 |
+
choices=["canny", "depth", "pose"],
|
296 |
+
value="canny",
|
297 |
+
info="Choose the type of control guidance for video generation"
|
298 |
+
)
|
299 |
+
|
300 |
+
duration = gr.Slider(
|
301 |
+
label="Duration (seconds)",
|
302 |
+
minimum=1.0,
|
303 |
+
maximum=10.0,
|
304 |
+
step=0.5,
|
305 |
+
value=3.0
|
306 |
+
)
|
307 |
+
|
308 |
+
negative_prompt = gr.Textbox(
|
309 |
+
label="Negative Prompt",
|
310 |
+
placeholder="What you don't want in the video...",
|
311 |
+
lines=2,
|
312 |
+
value="worst quality, inconsistent motion, blurry, jittery, distorted"
|
313 |
+
)
|
314 |
+
|
315 |
+
# Advanced Settings
|
316 |
+
with gr.Accordion("Advanced Settings", open=False):
|
317 |
+
with gr.Row():
|
318 |
+
height = gr.Slider(
|
319 |
+
label="Height",
|
320 |
+
minimum=256,
|
321 |
+
maximum=1024,
|
322 |
+
step=32,
|
323 |
+
value=768
|
324 |
+
)
|
325 |
+
width = gr.Slider(
|
326 |
+
label="Width",
|
327 |
+
minimum=256,
|
328 |
+
maximum=1536,
|
329 |
+
step=32,
|
330 |
+
value=1152
|
331 |
+
)
|
332 |
+
|
333 |
+
num_inference_steps = gr.Slider(
|
334 |
+
label="Inference Steps",
|
335 |
+
minimum=10,
|
336 |
+
maximum=50,
|
337 |
+
step=1,
|
338 |
+
value=30
|
339 |
+
)
|
340 |
+
|
341 |
+
with gr.Row():
|
342 |
+
guidance_scale = gr.Slider(
|
343 |
+
label="Guidance Scale",
|
344 |
+
minimum=1.0,
|
345 |
+
maximum=15.0,
|
346 |
+
step=0.1,
|
347 |
+
value=5.0
|
348 |
+
)
|
349 |
+
guidance_rescale = gr.Slider(
|
350 |
+
label="Guidance Rescale",
|
351 |
+
minimum=0.0,
|
352 |
+
maximum=1.0,
|
353 |
+
step=0.05,
|
354 |
+
value=0.7
|
355 |
+
)
|
356 |
+
|
357 |
+
with gr.Row():
|
358 |
+
decode_timestep = gr.Slider(
|
359 |
+
label="Decode Timestep",
|
360 |
+
minimum=0.0,
|
361 |
+
maximum=1.0,
|
362 |
+
step=0.01,
|
363 |
+
value=0.05
|
364 |
+
)
|
365 |
+
decode_noise_scale = gr.Slider(
|
366 |
+
label="Decode Noise Scale",
|
367 |
+
minimum=0.0,
|
368 |
+
maximum=0.1,
|
369 |
+
step=0.005,
|
370 |
+
value=0.025
|
371 |
+
)
|
372 |
+
|
373 |
+
image_cond_noise_scale = gr.Slider(
|
374 |
+
label="Image Condition Noise Scale",
|
375 |
+
minimum=0.0,
|
376 |
+
maximum=0.5,
|
377 |
+
step=0.01,
|
378 |
+
value=0.0
|
379 |
+
)
|
380 |
+
|
381 |
+
with gr.Row():
|
382 |
+
randomize_seed = gr.Checkbox(
|
383 |
+
label="Randomize Seed",
|
384 |
+
value=False
|
385 |
+
)
|
386 |
+
seed = gr.Number(
|
387 |
+
label="Seed",
|
388 |
+
value=0,
|
389 |
+
precision=0
|
390 |
+
)
|
391 |
+
|
392 |
+
generate_btn = gr.Button(
|
393 |
+
"Generate",
|
394 |
+
)
|
395 |
+
|
396 |
+
with gr.Column(scale=1):
|
397 |
+
|
398 |
+
output_video = gr.Video(
|
399 |
+
label="Generated Video",
|
400 |
+
height=400
|
401 |
+
)
|
402 |
+
|
403 |
+
|
404 |
+
|
405 |
+
# Event handlers
|
406 |
+
generate_btn.click(
|
407 |
+
fn=generate_video,
|
408 |
+
inputs=[
|
409 |
+
reference_video,
|
410 |
+
prompt,
|
411 |
+
control_type,
|
412 |
+
current_lora_state,
|
413 |
+
duration,
|
414 |
+
negative_prompt,
|
415 |
+
height,
|
416 |
+
width,
|
417 |
+
num_inference_steps,
|
418 |
+
guidance_scale,
|
419 |
+
guidance_rescale,
|
420 |
+
decode_timestep,
|
421 |
+
decode_noise_scale,
|
422 |
+
image_cond_noise_scale,
|
423 |
+
seed,
|
424 |
+
randomize_seed
|
425 |
+
],
|
426 |
+
outputs=[output_video, current_lora_state],
|
427 |
+
show_progress=True
|
428 |
+
)
|
429 |
+
|
430 |
+
if __name__ == "__main__":
|
431 |
+
demo.launch()
|