dagloop5 commited on
Commit
e40d438
·
verified ·
1 Parent(s): f5c3128

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -698
app.py DELETED
@@ -1,698 +0,0 @@
1
- import os
2
- import subprocess
3
- import sys
4
-
5
- # Disable torch.compile / dynamo before any torch import
6
- os.environ["TORCH_COMPILE_DISABLE"] = "1"
7
- os.environ["TORCHDYNAMO_DISABLE"] = "1"
8
-
9
- # Install xformers for memory-efficient attention
10
- subprocess.run([sys.executable, "-m", "pip", "install", "xformers==0.0.32.post2", "--no-build-isolation"], check=False)
11
-
12
- # Clone LTX-2 repo and install packages
13
- LTX_REPO_URL = "https://github.com/Lightricks/LTX-2.git"
14
- LTX_REPO_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "LTX-2")
15
-
16
- if not os.path.exists(LTX_REPO_DIR):
17
- print(f"Cloning {LTX_REPO_URL}...")
18
- subprocess.run(["git", "clone", "--depth", "1", LTX_REPO_URL, LTX_REPO_DIR], check=True)
19
-
20
- print("Installing ltx-core and ltx-pipelines from cloned repo...")
21
- subprocess.run(
22
- [sys.executable, "-m", "pip", "install", "--force-reinstall", "--no-deps", "-e",
23
- os.path.join(LTX_REPO_DIR, "packages", "ltx-core"),
24
- "-e", os.path.join(LTX_REPO_DIR, "packages", "ltx-pipelines")],
25
- check=True,
26
- )
27
-
28
- sys.path.insert(0, os.path.join(LTX_REPO_DIR, "packages", "ltx-pipelines", "src"))
29
- sys.path.insert(0, os.path.join(LTX_REPO_DIR, "packages", "ltx-core", "src"))
30
-
31
- import logging
32
- import random
33
- import tempfile
34
- from pathlib import Path
35
-
36
- import torch
37
- torch._dynamo.config.suppress_errors = True
38
- torch._dynamo.config.disable = True
39
-
40
- import spaces
41
- import gradio as gr
42
- import numpy as np
43
- from huggingface_hub import hf_hub_download, snapshot_download
44
-
45
- from ltx_core.components.diffusion_steps import EulerDiffusionStep
46
- from ltx_core.components.noisers import GaussianNoiser
47
- from ltx_core.model.audio_vae import encode_audio as vae_encode_audio
48
- from ltx_core.model.upsampler import upsample_video
49
- from ltx_core.model.video_vae import TilingConfig, get_video_chunks_number, decode_video as vae_decode_video
50
- from ltx_core.quantization import QuantizationPolicy
51
- from ltx_core.types import Audio, AudioLatentShape, VideoPixelShape
52
- from ltx_pipelines.distilled import DistilledPipeline
53
- from ltx_pipelines.utils import euler_denoising_loop
54
- from ltx_pipelines.utils.args import ImageConditioningInput
55
- from ltx_pipelines.utils.constants import DISTILLED_SIGMA_VALUES, STAGE_2_DISTILLED_SIGMA_VALUES
56
- from ltx_pipelines.utils.helpers import (
57
- cleanup_memory,
58
- combined_image_conditionings,
59
- denoise_video_only,
60
- encode_prompts,
61
- simple_denoising_func,
62
- )
63
-
64
- from ltx_core.loader.primitives import LoraPathStrengthAndSDOps
65
- from ltx_core.loader.sd_ops import LTXV_LORA_COMFY_RENAMING_MAP
66
-
67
- from ltx_pipelines.utils.media_io import decode_audio_from_file, encode_video
68
-
69
- # Force-patch xformers attention into the LTX attention module.
70
- from ltx_core.model.transformer import attention as _attn_mod
71
- print(f"[ATTN] Before patch: memory_efficient_attention={_attn_mod.memory_efficient_attention}")
72
- try:
73
- from xformers.ops import memory_efficient_attention as _mea
74
- _attn_mod.memory_efficient_attention = _mea
75
- print(f"[ATTN] After patch: memory_efficient_attention={_attn_mod.memory_efficient_attention}")
76
- except Exception as e:
77
- print(f"[ATTN] xformers patch FAILED: {type(e).__name__}: {e}")
78
-
79
- logging.getLogger().setLevel(logging.INFO)
80
-
81
- MAX_SEED = np.iinfo(np.int32).max
82
- DEFAULT_PROMPT = (
83
- "An astronaut hatches from a fragile egg on the surface of the Moon, "
84
- "the shell cracking and peeling apart in gentle low-gravity motion. "
85
- "Fine lunar dust lifts and drifts outward with each movement, floating "
86
- "in slow arcs before settling back onto the ground."
87
- )
88
- DEFAULT_FRAME_RATE = 24.0
89
-
90
- # Resolution presets: (width, height)
91
- RESOLUTIONS = {
92
- "high": {"16:9": (1536, 1024), "9:16": (1024, 1536), "1:1": (1024, 1024)},
93
- "low": {"16:9": (768, 512), "9:16": (512, 768), "1:1": (768, 768)},
94
- }
95
-
96
-
97
- class LTX23DistilledA2VPipeline(DistilledPipeline):
98
- """DistilledPipeline with optional audio conditioning."""
99
-
100
- def __call__(
101
- self,
102
- prompt: str,
103
- seed: int,
104
- height: int,
105
- width: int,
106
- num_frames: int,
107
- frame_rate: float,
108
- images: list[ImageConditioningInput],
109
- audio_path: str | None = None,
110
- tiling_config: TilingConfig | None = None,
111
- enhance_prompt: bool = False,
112
- ):
113
- # Standard path when no audio input is provided.
114
- print(prompt)
115
- if audio_path is None:
116
- return super().__call__(
117
- prompt=prompt,
118
- seed=seed,
119
- height=height,
120
- width=width,
121
- num_frames=num_frames,
122
- frame_rate=frame_rate,
123
- images=images,
124
- tiling_config=tiling_config,
125
- enhance_prompt=enhance_prompt,
126
- )
127
-
128
- generator = torch.Generator(device=self.device).manual_seed(seed)
129
- noiser = GaussianNoiser(generator=generator)
130
- stepper = EulerDiffusionStep()
131
- dtype = torch.bfloat16
132
-
133
- (ctx_p,) = encode_prompts(
134
- [prompt],
135
- self.model_ledger,
136
- enhance_first_prompt=enhance_prompt,
137
- enhance_prompt_image=images[0].path if len(images) > 0 else None,
138
- )
139
- video_context, audio_context = ctx_p.video_encoding, ctx_p.audio_encoding
140
-
141
- video_duration = num_frames / frame_rate
142
- decoded_audio = decode_audio_from_file(audio_path, self.device, 0.0, video_duration)
143
- if decoded_audio is None:
144
- raise ValueError(f"Could not extract audio stream from {audio_path}")
145
-
146
- encoded_audio_latent = vae_encode_audio(decoded_audio, self.model_ledger.audio_encoder())
147
- audio_shape = AudioLatentShape.from_duration(batch=1, duration=video_duration, channels=8, mel_bins=16)
148
- expected_frames = audio_shape.frames
149
- actual_frames = encoded_audio_latent.shape[2]
150
-
151
- if actual_frames > expected_frames:
152
- encoded_audio_latent = encoded_audio_latent[:, :, :expected_frames, :]
153
- elif actual_frames < expected_frames:
154
- pad = torch.zeros(
155
- encoded_audio_latent.shape[0],
156
- encoded_audio_latent.shape[1],
157
- expected_frames - actual_frames,
158
- encoded_audio_latent.shape[3],
159
- device=encoded_audio_latent.device,
160
- dtype=encoded_audio_latent.dtype,
161
- )
162
- encoded_audio_latent = torch.cat([encoded_audio_latent, pad], dim=2)
163
-
164
- video_encoder = self.model_ledger.video_encoder()
165
- transformer = self.model_ledger.transformer()
166
- stage_1_sigmas = torch.tensor(DISTILLED_SIGMA_VALUES, device=self.device)
167
-
168
- def denoising_loop(sigmas, video_state, audio_state, stepper):
169
- return euler_denoising_loop(
170
- sigmas=sigmas,
171
- video_state=video_state,
172
- audio_state=audio_state,
173
- stepper=stepper,
174
- denoise_fn=simple_denoising_func(
175
- video_context=video_context,
176
- audio_context=audio_context,
177
- transformer=transformer,
178
- ),
179
- )
180
-
181
- stage_1_output_shape = VideoPixelShape(
182
- batch=1,
183
- frames=num_frames,
184
- width=width // 2,
185
- height=height // 2,
186
- fps=frame_rate,
187
- )
188
- stage_1_conditionings = combined_image_conditionings(
189
- images=images,
190
- height=stage_1_output_shape.height,
191
- width=stage_1_output_shape.width,
192
- video_encoder=video_encoder,
193
- dtype=dtype,
194
- device=self.device,
195
- )
196
- video_state = denoise_video_only(
197
- output_shape=stage_1_output_shape,
198
- conditionings=stage_1_conditionings,
199
- noiser=noiser,
200
- sigmas=stage_1_sigmas,
201
- stepper=stepper,
202
- denoising_loop_fn=denoising_loop,
203
- components=self.pipeline_components,
204
- dtype=dtype,
205
- device=self.device,
206
- initial_audio_latent=encoded_audio_latent,
207
- )
208
-
209
- torch.cuda.synchronize()
210
- cleanup_memory()
211
-
212
- upscaled_video_latent = upsample_video(
213
- latent=video_state.latent[:1],
214
- video_encoder=video_encoder,
215
- upsampler=self.model_ledger.spatial_upsampler(),
216
- )
217
- stage_2_sigmas = torch.tensor(STAGE_2_DISTILLED_SIGMA_VALUES, device=self.device)
218
- stage_2_output_shape = VideoPixelShape(batch=1, frames=num_frames, width=width, height=height, fps=frame_rate)
219
- stage_2_conditionings = combined_image_conditionings(
220
- images=images,
221
- height=stage_2_output_shape.height,
222
- width=stage_2_output_shape.width,
223
- video_encoder=video_encoder,
224
- dtype=dtype,
225
- device=self.device,
226
- )
227
- video_state = denoise_video_only(
228
- output_shape=stage_2_output_shape,
229
- conditionings=stage_2_conditionings,
230
- noiser=noiser,
231
- sigmas=stage_2_sigmas,
232
- stepper=stepper,
233
- denoising_loop_fn=denoising_loop,
234
- components=self.pipeline_components,
235
- dtype=dtype,
236
- device=self.device,
237
- noise_scale=stage_2_sigmas[0],
238
- initial_video_latent=upscaled_video_latent,
239
- initial_audio_latent=encoded_audio_latent,
240
- )
241
-
242
- torch.cuda.synchronize()
243
- del transformer
244
- del video_encoder
245
- cleanup_memory()
246
-
247
- decoded_video = vae_decode_video(
248
- video_state.latent,
249
- self.model_ledger.video_decoder(),
250
- tiling_config,
251
- generator,
252
- )
253
- original_audio = Audio(
254
- waveform=decoded_audio.waveform.squeeze(0),
255
- sampling_rate=decoded_audio.sampling_rate,
256
- )
257
- return decoded_video, original_audio
258
-
259
-
260
- # Model repos
261
- LTX_MODEL_REPO = "Lightricks/LTX-2.3"
262
- GEMMA_REPO ="rahul7star/gemma-3-12b-it-heretic"
263
-
264
-
265
- # Download model checkpoints
266
- print("=" * 80)
267
- print("Downloading LTX-2.3 distilled model + Gemma...")
268
- print("=" * 80)
269
-
270
- checkpoint_path = hf_hub_download(repo_id=LTX_MODEL_REPO, filename="ltx-2.3-22b-distilled.safetensors")
271
- spatial_upsampler_path = hf_hub_download(repo_id=LTX_MODEL_REPO, filename="ltx-2.3-spatial-upscaler-x2-1.0.safetensors")
272
- gemma_root = snapshot_download(repo_id=GEMMA_REPO)
273
-
274
- print(f"Checkpoint: {checkpoint_path}")
275
- print(f"Spatial upsampler: {spatial_upsampler_path}")
276
- print(f"Gemma root: {gemma_root}")
277
-
278
- # Download the LoRAs we want to support and prepare helper to create LoraPathStrengthAndSDOps
279
- LORA_REPO = "dagloop5/LoRA"
280
- pose_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="pose_enhancer.safetensors")
281
- general_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="general_enhancer.safetensors")
282
- motion_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="motion_helper.safetensors")
283
-
284
- print(f"Downloaded LoRAs: {pose_lora_path}, {general_lora_path}, {motion_lora_path}")
285
-
286
- def build_loras_tuple(pose_strength: float, general_strength: float, motion_strength: float):
287
- """
288
- Return a list of LoraPathStrengthAndSDOps matching LTX loader expectations.
289
- Uses the LTX renaming map for SD key remapping (helps with some LoRA formats).
290
- """
291
- return [
292
- LoraPathStrengthAndSDOps(path=str(pose_lora_path), strength=float(pose_strength), sd_ops=LTXV_LORA_COMFY_RENAMING_MAP),
293
- LoraPathStrengthAndSDOps(path=str(general_lora_path), strength=float(general_strength), sd_ops=LTXV_LORA_COMFY_RENAMING_MAP),
294
- LoraPathStrengthAndSDOps(path=str(motion_lora_path), strength=float(motion_strength), sd_ops=LTXV_LORA_COMFY_RENAMING_MAP),
295
- ]
296
-
297
- # initial strengths (you can change defaults)
298
- INITIAL_LORAS = build_loras_tuple(1.0, 1.0, 1.0)
299
-
300
- # --- START robust CUDA detection and quant selection ---
301
- def _probe_cuda_ready() -> bool:
302
- """
303
- Return True if a CUDA-capable device is actually available and can be initialized.
304
- Uses multiple checks and a tiny safe probe to avoid later surprise RuntimeError.
305
- """
306
- try:
307
- # First quick checks
308
- if not torch.cuda.is_available():
309
- return False
310
- if torch.cuda.device_count() <= 0:
311
- return False
312
- # Try a tiny CUDA probe (safe): allocate a tiny tensor on CUDA and free it.
313
- try:
314
- t = torch.tensor([0], device="cuda")
315
- del t
316
- except Exception:
317
- return False
318
- # If we reached here, CUDA seems usable.
319
- return True
320
- except Exception:
321
- return False
322
-
323
-
324
- use_cuda = _probe_cuda_ready()
325
- print(f"[INFO] cuda probe -> use_cuda = {use_cuda}")
326
-
327
- # Only enable FP8 quantization if a usable CUDA device is present.
328
- quant = None
329
- if use_cuda:
330
- # Safe to enable FP8 (Triton-backed) quantization.
331
- quant = QuantizationPolicy.fp8_cast()
332
- else:
333
- # Fallback to no quantization (if available) to avoid Triton paths.
334
- quant = getattr(QuantizationPolicy, "none", None)
335
-
336
- quant_kwargs = {}
337
- if quant is not None:
338
- quant_kwargs["quantization"] = quant
339
- # --- END robust CUDA detection and quant selection ---
340
-
341
- pipeline = LTX23DistilledA2VPipeline(
342
- distilled_checkpoint_path=checkpoint_path,
343
- spatial_upsampler_path=spatial_upsampler_path,
344
- gemma_root=gemma_root,
345
- loras=INITIAL_LORAS,
346
- **quant_kwargs,
347
- )
348
- # --- end replace ---
349
-
350
- # --- REPLACE preload block with CUDA-aware version ---
351
- print("Preloading models (GPU preloads only if CUDA is available)...")
352
- ledger = pipeline.model_ledger
353
-
354
- if use_cuda:
355
- try:
356
- # Preload models (this will trigger GPU-side building; only do this when CUDA is present)
357
- _transformer = ledger.transformer()
358
- _video_encoder = ledger.video_encoder()
359
- _video_decoder = ledger.video_decoder()
360
- _audio_encoder = ledger.audio_encoder()
361
- _audio_decoder = ledger.audio_decoder()
362
- _vocoder = ledger.vocoder()
363
- _spatial_upsampler = ledger.spatial_upsampler()
364
- _text_encoder = ledger.text_encoder()
365
- _embeddings_processor = ledger.gemma_embeddings_processor()
366
- print("All models preloaded onto GPU (Gemma text encoder and audio encoder included).")
367
- except Exception as e:
368
- # If FP8/Triton or other GPU initialization fails, print warning and continue in safe (lazy) mode.
369
- print(f"[WARNING] Failed to preload GPU models at startup: {type(e).__name__}: {e}")
370
- print("[WARNING] Falling back to lazy model loading / reduced quantization (if possible).")
371
- else:
372
- # No CUDA — do not attempt GPU preloads that will invoke Triton kernels.
373
- print("[INFO] No CUDA device detected — skipping GPU preloads. Models will be loaded lazily (CPU).")
374
- # --- end replace ---
375
-
376
- print("=" * 80)
377
- print("Pipeline ready!")
378
- print("=" * 80)
379
-
380
-
381
- def log_memory(tag: str):
382
- try:
383
- if torch.cuda.is_available():
384
- allocated = torch.cuda.memory_allocated() / 1024**3
385
- peak = torch.cuda.max_memory_allocated() / 1024**3
386
- try:
387
- free, total = torch.cuda.mem_get_info()
388
- free_gb = free / 1024**3
389
- total_gb = total / 1024**3
390
- except Exception:
391
- free_gb = total_gb = 0.0
392
- print(f"[VRAM {tag}] allocated={allocated:.2f}GB peak={peak:.2f}GB free={free_gb:.2f}GB total={total_gb:.2f}GB")
393
- else:
394
- # Basic CPU fallback logging
395
- print(f"[VRAM {tag}] CUDA not available — running on CPU.")
396
- except Exception as e:
397
- # Defensive: don't let logging crash the app
398
- print(f"[log_memory error] {type(e).__name__}: {e}")
399
-
400
-
401
- def detect_aspect_ratio(image) -> str:
402
- if image is None:
403
- return "16:9"
404
- if hasattr(image, "size"):
405
- w, h = image.size
406
- elif hasattr(image, "shape"):
407
- h, w = image.shape[:2]
408
- else:
409
- return "16:9"
410
- ratio = w / h
411
- candidates = {"16:9": 16 / 9, "9:16": 9 / 16, "1:1": 1.0}
412
- return min(candidates, key=lambda k: abs(ratio - candidates[k]))
413
-
414
-
415
- def on_image_upload(first_image, last_image, high_res):
416
- ref_image = first_image if first_image is not None else last_image
417
- aspect = detect_aspect_ratio(ref_image)
418
- tier = "high" if high_res else "low"
419
- w, h = RESOLUTIONS[tier][aspect]
420
- return gr.update(value=w), gr.update(value=h)
421
-
422
-
423
- def on_highres_toggle(first_image, last_image, high_res):
424
- ref_image = first_image if first_image is not None else last_image
425
- aspect = detect_aspect_ratio(ref_image)
426
- tier = "high" if high_res else "low"
427
- w, h = RESOLUTIONS[tier][aspect]
428
- return gr.update(value=w), gr.update(value=h)
429
-
430
- @torch.inference_mode()
431
- def generate_video(
432
- first_image,
433
- last_image,
434
- input_audio,
435
- prompt: str,
436
- duration: float,
437
- enhance_prompt: bool = True,
438
- seed: int = 42,
439
- randomize_seed: bool = True,
440
- height: int = 1024,
441
- width: int = 1536,
442
- pose_lora_strength: float = 1.0,
443
- general_lora_strength: float = 1.0,
444
- motion_lora_strength: float = 1.0,
445
- progress=gr.Progress(track_tqdm=True),
446
- ):
447
- try:
448
- if use_cuda:
449
- try:
450
- torch.cuda.reset_peak_memory_stats()
451
- except Exception:
452
- pass
453
- log_memory("start")
454
-
455
- current_seed = random.randint(0, MAX_SEED) if randomize_seed else int(seed)
456
-
457
- # --- LoRA dynamic update: rebuild ledger models in-place when strengths change ---
458
- try:
459
- current_ledger = pipeline.model_ledger
460
- # helper to compare strengths quickly
461
- def _get_current_strengths(ledger_obj):
462
- return tuple(float(lora.strength) for lora in getattr(ledger_obj, "loras", ()))
463
-
464
- requested_strengths = (float(pose_lora_strength), float(general_lora_strength), float(motion_lora_strength))
465
- if _get_current_strengths(current_ledger) != requested_strengths:
466
- # replace ledger.loras with new strengths (list)
467
- current_ledger.loras = build_loras_tuple(*requested_strengths)
468
-
469
- if torch.cuda.is_available():
470
- # Only try to clear VRAM and rebuild on GPU-enabled hosts
471
- try:
472
- current_ledger.clear_vram()
473
- except Exception:
474
- # Fallback: remove cached attributes to force rebuild on next access
475
- for k in list(vars(current_ledger).keys()):
476
- if k in (
477
- "_transformer",
478
- "_video_encoder",
479
- "_video_decoder",
480
- "_audio_encoder",
481
- "_audio_decoder",
482
- "_vocoder",
483
- "_spatial_upsampler",
484
- "_text_encoder",
485
- "_gemma_embeddings_processor",
486
- ):
487
- vars(current_ledger).pop(k, None)
488
- # Preload the models again on GPU so they're available before pipeline call
489
- try:
490
- _ = current_ledger.transformer()
491
- _ = current_ledger.video_encoder()
492
- _ = current_ledger.video_decoder()
493
- _ = current_ledger.audio_encoder()
494
- _ = current_ledger.audio_decoder()
495
- _ = current_ledger.vocoder()
496
- _ = current_ledger.spatial_upsampler()
497
- _ = current_ledger.text_encoder()
498
- _ = current_ledger.gemma_embeddings_processor()
499
- torch.cuda.empty_cache()
500
- except Exception as e:
501
- print(f"[LoRA preload warning] Failed to preload models after LoRA change: {type(e).__name__}: {e}")
502
- # continue — the pipeline will attempt to build when called
503
- else:
504
- # No CUDA: we updated the ledger.loras but won't attempt GPU preloads.
505
- print("[INFO] LoRA strengths updated (CPU-only; models will be applied lazily).")
506
- except Exception as e:
507
- # if this fails, proceed with the existing pipeline (safer to continue than to crash)
508
- print(f"[LoRA rebuild warning] Could not update LoRA strengths in-place: {type(e).__name__}: {e}")
509
- # --- end LoRA update ---
510
-
511
- frame_rate = DEFAULT_FRAME_RATE
512
- num_frames = int(duration * frame_rate) + 1
513
- num_frames = ((num_frames - 1 + 7) // 8) * 8 + 1
514
-
515
- print(f"Generating: {height}x{width}, {num_frames} frames ({duration}s), seed={current_seed}")
516
-
517
- images = []
518
- output_dir = Path("outputs")
519
- output_dir.mkdir(exist_ok=True)
520
-
521
- if first_image is not None:
522
- temp_first_path = output_dir / f"temp_first_{current_seed}.jpg"
523
- if hasattr(first_image, "save"):
524
- first_image.save(temp_first_path)
525
- else:
526
- temp_first_path = Path(first_image)
527
- images.append(ImageConditioningInput(path=str(temp_first_path), frame_idx=0, strength=1.0))
528
-
529
- if last_image is not None:
530
- temp_last_path = output_dir / f"temp_last_{current_seed}.jpg"
531
- if hasattr(last_image, "save"):
532
- last_image.save(temp_last_path)
533
- else:
534
- temp_last_path = Path(last_image)
535
- images.append(ImageConditioningInput(path=str(temp_last_path), frame_idx=num_frames - 1, strength=1.0))
536
-
537
- tiling_config = TilingConfig.default()
538
- video_chunks_number = get_video_chunks_number(num_frames, tiling_config)
539
-
540
- log_memory("before pipeline call")
541
-
542
- try:
543
- video, audio = pipeline(
544
- prompt=prompt,
545
- seed=current_seed,
546
- height=int(height),
547
- width=int(width),
548
- num_frames=num_frames,
549
- frame_rate=frame_rate,
550
- images=images,
551
- audio_path=input_audio,
552
- tiling_config=tiling_config,
553
- enhance_prompt=enhance_prompt,
554
- )
555
- except Exception as e:
556
- msg = str(e).lower()
557
-
558
- if "no cuda" in msg or "cuda error" in msg or "triton" in msg or "no cuda-capable" in msg:
559
- print(f"[ERROR] GPU initialization failed during pipeline call: {type(e).__name__}: {e}")
560
- print("[ERROR] This environment reports CUDA availability but failed to initialize a GPU.")
561
- return None, current_seed
562
-
563
- raise
564
-
565
- log_memory("after pipeline call")
566
-
567
- output_path = tempfile.mktemp(suffix=".mp4")
568
- encode_video(
569
- video=video,
570
- fps=frame_rate,
571
- audio=audio,
572
- output_path=output_path,
573
- video_chunks_number=video_chunks_number,
574
- )
575
-
576
- log_memory("after encode_video")
577
- return str(output_path), current_seed
578
-
579
- except Exception as e:
580
- import traceback
581
- log_memory("on error")
582
- print(f"Error: {str(e)}\n{traceback.format_exc()}")
583
- return None, current_seed
584
-
585
- # Attach spaces GPU decorator only if the CUDA probe succeeded.
586
- try:
587
- if use_cuda:
588
- try:
589
- generate_video = spaces.GPU(duration=80)(generate_video)
590
- print("[INFO] generate_video wrapped with spaces.GPU decorator.")
591
- except Exception as e:
592
- print(f"[WARNING] could not attach spaces.GPU decorator: {type(e).__name__}: {e}")
593
- else:
594
- print("[INFO] Not attaching spaces.GPU decorator (CPU-only environment).")
595
- except Exception as e:
596
- # Defensive logging
597
- print(f"[WARNING] Error while attaching GPU decorator: {type(e).__name__}: {e}")
598
-
599
-
600
- with gr.Blocks(title="LTX-2.3 Heretic Distilled") as demo:
601
- gr.Markdown("# LTX-2.3 F2LF:Heretic with Fast Audio-Video Generation with Frame Conditioning")
602
-
603
-
604
- with gr.Row():
605
- with gr.Column():
606
- with gr.Row():
607
- first_image = gr.Image(label="First Frame (Optional)", type="pil")
608
- last_image = gr.Image(label="Last Frame (Optional)", type="pil")
609
- input_audio = gr.Audio(label="Audio Input (Optional)", type="filepath")
610
- prompt = gr.Textbox(
611
- label="Prompt",
612
- info="for best results - make it as elaborate as possible",
613
- value="Make this image come alive with cinematic motion, smooth animation",
614
- lines=3,
615
- placeholder="Describe the motion and animation you want...",
616
- )
617
- duration = gr.Slider(label="Duration (seconds)", minimum=1.0, maximum=10.0, value=3.0, step=0.1)
618
-
619
-
620
- generate_btn = gr.Button("Generate Video", variant="primary", size="lg")
621
-
622
- with gr.Accordion("Advanced Settings", open=False):
623
- seed = gr.Slider(label="Seed", minimum=0, maximum=MAX_SEED, value=10, step=1)
624
- randomize_seed = gr.Checkbox(label="Randomize Seed", value=True)
625
- with gr.Row():
626
- width = gr.Number(label="Width", value=1536, precision=0)
627
- height = gr.Number(label="Height", value=1024, precision=0)
628
- with gr.Row():
629
- enhance_prompt = gr.Checkbox(label="Enhance Prompt", value=False)
630
- high_res = gr.Checkbox(label="High Resolution", value=True)
631
- pose_lora_strength = gr.Slider(label="Pose LoRA Strength", minimum=0.0, maximum=2.0, value=1.0, step=0.01)
632
- general_lora_strength = gr.Slider(label="General LoRA Strength", minimum=0.0, maximum=2.0, value=1.0, step=0.01)
633
- motion_lora_strength = gr.Slider(label="Motion LoRA Strength", minimum=0.0, maximum=2.0, value=1.0, step=0.01)
634
-
635
- with gr.Column():
636
- output_video = gr.Video(label="Generated Video", autoplay=False)
637
-
638
- gr.Examples(
639
- examples=[
640
- [
641
- None,
642
- "pinkknit.jpg",
643
- None,
644
- "The camera falls downward through darkness as if dropped into a tunnel. "
645
- "As it slows, five friends wearing pink knitted hats and sunglasses lean "
646
- "over and look down toward the camera with curious expressions. The lens "
647
- "has a strong fisheye effect, creating a circular frame around them. They "
648
- "crowd together closely, forming a symmetrical cluster while staring "
649
- "directly into the lens.",
650
- 3.0,
651
- False,
652
- 42,
653
- True,
654
- 1024,
655
- 1024,
656
- ],
657
- ],
658
- inputs=[
659
- first_image, last_image, input_audio, prompt, duration,
660
- enhance_prompt, seed, randomize_seed, height, width,
661
- ],
662
- )
663
-
664
- first_image.change(
665
- fn=on_image_upload,
666
- inputs=[first_image, last_image, high_res],
667
- outputs=[width, height],
668
- )
669
-
670
- last_image.change(
671
- fn=on_image_upload,
672
- inputs=[first_image, last_image, high_res],
673
- outputs=[width, height],
674
- )
675
-
676
- high_res.change(
677
- fn=on_highres_toggle,
678
- inputs=[first_image, last_image, high_res],
679
- outputs=[width, height],
680
- )
681
-
682
- generate_btn.click(
683
- fn=generate_video,
684
- inputs=[
685
- first_image, last_image, input_audio, prompt, duration, enhance_prompt,
686
- seed, randomize_seed, height, width,
687
- pose_lora_strength, general_lora_strength, motion_lora_strength,
688
- ],
689
- outputs=[output_video, seed],
690
- )
691
-
692
-
693
- css = """
694
- .fillable{max-width: 1200px !important}
695
- """
696
-
697
- if __name__ == "__main__":
698
- demo.launch(theme=gr.themes.Citrus(), css=css)