dagloop5 commited on
Commit
6fee77f
·
verified ·
1 Parent(s): ed30cd0

Delete app(wip2).py

Browse files
Files changed (1) hide show
  1. app(wip2).py +0 -783
app(wip2).py DELETED
@@ -1,783 +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
- import gc
36
- import hashlib
37
-
38
- import torch
39
- torch._dynamo.config.suppress_errors = True
40
- torch._dynamo.config.disable = True
41
-
42
- import spaces
43
- import gradio as gr
44
- import numpy as np
45
- from huggingface_hub import hf_hub_download, snapshot_download
46
-
47
- from ltx_core.components.diffusion_steps import EulerDiffusionStep
48
- from ltx_core.components.noisers import GaussianNoiser
49
- from ltx_core.model.audio_vae import encode_audio as vae_encode_audio
50
- from ltx_core.model.upsampler import upsample_video
51
- from ltx_core.model.video_vae import TilingConfig, get_video_chunks_number, decode_video as vae_decode_video
52
- from ltx_core.quantization import QuantizationPolicy
53
- from ltx_core.types import Audio, AudioLatentShape, VideoPixelShape
54
- from ltx_pipelines.distilled import DistilledPipeline
55
- from ltx_pipelines.utils import euler_denoising_loop
56
- from ltx_pipelines.utils.args import ImageConditioningInput
57
- from ltx_pipelines.utils.constants import DISTILLED_SIGMA_VALUES, STAGE_2_DISTILLED_SIGMA_VALUES
58
- from ltx_pipelines.utils.helpers import (
59
- cleanup_memory,
60
- combined_image_conditionings,
61
- denoise_video_only,
62
- encode_prompts,
63
- simple_denoising_func,
64
- )
65
- from ltx_pipelines.utils.media_io import decode_audio_from_file, encode_video
66
- from ltx_core.loader.primitives import LoraPathStrengthAndSDOps
67
- from ltx_core.loader.sd_ops import LTXV_LORA_COMFY_RENAMING_MAP
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
- # LoRA cache directory and currently-applied key
271
- LORA_CACHE_DIR = Path("lora_cache")
272
- LORA_CACHE_DIR.mkdir(exist_ok=True)
273
- current_lora_key: str | None = None
274
-
275
- PENDING_LORA_KEY: str | None = None
276
- PENDING_LORA_STATE: dict[str, torch.Tensor] | None = None
277
- PENDING_LORA_STATUS: str = "No LoRA state prepared yet."
278
-
279
- weights_dir = Path("weights")
280
- weights_dir.mkdir(exist_ok=True)
281
- checkpoint_path = hf_hub_download(
282
- repo_id=LTX_MODEL_REPO,
283
- filename="ltx-2.3-22b-distilled.safetensors",
284
- local_dir=str(weights_dir),
285
- local_dir_use_symlinks=False,
286
- )
287
- spatial_upsampler_path = hf_hub_download(repo_id=LTX_MODEL_REPO, filename="ltx-2.3-spatial-upscaler-x2-1.1.safetensors")
288
- gemma_root = snapshot_download(repo_id=GEMMA_REPO)
289
-
290
- # ---- Insert block (LoRA downloads) between lines 268 and 269 ----
291
- # LoRA repo + download the requested LoRA adapters
292
- LORA_REPO = "dagloop5/LoRA"
293
-
294
- print("=" * 80)
295
- print("Downloading LoRA adapters from dagloop5/LoRA...")
296
- print("=" * 80)
297
- pose_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="LTX2_3_NSFW_furry_concat_v2.safetensors")
298
- general_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="LTX2.3_Reasoning_V1.safetensors")
299
- motion_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="motion_helper.safetensors")
300
-
301
- print(f"Pose LoRA: {pose_lora_path}")
302
- print(f"General LoRA: {general_lora_path}")
303
- print(f"Motion LoRA: {motion_lora_path}")
304
- # ----------------------------------------------------------------
305
-
306
- print(f"Checkpoint: {checkpoint_path}")
307
- print(f"Spatial upsampler: {spatial_upsampler_path}")
308
- print(f"Gemma root: {gemma_root}")
309
-
310
- # Initialize pipeline WITH text encoder and optional audio support
311
- # ---- Replace block (pipeline init) lines 275-281 ----
312
- pipeline = LTX23DistilledA2VPipeline(
313
- distilled_checkpoint_path=checkpoint_path,
314
- spatial_upsampler_path=spatial_upsampler_path,
315
- gemma_root=gemma_root,
316
- loras=[],
317
- quantization=QuantizationPolicy.fp8_cast(), # keep FP8 quantization unchanged
318
- )
319
- # ----------------------------------------------------------------
320
-
321
- def _make_lora_key(pose_strength: float, general_strength: float, motion_strength: float) -> tuple[str, str]:
322
- rp = round(float(pose_strength), 2)
323
- rg = round(float(general_strength), 2)
324
- rm = round(float(motion_strength), 2)
325
- key_str = f"{pose_lora_path}:{rp}|{general_lora_path}:{rg}|{motion_lora_path}:{rm}"
326
- key = hashlib.sha256(key_str.encode("utf-8")).hexdigest()
327
- return key, key_str
328
-
329
-
330
- def prepare_lora_cache(
331
- pose_strength: float,
332
- general_strength: float,
333
- motion_strength: float,
334
- progress=gr.Progress(track_tqdm=True),
335
- ):
336
- """
337
- CPU-only step:
338
- - checks cache
339
- - loads cached fused transformer state_dict, or
340
- - builds fused transformer on CPU and saves it
341
- The resulting state_dict is stored in memory and can be applied later.
342
- """
343
- global PENDING_LORA_KEY, PENDING_LORA_STATE, PENDING_LORA_STATUS
344
-
345
- ledger = pipeline.model_ledger
346
- key, _ = _make_lora_key(pose_strength, general_strength, motion_strength)
347
- cache_path = LORA_CACHE_DIR / f"{key}.pt"
348
-
349
- progress(0.05, desc="Preparing LoRA state")
350
- if cache_path.exists():
351
- try:
352
- progress(0.20, desc="Loading cached fused state")
353
- state = torch.load(cache_path, map_location="cpu")
354
- PENDING_LORA_KEY = key
355
- PENDING_LORA_STATE = state
356
- PENDING_LORA_STATUS = f"Loaded cached LoRA state: {cache_path.name}"
357
- return PENDING_LORA_STATUS
358
- except Exception as e:
359
- print(f"[LoRA] Cache load failed: {type(e).__name__}: {e}")
360
-
361
- entries = [
362
- (pose_lora_path, round(float(pose_strength), 2)),
363
- (general_lora_path, round(float(general_strength), 2)),
364
- (motion_lora_path, round(float(motion_strength), 2)),
365
- ]
366
- loras_for_builder = [
367
- LoraPathStrengthAndSDOps(path, strength, LTXV_LORA_COMFY_RENAMING_MAP)
368
- for path, strength in entries
369
- if path is not None and float(strength) != 0.0
370
- ]
371
-
372
- if not loras_for_builder:
373
- PENDING_LORA_KEY = None
374
- PENDING_LORA_STATE = None
375
- PENDING_LORA_STATUS = "No non-zero LoRA strengths selected; nothing to prepare."
376
- return PENDING_LORA_STATUS
377
-
378
- tmp_ledger = None
379
- new_transformer_cpu = None
380
- try:
381
- progress(0.35, desc="Building fused CPU transformer")
382
- tmp_ledger = pipeline.model_ledger.__class__(
383
- dtype=ledger.dtype,
384
- device=torch.device("cpu"),
385
- checkpoint_path=str(checkpoint_path),
386
- spatial_upsampler_path=str(spatial_upsampler_path),
387
- gemma_root_path=str(gemma_root),
388
- loras=tuple(loras_for_builder),
389
- quantization=getattr(ledger, "quantization", None),
390
- )
391
- new_transformer_cpu = tmp_ledger.transformer()
392
-
393
- progress(0.70, desc="Extracting fused state_dict")
394
- state = new_transformer_cpu.state_dict()
395
- torch.save(state, cache_path)
396
-
397
- PENDING_LORA_KEY = key
398
- PENDING_LORA_STATE = state
399
- PENDING_LORA_STATUS = f"Built and cached LoRA state: {cache_path.name}"
400
- return PENDING_LORA_STATUS
401
-
402
- except Exception as e:
403
- import traceback
404
- print(f"[LoRA] Prepare failed: {type(e).__name__}: {e}")
405
- print(traceback.format_exc())
406
- PENDING_LORA_KEY = None
407
- PENDING_LORA_STATE = None
408
- PENDING_LORA_STATUS = f"LoRA prepare failed: {type(e).__name__}: {e}"
409
- return PENDING_LORA_STATUS
410
-
411
- finally:
412
- try:
413
- del new_transformer_cpu
414
- except Exception:
415
- pass
416
- try:
417
- del tmp_ledger
418
- except Exception:
419
- pass
420
- gc.collect()
421
-
422
-
423
- def apply_prepared_lora_state_to_pipeline():
424
- """
425
- Fast step: copy the already prepared CPU state into the live transformer.
426
- This is the only part that should remain near generation time.
427
- """
428
- global current_lora_key, PENDING_LORA_KEY, PENDING_LORA_STATE
429
-
430
- if PENDING_LORA_STATE is None or PENDING_LORA_KEY is None:
431
- print("[LoRA] No prepared LoRA state available; skipping.")
432
- return False
433
-
434
- if current_lora_key == PENDING_LORA_KEY:
435
- print("[LoRA] Prepared LoRA state already active; skipping.")
436
- return True
437
-
438
- existing_transformer = _transformer
439
- existing_params = {name: param for name, param in existing_transformer.named_parameters()}
440
- existing_buffers = {name: buf for name, buf in existing_transformer.named_buffers()}
441
-
442
- with torch.no_grad():
443
- for k, v in PENDING_LORA_STATE.items():
444
- if k in existing_params:
445
- existing_params[k].data.copy_(v.to(existing_params[k].device))
446
- elif k in existing_buffers:
447
- existing_buffers[k].data.copy_(v.to(existing_buffers[k].device))
448
-
449
- current_lora_key = PENDING_LORA_KEY
450
- print("[LoRA] Prepared LoRA state applied to the pipeline.")
451
- return True
452
-
453
- # ---- REPLACE PRELOAD BLOCK START ----
454
- # Preload all models for ZeroGPU tensor packing.
455
- print("Preloading all models (including Gemma and audio components)...")
456
- ledger = pipeline.model_ledger
457
-
458
- # Save the original factory methods so we can rebuild individual components later.
459
- # These are bound callables on ledger that will call the builder when invoked.
460
- _orig_transformer_factory = ledger.transformer
461
- _orig_video_encoder_factory = ledger.video_encoder
462
- _orig_video_decoder_factory = ledger.video_decoder
463
- _orig_audio_encoder_factory = ledger.audio_encoder
464
- _orig_audio_decoder_factory = ledger.audio_decoder
465
- _orig_vocoder_factory = ledger.vocoder
466
- _orig_spatial_upsampler_factory = ledger.spatial_upsampler
467
- _orig_text_encoder_factory = ledger.text_encoder
468
- _orig_gemma_embeddings_factory = ledger.gemma_embeddings_processor
469
-
470
- # Call the original factories once to create the cached instances we will serve by default.
471
- _transformer = _orig_transformer_factory()
472
- _video_encoder = _orig_video_encoder_factory()
473
- _video_decoder = _orig_video_decoder_factory()
474
- _audio_encoder = _orig_audio_encoder_factory()
475
- _audio_decoder = _orig_audio_decoder_factory()
476
- _vocoder = _orig_vocoder_factory()
477
- _spatial_upsampler = _orig_spatial_upsampler_factory()
478
- _text_encoder = _orig_text_encoder_factory()
479
- _embeddings_processor = _orig_gemma_embeddings_factory()
480
-
481
- # Replace ledger methods with lightweight lambdas that return the cached instances.
482
- # We keep the original factories above so we can call them later to rebuild components.
483
- ledger.transformer = lambda: _transformer
484
- ledger.video_encoder = lambda: _video_encoder
485
- ledger.video_decoder = lambda: _video_decoder
486
- ledger.audio_encoder = lambda: _audio_encoder
487
- ledger.audio_decoder = lambda: _audio_decoder
488
- ledger.vocoder = lambda: _vocoder
489
- ledger.spatial_upsampler = lambda: _spatial_upsampler
490
- ledger.text_encoder = lambda: _text_encoder
491
- ledger.gemma_embeddings_processor = lambda: _embeddings_processor
492
-
493
- print("All models preloaded (including Gemma text encoder and audio encoder)!")
494
- # ---- REPLACE PRELOAD BLOCK END ----
495
-
496
- print("=" * 80)
497
- print("Pipeline ready!")
498
- print("=" * 80)
499
-
500
-
501
- def log_memory(tag: str):
502
- if torch.cuda.is_available():
503
- allocated = torch.cuda.memory_allocated() / 1024**3
504
- peak = torch.cuda.max_memory_allocated() / 1024**3
505
- free, total = torch.cuda.mem_get_info()
506
- print(f"[VRAM {tag}] allocated={allocated:.2f}GB peak={peak:.2f}GB free={free / 1024**3:.2f}GB total={total / 1024**3:.2f}GB")
507
-
508
-
509
- def detect_aspect_ratio(image) -> str:
510
- if image is None:
511
- return "16:9"
512
- if hasattr(image, "size"):
513
- w, h = image.size
514
- elif hasattr(image, "shape"):
515
- h, w = image.shape[:2]
516
- else:
517
- return "16:9"
518
- ratio = w / h
519
- candidates = {"16:9": 16 / 9, "9:16": 9 / 16, "1:1": 1.0}
520
- return min(candidates, key=lambda k: abs(ratio - candidates[k]))
521
-
522
-
523
- def on_image_upload(first_image, last_image, high_res):
524
- ref_image = first_image if first_image is not None else last_image
525
- aspect = detect_aspect_ratio(ref_image)
526
- tier = "high" if high_res else "low"
527
- w, h = RESOLUTIONS[tier][aspect]
528
- return gr.update(value=w), gr.update(value=h)
529
-
530
-
531
- def on_highres_toggle(first_image, last_image, high_res):
532
- ref_image = first_image if first_image is not None else last_image
533
- aspect = detect_aspect_ratio(ref_image)
534
- tier = "high" if high_res else "low"
535
- w, h = RESOLUTIONS[tier][aspect]
536
- return gr.update(value=w), gr.update(value=h)
537
-
538
-
539
- def get_gpu_duration(
540
- first_image,
541
- last_image,
542
- input_audio,
543
- prompt: str,
544
- duration: float,
545
- gpu_duration: float,
546
- enhance_prompt: bool = True,
547
- seed: int = 42,
548
- randomize_seed: bool = True,
549
- height: int = 1024,
550
- width: int = 1536,
551
- pose_strength: float = 0.0,
552
- general_strength: float = 0.0,
553
- motion_strength: float = 0.0,
554
- progress=None,
555
- ):
556
- return int(gpu_duration)
557
-
558
- @spaces.GPU(duration=get_gpu_duration)
559
- @torch.inference_mode()
560
- def generate_video(
561
- first_image,
562
- last_image,
563
- input_audio,
564
- prompt: str,
565
- duration: float,
566
- gpu_duration: float,
567
- enhance_prompt: bool = True,
568
- seed: int = 42,
569
- randomize_seed: bool = True,
570
- height: int = 1024,
571
- width: int = 1536,
572
- pose_strength: float = 0.0,
573
- general_strength: float = 0.0,
574
- motion_strength: float = 0.0,
575
- progress=gr.Progress(track_tqdm=True),
576
- ):
577
- try:
578
- torch.cuda.reset_peak_memory_stats()
579
- log_memory("start")
580
-
581
- current_seed = random.randint(0, MAX_SEED) if randomize_seed else int(seed)
582
-
583
- frame_rate = DEFAULT_FRAME_RATE
584
- num_frames = int(duration * frame_rate) + 1
585
- num_frames = ((num_frames - 1 + 7) // 8) * 8 + 1
586
-
587
- print(f"Generating: {height}x{width}, {num_frames} frames ({duration}s), seed={current_seed}")
588
-
589
- images = []
590
- output_dir = Path("outputs")
591
- output_dir.mkdir(exist_ok=True)
592
-
593
- if first_image is not None:
594
- temp_first_path = output_dir / f"temp_first_{current_seed}.jpg"
595
- if hasattr(first_image, "save"):
596
- first_image.save(temp_first_path)
597
- else:
598
- temp_first_path = Path(first_image)
599
- images.append(ImageConditioningInput(path=str(temp_first_path), frame_idx=0, strength=1.0))
600
-
601
- if last_image is not None:
602
- temp_last_path = output_dir / f"temp_last_{current_seed}.jpg"
603
- if hasattr(last_image, "save"):
604
- last_image.save(temp_last_path)
605
- else:
606
- temp_last_path = Path(last_image)
607
- images.append(ImageConditioningInput(path=str(temp_last_path), frame_idx=num_frames - 1, strength=1.0))
608
-
609
- tiling_config = TilingConfig.default()
610
- video_chunks_number = get_video_chunks_number(num_frames, tiling_config)
611
-
612
- log_memory("before pipeline call")
613
-
614
- apply_prepared_lora_state_to_pipeline()
615
-
616
- video, audio = pipeline(
617
- prompt=prompt,
618
- seed=current_seed,
619
- height=int(height),
620
- width=int(width),
621
- num_frames=num_frames,
622
- frame_rate=frame_rate,
623
- images=images,
624
- audio_path=input_audio,
625
- tiling_config=tiling_config,
626
- enhance_prompt=enhance_prompt,
627
- )
628
-
629
- log_memory("after pipeline call")
630
-
631
- output_path = tempfile.mktemp(suffix=".mp4")
632
- encode_video(
633
- video=video,
634
- fps=frame_rate,
635
- audio=audio,
636
- output_path=output_path,
637
- video_chunks_number=video_chunks_number,
638
- )
639
-
640
- log_memory("after encode_video")
641
- return str(output_path), current_seed
642
-
643
- except Exception as e:
644
- import traceback
645
- log_memory("on error")
646
- print(f"Error: {str(e)}\n{traceback.format_exc()}")
647
- return None, current_seed
648
-
649
-
650
- with gr.Blocks(title="LTX-2.3 Heretic Distilled") as demo:
651
- gr.Markdown("# LTX-2.3 F2LF:Heretic with Fast Audio-Video Generation with Frame Conditioning")
652
-
653
-
654
- with gr.Row():
655
- with gr.Column():
656
- with gr.Row():
657
- first_image = gr.Image(label="First Frame (Optional)", type="pil")
658
- last_image = gr.Image(label="Last Frame (Optional)", type="pil")
659
- input_audio = gr.Audio(label="Audio Input (Optional)", type="filepath")
660
- prompt = gr.Textbox(
661
- label="Prompt",
662
- info="for best results - make it as elaborate as possible",
663
- value="Make this image come alive with cinematic motion, smooth animation",
664
- lines=3,
665
- placeholder="Describe the motion and animation you want...",
666
- )
667
- duration = gr.Slider(label="Duration (seconds)", minimum=1.0, maximum=30.0, value=10.0, step=0.1)
668
-
669
-
670
- generate_btn = gr.Button("Generate Video", variant="primary", size="lg")
671
-
672
- with gr.Accordion("Advanced Settings", open=False):
673
- seed = gr.Slider(label="Seed", minimum=0, maximum=MAX_SEED, value=10, step=1)
674
- randomize_seed = gr.Checkbox(label="Randomize Seed", value=True)
675
- with gr.Row():
676
- width = gr.Number(label="Width", value=1536, precision=0)
677
- height = gr.Number(label="Height", value=1024, precision=0)
678
- with gr.Row():
679
- enhance_prompt = gr.Checkbox(label="Enhance Prompt", value=False)
680
- high_res = gr.Checkbox(label="High Resolution", value=True)
681
- with gr.Column():
682
- gr.Markdown("### LoRA adapter strengths (set to 0 to disable)")
683
- pose_strength = gr.Slider(
684
- label="Pose Enhancer strength",
685
- minimum=0.0, maximum=2.0, value=0.0, step=0.01
686
- )
687
- general_strength = gr.Slider(
688
- label="General Enhancer strength",
689
- minimum=0.0, maximum=2.0, value=0.0, step=0.01
690
- )
691
- motion_strength = gr.Slider(
692
- label="Motion Helper strength",
693
- minimum=0.0, maximum=2.0, value=0.0, step=0.01
694
- )
695
- prepare_lora_btn = gr.Button("Prepare / Load LoRA Cache", variant="secondary")
696
- lora_status = gr.Textbox(
697
- label="LoRA Cache Status",
698
- value="No LoRA state prepared yet.",
699
- interactive=False,
700
- )
701
-
702
- with gr.Column():
703
- output_video = gr.Video(label="Generated Video", autoplay=False)
704
- gpu_duration = gr.Slider(
705
- label="ZeroGPU duration (seconds)",
706
- minimum=40.0,
707
- maximum=240.0,
708
- value=85.0,
709
- step=1.0,
710
- )
711
-
712
- gr.Examples(
713
- examples=[
714
- [
715
- None,
716
- "pinkknit.jpg",
717
- None,
718
- "The camera falls downward through darkness as if dropped into a tunnel. "
719
- "As it slows, five friends wearing pink knitted hats and sunglasses lean "
720
- "over and look down toward the camera with curious expressions. The lens "
721
- "has a strong fisheye effect, creating a circular frame around them. They "
722
- "crowd together closely, forming a symmetrical cluster while staring "
723
- "directly into the lens.",
724
- 3.0,
725
- 80.0,
726
- False,
727
- 42,
728
- True,
729
- 1024,
730
- 1024,
731
- 0.0, # pose_strength (example)
732
- 0.0, # general_strength (example)
733
- 0.0, # motion_strength (example)
734
- ],
735
- ],
736
- inputs=[
737
- first_image, last_image, input_audio, prompt, duration, gpu_duration,
738
- enhance_prompt, seed, randomize_seed, height, width,
739
- pose_strength, general_strength, motion_strength,
740
- ],
741
- )
742
-
743
- first_image.change(
744
- fn=on_image_upload,
745
- inputs=[first_image, last_image, high_res],
746
- outputs=[width, height],
747
- )
748
-
749
- last_image.change(
750
- fn=on_image_upload,
751
- inputs=[first_image, last_image, high_res],
752
- outputs=[width, height],
753
- )
754
-
755
- high_res.change(
756
- fn=on_highres_toggle,
757
- inputs=[first_image, last_image, high_res],
758
- outputs=[width, height],
759
- )
760
-
761
- prepare_lora_btn.click(
762
- fn=prepare_lora_cache,
763
- inputs=[pose_strength, general_strength, motion_strength],
764
- outputs=[lora_status],
765
- )
766
-
767
- generate_btn.click(
768
- fn=generate_video,
769
- inputs=[
770
- first_image, last_image, input_audio, prompt, duration, gpu_duration, enhance_prompt,
771
- seed, randomize_seed, height, width,
772
- pose_strength, general_strength, motion_strength,
773
- ],
774
- outputs=[output_video, seed],
775
- )
776
-
777
-
778
- css = """
779
- .fillable{max-width: 1200px !important}
780
- """
781
-
782
- if __name__ == "__main__":
783
- demo.launch(theme=gr.themes.Citrus(), css=css)