dagloop5 commited on
Commit
884d0d1
·
verified ·
1 Parent(s): f47c107

Create app.py

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