dagloop5 commited on
Commit
fa7c9d4
·
verified ·
1 Parent(s): b8a4ec8

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +635 -0
app.py ADDED
@@ -0,0 +1,635 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import subprocess
3
+ import sys
4
+ import json
5
+ import struct
6
+
7
+ # Disable torch.compile / dynamo before any torch import
8
+ os.environ["TORCH_COMPILE_DISABLE"] = "1"
9
+ os.environ["TORCHDYNAMO_DISABLE"] = "1"
10
+
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
+ LTX_COMMIT = "ae855f8538843825f9015a419cf4ba5edaf5eec2" # known working commit with decode_video
17
+
18
+ if not os.path.exists(LTX_REPO_DIR):
19
+ print(f"Cloning {LTX_REPO_URL}...")
20
+ subprocess.run(["git", "clone", LTX_REPO_URL, LTX_REPO_DIR], check=True)
21
+ subprocess.run(["git", "checkout", LTX_COMMIT], cwd=LTX_REPO_DIR, check=True)
22
+
23
+ print("Installing ltx-core and ltx-pipelines from cloned repo...")
24
+ subprocess.run(
25
+ [sys.executable, "-m", "pip", "install", "--force-reinstall", "--no-deps", "-e",
26
+ os.path.join(LTX_REPO_DIR, "packages", "ltx-core"),
27
+ "-e", os.path.join(LTX_REPO_DIR, "packages", "ltx-pipelines")],
28
+ check=True,
29
+ )
30
+
31
+ sys.path.insert(0, os.path.join(LTX_REPO_DIR, "packages", "ltx-pipelines", "src"))
32
+ sys.path.insert(0, os.path.join(LTX_REPO_DIR, "packages", "ltx-core", "src"))
33
+
34
+ import logging
35
+ import random
36
+ import tempfile
37
+ from pathlib import Path
38
+ import gc
39
+ import hashlib
40
+ import shutil
41
+
42
+ import spaces
43
+ import torch
44
+
45
+ torch._dynamo.config.suppress_errors = True
46
+ torch._dynamo.config.disable = True
47
+
48
+ # --- CRITICAL FIX: ZERO-GPU LOAD PATCH START ---
49
+ from ltx_core.loader.primitives import StateDict
50
+ from ltx_core.loader.sft_loader import SafetensorsStateDictLoader
51
+
52
+ _SAFETENSORS_DTYPE_MAP = {
53
+ "F64": torch.float64,
54
+ "F32": torch.float32,
55
+ "F16": torch.float16,
56
+ "BF16": torch.bfloat16,
57
+ "F8_E5M2": torch.float8_e5m2,
58
+ "F8_E4M3": torch.float8_e4m3fn,
59
+ "I64": torch.int64,
60
+ "I32": torch.int32,
61
+ "I16": torch.int16,
62
+ "I8": torch.int8,
63
+ "U8": torch.uint8,
64
+ "BOOL": torch.bool,
65
+ }
66
+
67
+ def _patched_load(self, path, sd_ops, device=None):
68
+ """
69
+ Forces tensors to load onto CPU during the startup phase to prevent
70
+ 'No CUDA GPUs are available' errors in ZeroGPU.
71
+ """
72
+ sd = {}
73
+ size = 0
74
+ dtype = set()
75
+ # FORCE CPU during preloading
76
+ device = torch.device("cpu")
77
+ model_paths = path if isinstance(path, list) else [path]
78
+ for shard_path in model_paths:
79
+ with open(shard_path, "rb") as f:
80
+ header_len = struct.unpack("<Q", f.read(8))[0]
81
+ header = json.loads(f.read(header_len).decode("utf-8"))
82
+ data_base = 8 + header_len
83
+ for name, meta in header.items():
84
+ if name == "__metadata__":
85
+ continue
86
+ expected_name = name if sd_ops is None else sd_ops.apply_to_key(name)
87
+ if expected_name is None:
88
+ continue
89
+ start, end = meta["data_offsets"]
90
+ f.seek(data_base + start)
91
+ buf = f.read(end - start)
92
+ t = torch.frombuffer(
93
+ bytearray(buf), dtype=_SAFETENSORS_DTYPE_MAP[meta["dtype"]]
94
+ ).reshape(meta["shape"])
95
+ t = t.to(device=device, non_blocking=True, copy=False)
96
+ kvs = (
97
+ ((expected_name, t),)
98
+ if sd_ops is None
99
+ else sd_ops.apply_to_key_value(expected_name, t)
100
+ )
101
+ for key, v in kvs:
102
+ size += v.nbytes
103
+ dtype.add(v.dtype)
104
+ sd[key] = v
105
+ return StateDict(sd=sd, device=device, size=size, dtype=dtype)
106
+
107
+ SafetensorsStateDictLoader.load = _patched_load
108
+ print("[FIX] SafetensorsStateDictLoader.load patched for ZeroGPU")
109
+ # --- CRITICAL FIX END ---
110
+
111
+ _original_tensor_to = torch.Tensor.to
112
+
113
+
114
+ def _is_cuda_target(x):
115
+ return (
116
+ x == "cuda"
117
+ or (isinstance(x, torch.device) and x.type == "cuda")
118
+ or (isinstance(x, str) and x.startswith("cuda"))
119
+ or (isinstance(x, int) and x == 0)
120
+ )
121
+
122
+
123
+ def _spaces_safe_to(self, *args, **kwargs):
124
+ """ZeroGPU emulates bare .to('cuda'), but LTX-2 uses non_blocking/copy."""
125
+ if args and _is_cuda_target(args[0]):
126
+ new_args = ("cuda",) + args[1:]
127
+ new_kwargs = {k: v for k, v in kwargs.items() if k not in ("non_blocking", "copy")}
128
+ return _original_tensor_to(self, *new_args, **new_kwargs)
129
+
130
+ if kwargs.get("device") is not None and _is_cuda_target(kwargs["device"]):
131
+ new_kwargs = {k: v for k, v in kwargs.items() if k not in ("non_blocking", "copy")}
132
+ new_kwargs["device"] = "cuda"
133
+ return _original_tensor_to(self, *args, **new_kwargs)
134
+
135
+ return _original_tensor_to(self, *args, **kwargs)
136
+
137
+
138
+ torch.Tensor.to = _spaces_safe_to
139
+
140
+ import gradio as gr
141
+ import numpy as np
142
+ from huggingface_hub import hf_hub_download, snapshot_download
143
+ from safetensors import safe_open
144
+ import requests
145
+
146
+ from ltx_core.components.diffusion_steps import EulerDiffusionStep
147
+ from ltx_core.components.noisers import GaussianNoiser
148
+ from ltx_core.model.audio_vae import encode_audio as vae_encode_audio
149
+ from ltx_core.model.upsampler import upsample_video
150
+ from ltx_core.model.video_vae import TilingConfig, get_video_chunks_number, decode_video as vae_decode_video
151
+ from ltx_core.quantization import QuantizationPolicy
152
+ from ltx_core.types import Audio, AudioLatentShape, VideoPixelShape
153
+ from ltx_pipelines.distilled import DistilledPipeline
154
+ from ltx_pipelines.utils import euler_denoising_loop
155
+ from ltx_pipelines.utils.args import ImageConditioningInput
156
+ from ltx_pipelines.utils.constants import DISTILLED_SIGMA_VALUES, STAGE_2_DISTILLED_SIGMA_VALUES
157
+ from ltx_pipelines.utils.helpers import (
158
+ cleanup_memory,
159
+ combined_image_conditionings,
160
+ denoise_video_only,
161
+ encode_prompts,
162
+ simple_denoising_func,
163
+ )
164
+ from ltx_pipelines.utils.media_io import decode_audio_from_file, encode_video
165
+ from ltx_core.loader.primitives import LoraPathStrengthAndSDOps
166
+ from ltx_core.loader.sd_ops import LTXV_LORA_COMFY_RENAMING_MAP
167
+
168
+ logging.getLogger().setLevel(logging.INFO)
169
+
170
+ MAX_SEED = np.iinfo(np.int32).max
171
+ DEFAULT_VIDEO_PROMPT = (
172
+ "An astronaut hatches from a fragile egg on the surface of the Moon, "
173
+ "the shell cracking and peeling apart in gentle low-gravity motion. "
174
+ "Fine lunar dust lifts and drifts outward with each movement, floating "
175
+ "in slow arcs before settling back onto the ground."
176
+ )
177
+ DEFAULT_AUDIO_PROMPT = "Ambient space sounds with subtle crackling and distant echoes"
178
+ DEFAULT_FRAME_RATE = 24.0
179
+
180
+ RESOLUTIONS = {
181
+ "low": {"16:9": (768, 512), "9:16": (512, 768), "1:1": (768, 768),
182
+ "4:3": (768, 576), "3:4": (576, 768), "21:9": (768, 384)},
183
+ "high": {"16:9": (1536, 1024), "9:16": (1024, 1536), "1:1": (1024, 1024),
184
+ "4:3": (1536, 1152), "3:4": (1152, 1536), "21:9": (1536, 768)},
185
+ }
186
+
187
+
188
+ class LTX23DistilledA2VPipeline(DistilledPipeline):
189
+ def __call__(
190
+ self,
191
+ video_prompt: str,
192
+ audio_prompt: str,
193
+ seed: int,
194
+ height: int,
195
+ width: int,
196
+ num_frames: int,
197
+ frame_rate: float,
198
+ images: list[ImageConditioningInput],
199
+ audio_path: str | None = None,
200
+ tiling_config: TilingConfig | None = None,
201
+ enhance_prompt: bool = False,
202
+ ):
203
+ print(f"Video prompt: {video_prompt}")
204
+ print(f"Audio prompt: {audio_prompt}")
205
+ if audio_path is None:
206
+ # Handle case when no audio is provided
207
+ raise NotImplementedError("This implementation requires audio input for audio-video generation")
208
+
209
+ generator = torch.Generator(device=self.device).manual_seed(seed)
210
+ noiser = GaussianNoiser(generator=generator)
211
+ stepper = EulerDiffusionStep()
212
+ dtype = torch.bfloat16
213
+
214
+ # Encode video and audio prompts separately
215
+ (video_ctx,) = encode_prompts(
216
+ [video_prompt],
217
+ self.model_ledger,
218
+ enhance_first_prompt=enhance_prompt,
219
+ enhance_prompt_image=images[0].path if len(images) > 0 else None,
220
+ )
221
+ (audio_ctx,) = encode_prompts(
222
+ [audio_prompt],
223
+ self.model_ledger,
224
+ enhance_first_prompt=enhance_prompt,
225
+ enhance_prompt_image=images[0].path if len(images) > 0 else None,
226
+ )
227
+ video_context, audio_context = video_ctx.video_encoding, audio_ctx.audio_encoding
228
+
229
+ video_duration = num_frames / frame_rate
230
+ decoded_audio = decode_audio_from_file(audio_path, self.device, 0.0, video_duration)
231
+ if decoded_audio is None:
232
+ raise ValueError(f"Could not extract audio stream from {audio_path}")
233
+
234
+ encoded_audio_latent = vae_encode_audio(decoded_audio, self.model_ledger.audio_encoder())
235
+ audio_shape = AudioLatentShape.from_duration(batch=1, duration=video_duration, channels=8, mel_bins=16)
236
+ expected_frames = audio_shape.frames
237
+ actual_frames = encoded_audio_latent.shape[2]
238
+
239
+ if actual_frames > expected_frames:
240
+ encoded_audio_latent = encoded_audio_latent[:, :, :expected_frames, :]
241
+ elif actual_frames < expected_frames:
242
+ pad = torch.zeros(
243
+ encoded_audio_latent.shape[0],
244
+ encoded_audio_latent.shape[1],
245
+ expected_frames - actual_frames,
246
+ encoded_audio_latent.shape[3],
247
+ device=encoded_audio_latent.device,
248
+ dtype=encoded_audio_latent.dtype,
249
+ )
250
+ encoded_audio_latent = torch.cat([encoded_audio_latent, pad], dim=2)
251
+
252
+ video_encoder = self.model_ledger.video_encoder()
253
+ transformer = self.model_ledger.transformer()
254
+ stage_1_sigmas = torch.tensor(DISTILLED_SIGMA_VALUES, device=self.device)
255
+
256
+ def denoising_loop(sigmas, video_state, audio_state, stepper):
257
+ return euler_denoising_loop(
258
+ sigmas=sigmas,
259
+ video_state=video_state,
260
+ audio_state=audio_state,
261
+ stepper=stepper,
262
+ denoise_fn=simple_denoising_func(
263
+ video_context=video_context,
264
+ audio_context=audio_context,
265
+ transformer=transformer,
266
+ ),
267
+ )
268
+
269
+ stage_1_output_shape = VideoPixelShape(
270
+ batch=1,
271
+ frames=num_frames,
272
+ width=width // 2,
273
+ height=height // 2,
274
+ fps=frame_rate,
275
+ )
276
+ stage_1_conditionings = combined_image_conditionings(
277
+ images=images,
278
+ height=stage_1_output_shape.height,
279
+ width=stage_1_output_shape.width,
280
+ video_encoder=video_encoder,
281
+ dtype=dtype,
282
+ device=self.device,
283
+ )
284
+ video_state = denoise_video_only(
285
+ output_shape=stage_1_output_shape,
286
+ conditionings=stage_1_conditionings,
287
+ noiser=noiser,
288
+ sigmas=stage_1_sigmas,
289
+ stepper=stepper,
290
+ denoising_loop_fn=denoising_loop,
291
+ components=self.pipeline_components,
292
+ dtype=dtype,
293
+ device=self.device,
294
+ initial_audio_latent=encoded_audio_latent,
295
+ )
296
+
297
+ torch.cuda.synchronize()
298
+ cleanup_memory()
299
+
300
+ upscaled_video_latent = upsample_video(
301
+ latent=video_state.latent[:1],
302
+ video_encoder=video_encoder,
303
+ upsampler=self.model_ledger.spatial_upsampler(),
304
+ )
305
+ stage_2_sigmas = torch.tensor(STAGE_2_DISTILLED_SIGMA_VALUES, device=self.device)
306
+ stage_2_output_shape = VideoPixelShape(batch=1, frames=num_frames, width=width, height=height, fps=frame_rate)
307
+ stage_2_conditionings = combined_image_conditionings(
308
+ images=images,
309
+ height=stage_2_output_shape.height,
310
+ width=stage_2_output_shape.width,
311
+ video_encoder=video_encoder,
312
+ dtype=dtype,
313
+ device=self.device,
314
+ )
315
+ video_state = denoise_video_only(
316
+ output_shape=stage_2_output_shape,
317
+ conditionings=stage_2_conditionings,
318
+ noiser=noiser,
319
+ sigmas=stage_2_sigmas,
320
+ stepper=stepper,
321
+ denoising_loop_fn=denoising_loop,
322
+ components=self.pipeline_components,
323
+ dtype=dtype,
324
+ device=self.device,
325
+ noise_scale=stage_2_sigmas[0],
326
+ initial_video_latent=upscaled_video_latent,
327
+ initial_audio_latent=encoded_audio_latent,
328
+ )
329
+
330
+ torch.cuda.synchronize()
331
+ del transformer
332
+ del video_encoder
333
+ cleanup_memory()
334
+
335
+ decoded_video = vae_decode_video(
336
+ video_state.latent,
337
+ self.model_ledger.video_decoder(),
338
+ tiling_config,
339
+ generator,
340
+ )
341
+ original_audio = Audio(
342
+ waveform=decoded_audio.waveform.squeeze(0),
343
+ sampling_rate=decoded_audio.sampling_rate,
344
+ )
345
+ return decoded_video, original_audio
346
+
347
+
348
+ # Model repos
349
+ LTX_MODEL_REPO = "Lightricks/LTX-2.3"
350
+ GEMMA_REPO ="Lightricks/gemma-3-12b-it-qat-q4_0-unquantized"
351
+
352
+ print("=" * 80)
353
+ print("Downloading LTX-2.3 distilled model + Gemma...")
354
+ print("=" * 80)
355
+
356
+ _legacy_lora_cache_dir = Path("lora_cache")
357
+ if _legacy_lora_cache_dir.exists():
358
+ shutil.rmtree(_legacy_lora_cache_dir, ignore_errors=True)
359
+
360
+ current_lora_key: str | None = None
361
+ PENDING_LORA_KEY: str | None = None
362
+ PENDING_LORA_STATE: dict[str, torch.Tensor] | None = None
363
+ PENDING_LORA_STATUS: str = "No LoRA state prepared yet."
364
+
365
+ weights_dir = Path("weights")
366
+ weights_dir.mkdir(exist_ok=True)
367
+ checkpoint_path = hf_hub_download(
368
+ repo_id="TenStrip/LTX2.3-10Eros",
369
+ filename="10Eros_v1.3_bf16.safetensors",
370
+ local_dir=str(weights_dir),
371
+ local_dir_use_symlinks=False,
372
+ )
373
+
374
+ spatial_upsampler_path = hf_hub_download(repo_id=LTX_MODEL_REPO, filename="ltx-2.3-spatial-upscaler-x2-1.1.safetensors")
375
+ gemma_root = snapshot_download(repo_id=GEMMA_REPO)
376
+
377
+ LORA_REPO = "dagloop5/LoRA"
378
+ print("=" * 80)
379
+ print("Downloading LoRA adapters from dagloop5/LoRA...")
380
+ print("=" * 80)
381
+ singularity_lora_path = hf_hub_download(repo_id="TenStrip/LTX2.3_Distilled_Lora_1.1_Experiments", filename="ltx-2.3-22b-distilled-lora-1.1_rank72_energy.safetensors")
382
+ teneros_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="LTX2.3-Furry-2D-NSFW-Multi-Purpose-Lora+Cum.safetensors")
383
+ sulphur_lora_path =hf_hub_download(repo_id=LORA_REPO, filename="ltx23E28093SlowMotion26.Pkrs.safetensors")
384
+ pose_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="LTX2_3_NSFW_furry_concat_v2.safetensors")
385
+ general_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="LTX2.3_reasoning_Sulphur-2_I2V_V4.safetensors")
386
+ motion_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="Sulphur_LTX 2.3_better _NSFW_motion.safetensors")
387
+ dreamlay_lora_path = hf_hub_download(repo_id="lynaNSFW/DR34ML4Y_AIO_NSFW_LTX23", filename="DR34ML4Y_LTXXX_V2.safetensors")
388
+ mself_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="LTX2.3_2d_NSFW_motion_enhancer.safetensors")
389
+ dramatic_lora_path = hf_hub_download(repo_id="Muapi/valiantcat-ltx-2.3-transition-lora", filename="valiantcat-ltx-2.3-transition-lora.safetensors")
390
+ fluid_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="Cr3ampi3_animation_sulphur-2_i2v_v1.0.safetensors")
391
+ liquid_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="liquid_wet_dr1pp_ltx2_v1.0_scaled.safetensors")
392
+ demopose_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="clapping-cheeks-audio-v001-alpha.safetensors")
393
+ voice_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="hentai_voice_ltx23_v2.comfy.safetensors")
394
+ realism_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="FurryenhancerLTX2.3V4.094fused.safetensors")
395
+ transition_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="LTX_10Eros_takerpov_V2.safetensors")
396
+ physics_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="LTX2.3_Physics_V2_000002000.safetensors")
397
+ reasoning_lora_path = hf_hub_download(repo_id="LiconStudio/Ltx2.3-VBVR-lora-I2V", filename="Ltx2.3-Licon-VBVR-I2V-390K-R32.safetensors")
398
+ twostep_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="LTX2.3_Multi_step_video_reasoning_V0.1.safetensors")
399
+ mcfurry_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="mvmt_lora_v2_600.safetensors")
400
+ dm_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="Doggy_mission_sulphur-2_v0.5.safetensors")
401
+ praxis_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="Penile_Praxis_V4.safetensors")
402
+ threed_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="ltx2-3d-animations-12500-steps-k3nk.safetensors")
403
+ concept_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="ltx23_nsfw_helper_multi_concept_lora_v2.safetensors")
404
+ bulge_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="stomach_bulge_10eros_sulphur_v1.safetensors")
405
+
406
+ pipeline = LTX23DistilledA2VPipeline(
407
+ distilled_checkpoint_path=checkpoint_path,
408
+ spatial_upsampler_path=spatial_upsampler_path,
409
+ gemma_root=gemma_root,
410
+ loras=[],
411
+ quantization=QuantizationPolicy.fp8_cast(),
412
+ )
413
+
414
+ def _make_lora_key(singularity_strength, teneros_strength, sulphur_strength, pose_strength, general_strength, motion_strength, dreamlay_strength, mself_strength, dramatic_strength, fluid_strength, liquid_strength, demopose_strength, voice_strength, realism_strength, transition_strength, physics_strength, reasoning_strength, twostep_strength, mcfurry_strength, dm_strength, praxis_strength, threed_strength, concept_strength, bulge_strength) -> tuple[str, str]:
415
+ rx, ra, rb, rp, rg, rm, rd, rs, rr, rf, rl, ro, rv, re, rt, ry, ri, rw, mc, dm, pr, td, co, bu = [round(float(x), 2) for x in [singularity_strength, teneros_strength, sulphur_strength, pose_strength, general_strength, motion_strength, dreamlay_strength, mself_strength, dramatic_strength, fluid_strength, liquid_strength, demopose_strength, voice_strength, realism_strength, transition_strength, physics_strength, reasoning_strength, twostep_strength, mcfurry_strength, dm_strength, praxis_strength, threed_strength, concept_strength, bulge_strength]]
416
+ key_str = f"{singularity_lora_path}:{rx}|{teneros_lora_path}:{ra}|{sulphur_lora_path}:{rb}|{pose_lora_path}:{rp}|{general_lora_path}:{rg}|{motion_lora_path}:{rm}|{dreamlay_lora_path}:{rd}|{mself_lora_path}:{rs}|{dramatic_lora_path}:{rr}|{fluid_lora_path}:{rf}|{liquid_lora_path}:{rl}|{demopose_lora_path}:{ro}|{voice_lora_path}:{rv}|{realism_lora_path}:{re}|{transition_lora_path}:{rt}|{physics_lora_path}:{ry}|{reasoning_lora_path}:{ri}|{twostep_lora_path}:{rw}|{mcfurry_lora_path}:{mc}|{dm_lora_path}:{dm}|{praxis_lora_path}:{pr}|{threed_lora_path}:{td}|{concept_lora_path}:{co}|{bulge_lora_path}:{bu}"
417
+ key = hashlib.sha256(key_str.encode("utf-8")).hexdigest()
418
+ return key, key_str
419
+
420
+ def prepare_lora_cache(
421
+ singularity_strength, teneros_strength, sulphur_strength, pose_strength, general_strength, motion_strength, dreamlay_strength, mself_strength, dramatic_strength, fluid_strength, liquid_strength, demopose_strength, voice_strength, realism_strength, transition_strength, physics_strength, reasoning_strength, twostep_strength, mcfurry_strength, dm_strength, praxis_strength, threed_strength, concept_strength, bulge_strength,
422
+ progress=gr.Progress(track_tqdm=True),
423
+ ):
424
+ global PENDING_LORA_KEY, PENDING_LORA_STATE, PENDING_LORA_STATUS
425
+ ledger = pipeline.model_ledger
426
+ key, _ = _make_lora_key(singularity_strength, teneros_strength, sulphur_strength, pose_strength, general_strength, motion_strength, dreamlay_strength, mself_strength, dramatic_strength, fluid_strength, liquid_strength, demopose_strength, voice_strength, realism_strength, transition_strength, physics_strength, reasoning_strength, twostep_strength, mcfurry_strength, dm_strength, praxis_strength, threed_strength, concept_strength, bulge_strength)
427
+ progress(0.05, desc="Preparing LoRA state")
428
+ entries = [
429
+ (singularity_lora_path, round(float(singularity_strength), 2)), (teneros_lora_path, round(float(teneros_strength), 2)), (sulphur_lora_path, round(float(sulphur_strength), 2)), (pose_lora_path, round(float(pose_strength), 2)), (general_lora_path, round(float(general_strength), 2)), (motion_lora_path, round(float(motion_strength), 2)), (dreamlay_lora_path, round(float(dreamlay_strength), 2)), (mself_lora_path, round(float(mself_strength), 2)), (dramatic_lora_path, round(float(dramatic_strength), 2)), (fluid_lora_path, round(float(fluid_strength), 2)), (liquid_lora_path, round(float(liquid_strength), 2)), (demopose_lora_path, round(float(demopose_strength), 2)), (voice_lora_path, round(float(voice_strength), 2)), (realism_lora_path, round(float(realism_strength), 2)), (transition_lora_path, round(float(transition_strength), 2)), (physics_lora_path, round(float(physics_strength), 2)), (reasoning_lora_path, round(float(reasoning_strength), 2)), (twostep_lora_path, round(float(twostep_strength), 2)), (mcfurry_lora_path, round(float(mcfurry_strength), 2)), (dm_lora_path, round(float(dm_strength), 2)), (praxis_lora_path, round(float(praxis_strength), 2)), (threed_lora_path, round(float(threed_strength), 2)), (concept_lora_path, round(float(concept_strength), 2)), (bulge_lora_path, round(float(bulge_strength), 2)),
430
+ ]
431
+ loras_for_builder = [LoraPathStrengthAndSDOps(path, strength, LTXV_LORA_COMFY_RENAMING_MAP) for path, strength in entries if path is not None and float(strength) != 0.0]
432
+ if not loras_for_builder:
433
+ PENDING_LORA_KEY = None
434
+ PENDING_LORA_STATE = None
435
+ PENDING_LORA_STATUS = "No non-zero LoRA strengths selected; nothing to prepare."
436
+ return PENDING_LORA_STATUS
437
+ try:
438
+ progress(0.35, desc="Building fused CPU transformer")
439
+ tmp_ledger = pipeline.model_ledger.__class__(dtype=ledger.dtype, device=torch.device("cpu"), checkpoint_path=str(checkpoint_path), spatial_upsampler_path=str(spatial_upsampler_path), gemma_root_path=str(gemma_root), loras=tuple(loras_for_builder), quantization=QuantizationPolicy.fp8_cast())
440
+ new_transformer_cpu = tmp_ledger.transformer()
441
+ progress(0.70, desc="Extracting fused state_dict")
442
+ state = {k: v.detach().cpu().contiguous() for k, v in new_transformer_cpu.state_dict().items()}
443
+ PENDING_LORA_KEY = key
444
+ PENDING_LORA_STATE = state
445
+ PENDING_LORA_STATUS = "Built LoRA state (ready to apply)."
446
+ return PENDING_LORA_STATUS
447
+ except Exception as e:
448
+ PENDING_LORA_KEY = None
449
+ PENDING_LORA_STATE = None
450
+ PENDING_LORA_STATUS = f"LoRA prepare failed: {type(e).__name__}: {e}"
451
+ return PENDING_LORA_STATUS
452
+ finally:
453
+ gc.collect()
454
+
455
+ def apply_prepared_lora_state_to_pipeline():
456
+ global current_lora_key, PENDING_LORA_KEY, PENDING_LORA_STATE, PENDING_LORA_STATUS
457
+ if PENDING_LORA_KEY is None: return False
458
+ if current_lora_key == PENDING_LORA_KEY:
459
+ if PENDING_LORA_STATE is not None: PENDING_LORA_STATE = None
460
+ return True
461
+ if PENDING_LORA_STATE is None: return False
462
+ with torch.no_grad():
463
+ _transformer.load_state_dict(PENDING_LORA_STATE, strict=False)
464
+ current_lora_key = PENDING_LORA_KEY
465
+ PENDING_LORA_STATE = None
466
+ PENDING_LORA_STATUS = "LoRA state applied to pipeline."
467
+ return True
468
+
469
+ print("Preloading all models...")
470
+ ledger = pipeline.model_ledger
471
+ _transformer = ledger.transformer()
472
+ _video_encoder = ledger.video_encoder()
473
+ _video_decoder = ledger.video_decoder()
474
+ _audio_encoder = ledger.audio_encoder()
475
+ _audio_decoder = ledger.audio_decoder()
476
+ _vocoder = ledger.vocoder()
477
+ _spatial_upsampler = ledger.spatial_upsampler()
478
+ _text_encoder = ledger.text_encoder()
479
+ _embeddings_processor = ledger.gemma_embeddings_processor()
480
+
481
+ ledger.transformer = lambda: _transformer
482
+ ledger.video_encoder = lambda: _video_encoder
483
+ ledger.video_decoder = lambda: _video_decoder
484
+ ledger.audio_encoder = lambda: _audio_encoder
485
+ ledger.audio_decoder = lambda: _audio_decoder
486
+ ledger.vocoder = lambda: _vocoder
487
+ ledger.spatial_upsampler = lambda: _spatial_upsampler
488
+ ledger.text_encoder = lambda: _text_encoder
489
+ ledger.gemma_embeddings_processor = lambda: _embeddings_processor
490
+ print("All models preloaded!")
491
+
492
+ def log_memory(tag: str):
493
+ if torch.cuda.is_available():
494
+ allocated = torch.cuda.memory_allocated() / 1024**3
495
+ print(f"[VRAM {tag}] allocated={allocated:.2f}GB")
496
+
497
+ def detect_aspect_ratio(image) -> str:
498
+ if image is None: return "16:9"
499
+ w, h = (image.size if hasattr(image, "size") else image.shape[:2][::-1])
500
+ ratio = w / h
501
+ candidates = {"16:9": 16 / 9, "9:16": 9 / 16, "1:1": 1.0}
502
+ return min(candidates, key=lambda k: abs(ratio - candidates[k]))
503
+
504
+ def on_image_upload(first_image, last_image, high_res):
505
+ ref_image = first_image if first_image is not None else last_image
506
+ aspect = detect_aspect_ratio(ref_image)
507
+ tier = "high" if high_res else "low"
508
+ w, h = RESOLUTIONS[tier][aspect]
509
+ return gr.update(value=w), gr.update(value=h)
510
+
511
+ def on_highres_toggle(first_image, last_image, high_res):
512
+ ref_image = first_image if first_image is not None else last_image
513
+ aspect = detect_aspect_ratio(ref_image)
514
+ tier = "high" if high_res else "low"
515
+ w, h = RESOLUTIONS[tier][aspect]
516
+ return gr.update(value=w), gr.update(value=h)
517
+
518
+ def get_gpu_duration(first_image, last_image, input_audio, video_prompt, audio_prompt, duration, gpu_duration, enhance_prompt, seed, randomize_seed, height, width, singularity_strength, teneros_strength, sulphur_strength, pose_strength, general_strength, motion_strength, dreamlay_strength, mself_strength, dramatic_strength, fluid_strength, liquid_strength, demopose_strength, voice_strength, realism_strength, transition_strength, physics_strength, reasoning_strength, twostep_strength, mcfurry_strength, dm_strength, praxis_strength, threed_strength, concept_strength, bulge_strength, progress=None):
519
+ return int(gpu_duration)
520
+
521
+ @spaces.GPU(size="xlarge", duration=get_gpu_duration)
522
+ @torch.inference_mode()
523
+ def generate_video(first_image, last_image, input_audio, video_prompt, audio_prompt, duration, gpu_duration, enhance_prompt, seed, randomize_seed, height, width, singularity_strength, teneros_strength, sulphur_strength, pose_strength, general_strength, motion_strength, dreamlay_strength, mself_strength, dramatic_strength, fluid_strength, liquid_strength, demopose_strength, voice_strength, realism_strength, transition_strength, physics_strength, reasoning_strength, twostep_strength, mcfurry_strength, dm_strength, praxis_strength, threed_strength, concept_strength, bulge_strength, progress=gr.Progress(track_tqdm=True)):
524
+ try:
525
+ current_seed = random.randint(0, MAX_SEED) if randomize_seed else int(seed)
526
+ frame_rate = DEFAULT_FRAME_RATE
527
+ num_frames = int(duration * frame_rate) + 1
528
+ num_frames = ((num_frames - 1 + 7) // 8) * 8 + 1
529
+ images = []
530
+ output_dir = Path("outputs")
531
+ output_dir.mkdir(exist_ok=True)
532
+ if first_image is not None:
533
+ temp_first_path = output_dir / f"temp_first_{current_seed}.jpg"
534
+ if hasattr(first_image, "save"): first_image.save(temp_first_path)
535
+ else: temp_first_path = Path(first_image)
536
+ images.append(ImageConditioningInput(path=str(temp_first_path), frame_idx=0, strength=1.0))
537
+ if last_image is not None:
538
+ temp_last_path = output_dir / f"temp_last_{current_seed}.jpg"
539
+ if hasattr(last_image, "save"): last_image.save(temp_last_path)
540
+ else: temp_last_path = Path(last_image)
541
+ images.append(ImageConditioningInput(path=str(temp_last_path), frame_idx=num_frames - 1, strength=1.0))
542
+ tiling_config = TilingConfig.default()
543
+ video_chunks_number = get_video_chunks_number(num_frames, tiling_config)
544
+ apply_prepared_lora_state_to_pipeline()
545
+ video, audio = pipeline(
546
+ video_prompt=video_prompt,
547
+ audio_prompt=audio_prompt,
548
+ seed=current_seed,
549
+ height=int(height),
550
+ width=int(width),
551
+ num_frames=num_frames,
552
+ frame_rate=frame_rate,
553
+ images=images,
554
+ audio_path=input_audio,
555
+ tiling_config=tiling_config,
556
+ enhance_prompt=enhance_prompt
557
+ )
558
+ output_path = tempfile.mktemp(suffix=".mp4")
559
+ encode_video(video=video, fps=frame_rate, audio=audio, output_path=output_path, video_chunks_number=video_chunks_number)
560
+ return str(output_path), current_seed
561
+ except Exception as e:
562
+ return None, current_seed
563
+
564
+ with gr.Blocks(title="LTX-2.3 Distilled") as demo:
565
+ gr.Markdown("# LTX-2.3 F2LF with Fast Audio-Video Generation with Frame Conditioning")
566
+ with gr.Row():
567
+ with gr.Column():
568
+ with gr.Row():
569
+ first_image = gr.Image(label="First Frame (Optional)", type="pil")
570
+ last_image = gr.Image(label="Last Frame (Optional)", type="pil")
571
+ input_audio = gr.Audio(label="Audio Input (Optional)", type="filepath")
572
+
573
+ with gr.Tab("Prompts"):
574
+ video_prompt = gr.Textbox(
575
+ label="Video Prompt",
576
+ value=DEFAULT_VIDEO_PROMPT,
577
+ lines=3
578
+ )
579
+ audio_prompt = gr.Textbox(
580
+ label="Audio Prompt",
581
+ value=DEFAULT_AUDIO_PROMPT,
582
+ lines=3
583
+ )
584
+
585
+ duration = gr.Slider(label="Duration (seconds)", minimum=1.0, maximum=30.0, value=10.0, step=0.1)
586
+ generate_btn = gr.Button("Generate Video", variant="primary", size="lg")
587
+ with gr.Accordion("Advanced Settings", open=False):
588
+ seed = gr.Slider(label="Seed", minimum=0, maximum=MAX_SEED, value=10, step=1)
589
+ randomize_seed = gr.Checkbox(label="Randomize Seed", value=True)
590
+ with gr.Row():
591
+ width = gr.Number(label="Width", value=1536, precision=0)
592
+ height = gr.Number(label="Height", value=1024, precision=0)
593
+ with gr.Row():
594
+ enhance_prompt = gr.Checkbox(label="Enhance Prompt", value=False)
595
+ high_res = gr.Checkbox(label="High Resolution", value=True)
596
+ with gr.Column():
597
+ gr.Markdown("### LoRA adapter strengths")
598
+ singularity_strength = gr.Slider(label="Distilled Lora strength", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
599
+ teneros_strength = gr.Slider(label="Multipurpose furry strength", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
600
+ sulphur_strength = gr.Slider(label="Floaty/Slow Motion Reducer strength", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
601
+ pose_strength = gr.Slider(label="Anthro Enhancer strength", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
602
+ general_strength = gr.Slider(label="Reasoning Enhancer strength", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
603
+ motion_strength = gr.Slider(label="Anthro Posing Helper strength", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
604
+ dreamlay_strength = gr.Slider(label="Dreamlay strength", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
605
+ mself_strength = gr.Slider(label="2D enhancer strength", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
606
+ dramatic_strength = gr.Slider(label="Transition enhancer strength", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
607
+ fluid_strength = gr.Slider(label="Fluid Helper strength", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
608
+ liquid_strength = gr.Slider(label="Liquid Helper strength", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
609
+ demopose_strength = gr.Slider(label="Audio Helper strength", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
610
+ voice_strength = gr.Slider(label="Voice Helper strength", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
611
+ realism_strength = gr.Slider(label="Anthro Realism strength", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
612
+ transition_strength = gr.Slider(label="POV strength", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
613
+ physics_strength = gr.Slider(label="Physics strength", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
614
+ reasoning_strength = gr.Slider(label="Official Reasoning strength", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
615
+ twostep_strength = gr.Slider(label="Two Step Reasoning strength", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
616
+ mcfurry_strength = gr.Slider(label="I2V Motion enhancer strength", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
617
+ dm_strength = gr.Slider(label="DM3D strength", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
618
+ praxis_strength = gr.Slider(label="Praxis strength", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
619
+ threed_strength = gr.Slider(label="3D animation strength", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
620
+ concept_strength = gr.Slider(label="Conceptual strength", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
621
+ bulge_strength = gr.Slider(label="Bulge strength", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
622
+ prepare_lora_btn = gr.Button("Prepare / Load LoRA Cache", variant="secondary")
623
+ lora_status = gr.Textbox(label="LoRA Cache Status", value="No LoRA state prepared yet.", interactive=False)
624
+ with gr.Column():
625
+ output_video = gr.Video(label="Generated Video", autoplay=False)
626
+ gpu_duration = gr.Slider(label="ZeroGPU duration (seconds)", minimum=30.0, maximum=240.0, value=75.0, step=1.0)
627
+
628
+ first_image.change(fn=on_image_upload, inputs=[first_image, last_image, high_res], outputs=[width, height])
629
+ last_image.change(fn=on_image_upload, inputs=[first_image, last_image, high_res], outputs=[width, height])
630
+ high_res.change(fn=on_highres_toggle, inputs=[first_image, last_image, high_res], outputs=[width, height])
631
+ prepare_lora_btn.click(fn=prepare_lora_cache, inputs=[singularity_strength, teneros_strength, sulphur_strength, pose_strength, general_strength, motion_strength, dreamlay_strength, mself_strength, dramatic_strength, fluid_strength, liquid_strength, demopose_strength, voice_strength, realism_strength, transition_strength, physics_strength, reasoning_strength, twostep_strength, mcfurry_strength, dm_strength, praxis_strength, threed_strength, concept_strength, bulge_strength], outputs=[lora_status])
632
+ generate_btn.click(fn=generate_video, inputs=[first_image, last_image, input_audio, video_prompt, audio_prompt, duration, gpu_duration, enhance_prompt, seed, randomize_seed, height, width, singularity_strength, teneros_strength, sulphur_strength, pose_strength, general_strength, motion_strength, dreamlay_strength, mself_strength, dramatic_strength, fluid_strength, liquid_strength, demopose_strength, voice_strength, realism_strength, transition_strength, physics_strength, reasoning_strength, twostep_strength, mcfurry_strength, dm_strength, praxis_strength, threed_strength, concept_strength, bulge_strength], outputs=[output_video, seed])
633
+
634
+ if __name__ == "__main__":
635
+ demo.launch(theme=gr.themes.Citrus(), css=".fillable{max-width: 1200px !important}")