dagloop5 commited on
Commit
b49e078
·
verified ·
1 Parent(s): c70dc2c

Upload app(2stageres2).py

Browse files
Files changed (1) hide show
  1. app(2stageres2).py +1031 -0
app(2stageres2).py ADDED
@@ -0,0 +1,1031 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # Clone LTX-2 repo and install packages
10
+ LTX_REPO_URL = "https://github.com/Lightricks/LTX-2.git"
11
+ LTX_REPO_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "LTX-2")
12
+
13
+ LTX_COMMIT = "ae855f8538843825f9015a419cf4ba5edaf5eec2" # known working commit with decode_video
14
+
15
+ if not os.path.exists(LTX_REPO_DIR):
16
+ print(f"Cloning {LTX_REPO_URL}...")
17
+ subprocess.run(["git", "clone", LTX_REPO_URL, LTX_REPO_DIR], check=True)
18
+ subprocess.run(["git", "checkout", LTX_COMMIT], cwd=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
+ from safetensors.torch import load_file, save_file
47
+ from safetensors import safe_open
48
+ import json
49
+ import requests
50
+
51
+ from ltx_core.components.diffusion_steps import Res2sDiffusionStep
52
+ from ltx_core.components.guiders import MultiModalGuider, MultiModalGuiderParams
53
+ from ltx_core.components.noisers import GaussianNoiser
54
+ from ltx_core.components.protocols import DiffusionStepProtocol
55
+ from ltx_core.components.schedulers import LTX2Scheduler
56
+ from ltx_core.model.audio_vae import encode_audio as vae_encode_audio
57
+ from ltx_core.model.audio_vae import decode_audio as vae_decode_audio
58
+ from ltx_core.model.upsampler import upsample_video
59
+ from ltx_core.model.video_vae import TilingConfig, get_video_chunks_number, decode_video as vae_decode_video
60
+ from ltx_core.quantization import QuantizationPolicy
61
+ from ltx_core.types import Audio, AudioLatentShape, VideoLatentShape, VideoPixelShape
62
+ from ltx_pipelines.distilled import DistilledPipeline
63
+ from ltx_pipelines.utils import (
64
+ res2s_audio_video_denoising_loop,
65
+ cleanup_memory,
66
+ encode_prompts,
67
+ denoise_audio_video,
68
+ )
69
+ from ltx_pipelines.utils.args import ImageConditioningInput
70
+ from ltx_pipelines.utils.constants import STAGE_2_DISTILLED_SIGMA_VALUES
71
+ from ltx_pipelines.utils.helpers import (
72
+ combined_image_conditionings,
73
+ denoise_video_only,
74
+ simple_denoising_func,
75
+ multi_modal_guider_denoising_func,
76
+ )
77
+ from ltx_pipelines.utils.media_io import decode_audio_from_file, encode_video
78
+ from ltx_core.loader.primitives import LoraPathStrengthAndSDOps
79
+ from ltx_core.loader.sd_ops import LTXV_LORA_COMFY_RENAMING_MAP
80
+
81
+ from ltx_core.model.transformer import attention as _attn_mod
82
+
83
+ print(f"[ATTN] Before patch: memory_efficient_attention={_attn_mod.memory_efficient_attention}")
84
+ try:
85
+ from xformers.ops import memory_efficient_attention as _mea
86
+ from xformers.ops.fmha import cutlass
87
+
88
+ def _cutlass_memory_efficient_attention(*args, **kwargs):
89
+ # Force CUTLASS and avoid FlashAttention paths that are crashing.
90
+ kwargs["op"] = (cutlass.FwOp, cutlass.BwOp)
91
+ return _mea(*args, **kwargs)
92
+
93
+ _attn_mod.memory_efficient_attention = _cutlass_memory_efficient_attention
94
+ print(f"[ATTN] After patch: memory_efficient_attention={_attn_mod.memory_efficient_attention}")
95
+ except Exception as e:
96
+ print(f"[ATTN] xformers patch FAILED: {type(e).__name__}: {e}")
97
+
98
+ logging.getLogger().setLevel(logging.INFO)
99
+
100
+ MAX_SEED = np.iinfo(np.int32).max
101
+ DEFAULT_PROMPT = (
102
+ "An astronaut hatches from a fragile egg on the surface of the Moon, "
103
+ "the shell cracking and peeling apart in gentle low-gravity motion. "
104
+ "Fine lunar dust lifts and drifts outward with each movement, floating "
105
+ "in slow arcs before settling back onto the ground."
106
+ )
107
+ DEFAULT_NEGATIVE_PROMPT = (
108
+ "worst quality, inconsistent motion, blurry, jittery, distorted, "
109
+ "deformed, artifacts, text, watermark, logo, frame, border, "
110
+ "low resolution, pixelated, unnatural, fake, CGI, cartoon"
111
+ )
112
+ DEFAULT_FRAME_RATE = 24.0
113
+
114
+ # Resolution presets: (width, height)
115
+ RESOLUTIONS = {
116
+ "high": {"16:9": (1536, 1024), "9:16": (1024, 1536), "1:1": (1024, 1024)},
117
+ "low": {"16:9": (768, 512), "9:16": (512, 768), "1:1": (768, 768)},
118
+ }
119
+
120
+ class LTX23DistilledA2VPipeline:
121
+ """Standalone pipeline with optional audio conditioning — no parent class."""
122
+
123
+ def __init__(
124
+ self,
125
+ distilled_checkpoint_path: str,
126
+ spatial_upsampler_path: str,
127
+ gemma_root: str,
128
+ loras: tuple,
129
+ quantization: QuantizationPolicy | None = None,
130
+ ):
131
+ from ltx_pipelines.utils import ModelLedger, denoise_audio_video
132
+ from ltx_pipelines.utils.types import PipelineComponents
133
+
134
+ self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
135
+ self.dtype = torch.bfloat16
136
+
137
+ self.model_ledger = ModelLedger(
138
+ dtype=self.dtype,
139
+ device=self.device,
140
+ checkpoint_path=distilled_checkpoint_path,
141
+ gemma_root_path=gemma_root,
142
+ spatial_upsampler_path=spatial_upsampler_path,
143
+ loras=loras,
144
+ quantization=quantization,
145
+ )
146
+
147
+ self.pipeline_components = PipelineComponents(
148
+ dtype=self.dtype,
149
+ device=self.device,
150
+ )
151
+
152
+ def __call__(
153
+ self,
154
+ prompt: str,
155
+ negative_prompt: str,
156
+ seed: int,
157
+ height: int,
158
+ width: int,
159
+ num_frames: int,
160
+ frame_rate: float,
161
+ video_guider_params: MultiModalGuiderParams,
162
+ audio_guider_params: MultiModalGuiderParams,
163
+ images: list[ImageConditioningInput],
164
+ num_inference_steps: int = 8,
165
+ audio_path: str | None = None,
166
+ tiling_config: TilingConfig | None = None,
167
+ enhance_prompt: bool = False,
168
+ ):
169
+ print(prompt)
170
+
171
+ generator = torch.Generator(device=self.device).manual_seed(seed)
172
+ noiser = GaussianNoiser(generator=generator)
173
+ stepper = Res2sDiffusionStep()
174
+ dtype = torch.bfloat16
175
+
176
+ ctx_p, ctx_n = encode_prompts(
177
+ [prompt, negative_prompt],
178
+ self.model_ledger,
179
+ enhance_first_prompt=enhance_prompt,
180
+ enhance_prompt_image=images[0].path if len(images) > 0 else None,
181
+ )
182
+ v_context_p, a_context_p = ctx_p.video_encoding, ctx_p.audio_encoding
183
+ v_context_n, a_context_n = ctx_n.video_encoding, ctx_n.audio_encoding
184
+
185
+ # ── Audio encoding (only for conditioning, not output generation) ──
186
+ encoded_audio_latent = None
187
+ decoded_audio = None
188
+ if audio_path is not None:
189
+ video_duration = num_frames / frame_rate
190
+ decoded_audio = decode_audio_from_file(audio_path, self.device, 0.0, video_duration)
191
+ if decoded_audio is None:
192
+ raise ValueError(f"Could not extract audio stream from {audio_path}")
193
+
194
+ encoded_audio_latent = vae_encode_audio(decoded_audio, self.model_ledger.audio_encoder())
195
+ audio_shape = AudioLatentShape.from_duration(batch=1, duration=video_duration, channels=8, mel_bins=16)
196
+ expected_frames = audio_shape.frames
197
+ actual_frames = encoded_audio_latent.shape[2]
198
+
199
+ if actual_frames > expected_frames:
200
+ encoded_audio_latent = encoded_audio_latent[:, :, :expected_frames, :]
201
+ elif actual_frames < expected_frames:
202
+ pad = torch.zeros(
203
+ encoded_audio_latent.shape[0],
204
+ encoded_audio_latent.shape[1],
205
+ expected_frames - actual_frames,
206
+ encoded_audio_latent.shape[3],
207
+ device=encoded_audio_latent.device,
208
+ dtype=encoded_audio_latent.dtype,
209
+ )
210
+ encoded_audio_latent = torch.cat([encoded_audio_latent, pad], dim=2)
211
+
212
+ video_encoder = self.model_ledger.video_encoder()
213
+ transformer = self.model_ledger.transformer()
214
+
215
+ # Stage 1: Generate sigmas using LTX2Scheduler with user-specified steps
216
+ empty_latent = torch.empty(VideoLatentShape.from_pixel_shape(
217
+ VideoPixelShape(batch=1, frames=num_frames, width=width // 2, height=height // 2, fps=frame_rate)
218
+ ).to_torch_shape())
219
+ stage_1_sigmas = (
220
+ LTX2Scheduler()
221
+ .execute(latent=empty_latent, steps=num_inference_steps)
222
+ .to(dtype=torch.float32, device=self.device)
223
+ )
224
+
225
+ def stage1_denoising_loop(sigmas: torch.Tensor, video_state, audio_state, stepper: DiffusionStepProtocol):
226
+ return res2s_audio_video_denoising_loop(
227
+ sigmas=sigmas,
228
+ video_state=video_state,
229
+ audio_state=audio_state,
230
+ stepper=stepper,
231
+ denoise_fn=multi_modal_guider_denoising_func(
232
+ video_guider=MultiModalGuider(
233
+ params=video_guider_params,
234
+ negative_context=v_context_n,
235
+ ),
236
+ audio_guider=MultiModalGuider(
237
+ params=audio_guider_params,
238
+ negative_context=a_context_n,
239
+ ),
240
+ v_context=v_context_p,
241
+ a_context=a_context_p,
242
+ transformer=transformer,
243
+ ),
244
+ )
245
+
246
+ def stage2_denoising_loop(sigmas: torch.Tensor, video_state, audio_state, stepper: DiffusionStepProtocol):
247
+ return res2s_audio_video_denoising_loop(
248
+ sigmas=sigmas,
249
+ video_state=video_state,
250
+ audio_state=audio_state,
251
+ stepper=stepper,
252
+ denoise_fn=simple_denoising_func(
253
+ video_context=v_context_p,
254
+ audio_context=a_context_p,
255
+ transformer=transformer, # noqa: F821
256
+ ),
257
+ )
258
+
259
+ # ── Stage 1: Half resolution ──
260
+ stage_1_output_shape = VideoPixelShape(
261
+ batch=1,
262
+ frames=num_frames,
263
+ width=width // 2,
264
+ height=height // 2,
265
+ fps=frame_rate,
266
+ )
267
+ stage_1_conditionings = combined_image_conditionings(
268
+ images=images,
269
+ height=stage_1_output_shape.height,
270
+ width=stage_1_output_shape.width,
271
+ video_encoder=video_encoder,
272
+ dtype=dtype,
273
+ device=self.device,
274
+ )
275
+
276
+ # Use denoise_audio_video so audio is ALWAYS generated
277
+ from ltx_pipelines.utils import denoise_audio_video
278
+ video_state, audio_state = denoise_audio_video(
279
+ output_shape=stage_1_output_shape,
280
+ conditionings=stage_1_conditionings,
281
+ noiser=noiser,
282
+ sigmas=stage_1_sigmas,
283
+ stepper=stepper,
284
+ denoising_loop_fn=stage1_denoising_loop,
285
+ components=self.pipeline_components,
286
+ dtype=dtype,
287
+ device=self.device,
288
+ initial_audio_latent=encoded_audio_latent,
289
+ )
290
+
291
+ torch.cuda.synchronize()
292
+ cleanup_memory()
293
+
294
+ # ── Upscaling ──
295
+ upscaled_video_latent = upsample_video(
296
+ latent=video_state.latent[:1],
297
+ video_encoder=video_encoder,
298
+ upsampler=self.model_ledger.spatial_upsampler(),
299
+ )
300
+
301
+ # ── Stage 2: Full resolution ──
302
+ stage_2_sigmas = torch.tensor(STAGE_2_DISTILLED_SIGMA_VALUES, device=self.device)
303
+ stage_2_output_shape = VideoPixelShape(batch=1, frames=num_frames, width=width, height=height, fps=frame_rate)
304
+ stage_2_conditionings = combined_image_conditionings(
305
+ images=images,
306
+ height=stage_2_output_shape.height,
307
+ width=stage_2_output_shape.width,
308
+ video_encoder=video_encoder,
309
+ dtype=dtype,
310
+ device=self.device,
311
+ )
312
+ video_state, audio_state = denoise_audio_video(
313
+ output_shape=stage_2_output_shape,
314
+ conditionings=stage_2_conditionings,
315
+ noiser=noiser,
316
+ sigmas=stage_2_sigmas,
317
+ stepper=stepper,
318
+ denoising_loop_fn=stage2_denoising_loop,
319
+ components=self.pipeline_components,
320
+ dtype=dtype,
321
+ device=self.device,
322
+ noise_scale=stage_2_sigmas[0],
323
+ initial_video_latent=upscaled_video_latent,
324
+ initial_audio_latent=audio_state.latent,
325
+ )
326
+
327
+ torch.cuda.synchronize()
328
+ cleanup_memory()
329
+
330
+ # ── Decode both video and audio ──
331
+ decoded_video = vae_decode_video(
332
+ video_state.latent,
333
+ self.model_ledger.video_decoder(),
334
+ tiling_config,
335
+ generator,
336
+ )
337
+ decoded_audio_output = vae_decode_audio(
338
+ audio_state.latent,
339
+ self.model_ledger.audio_decoder(),
340
+ self.model_ledger.vocoder(),
341
+ )
342
+
343
+ return decoded_video, decoded_audio_output
344
+
345
+ # Model repos
346
+ LTX_MODEL_REPO = "SulphurAI/Sulphur-2-base"
347
+ GEMMA_REPO ="Lightricks/gemma-3-12b-it-qat-q4_0-unquantized"
348
+
349
+ # Download model checkpoints
350
+ print("=" * 80)
351
+ print("Downloading LTX-2.3 distilled model + Gemma...")
352
+ print("=" * 80)
353
+
354
+ # LoRA cache directory and currently-applied key
355
+ LORA_CACHE_DIR = Path("lora_cache")
356
+ LORA_CACHE_DIR.mkdir(exist_ok=True)
357
+ current_lora_key: str | None = None
358
+
359
+ PENDING_LORA_KEY: str | None = None
360
+ PENDING_LORA_STATE: dict[str, torch.Tensor] | None = None
361
+ PENDING_LORA_STATUS: str = "No LoRA state prepared yet."
362
+
363
+ weights_dir = Path("weights")
364
+ weights_dir.mkdir(exist_ok=True)
365
+ checkpoint_path = hf_hub_download(
366
+ repo_id=LTX_MODEL_REPO,
367
+ filename="sulphur_distil_bf16.safetensors",
368
+ local_dir=str(weights_dir),
369
+ local_dir_use_symlinks=False,
370
+ )
371
+ spatial_upsampler_path = hf_hub_download(repo_id="Lightricks/LTX-2.3", filename="ltx-2.3-spatial-upscaler-x2-1.1.safetensors")
372
+ gemma_root = snapshot_download(repo_id=GEMMA_REPO)
373
+
374
+
375
+ LORA_REPO = "dagloop5/LoRA"
376
+
377
+ print("=" * 80)
378
+ print("Downloading LoRA adapters from dagloop5/LoRA...")
379
+ print("=" * 80)
380
+ pose_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="LTX2_3_NSFW_furry_concat_v2.safetensors")
381
+ general_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="LTX2.3_reasoning_I2V_V3.safetensors")
382
+ motion_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="motion_helper.safetensors")
383
+ dreamlay_lora_path = hf_hub_download(repo_id="lynaNSFW/DR34ML4Y_AIO_NSFW_LTX23", filename="DR34ML4Y_LTXXX_V2.safetensors") # m15510n4ry, bl0wj0b, d0ubl3_bj, d0gg1e, c0wg1rl
384
+ mself_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="Furry Hyper Masturbation - LTX-2 I2V v1.safetensors") # Hyperfap
385
+ 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?)
386
+ fluid_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="Cr3ampi3_animation_sulphur-2_i2v_v1.0.safetensors") # cr3ampi3 animation
387
+ liquid_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="liquid_wet_dr1pp_ltx2_v1.0_scaled.safetensors") # wet dr1pp
388
+ demopose_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="clapping-cheeks-audio-v001-alpha.safetensors")
389
+ voice_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="hentai_voice_ltx23.safetensors")
390
+ realism_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="FurryenhancerLTX2.3V4.094fused.safetensors")
391
+ transition_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="LTX-2_takerpov_lora_v1.2.safetensors") # takerpov1, taker pov
392
+ physics_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="LTX2.3_Physics_V2_000002000.safetensors")
393
+ reasoning_lora_path = hf_hub_download(repo_id="LiconStudio/Ltx2.3-VBVR-lora-I2V", filename="Ltx2.3-Licon-VBVR-I2V-390K-R32.safetensors")
394
+ twostep_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="LTX2.3_Multi_step_video_reasoning_V0.1.safetensors")
395
+
396
+ print(f"Pose LoRA: {pose_lora_path}")
397
+ print(f"General LoRA: {general_lora_path}")
398
+ print(f"Motion LoRA: {motion_lora_path}")
399
+ print(f"Dreamlay LoRA: {dreamlay_lora_path}")
400
+ print(f"Mself LoRA: {mself_lora_path}")
401
+ print(f"Dramatic LoRA: {dramatic_lora_path}")
402
+ print(f"Fluid LoRA: {fluid_lora_path}")
403
+ print(f"Liquid LoRA: {liquid_lora_path}")
404
+ print(f"Demopose LoRA: {demopose_lora_path}")
405
+ print(f"Voice LoRA: {voice_lora_path}")
406
+ print(f"Realism LoRA: {realism_lora_path}")
407
+ print(f"Transition LoRA: {transition_lora_path}")
408
+ print(f"Physics LoRA: {physics_lora_path}")
409
+ print(f"Reasoning LoRA: {reasoning_lora_path}")
410
+ print(f"Twostep LoRA: {twostep_lora_path}")
411
+
412
+ print(f"Checkpoint: {checkpoint_path}")
413
+ print(f"Spatial upsampler: {spatial_upsampler_path}")
414
+ print(f"[Gemma] Root ready: {gemma_root}")
415
+
416
+ pipeline = LTX23DistilledA2VPipeline(
417
+ distilled_checkpoint_path=checkpoint_path,
418
+ spatial_upsampler_path=spatial_upsampler_path,
419
+ gemma_root=gemma_root,
420
+ loras=[],
421
+ quantization=QuantizationPolicy.fp8_cast(),
422
+ )
423
+
424
+ 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, physics_strength: float, reasoning_strength: float, twostep_strength: float) -> tuple[str, str]:
425
+ rp = round(float(pose_strength), 2)
426
+ rg = round(float(general_strength), 2)
427
+ rm = round(float(motion_strength), 2)
428
+ rd = round(float(dreamlay_strength), 2)
429
+ rs = round(float(mself_strength), 2)
430
+ rr = round(float(dramatic_strength), 2)
431
+ rf = round(float(fluid_strength), 2)
432
+ rl = round(float(liquid_strength), 2)
433
+ ro = round(float(demopose_strength), 2)
434
+ rv = round(float(voice_strength), 2)
435
+ re = round(float(realism_strength), 2)
436
+ rt = round(float(transition_strength), 2)
437
+ ry = round(float(physics_strength), 2)
438
+ ri = round(float(reasoning_strength), 2)
439
+ rw = round(float(twostep_strength), 2)
440
+ 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}|{physics_lora_path}:{ry}|{reasoning_lora_path}:{ri}|{twostep_lora_path}:{rw}"
441
+ key = hashlib.sha256(key_str.encode("utf-8")).hexdigest()
442
+ return key, key_str
443
+
444
+
445
+ def prepare_lora_cache(
446
+ pose_strength: float,
447
+ general_strength: float,
448
+ motion_strength: float,
449
+ dreamlay_strength: float,
450
+ mself_strength: float,
451
+ dramatic_strength: float,
452
+ fluid_strength: float,
453
+ liquid_strength: float,
454
+ demopose_strength: float,
455
+ voice_strength: float,
456
+ realism_strength: float,
457
+ transition_strength: float,
458
+ physics_strength: float,
459
+ reasoning_strength: float,
460
+ twostep_strength: float,
461
+ progress=gr.Progress(track_tqdm=True),
462
+ ):
463
+ """
464
+ CPU-only step:
465
+ - checks cache
466
+ - loads cached fused transformer state_dict, or
467
+ - builds fused transformer on CPU and saves it
468
+ The resulting state_dict is stored in memory and can be applied later.
469
+ """
470
+ global PENDING_LORA_KEY, PENDING_LORA_STATE, PENDING_LORA_STATUS
471
+
472
+ ledger = pipeline.model_ledger
473
+ 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, physics_strength, reasoning_strength, twostep_strength)
474
+ cache_path = LORA_CACHE_DIR / f"{key}.safetensors"
475
+
476
+ progress(0.05, desc="Preparing LoRA state")
477
+ if cache_path.exists():
478
+ try:
479
+ progress(0.20, desc="Loading cached fused state")
480
+ state = load_file(str(cache_path))
481
+ PENDING_LORA_KEY = key
482
+ PENDING_LORA_STATE = state
483
+ PENDING_LORA_STATUS = f"Loaded cached LoRA state: {cache_path.name}"
484
+ return PENDING_LORA_STATUS
485
+ except Exception as e:
486
+ print(f"[LoRA] Cache load failed: {type(e).__name__}: {e}")
487
+
488
+ entries = [
489
+ (pose_lora_path, round(float(pose_strength), 2)),
490
+ (general_lora_path, round(float(general_strength), 2)),
491
+ (motion_lora_path, round(float(motion_strength), 2)),
492
+ (dreamlay_lora_path, round(float(dreamlay_strength), 2)),
493
+ (mself_lora_path, round(float(mself_strength), 2)),
494
+ (dramatic_lora_path, round(float(dramatic_strength), 2)),
495
+ (fluid_lora_path, round(float(fluid_strength), 2)),
496
+ (liquid_lora_path, round(float(liquid_strength), 2)),
497
+ (demopose_lora_path, round(float(demopose_strength), 2)),
498
+ (voice_lora_path, round(float(voice_strength), 2)),
499
+ (realism_lora_path, round(float(realism_strength), 2)),
500
+ (transition_lora_path, round(float(transition_strength), 2)),
501
+ (physics_lora_path, round(float(physics_strength), 2)),
502
+ (reasoning_lora_path, round(float(reasoning_strength), 2)),
503
+ (twostep_lora_path, round(float(twostep_strength), 2)),
504
+ ]
505
+ loras_for_builder = [
506
+ LoraPathStrengthAndSDOps(path, strength, LTXV_LORA_COMFY_RENAMING_MAP)
507
+ for path, strength in entries
508
+ if path is not None and float(strength) != 0.0
509
+ ]
510
+
511
+ if not loras_for_builder:
512
+ PENDING_LORA_KEY = None
513
+ PENDING_LORA_STATE = None
514
+ PENDING_LORA_STATUS = "No non-zero LoRA strengths selected; nothing to prepare."
515
+ return PENDING_LORA_STATUS
516
+
517
+ tmp_ledger = None
518
+ new_transformer_cpu = None
519
+ try:
520
+ progress(0.35, desc="Building fused CPU transformer")
521
+ tmp_ledger = pipeline.model_ledger.__class__(
522
+ dtype=ledger.dtype,
523
+ device=torch.device("cpu"),
524
+ checkpoint_path=str(checkpoint_path),
525
+ spatial_upsampler_path=str(spatial_upsampler_path),
526
+ gemma_root_path=str(gemma_root),
527
+ loras=tuple(loras_for_builder),
528
+ quantization=getattr(ledger, "quantization", None),
529
+ )
530
+ new_transformer_cpu = tmp_ledger.transformer()
531
+
532
+ progress(0.70, desc="Extracting fused state_dict")
533
+ state = {
534
+ k: v.detach().cpu().contiguous()
535
+ for k, v in new_transformer_cpu.state_dict().items()
536
+ }
537
+ save_file(state, str(cache_path))
538
+
539
+ PENDING_LORA_KEY = key
540
+ PENDING_LORA_STATE = state
541
+ PENDING_LORA_STATUS = f"Built and cached LoRA state: {cache_path.name}"
542
+ return PENDING_LORA_STATUS
543
+
544
+ except Exception as e:
545
+ import traceback
546
+ print(f"[LoRA] Prepare failed: {type(e).__name__}: {e}")
547
+ print(traceback.format_exc())
548
+ PENDING_LORA_KEY = None
549
+ PENDING_LORA_STATE = None
550
+ PENDING_LORA_STATUS = f"LoRA prepare failed: {type(e).__name__}: {e}"
551
+ return PENDING_LORA_STATUS
552
+
553
+ finally:
554
+ try:
555
+ del new_transformer_cpu
556
+ except Exception:
557
+ pass
558
+ try:
559
+ del tmp_ledger
560
+ except Exception:
561
+ pass
562
+ gc.collect()
563
+
564
+
565
+ def apply_prepared_lora_state_to_pipeline():
566
+ """
567
+ Fast step: copy the already prepared CPU state into the live transformer.
568
+ This is the only part that should remain near generation time.
569
+ """
570
+ global current_lora_key, PENDING_LORA_KEY, PENDING_LORA_STATE
571
+
572
+ if PENDING_LORA_STATE is None or PENDING_LORA_KEY is None:
573
+ print("[LoRA] No prepared LoRA state available; skipping.")
574
+ return False
575
+
576
+ if current_lora_key == PENDING_LORA_KEY:
577
+ print("[LoRA] Prepared LoRA state already active; skipping.")
578
+ return True
579
+
580
+ existing_transformer = _transformer
581
+ with torch.no_grad():
582
+ missing, unexpected = existing_transformer.load_state_dict(PENDING_LORA_STATE, strict=False)
583
+ if missing or unexpected:
584
+ print(f"[LoRA] load_state_dict mismatch: missing={len(missing)}, unexpected={len(unexpected)}")
585
+
586
+ current_lora_key = PENDING_LORA_KEY
587
+ print("[LoRA] Prepared LoRA state applied to the pipeline.")
588
+ return True
589
+
590
+ # Preload all models for ZeroGPU tensor packing.
591
+ print("Preloading all models (including Gemma and audio components)...")
592
+ ledger = pipeline.model_ledger
593
+
594
+ # Save the original factory methods so we can rebuild individual components later.
595
+ # These are bound callables on ledger that will call the builder when invoked.
596
+ _orig_transformer_factory = ledger.transformer
597
+ _orig_video_encoder_factory = ledger.video_encoder
598
+ _orig_video_decoder_factory = ledger.video_decoder
599
+ _orig_audio_encoder_factory = ledger.audio_encoder
600
+ _orig_audio_decoder_factory = ledger.audio_decoder
601
+ _orig_vocoder_factory = ledger.vocoder
602
+ _orig_spatial_upsampler_factory = ledger.spatial_upsampler
603
+ _orig_text_encoder_factory = ledger.text_encoder
604
+ _orig_gemma_embeddings_factory = ledger.gemma_embeddings_processor
605
+
606
+ # Call the original factories once to create the cached instances we will serve by default.
607
+ _transformer = _orig_transformer_factory()
608
+ _video_encoder = _orig_video_encoder_factory()
609
+ _video_decoder = _orig_video_decoder_factory()
610
+ _audio_encoder = _orig_audio_encoder_factory()
611
+ _audio_decoder = _orig_audio_decoder_factory()
612
+ _vocoder = _orig_vocoder_factory()
613
+ _spatial_upsampler = _orig_spatial_upsampler_factory()
614
+ _text_encoder = _orig_text_encoder_factory()
615
+ _embeddings_processor = _orig_gemma_embeddings_factory()
616
+
617
+ # Replace ledger methods with lightweight lambdas that return the cached instances.
618
+ # We keep the original factories above so we can call them later to rebuild components.
619
+ ledger.transformer = lambda: _transformer
620
+ ledger.video_encoder = lambda: _video_encoder
621
+ ledger.video_decoder = lambda: _video_decoder
622
+ ledger.audio_encoder = lambda: _audio_encoder
623
+ ledger.audio_decoder = lambda: _audio_decoder
624
+ ledger.vocoder = lambda: _vocoder
625
+ ledger.spatial_upsampler = lambda: _spatial_upsampler
626
+ ledger.text_encoder = lambda: _text_encoder
627
+ ledger.gemma_embeddings_processor = lambda: _embeddings_processor
628
+
629
+ print("All models preloaded (including Gemma text encoder and audio encoder)!")
630
+ # ---- REPLACE PRELOAD BLOCK END ----
631
+
632
+ print("=" * 80)
633
+ print("Pipeline ready!")
634
+ print("=" * 80)
635
+
636
+ def log_memory(tag: str):
637
+ if torch.cuda.is_available():
638
+ allocated = torch.cuda.memory_allocated() / 1024**3
639
+ peak = torch.cuda.max_memory_allocated() / 1024**3
640
+ free, total = torch.cuda.mem_get_info()
641
+ print(f"[VRAM {tag}] allocated={allocated:.2f}GB peak={peak:.2f}GB free={free / 1024**3:.2f}GB total={total / 1024**3:.2f}GB")
642
+
643
+
644
+ def detect_aspect_ratio(image) -> str:
645
+ if image is None:
646
+ return "16:9"
647
+ if hasattr(image, "size"):
648
+ w, h = image.size
649
+ elif hasattr(image, "shape"):
650
+ h, w = image.shape[:2]
651
+ else:
652
+ return "16:9"
653
+ ratio = w / h
654
+ candidates = {"16:9": 16 / 9, "9:16": 9 / 16, "1:1": 1.0}
655
+ return min(candidates, key=lambda k: abs(ratio - candidates[k]))
656
+
657
+
658
+ def on_image_upload(first_image, last_image, high_res):
659
+ ref_image = first_image if first_image is not None else last_image
660
+ aspect = detect_aspect_ratio(ref_image)
661
+ tier = "high" if high_res else "low"
662
+ w, h = RESOLUTIONS[tier][aspect]
663
+ return gr.update(value=w), gr.update(value=h)
664
+
665
+
666
+ def on_highres_toggle(first_image, last_image, high_res):
667
+ ref_image = first_image if first_image is not None else last_image
668
+ aspect = detect_aspect_ratio(ref_image)
669
+ tier = "high" if high_res else "low"
670
+ w, h = RESOLUTIONS[tier][aspect]
671
+ return gr.update(value=w), gr.update(value=h)
672
+
673
+ def get_gpu_duration(
674
+ first_image,
675
+ last_image,
676
+ input_audio,
677
+ prompt: str,
678
+ negative_prompt: str,
679
+ duration: float,
680
+ gpu_duration: float,
681
+ enhance_prompt: bool = True,
682
+ seed: int = 42,
683
+ randomize_seed: bool = True,
684
+ height: int = 1024,
685
+ width: int = 1536,
686
+ video_cfg_scale: float = 1.0,
687
+ video_stg_scale: float = 0.0,
688
+ video_rescale_scale: float = 0.45,
689
+ video_a2v_scale: float = 3.0,
690
+ audio_cfg_scale: float = 1.0,
691
+ audio_stg_scale: float = 0.0,
692
+ audio_rescale_scale: float = 1.0,
693
+ audio_v2a_scale: float = 3.0,
694
+ pose_strength: float = 0.0,
695
+ general_strength: float = 0.0,
696
+ motion_strength: float = 0.0,
697
+ dreamlay_strength: float = 0.0,
698
+ mself_strength: float = 0.0,
699
+ dramatic_strength: float = 0.0,
700
+ fluid_strength: float = 0.0,
701
+ liquid_strength: float = 0.0,
702
+ demopose_strength: float = 0.0,
703
+ voice_strength: float = 0.0,
704
+ realism_strength: float = 0.0,
705
+ transition_strength: float = 0.0,
706
+ physics_strength: float = 0.0,
707
+ reasoning_strength: float = 0.0,
708
+ twostep_strength: float = 0.0,
709
+ num_inference_steps: int = 8,
710
+ progress=None,
711
+ ):
712
+ return int(gpu_duration)
713
+
714
+ @spaces.GPU(duration=get_gpu_duration)
715
+ @torch.inference_mode()
716
+ def generate_video(
717
+ first_image,
718
+ last_image,
719
+ input_audio,
720
+ prompt: str,
721
+ negative_prompt: str,
722
+ duration: float,
723
+ gpu_duration: float,
724
+ enhance_prompt: bool = True,
725
+ seed: int = 42,
726
+ randomize_seed: bool = True,
727
+ height: int = 1024,
728
+ width: int = 1536,
729
+ video_cfg_scale: float = 1.0,
730
+ video_stg_scale: float = 0.0,
731
+ video_rescale_scale: float = 0.45,
732
+ video_a2v_scale: float = 3.0,
733
+ audio_cfg_scale: float = 1.0,
734
+ audio_stg_scale: float = 0.0,
735
+ audio_rescale_scale: float = 1.0,
736
+ audio_v2a_scale: float = 3.0,
737
+ pose_strength: float = 0.0,
738
+ general_strength: float = 0.0,
739
+ motion_strength: float = 0.0,
740
+ dreamlay_strength: float = 0.0,
741
+ mself_strength: float = 0.0,
742
+ dramatic_strength: float = 0.0,
743
+ fluid_strength: float = 0.0,
744
+ liquid_strength: float = 0.0,
745
+ demopose_strength: float = 0.0,
746
+ voice_strength: float = 0.0,
747
+ realism_strength: float = 0.0,
748
+ transition_strength: float = 0.0,
749
+ physics_strength: float = 0.0,
750
+ reasoning_strength: float = 0.0,
751
+ twostep_strength: float = 0.0,
752
+ num_inference_steps: int = 8,
753
+ progress=gr.Progress(track_tqdm=True),
754
+ ):
755
+ try:
756
+ torch.cuda.reset_peak_memory_stats()
757
+ log_memory("start")
758
+
759
+ current_seed = random.randint(0, MAX_SEED) if randomize_seed else int(seed)
760
+
761
+ frame_rate = DEFAULT_FRAME_RATE
762
+ num_frames = int(duration * frame_rate) + 1
763
+ num_frames = ((num_frames - 1 + 7) // 8) * 8 + 1
764
+
765
+ print(f"Generating: {height}x{width}, {num_frames} frames ({duration}s), seed={current_seed}")
766
+
767
+ images = []
768
+ output_dir = Path("outputs")
769
+ output_dir.mkdir(exist_ok=True)
770
+
771
+ if first_image is not None:
772
+ temp_first_path = output_dir / f"temp_first_{current_seed}.jpg"
773
+ if hasattr(first_image, "save"):
774
+ first_image.save(temp_first_path)
775
+ else:
776
+ temp_first_path = Path(first_image)
777
+ images.append(ImageConditioningInput(path=str(temp_first_path), frame_idx=0, strength=1.0))
778
+
779
+ if last_image is not None:
780
+ temp_last_path = output_dir / f"temp_last_{current_seed}.jpg"
781
+ if hasattr(last_image, "save"):
782
+ last_image.save(temp_last_path)
783
+ else:
784
+ temp_last_path = Path(last_image)
785
+ images.append(ImageConditioningInput(path=str(temp_last_path), frame_idx=num_frames - 1, strength=1.0))
786
+
787
+ tiling_config = TilingConfig.default()
788
+ video_chunks_number = get_video_chunks_number(num_frames, tiling_config)
789
+
790
+ video_guider_params = MultiModalGuiderParams(
791
+ cfg_scale=video_cfg_scale,
792
+ stg_scale=video_stg_scale,
793
+ rescale_scale=video_rescale_scale,
794
+ modality_scale=video_a2v_scale,
795
+ skip_step=0,
796
+ stg_blocks=[],
797
+ )
798
+
799
+ audio_guider_params = MultiModalGuiderParams(
800
+ cfg_scale=audio_cfg_scale,
801
+ stg_scale=audio_stg_scale,
802
+ rescale_scale=audio_rescale_scale,
803
+ modality_scale=audio_v2a_scale,
804
+ skip_step=0,
805
+ stg_blocks=[],
806
+ )
807
+
808
+ log_memory("before pipeline call")
809
+
810
+ apply_prepared_lora_state_to_pipeline()
811
+
812
+ video, audio = pipeline(
813
+ prompt=prompt,
814
+ negative_prompt=negative_prompt,
815
+ seed=current_seed,
816
+ height=int(height),
817
+ width=int(width),
818
+ num_frames=num_frames,
819
+ frame_rate=frame_rate,
820
+ video_guider_params=video_guider_params,
821
+ audio_guider_params=audio_guider_params,
822
+ images=images,
823
+ num_inference_steps=num_inference_steps,
824
+ audio_path=input_audio,
825
+ tiling_config=tiling_config,
826
+ enhance_prompt=enhance_prompt,
827
+ )
828
+
829
+ log_memory("after pipeline call")
830
+
831
+ output_path = tempfile.mktemp(suffix=".mp4")
832
+ encode_video(
833
+ video=video,
834
+ fps=frame_rate,
835
+ audio=audio,
836
+ output_path=output_path,
837
+ video_chunks_number=video_chunks_number,
838
+ )
839
+
840
+ log_memory("after encode_video")
841
+ return str(output_path), current_seed
842
+
843
+ except Exception as e:
844
+ import traceback
845
+ log_memory("on error")
846
+ print(f"Error: {str(e)}\n{traceback.format_exc()}")
847
+ return None, current_seed
848
+
849
+ # =============================================================================
850
+ # Gradio UI
851
+ # =============================================================================
852
+
853
+ css = """
854
+ .fillable {max-width: 1200px !important}
855
+ .progress-text {color: black}
856
+ """
857
+
858
+ with gr.Blocks(title="LTX-2.3 Distilled with LoRAs, Negative Prompting, and Advanced Settings") as demo:
859
+ gr.Markdown("# LTX-2.3 Two-Stage HQ Video Generation")
860
+ gr.Markdown(
861
+ "High-quality text/image-to-video with cached LoRA state + CFG guidance. "
862
+ "[[Model]](https://huggingface.co/Lightricks/LTX-2.3)"
863
+ )
864
+
865
+ with gr.Row():
866
+ # LEFT SIDE: Input Controls
867
+ with gr.Column():
868
+ with gr.Row():
869
+ first_image = gr.Image(label="First Frame (Optional)", type="pil")
870
+ last_image = gr.Image(label="Last Frame (Optional)", type="pil")
871
+
872
+ prompt = gr.Textbox(
873
+ label="Prompt",
874
+ value="Make this image come alive with cinematic motion, smooth animation",
875
+ lines=3,
876
+ placeholder="Describe the motion and animation you want...",
877
+ )
878
+
879
+ negative_prompt = gr.Textbox(
880
+ label="Negative Prompt",
881
+ value="blurry, out of focus, overexposed, underexposed, low contrast, washed out colors, excessive noise, grainy texture, poor lighting, flickering, motion blur, distorted proportions, unnatural skin tones, deformed facial features, asymmetrical face, missing facial features, extra limbs, disfigured hands, wrong hand count, artifacts around text, inconsistent perspective, camera shake, incorrect depth of field, background too sharp, background clutter, distracting reflections, harsh shadows, inconsistent lighting direction, color banding, cartoonish rendering, 3D CGI look, unrealistic materials, uncanny valley effect, incorrect ethnicity, wrong gender, exaggerated expressions, wrong gaze direction, mismatched lip sync, silent or muted audio, distorted voice, robotic voice, echo, background noise, off-sync audio, incorrect dialogue, added dialogue, repetitive speech, jittery movement, awkward pauses, incorrect timing, unnatural transitions, inconsistent framing, tilted camera, flat lighting, inconsistent tone, cinematic oversaturation, stylized filters, or AI artifacts.",
882
+ lines=2,
883
+ )
884
+
885
+ duration = gr.Slider(
886
+ label="Duration (seconds)",
887
+ minimum=1.0, maximum=30.0, value=10.0, step=0.1,
888
+ )
889
+
890
+ with gr.Row():
891
+ seed = gr.Number(label="Seed", value=42, precision=0, minimum=0, maximum=MAX_SEED)
892
+ randomize_seed = gr.Checkbox(label="Randomize Seed", value=True)
893
+
894
+ with gr.Row():
895
+ high_res = gr.Checkbox(label="High Resolution", value=True)
896
+ enhance_prompt = gr.Checkbox(label="Enhance Prompt", value=False)
897
+
898
+ with gr.Row():
899
+ width = gr.Number(label="Width", value=1536, precision=0)
900
+ height = gr.Number(label="Height", value=1024, precision=0)
901
+
902
+ with gr.Row():
903
+ num_inference_steps = gr.Slider(
904
+ label="Stage 1 Inference Steps",
905
+ minimum=2, maximum=16, value=8, step=1,
906
+ info="Higher = more quality but slower (Stage 2 uses fixed 3 steps)"
907
+ )
908
+
909
+ generate_btn = gr.Button("Generate Video", variant="primary", size="lg")
910
+
911
+ with gr.Accordion("Advanced Settings", open=False):
912
+ gr.Markdown("### Video Guidance Parameters")
913
+
914
+ with gr.Row():
915
+ video_cfg_scale = gr.Slider(
916
+ label="Video CFG Scale", minimum=1.0, maximum=10.0, value=1.0, step=0.1
917
+ )
918
+ video_stg_scale = gr.Slider(
919
+ label="Video STG Scale", minimum=0.0, maximum=2.0, value=0.0, step=0.1
920
+ )
921
+
922
+ with gr.Row():
923
+ video_rescale_scale = gr.Slider(
924
+ label="Video Rescale", minimum=0.0, maximum=2.0, value=0.45, step=0.1
925
+ )
926
+ video_a2v_scale = gr.Slider(
927
+ label="A2V Scale", minimum=0.0, maximum=5.0, value=3.0, step=0.1
928
+ )
929
+
930
+ gr.Markdown("### Audio Guidance Parameters")
931
+
932
+ with gr.Row():
933
+ audio_cfg_scale = gr.Slider(
934
+ label="Audio CFG Scale", minimum=1.0, maximum=15.0, value=1.0, step=0.1
935
+ )
936
+ audio_stg_scale = gr.Slider(
937
+ label="Audio STG Scale", minimum=0.0, maximum=2.0, value=0.0, step=0.1
938
+ )
939
+
940
+ with gr.Row():
941
+ audio_rescale_scale = gr.Slider(
942
+ label="Audio Rescale", minimum=0.0, maximum=2.0, value=1.0, step=0.1
943
+ )
944
+ audio_v2a_scale = gr.Slider(
945
+ label="V2A Scale", minimum=0.0, maximum=5.0, value=3.0, step=0.1
946
+ )
947
+ with gr.Row():
948
+ input_audio = gr.Audio(label="Audio Input (Optional)", type="filepath")
949
+
950
+ # RIGHT SIDE: Output and LoRA
951
+ with gr.Column():
952
+ output_video = gr.Video(label="Generated Video", autoplay=False)
953
+
954
+ gpu_duration = gr.Slider(
955
+ label="ZeroGPU duration (seconds)",
956
+ minimum=30.0, maximum=240.0, value=90.0, step=1.0,
957
+ info="Increase for longer videos, higher resolution, or LoRA usage"
958
+ )
959
+
960
+ gr.Markdown("### LoRA Adapter Strengths")
961
+ gr.Markdown("Set to 0 to disable, then click 'Prepare LoRA Cache'")
962
+
963
+ with gr.Row():
964
+ pose_strength = gr.Slider(label="Anthro Enhancer", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
965
+ gr.Markdown("") # Spacer for alignment
966
+
967
+ with gr.Row():
968
+ general_strength = gr.Slider(label="Reasoning Enhancer", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
969
+ motion_strength = gr.Slider(label="Anthro Posing", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
970
+
971
+ with gr.Row():
972
+ dreamlay_strength = gr.Slider(label="Dreamlay", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
973
+ mself_strength = gr.Slider(label="Mself", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
974
+
975
+ with gr.Row():
976
+ dramatic_strength = gr.Slider(label="Dramatic", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
977
+ fluid_strength = gr.Slider(label="Fluid Helper", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
978
+
979
+ with gr.Row():
980
+ liquid_strength = gr.Slider(label="Liquid Helper", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
981
+ demopose_strength = gr.Slider(label="Audio Helper", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
982
+
983
+ with gr.Row():
984
+ voice_strength = gr.Slider(label="Voice Helper", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
985
+ realism_strength = gr.Slider(label="Anthro Realism", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
986
+
987
+ with gr.Row():
988
+ transition_strength = gr.Slider(label="POV", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
989
+ physics_strength = gr.Slider(label="Physics", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
990
+ with gr.Row():
991
+ reasoning_strength = gr.Slider(label="Official Reasoning", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
992
+ twostep_strength = gr.Slider(label="Two Step Reasoning", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
993
+
994
+ prepare_lora_btn = gr.Button("Prepare / Load LoRA Cache", variant="secondary")
995
+ lora_status = gr.Textbox(
996
+ label="LoRA Cache Status",
997
+ value="No LoRA state prepared yet.",
998
+ interactive=False,
999
+ )
1000
+
1001
+ # Event handlers
1002
+ first_image.change(fn=on_image_upload, inputs=[first_image, last_image, high_res], outputs=[width, height])
1003
+ last_image.change(fn=on_image_upload, inputs=[first_image, last_image, high_res], outputs=[width, height])
1004
+ high_res.change(fn=on_highres_toggle, inputs=[first_image, last_image, high_res], outputs=[width, height])
1005
+
1006
+ prepare_lora_btn.click(
1007
+ fn=prepare_lora_cache,
1008
+ inputs=[pose_strength, general_strength, motion_strength, dreamlay_strength,
1009
+ mself_strength, dramatic_strength, fluid_strength, liquid_strength,
1010
+ demopose_strength, voice_strength, realism_strength, transition_strength, physics_strength, reasoning_strength, twostep_strength],
1011
+ outputs=[lora_status],
1012
+ )
1013
+
1014
+ generate_btn.click(
1015
+ fn=generate_video,
1016
+ inputs=[
1017
+ first_image, last_image, input_audio, prompt, negative_prompt, duration, gpu_duration,
1018
+ enhance_prompt, seed, randomize_seed, height, width,
1019
+ video_cfg_scale, video_stg_scale, video_rescale_scale, video_a2v_scale,
1020
+ audio_cfg_scale, audio_stg_scale, audio_rescale_scale, audio_v2a_scale,
1021
+ pose_strength, general_strength, motion_strength,
1022
+ dreamlay_strength, mself_strength, dramatic_strength, fluid_strength,
1023
+ liquid_strength, demopose_strength, voice_strength, realism_strength,
1024
+ transition_strength, physics_strength, reasoning_strength, twostep_strength, num_inference_steps,
1025
+ ],
1026
+ outputs=[output_video, seed],
1027
+ )
1028
+
1029
+
1030
+ if __name__ == "__main__":
1031
+ demo.queue().launch(theme=gr.themes.Citrus(), css=css, mcp_server=False)