Spaces:
Running on Zero
Running on Zero
Delete app.py
Browse files
app.py
DELETED
|
@@ -1,365 +0,0 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import subprocess
|
| 3 |
-
import sys
|
| 4 |
-
import json
|
| 5 |
-
import struct
|
| 6 |
-
import logging
|
| 7 |
-
import random
|
| 8 |
-
import tempfile
|
| 9 |
-
import hashlib
|
| 10 |
-
import shutil
|
| 11 |
-
import gc
|
| 12 |
-
from pathlib import Path
|
| 13 |
-
|
| 14 |
-
# Disable torch.compile / dynamo before any torch import
|
| 15 |
-
os.environ["TORCH_COMPILE_DISABLE"] = "1"
|
| 16 |
-
os.environ["TORCHDYNAMO_DISABLE"] = "1"
|
| 17 |
-
|
| 18 |
-
# Clone LTX-2 repo and install packages
|
| 19 |
-
LTX_REPO_URL = "https://github.com/Lightricks/LTX-2.git"
|
| 20 |
-
LTX_REPO_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "LTX-2")
|
| 21 |
-
LTX_COMMIT = "ae855f8538843825f9015a419cf4ba5edaf5eec2"
|
| 22 |
-
|
| 23 |
-
if not os.path.exists(LTX_REPO_DIR):
|
| 24 |
-
subprocess.run(["git", "clone", LTX_REPO_URL, LTX_REPO_DIR], check=True)
|
| 25 |
-
subprocess.run(["git", "checkout", LTX_COMMIT], cwd=LTX_REPO_DIR, check=True)
|
| 26 |
-
|
| 27 |
-
subprocess.run(
|
| 28 |
-
[sys.executable, "-m", "pip", "install", "--force-reinstall", "--no-deps", "-e",
|
| 29 |
-
os.path.join(LTX_REPO_DIR, "packages", "ltx-core"),
|
| 30 |
-
"-e", os.path.join(LTX_REPO_DIR, "packages", "ltx-pipelines")],
|
| 31 |
-
check=True,
|
| 32 |
-
)
|
| 33 |
-
|
| 34 |
-
sys.path.insert(0, os.path.join(LTX_REPO_DIR, "packages", "ltx-pipelines", "src"))
|
| 35 |
-
sys.path.insert(0, os.path.join(LTX_REPO_DIR, "packages", "ltx-core", "src"))
|
| 36 |
-
|
| 37 |
-
import spaces
|
| 38 |
-
import torch
|
| 39 |
-
import gradio as gr
|
| 40 |
-
import numpy as np
|
| 41 |
-
from huggingface_hub import hf_hub_download, snapshot_download
|
| 42 |
-
from ltx_core.loader.primitives import StateDict, LoraPathStrengthAndSDOps
|
| 43 |
-
from ltx_core.loader.sft_loader import SafetensorsStateDictLoader
|
| 44 |
-
from ltx_core.loader.sd_ops import LTXV_LORA_COMFY_RENAMING_MAP
|
| 45 |
-
from ltx_core.components.diffusion_steps import EulerDiffusionStep
|
| 46 |
-
from ltx_core.components.noisers import GaussianNoiser
|
| 47 |
-
from ltx_core.model.audio_vae import encode_audio as vae_encode_audio
|
| 48 |
-
from ltx_core.model.upsampler import upsample_video
|
| 49 |
-
from ltx_core.model.video_vae import TilingConfig, get_video_chunks_number, decode_video as vae_decode_video
|
| 50 |
-
from ltx_core.quantization import QuantizationPolicy
|
| 51 |
-
from ltx_core.types import Audio, AudioLatentShape, VideoPixelShape
|
| 52 |
-
from ltx_pipelines.distilled import DistilledPipeline
|
| 53 |
-
from ltx_pipelines.utils import euler_denoising_loop
|
| 54 |
-
from ltx_pipelines.utils.args import ImageConditioningInput
|
| 55 |
-
from ltx_pipelines.utils.constants import DISTILLED_SIGMA_VALUES, STAGE_2_DISTILLED_SIGMA_VALUES
|
| 56 |
-
from ltx_pipelines.utils.helpers import (
|
| 57 |
-
cleanup_memory, combined_image_conditionings, denoise_video_only,
|
| 58 |
-
encode_prompts, simple_denoising_func,
|
| 59 |
-
)
|
| 60 |
-
from ltx_pipelines.utils.media_io import decode_audio_from_file, encode_video
|
| 61 |
-
|
| 62 |
-
# --- ZERO-GPU PATCHES ---
|
| 63 |
-
_SAFETENSORS_DTYPE_MAP = {
|
| 64 |
-
"F64": torch.float64, "F32": torch.float32, "F16": torch.float16, "BF16": torch.bfloat16,
|
| 65 |
-
"F8_E5M2": torch.float8_e5m2, "F8_E4M3": torch.float8_e4m3fn, "I64": torch.int64,
|
| 66 |
-
"I32": torch.int32, "I16": torch.int16, "I8": torch.int8, "U8": torch.uint8, "BOOL": torch.bool,
|
| 67 |
-
}
|
| 68 |
-
|
| 69 |
-
def _patched_load(self, path, sd_ops, device=None):
|
| 70 |
-
sd = {}
|
| 71 |
-
size, dtype = 0, set()
|
| 72 |
-
device = torch.device("cpu")
|
| 73 |
-
model_paths = path if isinstance(path, list) else [path]
|
| 74 |
-
for shard_path in model_paths:
|
| 75 |
-
with open(shard_path, "rb") as f:
|
| 76 |
-
header_len = struct.unpack("<Q", f.read(8))[0]
|
| 77 |
-
header = json.loads(f.read(header_len).decode("utf-8"))
|
| 78 |
-
data_base = 8 + header_len
|
| 79 |
-
for name, meta in header.items():
|
| 80 |
-
if name == "__metadata__": continue
|
| 81 |
-
expected_name = name if sd_ops is None else sd_ops.apply_to_key(name)
|
| 82 |
-
if expected_name is None: continue
|
| 83 |
-
start, end = meta["data_offsets"]
|
| 84 |
-
f.seek(data_base + start)
|
| 85 |
-
buf = f.read(end - start)
|
| 86 |
-
t = torch.frombuffer(bytearray(buf), dtype=_SAFETENSORS_DTYPE_MAP[meta["dtype"]]).reshape(meta["shape"])
|
| 87 |
-
t = t.to(device=device, non_blocking=True, copy=False)
|
| 88 |
-
kvs = ((expected_name, t),) if sd_ops is None else sd_ops.apply_to_key_value(expected_name, t)
|
| 89 |
-
for key, v in kvs:
|
| 90 |
-
size += v.nbytes
|
| 91 |
-
dtype.add(v.dtype)
|
| 92 |
-
sd[key] = v
|
| 93 |
-
return StateDict(sd=sd, device=device, size=size, dtype=dtype)
|
| 94 |
-
|
| 95 |
-
SafetensorsStateDictLoader.load = _patched_load
|
| 96 |
-
|
| 97 |
-
_original_tensor_to = torch.Tensor.to
|
| 98 |
-
def _spaces_safe_to(self, *args, **kwargs):
|
| 99 |
-
def _is_cuda_target(x):
|
| 100 |
-
return x == "cuda" or (isinstance(x, torch.device) and x.type == "cuda") or (isinstance(x, str) and x.startswith("cuda"))
|
| 101 |
-
if args and _is_cuda_target(args[0]):
|
| 102 |
-
return _original_tensor_to(self, "cuda", *args[1:], **{k: v for k, v in kwargs.items() if k not in ("non_blocking", "copy")})
|
| 103 |
-
if kwargs.get("device") is not None and _is_cuda_target(kwargs["device"]):
|
| 104 |
-
return _original_tensor_to(self, *args, **{k: v for k, v in kwargs.items() if k not in ("non_blocking", "copy")})
|
| 105 |
-
return _original_tensor_to(self, *args, **kwargs)
|
| 106 |
-
|
| 107 |
-
torch.Tensor.to = _spaces_safe_to
|
| 108 |
-
|
| 109 |
-
class LTX23DistilledA2VPipeline(DistilledPipeline):
|
| 110 |
-
def __call__(self, prompt, seed, height, width, num_frames, frame_rate, images, audio_path=None, tiling_config=None, enhance_prompt=False):
|
| 111 |
-
if audio_path is None:
|
| 112 |
-
return super().__call__(prompt=prompt, seed=seed, height=height, width=width, num_frames=num_frames, frame_rate=frame_rate, images=images, tiling_config=tiling_config, enhance_prompt=enhance_prompt)
|
| 113 |
-
generator = torch.Generator(device=self.device).manual_seed(seed)
|
| 114 |
-
noiser = GaussianNoiser(generator=generator)
|
| 115 |
-
stepper = EulerDiffusionStep()
|
| 116 |
-
dtype = torch.bfloat16
|
| 117 |
-
(ctx_p,) = encode_prompts([prompt], self.model_ledger, enhance_first_prompt=enhance_prompt, enhance_prompt_image=images[0].path if len(images) > 0 else None)
|
| 118 |
-
video_context, audio_context = ctx_p.video_encoding, ctx_p.audio_encoding
|
| 119 |
-
video_duration = num_frames / frame_rate
|
| 120 |
-
decoded_audio = decode_audio_from_file(audio_path, self.device, 0.0, video_duration)
|
| 121 |
-
if decoded_audio is None: raise ValueError("Audio extraction failed")
|
| 122 |
-
encoded_audio_latent = vae_encode_audio(decoded_audio, self.model_ledger.audio_encoder())
|
| 123 |
-
audio_shape = AudioLatentShape.from_duration(batch=1, duration=video_duration, channels=8, mel_bins=16)
|
| 124 |
-
expected_frames = audio_shape.frames
|
| 125 |
-
actual_frames = encoded_audio_latent.shape[2]
|
| 126 |
-
if actual_frames > expected_frames: encoded_audio_latent = encoded_audio_latent[:, :, :expected_frames, :]
|
| 127 |
-
elif actual_frames < expected_frames:
|
| 128 |
-
pad = torch.zeros(encoded_audio_latent.shape[0], encoded_audio_latent.shape[1], expected_frames - actual_frames, encoded_audio_latent.shape[3], device=encoded_audio_latent.device, dtype=encoded_audio_latent.dtype)
|
| 129 |
-
encoded_audio_latent = torch.cat([encoded_audio_latent, pad], dim=2)
|
| 130 |
-
video_encoder = self.model_ledger.video_encoder()
|
| 131 |
-
transformer = self.model_ledger.transformer()
|
| 132 |
-
stage_1_sigmas = torch.tensor(DISTILLED_SIGMA_VALUES, device=self.device)
|
| 133 |
-
def denoising_loop(sigmas, video_state, audio_state, stepper):
|
| 134 |
-
return euler_denoising_loop(sigmas=sigmas, video_state=video_state, audio_state=audio_state, stepper=stepper, denoise_fn=simple_denoising_func(video_context=video_context, audio_context=audio_context, transformer=transformer))
|
| 135 |
-
stage_1_output_shape = VideoPixelShape(batch=1, frames=num_frames, width=width // 2, height=height // 2, fps=frame_rate)
|
| 136 |
-
stage_1_conditionings = combined_image_conditionings(images=images, height=stage_1_output_shape.height, width=stage_1_output_shape.width, video_encoder=video_encoder, dtype=dtype, device=self.device)
|
| 137 |
-
video_state = denoise_video_only(output_shape=stage_1_output_shape, conditionings=stage_1_conditionings, noiser=noiser, sigmas=stage_1_sigmas, stepper=stepper, denoising_loop_fn=denoising_loop, components=self.pipeline_components, dtype=dtype, device=self.device, initial_audio_latent=encoded_audio_latent)
|
| 138 |
-
torch.cuda.synchronize()
|
| 139 |
-
cleanup_memory()
|
| 140 |
-
upscaled_video_latent = upsample_video(latent=video_state.latent[:1], video_encoder=video_encoder, upsampler=self.model_ledger.spatial_upsampler())
|
| 141 |
-
stage_2_sigmas = torch.tensor(STAGE_2_DISTILLED_SIGMA_VALUES, device=self.device)
|
| 142 |
-
stage_2_output_shape = VideoPixelShape(batch=1, frames=num_frames, width=width, height=height, fps=frame_rate)
|
| 143 |
-
stage_2_conditionings = combined_image_conditionings(images=images, height=stage_2_output_shape.height, width=stage_2_output_shape.width, video_encoder=video_encoder, dtype=dtype, device=self.device)
|
| 144 |
-
video_state = denoise_video_only(output_shape=stage_2_output_shape, conditionings=stage_2_conditionings, noiser=noiser, sigmas=stage_2_sigmas, stepper=stepper, denoising_loop_fn=denoising_loop, components=self.pipeline_components, dtype=dtype, device=self.device, noise_scale=stage_2_sigmas[0], initial_video_latent=upscaled_video_latent, initial_audio_latent=encoded_audio_latent)
|
| 145 |
-
torch.cuda.synchronize()
|
| 146 |
-
del transformer, video_encoder
|
| 147 |
-
cleanup_memory()
|
| 148 |
-
decoded_video = vae_decode_video(video_state.latent, self.model_ledger.video_decoder(), tiling_config, generator)
|
| 149 |
-
original_audio = Audio(waveform=decoded_audio.waveform.squeeze(0), sampling_rate=decoded_audio.sampling_rate)
|
| 150 |
-
return decoded_video, original_audio
|
| 151 |
-
|
| 152 |
-
# --- MODEL LOADING ---
|
| 153 |
-
LTX_MODEL_REPO = "Lightricks/LTX-2.3"
|
| 154 |
-
GEMMA_REPO ="Lightricks/gemma-3-12b-it-qat-q4_0-unquantized"
|
| 155 |
-
weights_dir = Path("weights")
|
| 156 |
-
weights_dir.mkdir(exist_ok=True)
|
| 157 |
-
checkpoint_path = hf_hub_download(repo_id="ibyteohdear/Lightricks-LTX-2.3-DISTILLED-10-Eros", filename="LTX2.3_DISTILLED_BAKED_LTX_SULPHUR_STYLE_IS_10Eros_v14_r768.safetensors", local_dir=str(weights_dir))
|
| 158 |
-
spatial_upsampler_path = hf_hub_download(repo_id=LTX_MODEL_REPO, filename="ltx-2.3-spatial-upscaler-x2-1.1.safetensors")
|
| 159 |
-
gemma_root = snapshot_download(repo_id=GEMMA_REPO)
|
| 160 |
-
|
| 161 |
-
LORA_REPO = "dagloop5/LoRA"
|
| 162 |
-
LORA_FILES = {
|
| 163 |
-
"singularity": ("TenStrip/LTX2.3_DMD_Lora", "LTX2.3_DMD_reshaped_r256.safetensors"),
|
| 164 |
-
"teneros": (LORA_REPO, "LTX2.3-Furry-2D-NSFW-Multi-Purpose-Lora+Cum.safetensors"),
|
| 165 |
-
"sulphur": (LORA_REPO, "ltx23E28093SlowMotion26.Pkrs.safetensors"),
|
| 166 |
-
"pose": (LORA_REPO, "LTX2_3_NSFW_furry_concat_v2.safetensors"),
|
| 167 |
-
"general": (LORA_REPO, "LTX2.3_reasoning_Sulphur-2_I2V_V4.safetensors"),
|
| 168 |
-
"motion": (LORA_REPO, "Sulphur_LTX 2.3_better _NSFW_motion.safetensors"),
|
| 169 |
-
"dreamlay": ("lynaNSFW/DR34ML4Y_AIO_NSFW_LTX23", "DR34ML4Y_LTXXX_V2.safetensors"),
|
| 170 |
-
"mself": (LORA_REPO, "LTX2.3_2d_NSFW_motion_enhancer.safetensors"),
|
| 171 |
-
"dramatic": ("Muapi/valiantcat-ltx-2.3-transition-lora", "valiantcat-ltx-2.3-transition-lora.safetensors"),
|
| 172 |
-
"fluid": (LORA_REPO, "Cr3ampi3_animation_sulphur-2_i2v_v1.0.safetensors"),
|
| 173 |
-
"liquid": (LORA_REPO, "liquid_wet_dr1pp_ltx2_v1.0_scaled.safetensors"),
|
| 174 |
-
"demopose": (LORA_REPO, "clapping-cheeks-audio-v001-alpha.safetensors"),
|
| 175 |
-
"voice": (LORA_REPO, "hentai_voice_ltx23_v2.comfy.safetensors"),
|
| 176 |
-
"realism": (LORA_REPO, "FurryenhancerLTX2.3V4.094fused.safetensors"),
|
| 177 |
-
"transition": (LORA_REPO, "LTX-2_takerpov_lora_v1.2.safetensors"),
|
| 178 |
-
"physics": (LORA_REPO, "LTX2.3_Physics_V2_000002000.safetensors"),
|
| 179 |
-
"reasoning": ("LiconStudio/Ltx2.3-VBVR-lora-I2V", "Ltx2.3-Licon-VBVR-I2V-390K-R32.safetensors"),
|
| 180 |
-
"twostep": (LORA_REPO, "LTX2.3_Multi_step_video_reasoning_V0.1.safetensors"),
|
| 181 |
-
"mcfurry": (LORA_REPO, "mvmt_lora_v2_600.safetensors"),
|
| 182 |
-
"dm": (LORA_REPO, "Doggy_mission_sulphur-2_v0.5.safetensors"),
|
| 183 |
-
"praxis": (LORA_REPO, "Penile_Praxis_V4.safetensors"),
|
| 184 |
-
"threed": (LORA_REPO, "ltx2-3d-animations-12500-steps-k3nk.safetensors"),
|
| 185 |
-
"concept": (LORA_REPO, "ltx23_nsfw_helper_multi_concept_lora_v2.safetensors"),
|
| 186 |
-
"bulge": (LORA_REPO, "stomach_bulge_10eros_sulphur_v1.safetensors"),
|
| 187 |
-
}
|
| 188 |
-
LORA_PATHS = {k: hf_hub_download(repo_id=v[0], filename=v[1]) for k, v in LORA_FILES.items()}
|
| 189 |
-
|
| 190 |
-
pipeline = LTX23DistilledA2VPipeline(
|
| 191 |
-
distilled_checkpoint_path=checkpoint_path,
|
| 192 |
-
spatial_upsampler_path=spatial_upsampler_path,
|
| 193 |
-
gemma_root=gemma_root,
|
| 194 |
-
loras=[],
|
| 195 |
-
quantization=QuantizationPolicy.fp8_cast(),
|
| 196 |
-
)
|
| 197 |
-
|
| 198 |
-
ledger = pipeline.model_ledger
|
| 199 |
-
_transformer = ledger.transformer()
|
| 200 |
-
_video_encoder = ledger.video_encoder()
|
| 201 |
-
_video_decoder = ledger.video_decoder()
|
| 202 |
-
_audio_encoder = ledger.audio_encoder()
|
| 203 |
-
_audio_decoder = ledger.audio_decoder()
|
| 204 |
-
_vocoder = ledger.vocoder()
|
| 205 |
-
_spatial_upsampler = ledger.spatial_upsampler()
|
| 206 |
-
_text_encoder = ledger.text_encoder()
|
| 207 |
-
_embeddings_processor = ledger.gemma_embeddings_processor()
|
| 208 |
-
|
| 209 |
-
ledger.transformer = lambda: _transformer
|
| 210 |
-
ledger.video_encoder = lambda: _video_encoder
|
| 211 |
-
ledger.video_decoder = lambda: _video_decoder
|
| 212 |
-
ledger.audio_encoder = lambda: _audio_encoder
|
| 213 |
-
ledger.audio_decoder = lambda: _audio_decoder
|
| 214 |
-
ledger.vocoder = lambda: _vocoder
|
| 215 |
-
ledger.spatial_upsampler = lambda: _spatial_upsampler
|
| 216 |
-
ledger.text_encoder = lambda: _text_encoder
|
| 217 |
-
ledger.gemma_embeddings_processor = lambda: _embeddings_processor
|
| 218 |
-
|
| 219 |
-
# --- IMPROVED CPU LORA PREPARATION ---
|
| 220 |
-
current_lora_key = None
|
| 221 |
-
PENDING_LORA_STATE = None
|
| 222 |
-
|
| 223 |
-
def prepare_lora_cache(
|
| 224 |
-
*strengths,
|
| 225 |
-
progress=gr.Progress(track_tqdm=True),
|
| 226 |
-
):
|
| 227 |
-
global current_lora_key, PENDING_LORA_STATE
|
| 228 |
-
|
| 229 |
-
# Build key based on strength values
|
| 230 |
-
strength_vals = [round(float(x), 2) for x in strengths]
|
| 231 |
-
key_str = "|".join(map(str, strength_vals))
|
| 232 |
-
key = hashlib.sha256(key_str.encode()).hexdigest()
|
| 233 |
-
|
| 234 |
-
if current_lora_key == key:
|
| 235 |
-
return "LoRA state already cached."
|
| 236 |
-
|
| 237 |
-
progress(0.1, desc="Filtering active LoRAs")
|
| 238 |
-
active_entries = []
|
| 239 |
-
for (name, path), strength in zip(LORA_PATHS.items(), strengths):
|
| 240 |
-
if float(strength) != 0.0:
|
| 241 |
-
active_entries.append(LoraPathStrengthAndSDOps(path, float(strength), LTXV_LORA_COMFY_RENAMING_MAP))
|
| 242 |
-
|
| 243 |
-
if not active_entries:
|
| 244 |
-
PENDING_LORA_STATE = None
|
| 245 |
-
current_lora_key = key
|
| 246 |
-
return "No LoRAs selected."
|
| 247 |
-
|
| 248 |
-
try:
|
| 249 |
-
progress(0.3, desc="Applying LoRAs to base weights (CPU)")
|
| 250 |
-
# CRITICAL: We apply to the existing _transformer on CPU instead of creating a new ledger/model
|
| 251 |
-
# We save the original state to restore it later
|
| 252 |
-
original_state = {k: v.clone() for k, v in _transformer.state_dict().items() if "lora" not in k}
|
| 253 |
-
|
| 254 |
-
_transformer.load_loras(active_entries)
|
| 255 |
-
|
| 256 |
-
progress(0.7, desc="Extracting fused state")
|
| 257 |
-
# Only store the delta or the fused state to avoid keeping the whole model in memory twice
|
| 258 |
-
PENDING_LORA_STATE = {k: v.detach().cpu().contiguous() for k, v in _transformer.state_dict().items()}
|
| 259 |
-
|
| 260 |
-
# Restore base weights so the pipeline remains "clean" for the next prepare call
|
| 261 |
-
_transformer.load_state_dict(original_state, strict=False)
|
| 262 |
-
|
| 263 |
-
current_lora_key = key
|
| 264 |
-
return "Built LoRA state successfully."
|
| 265 |
-
except Exception as e:
|
| 266 |
-
return f"Error: {e}"
|
| 267 |
-
finally:
|
| 268 |
-
gc.collect()
|
| 269 |
-
|
| 270 |
-
def apply_lora_state():
|
| 271 |
-
global PENDING_LORA_STATE
|
| 272 |
-
if PENDING_LORA_STATE is None: return
|
| 273 |
-
with torch.no_grad():
|
| 274 |
-
_transformer.load_state_dict(PENDING_LORA_STATE, strict=False)
|
| 275 |
-
|
| 276 |
-
def get_gpu_duration(*args, gpu_duration=75.0, **kwargs):
|
| 277 |
-
return int(gpu_duration)
|
| 278 |
-
|
| 279 |
-
@spaces.GPU(size="xlarge", duration=get_gpu_duration)
|
| 280 |
-
@torch.inference_mode()
|
| 281 |
-
def generate_video(first_image, last_image, input_audio, prompt, duration, gpu_duration, enhance_prompt, seed, randomize_seed, height, width, *strengths, progress=gr.Progress(track_tqdm=True)):
|
| 282 |
-
try:
|
| 283 |
-
apply_lora_state()
|
| 284 |
-
|
| 285 |
-
current_seed = random.randint(0, np.iinfo(np.int32).max) if randomize_seed else int(seed)
|
| 286 |
-
frame_rate = 24.0
|
| 287 |
-
num_frames = int(duration * frame_rate) + 1
|
| 288 |
-
num_frames = ((num_frames - 1 + 7) // 8) * 8 + 1
|
| 289 |
-
images = []
|
| 290 |
-
output_dir = Path("outputs")
|
| 291 |
-
output_dir.mkdir(exist_ok=True)
|
| 292 |
-
if first_image is not None:
|
| 293 |
-
temp_first_path = output_dir / f"temp_first_{current_seed}.jpg"
|
| 294 |
-
if hasattr(first_image, "save"): first_image.save(temp_first_path)
|
| 295 |
-
else: temp_first_path = Path(first_image)
|
| 296 |
-
images.append(ImageConditioningInput(path=str(temp_first_path), frame_idx=0, strength=1.0))
|
| 297 |
-
if last_image is not None:
|
| 298 |
-
temp_last_path = output_dir / f"temp_last_{current_seed}.jpg"
|
| 299 |
-
if hasattr(last_image, "save"): last_image.save(temp_last_path)
|
| 300 |
-
else: temp_last_path = Path(last_image)
|
| 301 |
-
images.append(ImageConditioningInput(path=str(temp_last_path), frame_idx=num_frames - 1, strength=1.0))
|
| 302 |
-
|
| 303 |
-
tiling_config = TilingConfig.default()
|
| 304 |
-
video_chunks_number = get_video_chunks_number(num_frames, tiling_config)
|
| 305 |
-
|
| 306 |
-
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)
|
| 307 |
-
|
| 308 |
-
output_path = tempfile.mktemp(suffix=".mp4")
|
| 309 |
-
encode_video(video=video, fps=frame_rate, audio=audio, output_path=output_path, video_chunks_number=video_chunks_number)
|
| 310 |
-
|
| 311 |
-
return str(output_path), current_seed
|
| 312 |
-
except Exception as e:
|
| 313 |
-
return None, current_seed
|
| 314 |
-
|
| 315 |
-
RESOLUTIONS = {
|
| 316 |
-
"low": {"16:9": (768, 512), "9:16": (512, 768), "1:1": (768, 768), "4:3": (768, 576), "3:4": (576, 768), "21:9": (768, 384)},
|
| 317 |
-
"high": {"16:9": (1536, 1024), "9:16": (1024, 1536), "1:1": (1024, 1024), "4:3": (1536, 1152), "3:4": (1152, 1536), "21:9": (1536, 768)},
|
| 318 |
-
}
|
| 319 |
-
|
| 320 |
-
def update_res(first, last, high_res):
|
| 321 |
-
ref = first if first is not None else last
|
| 322 |
-
if ref is None: return gr.update(value=1536), gr.update(value=1024)
|
| 323 |
-
w, h = (ref.size if hasattr(ref, "size") else ref.shape[:2][::-1])
|
| 324 |
-
ratio = w / h
|
| 325 |
-
aspect = min({"16:9": 16/9, "9:16": 9/16, "1:1": 1.0}, key=lambda k: abs(ratio - (16/9 if k=="16:9" else 9/16 if k=="9:16" else 1.0)))
|
| 326 |
-
tier = "high" if high_res else "low"
|
| 327 |
-
res = RESOLUTIONS[tier][aspect]
|
| 328 |
-
return gr.update(value=res[0]), gr.update(value=res[1])
|
| 329 |
-
|
| 330 |
-
with gr.Blocks(title="LTX-2.3 CPU Optimized") as demo:
|
| 331 |
-
gr.Markdown("# LTX-2.3 CPU-Optimized LoRA")
|
| 332 |
-
with gr.Row():
|
| 333 |
-
with gr.Column():
|
| 334 |
-
with gr.Row():
|
| 335 |
-
first_image = gr.Image(label="First Frame", type="pil")
|
| 336 |
-
last_image = gr.Image(label="Last Frame", type="pil")
|
| 337 |
-
input_audio = gr.Audio(label="Audio Input", type="filepath")
|
| 338 |
-
prompt = gr.Textbox(label="Prompt", value="Make this image come alive", lines=3)
|
| 339 |
-
duration = gr.Slider(label="Duration (s)", minimum=1.0, maximum=30.0, value=10.0, step=0.1)
|
| 340 |
-
generate_btn = gr.Button("Generate Video", variant="primary", size="lg")
|
| 341 |
-
with gr.Accordion("Advanced Settings", open=False):
|
| 342 |
-
seed = gr.Slider(label="Seed", minimum=0, maximum=np.iinfo(np.int32).max, value=10, step=1)
|
| 343 |
-
randomize_seed = gr.Checkbox(label="Randomize Seed", value=True)
|
| 344 |
-
with gr.Row():
|
| 345 |
-
width = gr.Number(label="Width", value=1536, precision=0)
|
| 346 |
-
height = gr.Number(label="Height", value=1024, precision=0)
|
| 347 |
-
with gr.Row():
|
| 348 |
-
enhance_prompt = gr.Checkbox(label="Enhance Prompt", value=False)
|
| 349 |
-
high_res = gr.Checkbox(label="High Resolution", value=True)
|
| 350 |
-
gr.Markdown("### LoRA Adapter Strengths")
|
| 351 |
-
lora_sliders = [gr.Slider(label=f"{k} strength", minimum=0.0, maximum=2.0, value=0.0, step=0.01) for k in LORA_FILES.keys()]
|
| 352 |
-
prepare_btn = gr.Button("Prepare LoRA Cache", variant="secondary")
|
| 353 |
-
lora_status = gr.Textbox(label="Status", interactive=False)
|
| 354 |
-
with gr.Column():
|
| 355 |
-
output_video = gr.Video(label="Generated Video")
|
| 356 |
-
gpu_duration = gr.Slider(label="ZeroGPU Duration (s)", minimum=30.0, maximum=240.0, value=75.0, step=1.0)
|
| 357 |
-
|
| 358 |
-
first_image.change(fn=update_res, inputs=[first_image, last_image, high_res], outputs=[width, height])
|
| 359 |
-
last_image.change(fn=update_res, inputs=[first_image, last_image, high_res], outputs=[width, height])
|
| 360 |
-
high_res.change(fn=update_res, inputs=[first_image, last_image, high_res], outputs=[width, height])
|
| 361 |
-
prepare_btn.click(fn=prepare_lora_cache, inputs=lora_sliders, outputs=lora_status)
|
| 362 |
-
generate_btn.click(fn=generate_video, inputs=[first_image, last_image, input_audio, prompt, duration, gpu_duration, enhance_prompt, seed, randomize_seed, height, width] + lora_sliders, outputs=[output_video, seed])
|
| 363 |
-
|
| 364 |
-
if __name__ == "__main__":
|
| 365 |
-
demo.launch(theme=gr.themes.Citrus())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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