dagloop5 commited on
Commit
48630c4
·
verified ·
1 Parent(s): abaf5bb

Delete app.py

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