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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import subprocess
|
| 3 |
+
import sys
|
| 4 |
+
import json
|
| 5 |
+
import struct
|
| 6 |
+
|
| 7 |
+
# Disable torch.compile / dynamo before any torch import
|
| 8 |
+
os.environ["TORCH_COMPILE_DISABLE"] = "1"
|
| 9 |
+
os.environ["TORCHDYNAMO_DISABLE"] = "1"
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
# Clone LTX-2 repo and install packages
|
| 13 |
+
LTX_REPO_URL = "https://github.com/Lightricks/LTX-2.git"
|
| 14 |
+
LTX_REPO_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "LTX-2")
|
| 15 |
+
|
| 16 |
+
LTX_COMMIT = "ae855f8538843825f9015a419cf4ba5edaf5eec2" # known working commit with decode_video
|
| 17 |
+
|
| 18 |
+
if not os.path.exists(LTX_REPO_DIR):
|
| 19 |
+
print(f"Cloning {LTX_REPO_URL}...")
|
| 20 |
+
subprocess.run(["git", "clone", LTX_REPO_URL, LTX_REPO_DIR], check=True)
|
| 21 |
+
subprocess.run(["git", "checkout", LTX_COMMIT], cwd=LTX_REPO_DIR, check=True)
|
| 22 |
+
|
| 23 |
+
print("Installing ltx-core and ltx-pipelines from cloned repo...")
|
| 24 |
+
subprocess.run(
|
| 25 |
+
[sys.executable, "-m", "pip", "install", "--force-reinstall", "--no-deps", "-e",
|
| 26 |
+
os.path.join(LTX_REPO_DIR, "packages", "ltx-core"),
|
| 27 |
+
"-e", os.path.join(LTX_REPO_DIR, "packages", "ltx-pipelines")],
|
| 28 |
+
check=True,
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
sys.path.insert(0, os.path.join(LTX_REPO_DIR, "packages", "ltx-pipelines", "src"))
|
| 32 |
+
sys.path.insert(0, os.path.join(LTX_REPO_DIR, "packages", "ltx-core", "src"))
|
| 33 |
+
|
| 34 |
+
import logging
|
| 35 |
+
import random
|
| 36 |
+
import tempfile
|
| 37 |
+
from pathlib import Path
|
| 38 |
+
import gc
|
| 39 |
+
import hashlib
|
| 40 |
+
import shutil
|
| 41 |
+
|
| 42 |
+
import spaces
|
| 43 |
+
import torch
|
| 44 |
+
|
| 45 |
+
torch._dynamo.config.suppress_errors = True
|
| 46 |
+
torch._dynamo.config.disable = True
|
| 47 |
+
|
| 48 |
+
# --- CRITICAL FIX: ZERO-GPU LOAD PATCH START ---
|
| 49 |
+
from ltx_core.loader.primitives import StateDict
|
| 50 |
+
from ltx_core.loader.sft_loader import SafetensorsStateDictLoader
|
| 51 |
+
|
| 52 |
+
_SAFETENSORS_DTYPE_MAP = {
|
| 53 |
+
"F64": torch.float64,
|
| 54 |
+
"F32": torch.float32,
|
| 55 |
+
"F16": torch.float16,
|
| 56 |
+
"BF16": torch.bfloat16,
|
| 57 |
+
"F8_E5M2": torch.float8_e5m2,
|
| 58 |
+
"F8_E4M3": torch.float8_e4m3fn,
|
| 59 |
+
"I64": torch.int64,
|
| 60 |
+
"I32": torch.int32,
|
| 61 |
+
"I16": torch.int16,
|
| 62 |
+
"I8": torch.int8,
|
| 63 |
+
"U8": torch.uint8,
|
| 64 |
+
"BOOL": torch.bool,
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
def _patched_load(self, path, sd_ops, device=None):
|
| 68 |
+
"""
|
| 69 |
+
Forces tensors to load onto CPU during the startup phase to prevent
|
| 70 |
+
'No CUDA GPUs are available' errors in ZeroGPU.
|
| 71 |
+
"""
|
| 72 |
+
sd = {}
|
| 73 |
+
size = 0
|
| 74 |
+
dtype = set()
|
| 75 |
+
# FORCE CPU during preloading
|
| 76 |
+
device = torch.device("cpu")
|
| 77 |
+
model_paths = path if isinstance(path, list) else [path]
|
| 78 |
+
for shard_path in model_paths:
|
| 79 |
+
with open(shard_path, "rb") as f:
|
| 80 |
+
header_len = struct.unpack("<Q", f.read(8))[0]
|
| 81 |
+
header = json.loads(f.read(header_len).decode("utf-8"))
|
| 82 |
+
data_base = 8 + header_len
|
| 83 |
+
for name, meta in header.items():
|
| 84 |
+
if name == "__metadata__":
|
| 85 |
+
continue
|
| 86 |
+
expected_name = name if sd_ops is None else sd_ops.apply_to_key(name)
|
| 87 |
+
if expected_name is None:
|
| 88 |
+
continue
|
| 89 |
+
start, end = meta["data_offsets"]
|
| 90 |
+
f.seek(data_base + start)
|
| 91 |
+
buf = f.read(end - start)
|
| 92 |
+
t = torch.frombuffer(
|
| 93 |
+
bytearray(buf), dtype=_SAFETENSORS_DTYPE_MAP[meta["dtype"]]
|
| 94 |
+
).reshape(meta["shape"])
|
| 95 |
+
t = t.to(device=device, non_blocking=True, copy=False)
|
| 96 |
+
kvs = (
|
| 97 |
+
((expected_name, t),)
|
| 98 |
+
if sd_ops is None
|
| 99 |
+
else sd_ops.apply_to_key_value(expected_name, t)
|
| 100 |
+
)
|
| 101 |
+
for key, v in kvs:
|
| 102 |
+
size += v.nbytes
|
| 103 |
+
dtype.add(v.dtype)
|
| 104 |
+
sd[key] = v
|
| 105 |
+
return StateDict(sd=sd, device=device, size=size, dtype=dtype)
|
| 106 |
+
|
| 107 |
+
SafetensorsStateDictLoader.load = _patched_load
|
| 108 |
+
print("[FIX] SafetensorsStateDictLoader.load patched for ZeroGPU")
|
| 109 |
+
# --- CRITICAL FIX END ---
|
| 110 |
+
|
| 111 |
+
_original_tensor_to = torch.Tensor.to
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def _is_cuda_target(x):
|
| 115 |
+
return (
|
| 116 |
+
x == "cuda"
|
| 117 |
+
or (isinstance(x, torch.device) and x.type == "cuda")
|
| 118 |
+
or (isinstance(x, str) and x.startswith("cuda"))
|
| 119 |
+
or (isinstance(x, int) and x == 0)
|
| 120 |
+
)
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def _spaces_safe_to(self, *args, **kwargs):
|
| 124 |
+
"""ZeroGPU emulates bare .to('cuda'), but LTX-2 uses non_blocking/copy."""
|
| 125 |
+
if args and _is_cuda_target(args[0]):
|
| 126 |
+
new_args = ("cuda",) + args[1:]
|
| 127 |
+
new_kwargs = {k: v for k, v in kwargs.items() if k not in ("non_blocking", "copy")}
|
| 128 |
+
return _original_tensor_to(self, *new_args, **new_kwargs)
|
| 129 |
+
|
| 130 |
+
if kwargs.get("device") is not None and _is_cuda_target(kwargs["device"]):
|
| 131 |
+
new_kwargs = {k: v for k, v in kwargs.items() if k not in ("non_blocking", "copy")}
|
| 132 |
+
new_kwargs["device"] = "cuda"
|
| 133 |
+
return _original_tensor_to(self, *args, **new_kwargs)
|
| 134 |
+
|
| 135 |
+
return _original_tensor_to(self, *args, **kwargs)
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
torch.Tensor.to = _spaces_safe_to
|
| 139 |
+
|
| 140 |
+
import gradio as gr
|
| 141 |
+
import numpy as np
|
| 142 |
+
from huggingface_hub import hf_hub_download, snapshot_download
|
| 143 |
+
from safetensors import safe_open
|
| 144 |
+
import requests
|
| 145 |
+
|
| 146 |
+
from ltx_core.components.diffusion_steps import EulerDiffusionStep
|
| 147 |
+
from ltx_core.components.noisers import GaussianNoiser
|
| 148 |
+
from ltx_core.model.audio_vae import encode_audio as vae_encode_audio
|
| 149 |
+
from ltx_core.model.upsampler import upsample_video
|
| 150 |
+
from ltx_core.model.video_vae import TilingConfig, get_video_chunks_number, decode_video as vae_decode_video
|
| 151 |
+
from ltx_core.quantization import QuantizationPolicy
|
| 152 |
+
from ltx_core.types import Audio, AudioLatentShape, VideoPixelShape
|
| 153 |
+
from ltx_pipelines.distilled import DistilledPipeline
|
| 154 |
+
from ltx_pipelines.utils import euler_denoising_loop
|
| 155 |
+
from ltx_pipelines.utils.args import ImageConditioningInput
|
| 156 |
+
from ltx_pipelines.utils.constants import DISTILLED_SIGMA_VALUES, STAGE_2_DISTILLED_SIGMA_VALUES
|
| 157 |
+
from ltx_pipelines.utils.helpers import (
|
| 158 |
+
cleanup_memory,
|
| 159 |
+
combined_image_conditionings,
|
| 160 |
+
denoise_video_only,
|
| 161 |
+
encode_prompts,
|
| 162 |
+
simple_denoising_func,
|
| 163 |
+
)
|
| 164 |
+
from ltx_pipelines.utils.media_io import decode_audio_from_file, encode_video
|
| 165 |
+
from ltx_core.loader.primitives import LoraPathStrengthAndSDOps
|
| 166 |
+
from ltx_core.loader.sd_ops import LTXV_LORA_COMFY_RENAMING_MAP
|
| 167 |
+
|
| 168 |
+
logging.getLogger().setLevel(logging.INFO)
|
| 169 |
+
|
| 170 |
+
MAX_SEED = np.iinfo(np.int32).max
|
| 171 |
+
DEFAULT_PROMPT = (
|
| 172 |
+
"An astronaut hatches from a fragile egg on the surface of the Moon, "
|
| 173 |
+
"the shell cracking and peeling apart in gentle low-gravity motion. "
|
| 174 |
+
"Fine lunar dust lifts and drifts outward with each movement, floating "
|
| 175 |
+
"in slow arcs before settling back onto the ground."
|
| 176 |
+
)
|
| 177 |
+
DEFAULT_FRAME_RATE = 24.0
|
| 178 |
+
|
| 179 |
+
RESOLUTIONS = {
|
| 180 |
+
"low": {"16:9": (768, 512), "9:16": (512, 768), "1:1": (768, 768),
|
| 181 |
+
"4:3": (768, 576), "3:4": (576, 768), "21:9": (768, 384)},
|
| 182 |
+
"high": {"16:9": (1536, 1024), "9:16": (1024, 1536), "1:1": (1024, 1024),
|
| 183 |
+
"4:3": (1536, 1152), "3:4": (1152, 1536), "21:9": (1536, 768)},
|
| 184 |
+
}
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
class LTX23DistilledA2VPipeline(DistilledPipeline):
|
| 188 |
+
def __call__(
|
| 189 |
+
self,
|
| 190 |
+
prompt: str,
|
| 191 |
+
seed: int,
|
| 192 |
+
height: int,
|
| 193 |
+
width: int,
|
| 194 |
+
num_frames: int,
|
| 195 |
+
frame_rate: float,
|
| 196 |
+
images: list[ImageConditioningInput],
|
| 197 |
+
audio_path: str | None = None,
|
| 198 |
+
tiling_config: TilingConfig | None = None,
|
| 199 |
+
enhance_prompt: bool = False,
|
| 200 |
+
):
|
| 201 |
+
print(prompt)
|
| 202 |
+
if audio_path is None:
|
| 203 |
+
return super().__call__(
|
| 204 |
+
prompt=prompt,
|
| 205 |
+
seed=seed,
|
| 206 |
+
height=height,
|
| 207 |
+
width=width,
|
| 208 |
+
num_frames=num_frames,
|
| 209 |
+
frame_rate=frame_rate,
|
| 210 |
+
images=images,
|
| 211 |
+
tiling_config=tiling_config,
|
| 212 |
+
enhance_prompt=enhance_prompt,
|
| 213 |
+
)
|
| 214 |
+
|
| 215 |
+
generator = torch.Generator(device=self.device).manual_seed(seed)
|
| 216 |
+
noiser = GaussianNoiser(generator=generator)
|
| 217 |
+
stepper = EulerDiffusionStep()
|
| 218 |
+
dtype = torch.bfloat16
|
| 219 |
+
|
| 220 |
+
(ctx_p,) = encode_prompts(
|
| 221 |
+
[prompt],
|
| 222 |
+
self.model_ledger,
|
| 223 |
+
enhance_first_prompt=enhance_prompt,
|
| 224 |
+
enhance_prompt_image=images[0].path if len(images) > 0 else None,
|
| 225 |
+
)
|
| 226 |
+
video_context, audio_context = ctx_p.video_encoding, ctx_p.audio_encoding
|
| 227 |
+
|
| 228 |
+
video_duration = num_frames / frame_rate
|
| 229 |
+
decoded_audio = decode_audio_from_file(audio_path, self.device, 0.0, video_duration)
|
| 230 |
+
if decoded_audio is None:
|
| 231 |
+
raise ValueError(f"Could not extract audio stream from {audio_path}")
|
| 232 |
+
|
| 233 |
+
encoded_audio_latent = vae_encode_audio(decoded_audio, self.model_ledger.audio_encoder())
|
| 234 |
+
audio_shape = AudioLatentShape.from_duration(batch=1, duration=video_duration, channels=8, mel_bins=16)
|
| 235 |
+
expected_frames = audio_shape.frames
|
| 236 |
+
actual_frames = encoded_audio_latent.shape[2]
|
| 237 |
+
|
| 238 |
+
if actual_frames > expected_frames:
|
| 239 |
+
encoded_audio_latent = encoded_audio_latent[:, :, :expected_frames, :]
|
| 240 |
+
elif actual_frames < expected_frames:
|
| 241 |
+
pad = torch.zeros(
|
| 242 |
+
encoded_audio_latent.shape[0],
|
| 243 |
+
encoded_audio_latent.shape[1],
|
| 244 |
+
expected_frames - actual_frames,
|
| 245 |
+
encoded_audio_latent.shape[3],
|
| 246 |
+
device=encoded_audio_latent.device,
|
| 247 |
+
dtype=encoded_audio_latent.dtype,
|
| 248 |
+
)
|
| 249 |
+
encoded_audio_latent = torch.cat([encoded_audio_latent, pad], dim=2)
|
| 250 |
+
|
| 251 |
+
video_encoder = self.model_ledger.video_encoder()
|
| 252 |
+
transformer = self.model_ledger.transformer()
|
| 253 |
+
stage_1_sigmas = torch.tensor(DISTILLED_SIGMA_VALUES, device=self.device)
|
| 254 |
+
|
| 255 |
+
def denoising_loop(sigmas, video_state, audio_state, stepper):
|
| 256 |
+
return euler_denoising_loop(
|
| 257 |
+
sigmas=sigmas,
|
| 258 |
+
video_state=video_state,
|
| 259 |
+
audio_state=audio_state,
|
| 260 |
+
stepper=stepper,
|
| 261 |
+
denoise_fn=simple_denoising_func(
|
| 262 |
+
video_context=video_context,
|
| 263 |
+
audio_context=audio_context,
|
| 264 |
+
transformer=transformer,
|
| 265 |
+
),
|
| 266 |
+
)
|
| 267 |
+
|
| 268 |
+
stage_1_output_shape = VideoPixelShape(
|
| 269 |
+
batch=1,
|
| 270 |
+
frames=num_frames,
|
| 271 |
+
width=width // 2,
|
| 272 |
+
height=height // 2,
|
| 273 |
+
fps=frame_rate,
|
| 274 |
+
)
|
| 275 |
+
stage_1_conditionings = combined_image_conditionings(
|
| 276 |
+
images=images,
|
| 277 |
+
height=stage_1_output_shape.height,
|
| 278 |
+
width=stage_1_output_shape.width,
|
| 279 |
+
video_encoder=video_encoder,
|
| 280 |
+
dtype=dtype,
|
| 281 |
+
device=self.device,
|
| 282 |
+
)
|
| 283 |
+
video_state = denoise_video_only(
|
| 284 |
+
output_shape=stage_1_output_shape,
|
| 285 |
+
conditionings=stage_1_conditionings,
|
| 286 |
+
noiser=noiser,
|
| 287 |
+
sigmas=stage_1_sigmas,
|
| 288 |
+
stepper=stepper,
|
| 289 |
+
denoising_loop_fn=denoising_loop,
|
| 290 |
+
components=self.pipeline_components,
|
| 291 |
+
dtype=dtype,
|
| 292 |
+
device=self.device,
|
| 293 |
+
initial_audio_latent=encoded_audio_latent,
|
| 294 |
+
)
|
| 295 |
+
|
| 296 |
+
torch.cuda.synchronize()
|
| 297 |
+
cleanup_memory()
|
| 298 |
+
|
| 299 |
+
upscaled_video_latent = upsample_video(
|
| 300 |
+
latent=video_state.latent[:1],
|
| 301 |
+
video_encoder=video_encoder,
|
| 302 |
+
upsampler=self.model_ledger.spatial_upsampler(),
|
| 303 |
+
)
|
| 304 |
+
stage_2_sigmas = torch.tensor(STAGE_2_DISTILLED_SIGMA_VALUES, device=self.device)
|
| 305 |
+
stage_2_output_shape = VideoPixelShape(batch=1, frames=num_frames, width=width, height=height, fps=frame_rate)
|
| 306 |
+
stage_2_conditionings = combined_image_conditionings(
|
| 307 |
+
images=images,
|
| 308 |
+
height=stage_2_output_shape.height,
|
| 309 |
+
width=stage_2_output_shape.width,
|
| 310 |
+
video_encoder=video_encoder,
|
| 311 |
+
dtype=dtype,
|
| 312 |
+
device=self.device,
|
| 313 |
+
)
|
| 314 |
+
video_state = denoise_video_only(
|
| 315 |
+
output_shape=stage_2_output_shape,
|
| 316 |
+
conditionings=stage_2_conditionings,
|
| 317 |
+
noiser=noiser,
|
| 318 |
+
sigmas=stage_2_sigmas,
|
| 319 |
+
stepper=stepper,
|
| 320 |
+
denoising_loop_fn=denoising_loop,
|
| 321 |
+
components=self.pipeline_components,
|
| 322 |
+
dtype=dtype,
|
| 323 |
+
device=self.device,
|
| 324 |
+
noise_scale=stage_2_sigmas[0],
|
| 325 |
+
initial_video_latent=upscaled_video_latent,
|
| 326 |
+
initial_audio_latent=encoded_audio_latent,
|
| 327 |
+
)
|
| 328 |
+
|
| 329 |
+
torch.cuda.synchronize()
|
| 330 |
+
del transformer
|
| 331 |
+
del video_encoder
|
| 332 |
+
cleanup_memory()
|
| 333 |
+
|
| 334 |
+
decoded_video = vae_decode_video(
|
| 335 |
+
video_state.latent,
|
| 336 |
+
self.model_ledger.video_decoder(),
|
| 337 |
+
tiling_config,
|
| 338 |
+
generator,
|
| 339 |
+
)
|
| 340 |
+
original_audio = Audio(
|
| 341 |
+
waveform=decoded_audio.waveform.squeeze(0),
|
| 342 |
+
sampling_rate=decoded_audio.sampling_rate,
|
| 343 |
+
)
|
| 344 |
+
return decoded_video, original_audio
|
| 345 |
+
|
| 346 |
+
|
| 347 |
+
# Model repos
|
| 348 |
+
LTX_MODEL_REPO = "Lightricks/LTX-2.3"
|
| 349 |
+
GEMMA_REPO ="Lightricks/gemma-3-12b-it-qat-q4_0-unquantized"
|
| 350 |
+
|
| 351 |
+
print("=" * 80)
|
| 352 |
+
print("Downloading LTX-2.3 distilled model + Gemma...")
|
| 353 |
+
print("=" * 80)
|
| 354 |
+
|
| 355 |
+
_legacy_lora_cache_dir = Path("lora_cache")
|
| 356 |
+
if _legacy_lora_cache_dir.exists():
|
| 357 |
+
shutil.rmtree(_legacy_lora_cache_dir, ignore_errors=True)
|
| 358 |
+
|
| 359 |
+
current_lora_key: str | None = None
|
| 360 |
+
PENDING_LORA_KEY: str | None = None
|
| 361 |
+
PENDING_LORA_STATE: dict[str, torch.Tensor] | None = None
|
| 362 |
+
PENDING_LORA_STATUS: str = "No LoRA state prepared yet."
|
| 363 |
+
|
| 364 |
+
weights_dir = Path("weights")
|
| 365 |
+
weights_dir.mkdir(exist_ok=True)
|
| 366 |
+
checkpoint_path = hf_hub_download(
|
| 367 |
+
repo_id="ibyteohdear/Lightricks-LTX-2.3-DISTILLED-10-Eros",
|
| 368 |
+
filename="LTX2.3_DISTILLED_BAKED_LTX_SULPHUR_STYLE_IS_10Eros_v14_r768.safetensors",
|
| 369 |
+
local_dir=str(weights_dir),
|
| 370 |
+
local_dir_use_symlinks=False,
|
| 371 |
+
)
|
| 372 |
+
|
| 373 |
+
spatial_upsampler_path = hf_hub_download(repo_id=LTX_MODEL_REPO, filename="ltx-2.3-spatial-upscaler-x2-1.1.safetensors")
|
| 374 |
+
gemma_root = snapshot_download(repo_id=GEMMA_REPO)
|
| 375 |
+
|
| 376 |
+
LORA_REPO = "dagloop5/LoRA"
|
| 377 |
+
print("=" * 80)
|
| 378 |
+
print("Downloading LoRA adapters from dagloop5/LoRA...")
|
| 379 |
+
print("=" * 80)
|
| 380 |
+
singularity_lora_path = hf_hub_download(repo_id="TenStrip/LTX2.3_DMD_Lora", filename="LTX2.3_DMD_reshaped_r256.safetensors")
|
| 381 |
+
teneros_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="LTX2.3-Furry-2D-NSFW-Multi-Purpose-Lora+Cum.safetensors")
|
| 382 |
+
sulphur_lora_path =hf_hub_download(repo_id=LORA_REPO, filename="ltx23E28093SlowMotion26.Pkrs.safetensors")
|
| 383 |
+
pose_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="LTX2_3_NSFW_furry_concat_v2.safetensors")
|
| 384 |
+
general_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="LTX2.3_reasoning_Sulphur-2_I2V_V4.safetensors")
|
| 385 |
+
motion_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="Sulphur_LTX 2.3_better _NSFW_motion.safetensors")
|
| 386 |
+
dreamlay_lora_path = hf_hub_download(repo_id="lynaNSFW/DR34ML4Y_AIO_NSFW_LTX23", filename="DR34ML4Y_LTXXX_V2.safetensors")
|
| 387 |
+
mself_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="LTX2.3_2d_NSFW_motion_enhancer.safetensors")
|
| 388 |
+
dramatic_lora_path = hf_hub_download(repo_id="Muapi/valiantcat-ltx-2.3-transition-lora", filename="valiantcat-ltx-2.3-transition-lora.safetensors")
|
| 389 |
+
fluid_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="Cr3ampi3_animation_sulphur-2_i2v_v1.0.safetensors")
|
| 390 |
+
liquid_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="liquid_wet_dr1pp_ltx2_v1.0_scaled.safetensors")
|
| 391 |
+
demopose_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="clapping-cheeks-audio-v001-alpha.safetensors")
|
| 392 |
+
voice_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="hentai_voice_ltx23_v2.comfy.safetensors")
|
| 393 |
+
realism_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="FurryenhancerLTX2.3V4.094fused.safetensors")
|
| 394 |
+
transition_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="LTX-2_takerpov_lora_v1.2.safetensors")
|
| 395 |
+
physics_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="LTX2.3_Physics_V2_000002000.safetensors")
|
| 396 |
+
reasoning_lora_path = hf_hub_download(repo_id="LiconStudio/Ltx2.3-VBVR-lora-I2V", filename="Ltx2.3-Licon-VBVR-I2V-390K-R32.safetensors")
|
| 397 |
+
twostep_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="LTX2.3_Multi_step_video_reasoning_V0.1.safetensors")
|
| 398 |
+
mcfurry_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="mvmt_lora_v2_600.safetensors")
|
| 399 |
+
dm_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="Doggy_mission_sulphur-2_v0.5.safetensors")
|
| 400 |
+
praxis_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="Penile_Praxis_V4.safetensors")
|
| 401 |
+
threed_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="ltx2-3d-animations-12500-steps-k3nk.safetensors")
|
| 402 |
+
concept_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="ltx23_nsfw_helper_multi_concept_lora_v2.safetensors")
|
| 403 |
+
bulge_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="stomach_bulge_10eros_sulphur_v1.safetensors")
|
| 404 |
+
|
| 405 |
+
pipeline = LTX23DistilledA2VPipeline(
|
| 406 |
+
distilled_checkpoint_path=checkpoint_path,
|
| 407 |
+
spatial_upsampler_path=spatial_upsampler_path,
|
| 408 |
+
gemma_root=gemma_root,
|
| 409 |
+
loras=[],
|
| 410 |
+
quantization=QuantizationPolicy.fp8_cast(),
|
| 411 |
+
)
|
| 412 |
+
|
| 413 |
+
def _make_lora_key(singularity_strength, teneros_strength, sulphur_strength, 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, mcfurry_strength, dm_strength, praxis_strength, threed_strength, concept_strength, bulge_strength) -> tuple[str, str]:
|
| 414 |
+
rx, ra, rb, rp, rg, rm, rd, rs, rr, rf, rl, ro, rv, re, rt, ry, ri, rw, mc, dm, pr, td, co, bu = [round(float(x), 2) for x in [singularity_strength, teneros_strength, sulphur_strength, 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, mcfurry_strength, dm_strength, praxis_strength, threed_strength, concept_strength, bulge_strength]]
|
| 415 |
+
key_str = f"{singularity_lora_path}:{rx}|{teneros_lora_path}:{ra}|{sulphur_lora_path}:{rb}|{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}|{mcfurry_lora_path}:{mc}|{dm_lora_path}:{dm}|{praxis_lora_path}:{pr}|{threed_lora_path}:{td}|{concept_lora_path}:{co}|{bulge_lora_path}:{bu}"
|
| 416 |
+
key = hashlib.sha256(key_str.encode("utf-8")).hexdigest()
|
| 417 |
+
return key, key_str
|
| 418 |
+
|
| 419 |
+
def prepare_lora_cache(
|
| 420 |
+
singularity_strength, teneros_strength, sulphur_strength, 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, mcfurry_strength, dm_strength, praxis_strength, threed_strength, concept_strength, bulge_strength,
|
| 421 |
+
progress=gr.Progress(track_tqdm=True),
|
| 422 |
+
):
|
| 423 |
+
global PENDING_LORA_KEY, PENDING_LORA_STATE, PENDING_LORA_STATUS
|
| 424 |
+
ledger = pipeline.model_ledger
|
| 425 |
+
key, _ = _make_lora_key(singularity_strength, teneros_strength, sulphur_strength, 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, mcfurry_strength, dm_strength, praxis_strength, threed_strength, concept_strength, bulge_strength)
|
| 426 |
+
progress(0.05, desc="Preparing LoRA state")
|
| 427 |
+
entries = [
|
| 428 |
+
(singularity_lora_path, round(float(singularity_strength), 2)), (teneros_lora_path, round(float(teneros_strength), 2)), (sulphur_lora_path, round(float(sulphur_strength), 2)), (pose_lora_path, round(float(pose_strength), 2)), (general_lora_path, round(float(general_strength), 2)), (motion_lora_path, round(float(motion_strength), 2)), (dreamlay_lora_path, round(float(dreamlay_strength), 2)), (mself_lora_path, round(float(mself_strength), 2)), (dramatic_lora_path, round(float(dramatic_strength), 2)), (fluid_lora_path, round(float(fluid_strength), 2)), (liquid_lora_path, round(float(liquid_strength), 2)), (demopose_lora_path, round(float(demopose_strength), 2)), (voice_lora_path, round(float(voice_strength), 2)), (realism_lora_path, round(float(realism_strength), 2)), (transition_lora_path, round(float(transition_strength), 2)), (physics_lora_path, round(float(physics_strength), 2)), (reasoning_lora_path, round(float(reasoning_strength), 2)), (twostep_lora_path, round(float(twostep_strength), 2)), (mcfurry_lora_path, round(float(mcfurry_strength), 2)), (dm_lora_path, round(float(dm_strength), 2)), (praxis_lora_path, round(float(praxis_strength), 2)), (threed_lora_path, round(float(threed_strength), 2)), (concept_lora_path, round(float(concept_strength), 2)), (bulge_lora_path, round(float(bulge_strength), 2)),
|
| 429 |
+
]
|
| 430 |
+
loras_for_builder = [LoraPathStrengthAndSDOps(path, strength, LTXV_LORA_COMFY_RENAMING_MAP) for path, strength in entries if path is not None and float(strength) != 0.0]
|
| 431 |
+
if not loras_for_builder:
|
| 432 |
+
PENDING_LORA_KEY = None
|
| 433 |
+
PENDING_LORA_STATE = None
|
| 434 |
+
PENDING_LORA_STATUS = "No non-zero LoRA strengths selected; nothing to prepare."
|
| 435 |
+
return PENDING_LORA_STATUS
|
| 436 |
+
try:
|
| 437 |
+
progress(0.35, desc="Building fused CPU transformer")
|
| 438 |
+
tmp_ledger = pipeline.model_ledger.__class__(dtype=ledger.dtype, device=torch.device("cpu"), checkpoint_path=str(checkpoint_path), spatial_upsampler_path=str(spatial_upsampler_path), gemma_root_path=str(gemma_root), loras=tuple(loras_for_builder), quantization=QuantizationPolicy.fp8_cast())
|
| 439 |
+
new_transformer_cpu = tmp_ledger.transformer()
|
| 440 |
+
progress(0.70, desc="Extracting fused state_dict")
|
| 441 |
+
state = {k: v.detach().cpu().contiguous() for k, v in new_transformer_cpu.state_dict().items()}
|
| 442 |
+
PENDING_LORA_KEY = key
|
| 443 |
+
PENDING_LORA_STATE = state
|
| 444 |
+
PENDING_LORA_STATUS = "Built LoRA state (ready to apply)."
|
| 445 |
+
return PENDING_LORA_STATUS
|
| 446 |
+
except Exception as e:
|
| 447 |
+
PENDING_LORA_KEY = None
|
| 448 |
+
PENDING_LORA_STATE = None
|
| 449 |
+
PENDING_LORA_STATUS = f"LoRA prepare failed: {type(e).__name__}: {e}"
|
| 450 |
+
return PENDING_LORA_STATUS
|
| 451 |
+
finally:
|
| 452 |
+
gc.collect()
|
| 453 |
+
|
| 454 |
+
def apply_prepared_lora_state_to_pipeline():
|
| 455 |
+
global current_lora_key, PENDING_LORA_KEY, PENDING_LORA_STATE, PENDING_LORA_STATUS
|
| 456 |
+
if PENDING_LORA_KEY is None: return False
|
| 457 |
+
if current_lora_key == PENDING_LORA_KEY:
|
| 458 |
+
if PENDING_LORA_STATE is not None: PENDING_LORA_STATE = None
|
| 459 |
+
return True
|
| 460 |
+
if PENDING_LORA_STATE is None: return False
|
| 461 |
+
with torch.no_grad():
|
| 462 |
+
_transformer.load_state_dict(PENDING_LORA_STATE, strict=False)
|
| 463 |
+
current_lora_key = PENDING_LORA_KEY
|
| 464 |
+
PENDING_LORA_STATE = None
|
| 465 |
+
PENDING_LORA_STATUS = "LoRA state applied to pipeline."
|
| 466 |
+
return True
|
| 467 |
+
|
| 468 |
+
print("Preloading all models...")
|
| 469 |
+
ledger = pipeline.model_ledger
|
| 470 |
+
_transformer = ledger.transformer()
|
| 471 |
+
_video_encoder = ledger.video_encoder()
|
| 472 |
+
_video_decoder = ledger.video_decoder()
|
| 473 |
+
_audio_encoder = ledger.audio_encoder()
|
| 474 |
+
_audio_decoder = ledger.audio_decoder()
|
| 475 |
+
_vocoder = ledger.vocoder()
|
| 476 |
+
_spatial_upsampler = ledger.spatial_upsampler()
|
| 477 |
+
_text_encoder = ledger.text_encoder()
|
| 478 |
+
_embeddings_processor = ledger.gemma_embeddings_processor()
|
| 479 |
+
|
| 480 |
+
ledger.transformer = lambda: _transformer
|
| 481 |
+
ledger.video_encoder = lambda: _video_encoder
|
| 482 |
+
ledger.video_decoder = lambda: _video_decoder
|
| 483 |
+
ledger.audio_encoder = lambda: _audio_encoder
|
| 484 |
+
ledger.audio_decoder = lambda: _audio_decoder
|
| 485 |
+
ledger.vocoder = lambda: _vocoder
|
| 486 |
+
ledger.spatial_upsampler = lambda: _spatial_upsampler
|
| 487 |
+
ledger.text_encoder = lambda: _text_encoder
|
| 488 |
+
ledger.gemma_embeddings_processor = lambda: _embeddings_processor
|
| 489 |
+
print("All models preloaded!")
|
| 490 |
+
|
| 491 |
+
def log_memory(tag: str):
|
| 492 |
+
if torch.cuda.is_available():
|
| 493 |
+
allocated = torch.cuda.memory_allocated() / 1024**3
|
| 494 |
+
print(f"[VRAM {tag}] allocated={allocated:.2f}GB")
|
| 495 |
+
|
| 496 |
+
def detect_aspect_ratio(image) -> str:
|
| 497 |
+
if image is None: return "16:9"
|
| 498 |
+
w, h = (image.size if hasattr(image, "size") else image.shape[:2][::-1])
|
| 499 |
+
ratio = w / h
|
| 500 |
+
candidates = {"16:9": 16 / 9, "9:16": 9 / 16, "1:1": 1.0}
|
| 501 |
+
return min(candidates, key=lambda k: abs(ratio - candidates[k]))
|
| 502 |
+
|
| 503 |
+
def on_image_upload(first_image, last_image, high_res):
|
| 504 |
+
ref_image = first_image if first_image is not None else last_image
|
| 505 |
+
aspect = detect_aspect_ratio(ref_image)
|
| 506 |
+
tier = "high" if high_res else "low"
|
| 507 |
+
w, h = RESOLUTIONS[tier][aspect]
|
| 508 |
+
return gr.update(value=w), gr.update(value=h)
|
| 509 |
+
|
| 510 |
+
def on_highres_toggle(first_image, last_image, high_res):
|
| 511 |
+
ref_image = first_image if first_image is not None else last_image
|
| 512 |
+
aspect = detect_aspect_ratio(ref_image)
|
| 513 |
+
tier = "high" if high_res else "low"
|
| 514 |
+
w, h = RESOLUTIONS[tier][aspect]
|
| 515 |
+
return gr.update(value=w), gr.update(value=h)
|
| 516 |
+
|
| 517 |
+
def get_gpu_duration(first_image, last_image, input_audio, prompt, duration, gpu_duration, enhance_prompt, seed, randomize_seed, height, width, singularity_strength, teneros_strength, sulphur_strength, 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, mcfurry_strength, dm_strength, praxis_strength, threed_strength, concept_strength, bulge_strength, progress=None):
|
| 518 |
+
return int(gpu_duration)
|
| 519 |
+
|
| 520 |
+
@spaces.GPU(size="xlarge", duration=get_gpu_duration)
|
| 521 |
+
@torch.inference_mode()
|
| 522 |
+
def generate_video(first_image, last_image, input_audio, prompt, duration, gpu_duration, enhance_prompt, seed, randomize_seed, height, width, singularity_strength, teneros_strength, sulphur_strength, 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, mcfurry_strength, dm_strength, praxis_strength, threed_strength, concept_strength, bulge_strength, progress=gr.Progress(track_tqdm=True)):
|
| 523 |
+
try:
|
| 524 |
+
current_seed = random.randint(0, MAX_SEED) if randomize_seed else int(seed)
|
| 525 |
+
frame_rate = DEFAULT_FRAME_RATE
|
| 526 |
+
num_frames = int(duration * frame_rate) + 1
|
| 527 |
+
num_frames = ((num_frames - 1 + 7) // 8) * 8 + 1
|
| 528 |
+
images = []
|
| 529 |
+
output_dir = Path("outputs")
|
| 530 |
+
output_dir.mkdir(exist_ok=True)
|
| 531 |
+
if first_image is not None:
|
| 532 |
+
temp_first_path = output_dir / f"temp_first_{current_seed}.jpg"
|
| 533 |
+
if hasattr(first_image, "save"): first_image.save(temp_first_path)
|
| 534 |
+
else: temp_first_path = Path(first_image)
|
| 535 |
+
images.append(ImageConditioningInput(path=str(temp_first_path), frame_idx=0, strength=1.0))
|
| 536 |
+
if last_image is not None:
|
| 537 |
+
temp_last_path = output_dir / f"temp_last_{current_seed}.jpg"
|
| 538 |
+
if hasattr(last_image, "save"): last_image.save(temp_last_path)
|
| 539 |
+
else: temp_last_path = Path(last_image)
|
| 540 |
+
images.append(ImageConditioningInput(path=str(temp_last_path), frame_idx=num_frames - 1, strength=1.0))
|
| 541 |
+
tiling_config = TilingConfig.default()
|
| 542 |
+
video_chunks_number = get_video_chunks_number(num_frames, tiling_config)
|
| 543 |
+
apply_prepared_lora_state_to_pipeline()
|
| 544 |
+
video, audio = pipeline(prompt=prompt, seed=current_seed, height=int(height), width=int(width), num_frames=num_frames, frame_rate=frame_rate, images=images, audio_path=input_audio, tiling_config=tiling_config, enhance_prompt=enhance_prompt)
|
| 545 |
+
output_path = tempfile.mktemp(suffix=".mp4")
|
| 546 |
+
encode_video(video=video, fps=frame_rate, audio=audio, output_path=output_path, video_chunks_number=video_chunks_number)
|
| 547 |
+
return str(output_path), current_seed
|
| 548 |
+
except Exception as e:
|
| 549 |
+
return None, current_seed
|
| 550 |
+
|
| 551 |
+
with gr.Blocks(title="LTX-2.3 Distilled") as demo:
|
| 552 |
+
gr.Markdown("# LTX-2.3 F2LF with Fast Audio-Video Generation with Frame Conditioning")
|
| 553 |
+
with gr.Row():
|
| 554 |
+
with gr.Column():
|
| 555 |
+
with gr.Row():
|
| 556 |
+
first_image = gr.Image(label="First Frame (Optional)", type="pil")
|
| 557 |
+
last_image = gr.Image(label="Last Frame (Optional)", type="pil")
|
| 558 |
+
input_audio = gr.Audio(label="Audio Input (Optional)", type="filepath")
|
| 559 |
+
prompt = gr.Textbox(label="Prompt", value="Make this image come alive with cinematic motion, smooth animation", lines=3)
|
| 560 |
+
duration = gr.Slider(label="Duration (seconds)", minimum=1.0, maximum=30.0, value=10.0, step=0.1)
|
| 561 |
+
generate_btn = gr.Button("Generate Video", variant="primary", size="lg")
|
| 562 |
+
with gr.Accordion("Advanced Settings", open=False):
|
| 563 |
+
seed = gr.Slider(label="Seed", minimum=0, maximum=MAX_SEED, value=10, step=1)
|
| 564 |
+
randomize_seed = gr.Checkbox(label="Randomize Seed", value=True)
|
| 565 |
+
with gr.Row():
|
| 566 |
+
width = gr.Number(label="Width", value=1536, precision=0)
|
| 567 |
+
height = gr.Number(label="Height", value=1024, precision=0)
|
| 568 |
+
with gr.Row():
|
| 569 |
+
enhance_prompt = gr.Checkbox(label="Enhance Prompt", value=False)
|
| 570 |
+
high_res = gr.Checkbox(label="High Resolution", value=True)
|
| 571 |
+
with gr.Column():
|
| 572 |
+
gr.Markdown("### LoRA adapter strengths")
|
| 573 |
+
singularity_strength = gr.Slider(label="Distilled Lora strength", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
|
| 574 |
+
teneros_strength = gr.Slider(label="Multipurpose furry strength", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
|
| 575 |
+
sulphur_strength = gr.Slider(label="Floaty/Slow Motion Reducer strength", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
|
| 576 |
+
pose_strength = gr.Slider(label="Anthro Enhancer strength", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
|
| 577 |
+
general_strength = gr.Slider(label="Reasoning Enhancer strength", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
|
| 578 |
+
motion_strength = gr.Slider(label="Anthro Posing Helper strength", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
|
| 579 |
+
dreamlay_strength = gr.Slider(label="Dreamlay strength", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
|
| 580 |
+
mself_strength = gr.Slider(label="2D enhancer strength", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
|
| 581 |
+
dramatic_strength = gr.Slider(label="Transition enhancer strength", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
|
| 582 |
+
fluid_strength = gr.Slider(label="Fluid Helper strength", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
|
| 583 |
+
liquid_strength = gr.Slider(label="Liquid Helper strength", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
|
| 584 |
+
demopose_strength = gr.Slider(label="Audio Helper strength", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
|
| 585 |
+
voice_strength = gr.Slider(label="Voice Helper strength", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
|
| 586 |
+
realism_strength = gr.Slider(label="Anthro Realism strength", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
|
| 587 |
+
transition_strength = gr.Slider(label="POV strength", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
|
| 588 |
+
physics_strength = gr.Slider(label="Physics strength", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
|
| 589 |
+
reasoning_strength = gr.Slider(label="Official Reasoning strength", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
|
| 590 |
+
twostep_strength = gr.Slider(label="Two Step Reasoning strength", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
|
| 591 |
+
mcfurry_strength = gr.Slider(label="I2V Motion enhancer strength", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
|
| 592 |
+
dm_strength = gr.Slider(label="DM3D strength", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
|
| 593 |
+
praxis_strength = gr.Slider(label="Praxis strength", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
|
| 594 |
+
threed_strength = gr.Slider(label="3D animation strength", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
|
| 595 |
+
concept_strength = gr.Slider(label="Conceptual strength", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
|
| 596 |
+
bulge_strength = gr.Slider(label="Bulge strength", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
|
| 597 |
+
prepare_lora_btn = gr.Button("Prepare / Load LoRA Cache", variant="secondary")
|
| 598 |
+
lora_status = gr.Textbox(label="LoRA Cache Status", value="No LoRA state prepared yet.", interactive=False)
|
| 599 |
+
with gr.Column():
|
| 600 |
+
output_video = gr.Video(label="Generated Video", autoplay=False)
|
| 601 |
+
gpu_duration = gr.Slider(label="ZeroGPU duration (seconds)", minimum=30.0, maximum=240.0, value=75.0, step=1.0)
|
| 602 |
+
|
| 603 |
+
first_image.change(fn=on_image_upload, inputs=[first_image, last_image, high_res], outputs=[width, height])
|
| 604 |
+
last_image.change(fn=on_image_upload, inputs=[first_image, last_image, high_res], outputs=[width, height])
|
| 605 |
+
high_res.change(fn=on_highres_toggle, inputs=[first_image, last_image, high_res], outputs=[width, height])
|
| 606 |
+
prepare_lora_btn.click(fn=prepare_lora_cache, inputs=[singularity_strength, teneros_strength, sulphur_strength, 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, mcfurry_strength, dm_strength, praxis_strength, threed_strength, concept_strength, bulge_strength], outputs=[lora_status])
|
| 607 |
+
generate_btn.click(fn=generate_video, inputs=[first_image, last_image, input_audio, prompt, duration, gpu_duration, enhance_prompt, seed, randomize_seed, height, width, singularity_strength, teneros_strength, sulphur_strength, 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, mcfurry_strength, dm_strength, praxis_strength, threed_strength, concept_strength, bulge_strength], outputs=[output_video, seed])
|
| 608 |
+
|
| 609 |
+
if __name__ == "__main__":
|
| 610 |
+
demo.launch(theme=gr.themes.Citrus(), css=".fillable{max-width: 1200px !important}")
|