dagloop5 commited on
Commit
21df330
·
verified ·
1 Parent(s): 7481746

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +886 -0
app.py ADDED
@@ -0,0 +1,886 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ 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
+
41
+ import torch
42
+ torch._dynamo.config.suppress_errors = True
43
+ torch._dynamo.config.disable = True
44
+
45
+ import spaces
46
+ import gradio as gr
47
+ import numpy as np
48
+ from huggingface_hub import hf_hub_download, snapshot_download
49
+ from safetensors.torch import load_file, save_file
50
+
51
+ from ltx_core.components.diffusion_steps import EulerDiffusionStep
52
+ from ltx_core.components.noisers import GaussianNoiser
53
+ from ltx_core.model.audio_vae import encode_audio as vae_encode_audio
54
+ from ltx_core.model.upsampler import upsample_video
55
+ from ltx_core.model.video_vae import TilingConfig, get_video_chunks_number, decode_video as vae_decode_video
56
+ from ltx_core.quantization import QuantizationPolicy
57
+ from ltx_core.types import Audio, AudioLatentShape, VideoPixelShape
58
+ from ltx_pipelines.distilled import DistilledPipeline
59
+ from ltx_pipelines.utils import euler_denoising_loop
60
+ from ltx_pipelines.utils.args import ImageConditioningInput
61
+ from ltx_pipelines.utils.constants import DISTILLED_SIGMA_VALUES, STAGE_2_DISTILLED_SIGMA_VALUES
62
+ from ltx_pipelines.utils.helpers import (
63
+ cleanup_memory,
64
+ combined_image_conditionings,
65
+ denoise_video_only,
66
+ encode_prompts,
67
+ simple_denoising_func,
68
+ )
69
+ from ltx_pipelines.utils.media_io import decode_audio_from_file, encode_video
70
+ from ltx_core.loader.primitives import LoraPathStrengthAndSDOps
71
+ from ltx_core.loader.sd_ops import LTXV_LORA_COMFY_RENAMING_MAP
72
+
73
+ # Force-patch xformers attention into the LTX attention module.
74
+ from ltx_core.model.transformer import attention as _attn_mod
75
+ print(f"[ATTN] Before patch: memory_efficient_attention={_attn_mod.memory_efficient_attention}")
76
+ try:
77
+ from xformers.ops import memory_efficient_attention as _mea
78
+ _attn_mod.memory_efficient_attention = _mea
79
+ print(f"[ATTN] After patch: memory_efficient_attention={_attn_mod.memory_efficient_attention}")
80
+ except Exception as e:
81
+ print(f"[ATTN] xformers patch FAILED: {type(e).__name__}: {e}")
82
+
83
+ logging.getLogger().setLevel(logging.INFO)
84
+
85
+ MAX_SEED = np.iinfo(np.int32).max
86
+ DEFAULT_PROMPT = (
87
+ "An astronaut hatches from a fragile egg on the surface of the Moon, "
88
+ "the shell cracking and peeling apart in gentle low-gravity motion. "
89
+ "Fine lunar dust lifts and drifts outward with each movement, floating "
90
+ "in slow arcs before settling back onto the ground."
91
+ )
92
+ DEFAULT_FRAME_RATE = 24.0
93
+
94
+ # Resolution presets: (width, height)
95
+ RESOLUTIONS = {
96
+ "high": {"16:9": (1536, 1024), "9:16": (1024, 1536), "1:1": (1024, 1024), "9:7": (1408, 1088), "7:9": (1088, 1408), "19:13": (1472, 1008), "13:19": (1008, 1472)},
97
+ "low": {"16:9": (768, 512), "9:16": (512, 768), "1:1": (768, 768), "9:7": (704, 544), "7:9": (544, 704), "19:13": (736, 504), "13:19": (504, 736)},
98
+ }
99
+
100
+
101
+ class LTX23DistilledA2VPipeline(DistilledPipeline):
102
+ """DistilledPipeline with optional audio conditioning."""
103
+
104
+ def __call__(
105
+ self,
106
+ prompt: str,
107
+ seed: int,
108
+ height: int,
109
+ width: int,
110
+ num_frames: int,
111
+ frame_rate: float,
112
+ images: list[ImageConditioningInput],
113
+ audio_path: str | None = None,
114
+ tiling_config: TilingConfig | None = None,
115
+ enhance_prompt: bool = False,
116
+ ):
117
+ # Standard path when no audio input is provided.
118
+ print(prompt)
119
+ if audio_path is None:
120
+ return super().__call__(
121
+ prompt=prompt,
122
+ seed=seed,
123
+ height=height,
124
+ width=width,
125
+ num_frames=num_frames,
126
+ frame_rate=frame_rate,
127
+ images=images,
128
+ tiling_config=tiling_config,
129
+ enhance_prompt=enhance_prompt,
130
+ )
131
+
132
+ generator = torch.Generator(device=self.device).manual_seed(seed)
133
+ noiser = GaussianNoiser(generator=generator)
134
+ stepper = EulerDiffusionStep()
135
+ dtype = torch.bfloat16
136
+
137
+ (ctx_p,) = encode_prompts(
138
+ [prompt],
139
+ self.model_ledger,
140
+ enhance_first_prompt=enhance_prompt,
141
+ enhance_prompt_image=images[0].path if len(images) > 0 else None,
142
+ )
143
+ video_context, audio_context = ctx_p.video_encoding, ctx_p.audio_encoding
144
+
145
+ video_duration = num_frames / frame_rate
146
+ decoded_audio = decode_audio_from_file(audio_path, self.device, 0.0, video_duration)
147
+ if decoded_audio is None:
148
+ raise ValueError(f"Could not extract audio stream from {audio_path}")
149
+
150
+ encoded_audio_latent = vae_encode_audio(decoded_audio, self.model_ledger.audio_encoder())
151
+ audio_shape = AudioLatentShape.from_duration(batch=1, duration=video_duration, channels=8, mel_bins=16)
152
+ expected_frames = audio_shape.frames
153
+ actual_frames = encoded_audio_latent.shape[2]
154
+
155
+ if actual_frames > expected_frames:
156
+ encoded_audio_latent = encoded_audio_latent[:, :, :expected_frames, :]
157
+ elif actual_frames < expected_frames:
158
+ pad = torch.zeros(
159
+ encoded_audio_latent.shape[0],
160
+ encoded_audio_latent.shape[1],
161
+ expected_frames - actual_frames,
162
+ encoded_audio_latent.shape[3],
163
+ device=encoded_audio_latent.device,
164
+ dtype=encoded_audio_latent.dtype,
165
+ )
166
+ encoded_audio_latent = torch.cat([encoded_audio_latent, pad], dim=2)
167
+
168
+ video_encoder = self.model_ledger.video_encoder()
169
+ transformer = self.model_ledger.transformer()
170
+ stage_1_sigmas = torch.tensor(DISTILLED_SIGMA_VALUES, device=self.device)
171
+
172
+ def denoising_loop(sigmas, video_state, audio_state, stepper):
173
+ return euler_denoising_loop(
174
+ sigmas=sigmas,
175
+ video_state=video_state,
176
+ audio_state=audio_state,
177
+ stepper=stepper,
178
+ denoise_fn=simple_denoising_func(
179
+ video_context=video_context,
180
+ audio_context=audio_context,
181
+ transformer=transformer,
182
+ ),
183
+ )
184
+
185
+ stage_1_output_shape = VideoPixelShape(
186
+ batch=1,
187
+ frames=num_frames,
188
+ width=width // 2,
189
+ height=height // 2,
190
+ fps=frame_rate,
191
+ )
192
+ stage_1_conditionings = combined_image_conditionings(
193
+ images=images,
194
+ height=stage_1_output_shape.height,
195
+ width=stage_1_output_shape.width,
196
+ video_encoder=video_encoder,
197
+ dtype=dtype,
198
+ device=self.device,
199
+ )
200
+ video_state = denoise_video_only(
201
+ output_shape=stage_1_output_shape,
202
+ conditionings=stage_1_conditionings,
203
+ noiser=noiser,
204
+ sigmas=stage_1_sigmas,
205
+ stepper=stepper,
206
+ denoising_loop_fn=denoising_loop,
207
+ components=self.pipeline_components,
208
+ dtype=dtype,
209
+ device=self.device,
210
+ initial_audio_latent=encoded_audio_latent,
211
+ )
212
+
213
+ torch.cuda.synchronize()
214
+ cleanup_memory()
215
+
216
+ upscaled_video_latent = upsample_video(
217
+ latent=video_state.latent[:1],
218
+ video_encoder=video_encoder,
219
+ upsampler=self.model_ledger.spatial_upsampler(),
220
+ )
221
+ stage_2_sigmas = torch.tensor(STAGE_2_DISTILLED_SIGMA_VALUES, device=self.device)
222
+ stage_2_output_shape = VideoPixelShape(batch=1, frames=num_frames, width=width, height=height, fps=frame_rate)
223
+ stage_2_conditionings = combined_image_conditionings(
224
+ images=images,
225
+ height=stage_2_output_shape.height,
226
+ width=stage_2_output_shape.width,
227
+ video_encoder=video_encoder,
228
+ dtype=dtype,
229
+ device=self.device,
230
+ )
231
+ video_state = denoise_video_only(
232
+ output_shape=stage_2_output_shape,
233
+ conditionings=stage_2_conditionings,
234
+ noiser=noiser,
235
+ sigmas=stage_2_sigmas,
236
+ stepper=stepper,
237
+ denoising_loop_fn=denoising_loop,
238
+ components=self.pipeline_components,
239
+ dtype=dtype,
240
+ device=self.device,
241
+ noise_scale=stage_2_sigmas[0],
242
+ initial_video_latent=upscaled_video_latent,
243
+ initial_audio_latent=encoded_audio_latent,
244
+ )
245
+
246
+ torch.cuda.synchronize()
247
+ del transformer
248
+ del video_encoder
249
+ cleanup_memory()
250
+
251
+ decoded_video = vae_decode_video(
252
+ video_state.latent,
253
+ self.model_ledger.video_decoder(),
254
+ tiling_config,
255
+ generator,
256
+ )
257
+ original_audio = Audio(
258
+ waveform=decoded_audio.waveform.squeeze(0),
259
+ sampling_rate=decoded_audio.sampling_rate,
260
+ )
261
+ return decoded_video, original_audio
262
+
263
+
264
+ # Model repos
265
+ LTX_MODEL_REPO = "Lightricks/LTX-2.3"
266
+ GEMMA_REPO ="Lightricks/gemma-3-12b-it-qat-q4_0-unquantized"
267
+
268
+
269
+ # Download model checkpoints
270
+ print("=" * 80)
271
+ print("Downloading LTX-2.3 distilled model + Gemma...")
272
+ print("=" * 80)
273
+
274
+ # LoRA cache directory and currently-applied key
275
+ LORA_CACHE_DIR = Path("lora_cache")
276
+ LORA_CACHE_DIR.mkdir(exist_ok=True)
277
+ current_lora_key: str | None = None
278
+
279
+ PENDING_LORA_KEY: str | None = None
280
+ PENDING_LORA_STATE: dict[str, torch.Tensor] | None = None
281
+ PENDING_LORA_STATUS: str = "No LoRA state prepared yet."
282
+
283
+ checkpoint_path = hf_hub_download(repo_id=LORA_REPO, filename="ltx2310eros_beta.safetensors")
284
+ spatial_upsampler_path = hf_hub_download(repo_id=LTX_MODEL_REPO, filename="ltx-2.3-spatial-upscaler-x2-1.0.safetensors")
285
+ gemma_root = snapshot_download(repo_id=GEMMA_REPO)
286
+
287
+ # ---- Insert block (LoRA downloads) between lines 268 and 269 ----
288
+ # LoRA repo + download the requested LoRA adapters
289
+ LORA_REPO = "dagloop5/LoRA"
290
+
291
+ print("=" * 80)
292
+ print("Downloading LoRA adapters from dagloop5/LoRA...")
293
+ print("=" * 80)
294
+ pose_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="LTX2_3_NSFW_furry_concat_v2.safetensors")
295
+ general_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="LTX2.3_VBVR_Reasoning_I2V_V2.safetensors")
296
+ motion_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="motion_helper.safetensors")
297
+ dreamlay_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="DR34ML4Y_LTXXX_PREVIEW_RC1.safetensors") # m15510n4ry, bl0wj0b, d0ubl3_bj, d0gg1e, c0wg1rl
298
+ mself_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="Furry Hyper Masturbation - LTX-2 I2V v1.safetensors") # Hyperfap
299
+ dramatic_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="LTX-2.3 - Orgasm.safetensors") # "[He | She] is having am orgasm." (am or an?)
300
+ fluid_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="cr3ampi3_animation_i2v_ltx2_v1.0.safetensors") # cr3ampi3 animation., missionary animation, doggystyle bouncy animation, double penetration animation
301
+ liquid_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="liquid_wet_dr1pp_ltx2_v1.0_scaled.safetensors") # wet dr1pp
302
+ demopose_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="clapping-cheeks-audio-v001-alpha.safetensors")
303
+ voice_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="hentai_voice_ltx23.safetensors")
304
+ realism_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="FurryenhancerLTX2.3V1.215.safetensors")
305
+ transition_lora_path = hf_hub_download(repo_id="valiantcat/LTX-2.3-Transition-LORA", filename="ltx2.3-transition.safetensors")
306
+
307
+ print(f"Pose LoRA: {pose_lora_path}")
308
+ print(f"General LoRA: {general_lora_path}")
309
+ print(f"Motion LoRA: {motion_lora_path}")
310
+ print(f"Dreamlay LoRA: {dreamlay_lora_path}")
311
+ print(f"Mself LoRA: {mself_lora_path}")
312
+ print(f"Dramatic LoRA: {dramatic_lora_path}")
313
+ print(f"Fluid LoRA: {fluid_lora_path}")
314
+ print(f"Liquid LoRA: {liquid_lora_path}")
315
+ print(f"Demopose LoRA: {demopose_lora_path}")
316
+ print(f"Voice LoRA: {voice_lora_path}")
317
+ print(f"Realism LoRA: {realism_lora_path}")
318
+ print(f"Transition LoRA: {transition_lora_path}")
319
+ # ----------------------------------------------------------------
320
+
321
+ print(f"Checkpoint: {checkpoint_path}")
322
+ print(f"Spatial upsampler: {spatial_upsampler_path}")
323
+ print(f"Gemma root: {gemma_root}")
324
+
325
+ # Initialize pipeline WITH text encoder and optional audio support
326
+ # ---- Replace block (pipeline init) lines 275-281 ----
327
+ pipeline = LTX23DistilledA2VPipeline(
328
+ distilled_checkpoint_path=checkpoint_path,
329
+ spatial_upsampler_path=spatial_upsampler_path,
330
+ gemma_root=gemma_root,
331
+ loras=[],
332
+ quantization=None, # keep FP8 quantization unchanged
333
+ )
334
+ # ----------------------------------------------------------------
335
+
336
+ def _make_lora_key(pose_strength: float, general_strength: float, motion_strength: float, dreamlay_strength: float, mself_strength: float, dramatic_strength: float, fluid_strength: float, liquid_strength: float, demopose_strength: float, voice_strength: float, realism_strength: float, transition_strength: float) -> tuple[str, str]:
337
+ rp = round(float(pose_strength), 2)
338
+ rg = round(float(general_strength), 2)
339
+ rm = round(float(motion_strength), 2)
340
+ rd = round(float(dreamlay_strength), 2)
341
+ rs = round(float(mself_strength), 2)
342
+ rr = round(float(dramatic_strength), 2)
343
+ rf = round(float(fluid_strength), 2)
344
+ rl = round(float(liquid_strength), 2)
345
+ ro = round(float(demopose_strength), 2)
346
+ rv = round(float(voice_strength), 2)
347
+ re = round(float(realism_strength), 2)
348
+ rt = round(float(transition_strength), 2)
349
+ key_str = f"{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}"
350
+ key = hashlib.sha256(key_str.encode("utf-8")).hexdigest()
351
+ return key, key_str
352
+
353
+
354
+ def prepare_lora_cache(
355
+ pose_strength: float,
356
+ general_strength: float,
357
+ motion_strength: float,
358
+ dreamlay_strength: float,
359
+ mself_strength: float,
360
+ dramatic_strength: float,
361
+ fluid_strength: float,
362
+ liquid_strength: float,
363
+ demopose_strength: float,
364
+ voice_strength: float,
365
+ realism_strength: float,
366
+ transition_strength: float,
367
+ progress=gr.Progress(track_tqdm=True),
368
+ ):
369
+ """
370
+ CPU-only step:
371
+ - checks cache
372
+ - loads cached fused transformer state_dict, or
373
+ - builds fused transformer on CPU and saves it
374
+ The resulting state_dict is stored in memory and can be applied later.
375
+ """
376
+ global PENDING_LORA_KEY, PENDING_LORA_STATE, PENDING_LORA_STATUS
377
+
378
+ ledger = pipeline.model_ledger
379
+ key, _ = _make_lora_key(pose_strength, general_strength, motion_strength, dreamlay_strength, mself_strength, dramatic_strength, fluid_strength, liquid_strength, demopose_strength, voice_strength, realism_strength, transition_strength)
380
+ cache_path = LORA_CACHE_DIR / f"{key}.safetensors"
381
+
382
+ progress(0.05, desc="Preparing LoRA state")
383
+ if cache_path.exists():
384
+ try:
385
+ progress(0.20, desc="Loading cached fused state")
386
+ state = load_file(str(cache_path))
387
+ PENDING_LORA_KEY = key
388
+ PENDING_LORA_STATE = state
389
+ PENDING_LORA_STATUS = f"Loaded cached LoRA state: {cache_path.name}"
390
+ return PENDING_LORA_STATUS
391
+ except Exception as e:
392
+ print(f"[LoRA] Cache load failed: {type(e).__name__}: {e}")
393
+
394
+ entries = [
395
+ (pose_lora_path, round(float(pose_strength), 2)),
396
+ (general_lora_path, round(float(general_strength), 2)),
397
+ (motion_lora_path, round(float(motion_strength), 2)),
398
+ (dreamlay_lora_path, round(float(dreamlay_strength), 2)),
399
+ (mself_lora_path, round(float(mself_strength), 2)),
400
+ (dramatic_lora_path, round(float(dramatic_strength), 2)),
401
+ (fluid_lora_path, round(float(fluid_strength), 2)),
402
+ (liquid_lora_path, round(float(liquid_strength), 2)),
403
+ (demopose_lora_path, round(float(demopose_strength), 2)),
404
+ (voice_lora_path, round(float(voice_strength), 2)),
405
+ (realism_lora_path, round(float(realism_strength), 2)),
406
+ (transition_lora_path, round(float(transition_strength), 2)),
407
+ ]
408
+ loras_for_builder = [
409
+ LoraPathStrengthAndSDOps(path, strength, LTXV_LORA_COMFY_RENAMING_MAP)
410
+ for path, strength in entries
411
+ if path is not None and float(strength) != 0.0
412
+ ]
413
+
414
+ if not loras_for_builder:
415
+ PENDING_LORA_KEY = None
416
+ PENDING_LORA_STATE = None
417
+ PENDING_LORA_STATUS = "No non-zero LoRA strengths selected; nothing to prepare."
418
+ return PENDING_LORA_STATUS
419
+
420
+ tmp_ledger = None
421
+ new_transformer_cpu = None
422
+ try:
423
+ progress(0.35, desc="Building fused CPU transformer")
424
+ tmp_ledger = pipeline.model_ledger.__class__(
425
+ dtype=ledger.dtype,
426
+ device=torch.device("cpu"),
427
+ checkpoint_path=str(checkpoint_path),
428
+ spatial_upsampler_path=str(spatial_upsampler_path),
429
+ gemma_root_path=str(gemma_root),
430
+ loras=tuple(loras_for_builder),
431
+ quantization=None,
432
+ )
433
+ new_transformer_cpu = tmp_ledger.transformer()
434
+
435
+ progress(0.70, desc="Extracting fused state_dict")
436
+ state = {
437
+ k: v.detach().cpu().contiguous()
438
+ for k, v in new_transformer_cpu.state_dict().items()
439
+ }
440
+ save_file(state, str(cache_path))
441
+
442
+ PENDING_LORA_KEY = key
443
+ PENDING_LORA_STATE = state
444
+ PENDING_LORA_STATUS = f"Built and cached LoRA state: {cache_path.name}"
445
+ return PENDING_LORA_STATUS
446
+
447
+ except Exception as e:
448
+ import traceback
449
+ print(f"[LoRA] Prepare failed: {type(e).__name__}: {e}")
450
+ print(traceback.format_exc())
451
+ PENDING_LORA_KEY = None
452
+ PENDING_LORA_STATE = None
453
+ PENDING_LORA_STATUS = f"LoRA prepare failed: {type(e).__name__}: {e}"
454
+ return PENDING_LORA_STATUS
455
+
456
+ finally:
457
+ try:
458
+ del new_transformer_cpu
459
+ except Exception:
460
+ pass
461
+ try:
462
+ del tmp_ledger
463
+ except Exception:
464
+ pass
465
+ gc.collect()
466
+
467
+
468
+ def apply_prepared_lora_state_to_pipeline():
469
+ """
470
+ Fast step: copy the already prepared CPU state into the live transformer.
471
+ This is the only part that should remain near generation time.
472
+ """
473
+ global current_lora_key, PENDING_LORA_KEY, PENDING_LORA_STATE
474
+
475
+ if PENDING_LORA_STATE is None or PENDING_LORA_KEY is None:
476
+ print("[LoRA] No prepared LoRA state available; skipping.")
477
+ return False
478
+
479
+ if current_lora_key == PENDING_LORA_KEY:
480
+ print("[LoRA] Prepared LoRA state already active; skipping.")
481
+ return True
482
+
483
+ existing_transformer = _transformer
484
+ with torch.no_grad():
485
+ missing, unexpected = existing_transformer.load_state_dict(PENDING_LORA_STATE, strict=False)
486
+ if missing or unexpected:
487
+ print(f"[LoRA] load_state_dict mismatch: missing={len(missing)}, unexpected={len(unexpected)}")
488
+
489
+ current_lora_key = PENDING_LORA_KEY
490
+ print("[LoRA] Prepared LoRA state applied to the pipeline.")
491
+ return True
492
+
493
+ # ---- REPLACE PRELOAD BLOCK START ----
494
+ # Preload all models for ZeroGPU tensor packing.
495
+ print("Preloading all models (including Gemma and audio components)...")
496
+ ledger = pipeline.model_ledger
497
+
498
+ # Save the original factory methods so we can rebuild individual components later.
499
+ # These are bound callables on ledger that will call the builder when invoked.
500
+ _orig_transformer_factory = ledger.transformer
501
+ _orig_video_encoder_factory = ledger.video_encoder
502
+ _orig_video_decoder_factory = ledger.video_decoder
503
+ _orig_audio_encoder_factory = ledger.audio_encoder
504
+ _orig_audio_decoder_factory = ledger.audio_decoder
505
+ _orig_vocoder_factory = ledger.vocoder
506
+ _orig_spatial_upsampler_factory = ledger.spatial_upsampler
507
+ _orig_text_encoder_factory = ledger.text_encoder
508
+ _orig_gemma_embeddings_factory = ledger.gemma_embeddings_processor
509
+
510
+ # Call the original factories once to create the cached instances we will serve by default.
511
+ _transformer = _orig_transformer_factory()
512
+ _video_encoder = _orig_video_encoder_factory()
513
+ _video_decoder = _orig_video_decoder_factory()
514
+ _audio_encoder = _orig_audio_encoder_factory()
515
+ _audio_decoder = _orig_audio_decoder_factory()
516
+ _vocoder = _orig_vocoder_factory()
517
+ _spatial_upsampler = _orig_spatial_upsampler_factory()
518
+ _text_encoder = _orig_text_encoder_factory()
519
+ _embeddings_processor = _orig_gemma_embeddings_factory()
520
+
521
+ # Replace ledger methods with lightweight lambdas that return the cached instances.
522
+ # We keep the original factories above so we can call them later to rebuild components.
523
+ ledger.transformer = lambda: _transformer
524
+ ledger.video_encoder = lambda: _video_encoder
525
+ ledger.video_decoder = lambda: _video_decoder
526
+ ledger.audio_encoder = lambda: _audio_encoder
527
+ ledger.audio_decoder = lambda: _audio_decoder
528
+ ledger.vocoder = lambda: _vocoder
529
+ ledger.spatial_upsampler = lambda: _spatial_upsampler
530
+ ledger.text_encoder = lambda: _text_encoder
531
+ ledger.gemma_embeddings_processor = lambda: _embeddings_processor
532
+
533
+ print("All models preloaded (including Gemma text encoder and audio encoder)!")
534
+ # ---- REPLACE PRELOAD BLOCK END ----
535
+
536
+ print("=" * 80)
537
+ print("Pipeline ready!")
538
+ print("=" * 80)
539
+
540
+
541
+ def log_memory(tag: str):
542
+ if torch.cuda.is_available():
543
+ allocated = torch.cuda.memory_allocated() / 1024**3
544
+ peak = torch.cuda.max_memory_allocated() / 1024**3
545
+ free, total = torch.cuda.mem_get_info()
546
+ print(f"[VRAM {tag}] allocated={allocated:.2f}GB peak={peak:.2f}GB free={free / 1024**3:.2f}GB total={total / 1024**3:.2f}GB")
547
+
548
+
549
+ def detect_aspect_ratio(image) -> str:
550
+ if image is None:
551
+ return "16:9"
552
+ if hasattr(image, "size"):
553
+ w, h = image.size
554
+ elif hasattr(image, "shape"):
555
+ h, w = image.shape[:2]
556
+ else:
557
+ return "16:9"
558
+ ratio = w / h
559
+ candidates = {"16:9": 16 / 9, "9:16": 9 / 16, "1:1": 1.0}
560
+ return min(candidates, key=lambda k: abs(ratio - candidates[k]))
561
+
562
+
563
+ def on_image_upload(first_image, last_image, high_res):
564
+ ref_image = first_image if first_image is not None else last_image
565
+ aspect = detect_aspect_ratio(ref_image)
566
+ tier = "high" if high_res else "low"
567
+ w, h = RESOLUTIONS[tier][aspect]
568
+ return gr.update(value=w), gr.update(value=h)
569
+
570
+
571
+ def on_highres_toggle(first_image, last_image, high_res):
572
+ ref_image = first_image if first_image is not None else last_image
573
+ aspect = detect_aspect_ratio(ref_image)
574
+ tier = "high" if high_res else "low"
575
+ w, h = RESOLUTIONS[tier][aspect]
576
+ return gr.update(value=w), gr.update(value=h)
577
+
578
+
579
+ def get_gpu_duration(
580
+ first_image,
581
+ last_image,
582
+ input_audio,
583
+ prompt: str,
584
+ duration: float,
585
+ gpu_duration: float,
586
+ enhance_prompt: bool = True,
587
+ seed: int = 42,
588
+ randomize_seed: bool = True,
589
+ height: int = 1024,
590
+ width: int = 1536,
591
+ pose_strength: float = 0.0,
592
+ general_strength: float = 0.0,
593
+ motion_strength: float = 0.0,
594
+ dreamlay_strength: float = 0.0,
595
+ mself_strength: float = 0.0,
596
+ dramatic_strength: float = 0.0,
597
+ fluid_strength: float = 0.0,
598
+ liquid_strength: float = 0.0,
599
+ demopose_strength: float = 0.0,
600
+ voice_strength: float = 0.0,
601
+ realism_strength: float = 0.0,
602
+ transition_strength: float = 0.0,
603
+ progress=None,
604
+ ):
605
+ return int(gpu_duration)
606
+
607
+ @spaces.GPU(duration=get_gpu_duration)
608
+ @torch.inference_mode()
609
+ def generate_video(
610
+ first_image,
611
+ last_image,
612
+ input_audio,
613
+ prompt: str,
614
+ duration: float,
615
+ gpu_duration: float,
616
+ enhance_prompt: bool = True,
617
+ seed: int = 42,
618
+ randomize_seed: bool = True,
619
+ height: int = 1024,
620
+ width: int = 1536,
621
+ pose_strength: float = 0.0,
622
+ general_strength: float = 0.0,
623
+ motion_strength: float = 0.0,
624
+ dreamlay_strength: float = 0.0,
625
+ mself_strength: float = 0.0,
626
+ dramatic_strength: float = 0.0,
627
+ fluid_strength: float = 0.0,
628
+ liquid_strength: float = 0.0,
629
+ demopose_strength: float = 0.0,
630
+ voice_strength: float = 0.0,
631
+ realism_strength: float = 0.0,
632
+ transition_strength: float = 0.0,
633
+ progress=gr.Progress(track_tqdm=True),
634
+ ):
635
+ try:
636
+ torch.cuda.reset_peak_memory_stats()
637
+ log_memory("start")
638
+
639
+ current_seed = random.randint(0, MAX_SEED) if randomize_seed else int(seed)
640
+
641
+ frame_rate = DEFAULT_FRAME_RATE
642
+ num_frames = int(duration * frame_rate) + 1
643
+ num_frames = ((num_frames - 1 + 7) // 8) * 8 + 1
644
+
645
+ print(f"Generating: {height}x{width}, {num_frames} frames ({duration}s), seed={current_seed}")
646
+
647
+ images = []
648
+ output_dir = Path("outputs")
649
+ output_dir.mkdir(exist_ok=True)
650
+
651
+ if first_image is not None:
652
+ temp_first_path = output_dir / f"temp_first_{current_seed}.jpg"
653
+ if hasattr(first_image, "save"):
654
+ first_image.save(temp_first_path)
655
+ else:
656
+ temp_first_path = Path(first_image)
657
+ images.append(ImageConditioningInput(path=str(temp_first_path), frame_idx=0, strength=1.0))
658
+
659
+ if last_image is not None:
660
+ temp_last_path = output_dir / f"temp_last_{current_seed}.jpg"
661
+ if hasattr(last_image, "save"):
662
+ last_image.save(temp_last_path)
663
+ else:
664
+ temp_last_path = Path(last_image)
665
+ images.append(ImageConditioningInput(path=str(temp_last_path), frame_idx=num_frames - 1, strength=1.0))
666
+
667
+ tiling_config = TilingConfig.default()
668
+ video_chunks_number = get_video_chunks_number(num_frames, tiling_config)
669
+
670
+ log_memory("before pipeline call")
671
+
672
+ apply_prepared_lora_state_to_pipeline()
673
+
674
+ video, audio = pipeline(
675
+ prompt=prompt,
676
+ seed=current_seed,
677
+ height=int(height),
678
+ width=int(width),
679
+ num_frames=num_frames,
680
+ frame_rate=frame_rate,
681
+ images=images,
682
+ audio_path=input_audio,
683
+ tiling_config=tiling_config,
684
+ enhance_prompt=enhance_prompt,
685
+ )
686
+
687
+ log_memory("after pipeline call")
688
+
689
+ output_path = tempfile.mktemp(suffix=".mp4")
690
+ encode_video(
691
+ video=video,
692
+ fps=frame_rate,
693
+ audio=audio,
694
+ output_path=output_path,
695
+ video_chunks_number=video_chunks_number,
696
+ )
697
+
698
+ log_memory("after encode_video")
699
+ return str(output_path), current_seed
700
+
701
+ except Exception as e:
702
+ import traceback
703
+ log_memory("on error")
704
+ print(f"Error: {str(e)}\n{traceback.format_exc()}")
705
+ return None, current_seed
706
+
707
+
708
+ with gr.Blocks(title="LTX-2.3 Distilled") as demo:
709
+ gr.Markdown("# LTX-2.3 F2LF with Fast Audio-Video Generation with Frame Conditioning")
710
+
711
+
712
+ with gr.Row():
713
+ with gr.Column():
714
+ with gr.Row():
715
+ first_image = gr.Image(label="First Frame (Optional)", type="pil")
716
+ last_image = gr.Image(label="Last Frame (Optional)", type="pil")
717
+ input_audio = gr.Audio(label="Audio Input (Optional)", type="filepath")
718
+ prompt = gr.Textbox(
719
+ label="Prompt",
720
+ info="for best results - make it as elaborate as possible",
721
+ value="Make this image come alive with cinematic motion, smooth animation",
722
+ lines=3,
723
+ placeholder="Describe the motion and animation you want...",
724
+ )
725
+ duration = gr.Slider(label="Duration (seconds)", minimum=1.0, maximum=30.0, value=10.0, step=0.1)
726
+
727
+
728
+ generate_btn = gr.Button("Generate Video", variant="primary", size="lg")
729
+
730
+ with gr.Accordion("Advanced Settings", open=False):
731
+ seed = gr.Slider(label="Seed", minimum=0, maximum=MAX_SEED, value=10, step=1)
732
+ randomize_seed = gr.Checkbox(label="Randomize Seed", value=True)
733
+ with gr.Row():
734
+ width = gr.Number(label="Width", value=1536, precision=0)
735
+ height = gr.Number(label="Height", value=1024, precision=0)
736
+ with gr.Row():
737
+ enhance_prompt = gr.Checkbox(label="Enhance Prompt", value=False)
738
+ high_res = gr.Checkbox(label="High Resolution", value=True)
739
+ with gr.Column():
740
+ gr.Markdown("### LoRA adapter strengths (set to 0 to disable; slow and WIP)")
741
+ pose_strength = gr.Slider(
742
+ label="Anthro Enhancer strength",
743
+ minimum=0.0, maximum=2.0, value=0.0, step=0.01
744
+ )
745
+ general_strength = gr.Slider(
746
+ label="Reasoning Enhancer strength",
747
+ minimum=0.0, maximum=2.0, value=0.0, step=0.01
748
+ )
749
+ motion_strength = gr.Slider(
750
+ label="Anthro Posing Helper strength",
751
+ minimum=0.0, maximum=2.0, value=0.0, step=0.01
752
+ )
753
+ dreamlay_strength = gr.Slider(
754
+ label="Dreamlay strength",
755
+ minimum=0.0, maximum=2.0, value=0.0, step=0.01
756
+ )
757
+ mself_strength = gr.Slider(
758
+ label="Mself strength",
759
+ minimum=0.0, maximum=2.0, value=0.0, step=0.01
760
+ )
761
+ dramatic_strength = gr.Slider(
762
+ label="Dramatic strength",
763
+ minimum=0.0, maximum=2.0, value=0.0, step=0.01
764
+ )
765
+ fluid_strength = gr.Slider(
766
+ label="Fluid Helper strength",
767
+ minimum=0.0, maximum=2.0, value=0.0, step=0.01
768
+ )
769
+ liquid_strength = gr.Slider(
770
+ label="Transition Helper strength",
771
+ minimum=0.0, maximum=2.0, value=0.0, step=0.01
772
+ )
773
+ demopose_strength = gr.Slider(
774
+ label="Audio Helper strength",
775
+ minimum=0.0, maximum=2.0, value=0.0, step=0.01
776
+ )
777
+ voice_strength = gr.Slider(
778
+ label="Voice Helper strength",
779
+ minimum=0.0, maximum=2.0, value=0.0, step=0.01
780
+ )
781
+ realism_strength = gr.Slider(
782
+ label="Anthro Realism strength",
783
+ minimum=0.0, maximum=2.0, value=0.0, step=0.01
784
+ )
785
+ transition_strength = gr.Slider(
786
+ label="Transition strength",
787
+ minimum=0.0, maximum=2.0, value=0.0, step=0.01
788
+ )
789
+ prepare_lora_btn = gr.Button("Prepare / Load LoRA Cache", variant="secondary")
790
+ lora_status = gr.Textbox(
791
+ label="LoRA Cache Status",
792
+ value="No LoRA state prepared yet.",
793
+ interactive=False,
794
+ )
795
+
796
+ with gr.Column():
797
+ output_video = gr.Video(label="Generated Video", autoplay=False)
798
+ gpu_duration = gr.Slider(
799
+ label="ZeroGPU duration (seconds; 10 second Img2Vid with 1024x1024 and LoRAs = ~70)",
800
+ minimum=30.0,
801
+ maximum=240.0,
802
+ value=75.0,
803
+ step=1.0,
804
+ )
805
+
806
+ gr.Examples(
807
+ examples=[
808
+ [
809
+ None,
810
+ "pinkknit.jpg",
811
+ None,
812
+ "The camera falls downward through darkness as if dropped into a tunnel. "
813
+ "As it slows, five friends wearing pink knitted hats and sunglasses lean "
814
+ "over and look down toward the camera with curious expressions. The lens "
815
+ "has a strong fisheye effect, creating a circular frame around them. They "
816
+ "crowd together closely, forming a symmetrical cluster while staring "
817
+ "directly into the lens.",
818
+ 3.0,
819
+ 80.0,
820
+ False,
821
+ 42,
822
+ True,
823
+ 1024,
824
+ 1024,
825
+ 0.0, # pose_strength (example)
826
+ 0.0, # general_strength (example)
827
+ 0.0, # motion_strength (example)
828
+ 0.0,
829
+ 0.0,
830
+ 0.0,
831
+ 0.0,
832
+ 0.0,
833
+ 0.0,
834
+ 0.0,
835
+ 0.0,
836
+ 0.0,
837
+ ],
838
+ ],
839
+ inputs=[
840
+ first_image, last_image, input_audio, prompt, duration, gpu_duration,
841
+ enhance_prompt, seed, randomize_seed, height, width,
842
+ pose_strength, general_strength, motion_strength, dreamlay_strength, mself_strength, dramatic_strength, fluid_strength, liquid_strength, demopose_strength, voice_strength, realism_strength, transition_strength,
843
+ ],
844
+ )
845
+
846
+ first_image.change(
847
+ fn=on_image_upload,
848
+ inputs=[first_image, last_image, high_res],
849
+ outputs=[width, height],
850
+ )
851
+
852
+ last_image.change(
853
+ fn=on_image_upload,
854
+ inputs=[first_image, last_image, high_res],
855
+ outputs=[width, height],
856
+ )
857
+
858
+ high_res.change(
859
+ fn=on_highres_toggle,
860
+ inputs=[first_image, last_image, high_res],
861
+ outputs=[width, height],
862
+ )
863
+
864
+ prepare_lora_btn.click(
865
+ fn=prepare_lora_cache,
866
+ inputs=[pose_strength, general_strength, motion_strength, dreamlay_strength, mself_strength, dramatic_strength, fluid_strength, liquid_strength, demopose_strength, voice_strength, realism_strength, transition_strength],
867
+ outputs=[lora_status],
868
+ )
869
+
870
+ generate_btn.click(
871
+ fn=generate_video,
872
+ inputs=[
873
+ first_image, last_image, input_audio, prompt, duration, gpu_duration, enhance_prompt,
874
+ seed, randomize_seed, height, width,
875
+ pose_strength, general_strength, motion_strength, dreamlay_strength, mself_strength, dramatic_strength, fluid_strength, liquid_strength, demopose_strength, voice_strength, realism_strength, transition_strength,
876
+ ],
877
+ outputs=[output_video, seed],
878
+ )
879
+
880
+
881
+ css = """
882
+ .fillable{max-width: 1200px !important}
883
+ """
884
+
885
+ if __name__ == "__main__":
886
+ demo.launch(theme=gr.themes.Citrus(), css=css)