dagloop5 commited on
Commit
3ec538f
·
verified ·
1 Parent(s): 52ebc09

Delete app(template).py

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