Upload app.py with huggingface_hub
Browse files
app.py
CHANGED
|
@@ -1,20 +1,26 @@
|
|
| 1 |
-
"""LTX-2.3 Cinemagraph
|
| 2 |
-
|
| 3 |
-
Turns a still image into a looping cinemagraph
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
precomputed [ctx_p, ctx_n]
|
| 11 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
"""
|
| 13 |
|
| 14 |
import os
|
| 15 |
import subprocess
|
| 16 |
import sys
|
| 17 |
|
|
|
|
| 18 |
os.environ["TORCH_COMPILE_DISABLE"] = "1"
|
| 19 |
os.environ["TORCHDYNAMO_DISABLE"] = "1"
|
| 20 |
|
|
@@ -54,17 +60,14 @@ torch._dynamo.config.disable = True
|
|
| 54 |
import gradio as gr
|
| 55 |
import numpy as np
|
| 56 |
import spaces
|
| 57 |
-
from gradio_client import Client
|
| 58 |
from huggingface_hub import hf_hub_download
|
| 59 |
-
from PIL import Image, ImageOps
|
| 60 |
|
| 61 |
-
import ltx_pipelines.
|
| 62 |
from ltx_core.components.guiders import MultiModalGuiderParams
|
| 63 |
-
from ltx_core.loader import
|
| 64 |
-
from ltx_core.model.video_vae import TilingConfig, get_video_chunks_number
|
| 65 |
-
from ltx_core.quantization import QuantizationPolicy
|
| 66 |
from ltx_core.text_encoders.gemma.embeddings_processor import EmbeddingsProcessorOutput
|
| 67 |
-
from ltx_pipelines.
|
| 68 |
from ltx_pipelines.utils.args import ImageConditioningInput
|
| 69 |
from ltx_pipelines.utils.media_io import encode_video
|
| 70 |
|
|
@@ -122,78 +125,65 @@ def _patched_load(self, path, sd_ops, device=None):
|
|
| 122 |
|
| 123 |
SafetensorsStateDictLoader.load = _patched_load
|
| 124 |
|
| 125 |
-
# ZeroGPU LoRA-into-fp8 fusion patch:
|
| 126 |
-
# fuse_loras._fuse_delta_with_cast_fp8 upcasts the fp8 base weight + adds the LoRA delta via a
|
| 127 |
-
# Triton CUDA kernel (calculate_weight_float8 -> fused_add_round_kernel). That kernel launches a
|
| 128 |
-
# *real* CUDA op, which cannot be ZeroGPU-virtualised at module scope and dies with
|
| 129 |
-
# "CUDA error: no CUDA-capable device is detected". Replace it with a pure-torch equivalent
|
| 130 |
-
# (upcast to bf16, add delta, re-cast to fp8) that goes through torch.Tensor ops ZeroGPU can
|
| 131 |
-
# virtualise. dev-api avoids this only because it fuses no user LoRA into the fp8 stage-1 base.
|
| 132 |
-
import ltx_core.loader.fuse_loras as _fuse_mod
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
def _fuse_delta_with_cast_fp8_torch(deltas, weight, key, target_dtype, device):
|
| 136 |
-
fused = (deltas.to(torch.bfloat16) + weight.to(torch.bfloat16)).to(dtype=target_dtype)
|
| 137 |
-
return {key: fused}
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
_fuse_mod._fuse_delta_with_cast_fp8 = _fuse_delta_with_cast_fp8_torch
|
| 141 |
-
print("[PATCH] fp8 LoRA fusion -> pure-torch (ZeroGPU-virtualisable, no Triton kernel)")
|
| 142 |
-
|
| 143 |
logging.getLogger().setLevel(logging.INFO)
|
| 144 |
MAX_SEED = np.iinfo(np.int32).max
|
| 145 |
FRAME_RATE = 24.0
|
| 146 |
|
|
|
|
| 147 |
TRIGGER = "CINEMAGRAPH_MOTION"
|
| 148 |
-
|
| 149 |
DEFAULT_NEGATIVE = (
|
| 150 |
"cars moving, camera movement, pan, tilt, zoom, parallax, whole image moving, "
|
| 151 |
"background sliding, person moving, flicker on entire image, noisy texture, "
|
| 152 |
"crawling texture, distorted, blurry, low quality"
|
| 153 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 154 |
|
| 155 |
-
#
|
| 156 |
-
|
| 157 |
-
AUDIO_CFG, AUDIO_STG, AUDIO_RESCALE,
|
| 158 |
|
| 159 |
LTX_REPO = os.environ.get("LTX_REPO", "Lightricks/LTX-2.3")
|
| 160 |
-
DEV_FILE = "ltx-2.3-22b-dev.safetensors"
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
CINEMAGRAPH_REPO = os.environ.get("CINEMAGRAPH_REPO", "Lightricks/LTX-2.3-22b-LoRA-Cinemagraph")
|
| 164 |
-
CINEMAGRAPH_FILE = "ltx-2.3-22b-lora-cinemagraph-0.9.safetensors"
|
| 165 |
-
DEFAULT_LORA_STRENGTH = 1.0
|
| 166 |
TOKEN = os.environ.get("HF_TOKEN")
|
| 167 |
TEXT_ENCODER_SPACE = os.environ.get("TEXT_ENCODER_SPACE", "linoyts/ltx23-gemma-encoder-api")
|
| 168 |
|
| 169 |
-
print("Downloading
|
| 170 |
checkpoint_path = hf_hub_download(LTX_REPO, DEV_FILE, token=TOKEN)
|
| 171 |
-
|
| 172 |
-
upsampler_path = hf_hub_download(LTX_REPO, UPSCALER_FILE, token=TOKEN)
|
| 173 |
-
cinemagraph_lora_path = hf_hub_download(CINEMAGRAPH_REPO, CINEMAGRAPH_FILE, token=TOKEN)
|
| 174 |
|
| 175 |
-
|
|
|
|
| 176 |
checkpoint_path=checkpoint_path,
|
| 177 |
-
distilled_lora=[LoraPathStrengthAndSDOps(path=distilled_lora_path, strength=1.0, sd_ops=None)],
|
| 178 |
-
spatial_upsampler_path=upsampler_path,
|
| 179 |
gemma_root=None, # text encoding happens on TEXT_ENCODER_SPACE
|
| 180 |
-
# Cinemagraph LoRA fused into stage 1 (ComfyUI-format keys -> comfy renaming map).
|
| 181 |
loras=[LoraPathStrengthAndSDOps(
|
| 182 |
-
path=
|
| 183 |
-
|
| 184 |
-
|
|
|
|
|
|
|
| 185 |
)
|
| 186 |
|
| 187 |
print("Preloading models (ZeroGPU tensor packing)…")
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
for name, model in _cached_s2.items():
|
| 195 |
-
setattr(s2, name, (lambda m: (lambda: m))(model))
|
| 196 |
-
print("Pipeline ready.")
|
| 197 |
|
| 198 |
|
| 199 |
# ---- remote text encoding (positive + negative, needed for CFG) ----
|
|
@@ -201,19 +191,16 @@ print("Pipeline ready.")
|
|
| 201 |
_emb_cache = {}
|
| 202 |
|
| 203 |
|
| 204 |
-
def fetch_embeddings(prompt, negative_prompt, seed):
|
| 205 |
-
"""Call the Gemma encoder Space; returns {'positive', 'negative', 'final_prompt'}.
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
'only X moves, everything else frozen' structure that prompt-enhancement can dilute.
|
| 209 |
-
"""
|
| 210 |
-
key = (prompt, negative_prompt)
|
| 211 |
if key in _emb_cache:
|
| 212 |
return _emb_cache[key]
|
| 213 |
-
client = Client(TEXT_ENCODER_SPACE, token=TOKEN
|
| 214 |
emb_file, final_prompt, status = client.predict(
|
| 215 |
prompt=prompt, negative_prompt=negative_prompt or "", encode_negative=True,
|
| 216 |
-
enhance_prompt=
|
| 217 |
)
|
| 218 |
print(f"[encoder] {status} | final prompt: {final_prompt[:80]}…")
|
| 219 |
data = torch.load(emb_file, map_location="cpu", weights_only=True)
|
|
@@ -231,30 +218,20 @@ def _to_output(pack, device):
|
|
| 231 |
)
|
| 232 |
|
| 233 |
|
| 234 |
-
def
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
tmp = tempfile.mktemp(suffix=".png")
|
| 239 |
-
im.save(tmp)
|
| 240 |
-
return tmp
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
def gpu_duration(embeddings, image_path, prompt, negative_prompt="", duration=3.0, *args, **kwargs):
|
| 244 |
-
return min(600, 150 + int(duration) * 40)
|
| 245 |
|
| 246 |
|
| 247 |
-
@spaces.GPU(duration=gpu_duration)
|
| 248 |
@torch.inference_mode()
|
| 249 |
-
def _generate_gpu(embeddings, image_path, prompt, negative_prompt,
|
| 250 |
-
num_inference_steps, video_cfg_scale,
|
|
|
|
| 251 |
progress=gr.Progress(track_tqdm=True)):
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
video_chunks_number = get_video_chunks_number(num_frames, tiling_config)
|
| 255 |
-
|
| 256 |
-
cond_img = _prep_image(image_path, int(width), int(height))
|
| 257 |
-
images = [ImageConditioningInput(path=cond_img, frame_idx=0, strength=1.0)]
|
| 258 |
|
| 259 |
precomputed = [_to_output(embeddings["positive"], "cuda"),
|
| 260 |
_to_output(embeddings["negative"], "cuda")]
|
|
@@ -267,153 +244,170 @@ def _generate_gpu(embeddings, image_path, prompt, negative_prompt, duration, use
|
|
| 267 |
seed=used_seed,
|
| 268 |
height=int(height),
|
| 269 |
width=int(width),
|
| 270 |
-
num_frames=num_frames,
|
| 271 |
frame_rate=FRAME_RATE,
|
| 272 |
num_inference_steps=int(num_inference_steps),
|
| 273 |
video_guider_params=MultiModalGuiderParams(
|
| 274 |
-
cfg_scale=video_cfg_scale, stg_scale=
|
| 275 |
-
|
|
|
|
| 276 |
audio_guider_params=MultiModalGuiderParams(
|
| 277 |
cfg_scale=AUDIO_CFG, stg_scale=AUDIO_STG, rescale_scale=AUDIO_RESCALE,
|
| 278 |
-
modality_scale=
|
| 279 |
images=images,
|
| 280 |
-
|
| 281 |
-
enhance_prompt=False, # already handled remotely; cinemagraph wants literal prompts
|
| 282 |
)
|
| 283 |
finally:
|
| 284 |
ti2vid_module.encode_prompts = original
|
| 285 |
|
| 286 |
output_path = tempfile.mktemp(suffix=".mp4")
|
| 287 |
-
encode_video(video=video, fps=FRAME_RATE, audio=audio,
|
| 288 |
-
|
| 289 |
return output_path
|
| 290 |
|
| 291 |
|
| 292 |
-
def
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 297 |
|
| 298 |
|
| 299 |
def generate(
|
| 300 |
-
|
| 301 |
prompt: str,
|
| 302 |
negative_prompt: str = DEFAULT_NEGATIVE,
|
| 303 |
-
|
| 304 |
seed: int = 42,
|
| 305 |
randomize_seed: bool = True,
|
| 306 |
-
num_inference_steps: int =
|
| 307 |
-
video_cfg_scale: float =
|
| 308 |
-
|
| 309 |
-
width: int =
|
| 310 |
-
height: int =
|
|
|
|
|
|
|
| 311 |
progress=gr.Progress(track_tqdm=True),
|
| 312 |
):
|
| 313 |
-
"""
|
| 314 |
|
| 315 |
Args:
|
| 316 |
-
|
| 317 |
-
prompt: what should move
|
| 318 |
-
|
| 319 |
-
negative_prompt: things to
|
| 320 |
-
|
| 321 |
seed: RNG seed.
|
| 322 |
-
randomize_seed: draw a fresh random seed
|
| 323 |
-
num_inference_steps:
|
| 324 |
-
video_cfg_scale: classifier-free guidance scale (
|
| 325 |
-
|
| 326 |
-
width: output width (multiple of
|
| 327 |
-
height: output height (multiple of
|
|
|
|
|
|
|
| 328 |
|
| 329 |
Returns:
|
| 330 |
-
(video_path, used_seed)
|
| 331 |
"""
|
| 332 |
-
if
|
| 333 |
-
raise gr.Error("Please
|
| 334 |
-
if not (prompt or "").strip():
|
| 335 |
-
raise gr.Error("Describe what should move (e.g. 'only the neon sign flickers').")
|
| 336 |
used_seed = random.randint(0, MAX_SEED) if randomize_seed else int(seed)
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
full_prompt = f"{TRIGGER}, {full_prompt}"
|
| 340 |
-
if "seamless natural loop" not in full_prompt.lower():
|
| 341 |
-
full_prompt = f"{full_prompt}, seamless natural loop"
|
| 342 |
progress(0.05, desc="encoding prompts (Gemma Space)…")
|
| 343 |
-
embeddings = fetch_embeddings(full_prompt, negative_prompt,
|
|
|
|
| 344 |
output_path = _generate_gpu(
|
| 345 |
-
embeddings,
|
| 346 |
-
num_inference_steps, video_cfg_scale,
|
|
|
|
|
|
|
| 347 |
return output_path, used_seed
|
| 348 |
|
| 349 |
|
| 350 |
CSS = """
|
| 351 |
-
#col-container { max-width:
|
| 352 |
.dark .gradio-container { color: var(--body-text-color); }
|
| 353 |
"""
|
| 354 |
|
| 355 |
-
EX_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "examples")
|
| 356 |
EXAMPLES = [
|
| 357 |
-
[
|
| 358 |
-
"
|
| 359 |
-
|
| 360 |
-
"
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 365 |
]
|
| 366 |
|
| 367 |
-
with gr.Blocks(
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
|
| 380 |
-
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
)
|
| 386 |
-
|
| 387 |
-
with gr.
|
| 388 |
-
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
|
| 404 |
-
|
| 405 |
-
|
| 406 |
-
|
| 407 |
-
|
| 408 |
-
|
| 409 |
-
|
| 410 |
-
|
| 411 |
-
|
| 412 |
-
|
| 413 |
-
|
| 414 |
-
|
| 415 |
-
|
| 416 |
-
)
|
| 417 |
|
| 418 |
if __name__ == "__main__":
|
| 419 |
-
demo.launch(mcp_server=True
|
|
|
|
| 1 |
+
"""LTX-2.3 Cinemagraph (image-to-video) demo.
|
| 2 |
+
|
| 3 |
+
Turns a still image into a looping cinemagraph with selective motion, using the
|
| 4 |
+
`Lightricks/LTX-2.3-22b-LoRA-Cinemagraph` LoRA on top of the full LTX-2.3-22B base
|
| 5 |
+
model. Implementation follows the `linoyts/ltx23-dev-api` pattern:
|
| 6 |
+
|
| 7 |
+
- Text encoding (positive + negative, needed for CFG) is offloaded to the Gemma
|
| 8 |
+
encoder Space (`TEXT_ENCODER_SPACE`, default `linoyts/ltx23-gemma-encoder-api`)
|
| 9 |
+
via gradio_client, so Gemma is never held in-Space. `encode_prompts` is
|
| 10 |
+
monkeypatched with the precomputed [ctx_p, ctx_n].
|
| 11 |
+
- Unlike the dev-api hero backend, this build uses the **single-stage** full-model
|
| 12 |
+
pipeline (`TI2VidOneStagePipeline`) which matches the cinemagraph LoRA's
|
| 13 |
+
recommended CFG/STG single-pass workflow, and loads base + LoRA in **standard
|
| 14 |
+
bf16 precision** (quantization=None) — NO fp8 quantization and NO fp8 LoRA
|
| 15 |
+
fusion (maintainer reports fp8+fuse degrades quality). The LoRA fuses cleanly
|
| 16 |
+
into bf16 weights at load time.
|
| 17 |
"""
|
| 18 |
|
| 19 |
import os
|
| 20 |
import subprocess
|
| 21 |
import sys
|
| 22 |
|
| 23 |
+
os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")
|
| 24 |
os.environ["TORCH_COMPILE_DISABLE"] = "1"
|
| 25 |
os.environ["TORCHDYNAMO_DISABLE"] = "1"
|
| 26 |
|
|
|
|
| 60 |
import gradio as gr
|
| 61 |
import numpy as np
|
| 62 |
import spaces
|
| 63 |
+
from gradio_client import Client
|
| 64 |
from huggingface_hub import hf_hub_download
|
|
|
|
| 65 |
|
| 66 |
+
import ltx_pipelines.ti2vid_one_stage as ti2vid_module
|
| 67 |
from ltx_core.components.guiders import MultiModalGuiderParams
|
| 68 |
+
from ltx_core.loader import LTXV_LORA_COMFY_RENAMING_MAP, LoraPathStrengthAndSDOps
|
|
|
|
|
|
|
| 69 |
from ltx_core.text_encoders.gemma.embeddings_processor import EmbeddingsProcessorOutput
|
| 70 |
+
from ltx_pipelines.ti2vid_one_stage import TI2VidOneStagePipeline
|
| 71 |
from ltx_pipelines.utils.args import ImageConditioningInput
|
| 72 |
from ltx_pipelines.utils.media_io import encode_video
|
| 73 |
|
|
|
|
| 125 |
|
| 126 |
SafetensorsStateDictLoader.load = _patched_load
|
| 127 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 128 |
logging.getLogger().setLevel(logging.INFO)
|
| 129 |
MAX_SEED = np.iinfo(np.int32).max
|
| 130 |
FRAME_RATE = 24.0
|
| 131 |
|
| 132 |
+
# ---- Cinemagraph LoRA recommended settings (from the model card) ----
|
| 133 |
TRIGGER = "CINEMAGRAPH_MOTION"
|
|
|
|
| 134 |
DEFAULT_NEGATIVE = (
|
| 135 |
"cars moving, camera movement, pan, tilt, zoom, parallax, whole image moving, "
|
| 136 |
"background sliding, person moving, flicker on entire image, noisy texture, "
|
| 137 |
"crawling texture, distorted, blurry, low quality"
|
| 138 |
)
|
| 139 |
+
# Model card "Recommended Settings":
|
| 140 |
+
# inference steps 30, guidance (CFG) 4.0, STG stg_v scale 1.0 targeting block 29,
|
| 141 |
+
# LoRA strength 0.7-3.0 (default 1.0), best at 512x704, 25 frames.
|
| 142 |
+
DEFAULT_STEPS = 30
|
| 143 |
+
DEFAULT_CFG = 4.0
|
| 144 |
+
DEFAULT_STG_SCALE = 1.0
|
| 145 |
+
STG_BLOCKS = [29]
|
| 146 |
+
DEFAULT_RESCALE = 0.7 # LTX_2_3_PARAMS video guider default
|
| 147 |
+
DEFAULT_A2V_SCALE = 3.0 # LTX_2_3_PARAMS video guider default (modality)
|
| 148 |
+
DEFAULT_LORA_STRENGTH = 1.0
|
| 149 |
+
DEFAULT_HEIGHT = 704
|
| 150 |
+
DEFAULT_WIDTH = 512
|
| 151 |
+
DEFAULT_FRAMES = 25 # model card training resolution
|
| 152 |
|
| 153 |
+
# Audio guider defaults (LTX_2_3_PARAMS). We generate video only, but the pipeline
|
| 154 |
+
# still runs the audio branch; keep the shipped defaults.
|
| 155 |
+
AUDIO_CFG, AUDIO_STG, AUDIO_RESCALE, AUDIO_A2V = 7.0, 1.0, 0.7, 3.0
|
| 156 |
|
| 157 |
LTX_REPO = os.environ.get("LTX_REPO", "Lightricks/LTX-2.3")
|
| 158 |
+
DEV_FILE = "ltx-2.3-22b-dev.safetensors" # full (non-distilled) base model
|
| 159 |
+
LORA_REPO = os.environ.get("LORA_REPO", "Lightricks/LTX-2.3-22b-LoRA-Cinemagraph")
|
| 160 |
+
LORA_FILE = "ltx-2.3-22b-lora-cinemagraph-0.9.safetensors"
|
|
|
|
|
|
|
|
|
|
| 161 |
TOKEN = os.environ.get("HF_TOKEN")
|
| 162 |
TEXT_ENCODER_SPACE = os.environ.get("TEXT_ENCODER_SPACE", "linoyts/ltx23-gemma-encoder-api")
|
| 163 |
|
| 164 |
+
print("Downloading base checkpoint + cinemagraph LoRA…")
|
| 165 |
checkpoint_path = hf_hub_download(LTX_REPO, DEV_FILE, token=TOKEN)
|
| 166 |
+
lora_path = hf_hub_download(LORA_REPO, LORA_FILE, token=TOKEN)
|
|
|
|
|
|
|
| 167 |
|
| 168 |
+
# Standard bf16 precision, LoRA fused into bf16 weights (quantization=None → NO fp8).
|
| 169 |
+
pipeline = TI2VidOneStagePipeline(
|
| 170 |
checkpoint_path=checkpoint_path,
|
|
|
|
|
|
|
| 171 |
gemma_root=None, # text encoding happens on TEXT_ENCODER_SPACE
|
|
|
|
| 172 |
loras=[LoraPathStrengthAndSDOps(
|
| 173 |
+
path=lora_path,
|
| 174 |
+
strength=DEFAULT_LORA_STRENGTH,
|
| 175 |
+
sd_ops=LTXV_LORA_COMFY_RENAMING_MAP, # ComfyUI-format LoRA → native keys
|
| 176 |
+
)],
|
| 177 |
+
quantization=None,
|
| 178 |
)
|
| 179 |
|
| 180 |
print("Preloading models (ZeroGPU tensor packing)…")
|
| 181 |
+
_ledger = pipeline.model_ledger
|
| 182 |
+
_cached = {n: getattr(_ledger, n)() for n in (
|
| 183 |
+
"transformer", "video_encoder", "video_decoder", "audio_decoder", "vocoder")}
|
| 184 |
+
for name, model in _cached.items():
|
| 185 |
+
setattr(_ledger, name, (lambda m: (lambda: m))(model))
|
| 186 |
+
print("Pipeline ready (bf16, cinemagraph LoRA fused, no fp8).")
|
|
|
|
|
|
|
|
|
|
| 187 |
|
| 188 |
|
| 189 |
# ---- remote text encoding (positive + negative, needed for CFG) ----
|
|
|
|
| 191 |
_emb_cache = {}
|
| 192 |
|
| 193 |
|
| 194 |
+
def fetch_embeddings(prompt, negative_prompt, enhance_prompt, image_path, seed):
|
| 195 |
+
"""Call the Gemma encoder Space; returns {'positive', 'negative', 'final_prompt'}."""
|
| 196 |
+
key = (prompt, negative_prompt, bool(enhance_prompt),
|
| 197 |
+
image_path or "", int(seed) if enhance_prompt else 0)
|
|
|
|
|
|
|
|
|
|
| 198 |
if key in _emb_cache:
|
| 199 |
return _emb_cache[key]
|
| 200 |
+
client = Client(TEXT_ENCODER_SPACE, token=TOKEN)
|
| 201 |
emb_file, final_prompt, status = client.predict(
|
| 202 |
prompt=prompt, negative_prompt=negative_prompt or "", encode_negative=True,
|
| 203 |
+
enhance_prompt=enhance_prompt, seed=int(seed), api_name="/encode",
|
| 204 |
)
|
| 205 |
print(f"[encoder] {status} | final prompt: {final_prompt[:80]}…")
|
| 206 |
data = torch.load(emb_file, map_location="cpu", weights_only=True)
|
|
|
|
| 218 |
)
|
| 219 |
|
| 220 |
|
| 221 |
+
def gpu_duration(embeddings, image_path, prompt, negative_prompt="", num_frames=25,
|
| 222 |
+
num_inference_steps=30, *args, **kwargs):
|
| 223 |
+
# ~ linear in steps and frames; generous ceiling for the full bf16 22B model.
|
| 224 |
+
return min(660, 200 + int(num_inference_steps) * 6 + int(num_frames) * 4)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 225 |
|
| 226 |
|
| 227 |
+
@spaces.GPU(duration=gpu_duration, size="xlarge")
|
| 228 |
@torch.inference_mode()
|
| 229 |
+
def _generate_gpu(embeddings, image_path, prompt, negative_prompt, num_frames, used_seed,
|
| 230 |
+
num_inference_steps, video_cfg_scale, video_stg_scale,
|
| 231 |
+
width, height, image_strength,
|
| 232 |
progress=gr.Progress(track_tqdm=True)):
|
| 233 |
+
images = [ImageConditioningInput(path=image_path, frame_idx=0,
|
| 234 |
+
strength=float(image_strength))]
|
|
|
|
|
|
|
|
|
|
|
|
|
| 235 |
|
| 236 |
precomputed = [_to_output(embeddings["positive"], "cuda"),
|
| 237 |
_to_output(embeddings["negative"], "cuda")]
|
|
|
|
| 244 |
seed=used_seed,
|
| 245 |
height=int(height),
|
| 246 |
width=int(width),
|
| 247 |
+
num_frames=int(num_frames),
|
| 248 |
frame_rate=FRAME_RATE,
|
| 249 |
num_inference_steps=int(num_inference_steps),
|
| 250 |
video_guider_params=MultiModalGuiderParams(
|
| 251 |
+
cfg_scale=video_cfg_scale, stg_scale=video_stg_scale,
|
| 252 |
+
rescale_scale=DEFAULT_RESCALE, modality_scale=DEFAULT_A2V_SCALE,
|
| 253 |
+
skip_step=0, stg_blocks=STG_BLOCKS),
|
| 254 |
audio_guider_params=MultiModalGuiderParams(
|
| 255 |
cfg_scale=AUDIO_CFG, stg_scale=AUDIO_STG, rescale_scale=AUDIO_RESCALE,
|
| 256 |
+
modality_scale=AUDIO_A2V, skip_step=0, stg_blocks=STG_BLOCKS),
|
| 257 |
images=images,
|
| 258 |
+
enhance_prompt=False, # already enhanced on the encoder Space
|
|
|
|
| 259 |
)
|
| 260 |
finally:
|
| 261 |
ti2vid_module.encode_prompts = original
|
| 262 |
|
| 263 |
output_path = tempfile.mktemp(suffix=".mp4")
|
| 264 |
+
encode_video(video=video, fps=FRAME_RATE, audio=audio,
|
| 265 |
+
output_path=output_path, video_chunks_number=1)
|
| 266 |
return output_path
|
| 267 |
|
| 268 |
|
| 269 |
+
def _ensure_frames(n: int) -> int:
|
| 270 |
+
"""Round num_frames to the pipeline requirement num_frames = 8*K + 1."""
|
| 271 |
+
n = max(9, int(n))
|
| 272 |
+
return ((n - 1 + 7) // 8) * 8 + 1
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
def _prep_prompt(prompt: str) -> str:
|
| 276 |
+
"""Ensure the cinemagraph trigger word leads the prompt."""
|
| 277 |
+
p = (prompt or "").strip()
|
| 278 |
+
if TRIGGER.lower() not in p.lower():
|
| 279 |
+
p = f"{TRIGGER}, {p}" if p else TRIGGER
|
| 280 |
+
return p
|
| 281 |
|
| 282 |
|
| 283 |
def generate(
|
| 284 |
+
image_path: str,
|
| 285 |
prompt: str,
|
| 286 |
negative_prompt: str = DEFAULT_NEGATIVE,
|
| 287 |
+
num_frames: int = DEFAULT_FRAMES,
|
| 288 |
seed: int = 42,
|
| 289 |
randomize_seed: bool = True,
|
| 290 |
+
num_inference_steps: int = DEFAULT_STEPS,
|
| 291 |
+
video_cfg_scale: float = DEFAULT_CFG,
|
| 292 |
+
video_stg_scale: float = DEFAULT_STG_SCALE,
|
| 293 |
+
width: int = DEFAULT_WIDTH,
|
| 294 |
+
height: int = DEFAULT_HEIGHT,
|
| 295 |
+
image_strength: float = 1.0,
|
| 296 |
+
enhance_prompt: bool = True,
|
| 297 |
progress=gr.Progress(track_tqdm=True),
|
| 298 |
):
|
| 299 |
+
"""Generate a cinemagraph (looping video with selective motion) from a still image.
|
| 300 |
|
| 301 |
Args:
|
| 302 |
+
image_path: path to the input still image to animate.
|
| 303 |
+
prompt: describe what should move; everything else stays frozen. The
|
| 304 |
+
trigger word CINEMAGRAPH_MOTION is prepended automatically if absent.
|
| 305 |
+
negative_prompt: things to avoid (camera motion, whole-image movement, …).
|
| 306 |
+
num_frames: number of frames (rounded to 8*K+1); ~25 recommended.
|
| 307 |
seed: RNG seed.
|
| 308 |
+
randomize_seed: draw a fresh random seed each run.
|
| 309 |
+
num_inference_steps: diffusion steps (model card default 30).
|
| 310 |
+
video_cfg_scale: classifier-free guidance scale (model card default 4.0).
|
| 311 |
+
video_stg_scale: spatio-temporal guidance scale (model card default 1.0).
|
| 312 |
+
width: output width in px (multiple of 32).
|
| 313 |
+
height: output height in px (multiple of 32).
|
| 314 |
+
image_strength: image conditioning strength.
|
| 315 |
+
enhance_prompt: run Gemma prompt enhancement on the encoder Space.
|
| 316 |
|
| 317 |
Returns:
|
| 318 |
+
(video_path, used_seed)
|
| 319 |
"""
|
| 320 |
+
if not image_path:
|
| 321 |
+
raise gr.Error("Please provide an input image.")
|
|
|
|
|
|
|
| 322 |
used_seed = random.randint(0, MAX_SEED) if randomize_seed else int(seed)
|
| 323 |
+
n_frames = _ensure_frames(num_frames)
|
| 324 |
+
full_prompt = _prep_prompt(prompt)
|
|
|
|
|
|
|
|
|
|
| 325 |
progress(0.05, desc="encoding prompts (Gemma Space)…")
|
| 326 |
+
embeddings = fetch_embeddings(full_prompt, negative_prompt, enhance_prompt,
|
| 327 |
+
image_path, used_seed)
|
| 328 |
output_path = _generate_gpu(
|
| 329 |
+
embeddings, image_path, full_prompt, negative_prompt, n_frames, used_seed,
|
| 330 |
+
num_inference_steps, video_cfg_scale, video_stg_scale,
|
| 331 |
+
int(width), int(height), image_strength,
|
| 332 |
+
)
|
| 333 |
return output_path, used_seed
|
| 334 |
|
| 335 |
|
| 336 |
CSS = """
|
| 337 |
+
#col-container { max-width: 1180px; margin: 0 auto; }
|
| 338 |
.dark .gradio-container { color: var(--body-text-color); }
|
| 339 |
"""
|
| 340 |
|
|
|
|
| 341 |
EXAMPLES = [
|
| 342 |
+
["examples/Glasses.jpeg",
|
| 343 |
+
"CINEMAGRAPH_MOTION, tripod locked-off static camera, zero camera movement, the man, "
|
| 344 |
+
"face, hair, clothing, beach, sky, and background remain completely frozen, only the "
|
| 345 |
+
"beach reflection inside his sunglasses moves, reflected time-lapse of ocean waves roll "
|
| 346 |
+
"and shimmer in the lenses, everything outside the glasses stays still, seamless natural loop"],
|
| 347 |
+
["examples/Jump.jpeg",
|
| 348 |
+
"CINEMAGRAPH_MOTION, tripod locked-off static camera, zero camera movement, the man and "
|
| 349 |
+
"cow remain completely frozen, only the clouds in the sky move in fast time-lapse, clouds "
|
| 350 |
+
"drift and roll across the sky, grass and foreground remain still, seamless natural loop."],
|
| 351 |
+
["examples/Motel.jpeg",
|
| 352 |
+
"CINEMAGRAPH_MOTION, tripod locked-off static camera, zero camera movement, only the neon "
|
| 353 |
+
"sign flickers, the starburst, Desert, MOTEL, and NO VACANCY neon tubes subtly pulse and "
|
| 354 |
+
"flicker like a real vintage neon sign, everything else stays perfectly still, seamless natural loop"],
|
| 355 |
+
["examples/Tears.jpeg",
|
| 356 |
+
"CINEMAGRAPH_MOTION, tripod locked-off static camera, zero camera movement, the woman is "
|
| 357 |
+
"frozen, her face, eyes, hair, clothing, seat, and airplane interior remain completely frozen, "
|
| 358 |
+
"only the illustrated tear drops move downward along her cheeks like a cutout collage "
|
| 359 |
+
"animation, seamless natural loop."],
|
| 360 |
]
|
| 361 |
|
| 362 |
+
with gr.Blocks(theme=gr.themes.Citrus(), css=CSS, title="LTX-2.3 Cinemagraph") as demo:
|
| 363 |
+
gr.Markdown(
|
| 364 |
+
"# 🎞️ LTX-2.3 Cinemagraph\n"
|
| 365 |
+
"Turn a **still image** into a looping cinemagraph — one element moves, the rest stays "
|
| 366 |
+
"frozen. Powered by the "
|
| 367 |
+
"[LTX-2.3-22B Cinemagraph LoRA](https://huggingface.co/Lightricks/LTX-2.3-22b-LoRA-Cinemagraph) "
|
| 368 |
+
"on the full LTX-2.3-22B base model (bf16, no fp8). Describe *what should move*; keep "
|
| 369 |
+
"the camera static.",
|
| 370 |
+
elem_id="intro")
|
| 371 |
+
with gr.Row(elem_id="col-container"):
|
| 372 |
+
with gr.Column():
|
| 373 |
+
image = gr.Image(label="Input image", type="filepath")
|
| 374 |
+
prompt = gr.Textbox(
|
| 375 |
+
label="Prompt (what should move)", lines=3,
|
| 376 |
+
placeholder="only the neon sign flickers, everything else stays perfectly still, "
|
| 377 |
+
"seamless natural loop")
|
| 378 |
+
btn = gr.Button("Generate cinemagraph", variant="primary")
|
| 379 |
+
with gr.Accordion("Advanced settings", open=False):
|
| 380 |
+
negative_prompt = gr.Textbox(label="Negative prompt", value=DEFAULT_NEGATIVE, lines=2)
|
| 381 |
+
num_frames = gr.Slider(9, 121, value=DEFAULT_FRAMES, step=8, label="Frames (8·K+1)")
|
| 382 |
+
with gr.Row():
|
| 383 |
+
seed = gr.Number(label="Seed", value=42, precision=0)
|
| 384 |
+
randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
|
| 385 |
+
with gr.Row():
|
| 386 |
+
num_inference_steps = gr.Slider(10, 50, value=DEFAULT_STEPS, step=1, label="Steps")
|
| 387 |
+
video_cfg_scale = gr.Slider(1.0, 8.0, value=DEFAULT_CFG, step=0.1, label="CFG scale")
|
| 388 |
+
video_stg_scale = gr.Slider(0.0, 4.0, value=DEFAULT_STG_SCALE, step=0.1, label="STG scale")
|
| 389 |
+
with gr.Row():
|
| 390 |
+
width = gr.Slider(256, 1024, value=DEFAULT_WIDTH, step=32, label="Width")
|
| 391 |
+
height = gr.Slider(256, 1024, value=DEFAULT_HEIGHT, step=32, label="Height")
|
| 392 |
+
image_strength = gr.Slider(0.5, 1.0, value=1.0, step=0.05, label="Image conditioning strength")
|
| 393 |
+
enhance_prompt = gr.Checkbox(label="Enhance prompt (Gemma)", value=True)
|
| 394 |
+
with gr.Column():
|
| 395 |
+
video = gr.Video(label="Cinemagraph", autoplay=True, loop=True)
|
| 396 |
+
used_seed = gr.Number(label="Used seed", precision=0)
|
| 397 |
+
|
| 398 |
+
inputs = [image, prompt, negative_prompt, num_frames, seed, randomize_seed,
|
| 399 |
+
num_inference_steps, video_cfg_scale, video_stg_scale, width, height,
|
| 400 |
+
image_strength, enhance_prompt]
|
| 401 |
+
btn.click(generate, inputs, [video, used_seed], api_name="generate")
|
| 402 |
+
|
| 403 |
+
gr.Examples(
|
| 404 |
+
examples=EXAMPLES,
|
| 405 |
+
inputs=[image, prompt],
|
| 406 |
+
outputs=[video, used_seed],
|
| 407 |
+
fn=generate,
|
| 408 |
+
cache_examples=False,
|
| 409 |
+
run_on_click=True,
|
| 410 |
+
)
|
|
|
|
| 411 |
|
| 412 |
if __name__ == "__main__":
|
| 413 |
+
demo.launch(mcp_server=True)
|