dagloop5 commited on
Commit
d45398c
·
verified ·
1 Parent(s): 6df4e34

Delete app(wip1).py

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