multimodalart HF Staff commited on
Commit
dd4099a
·
verified ·
1 Parent(s): 4962d7f

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +195 -201
app.py CHANGED
@@ -1,20 +1,26 @@
1
- """LTX-2.3 Cinemagraph LoRA — image-to-video demo.
2
-
3
- Turns a still image into a looping cinemagraph: only the element you describe moves
4
- while the rest of the frame stays frozen (locked-off static camera). Built on the native
5
- LTX-2.3 `TI2VidTwoStagesPipeline` (dev/base stage 1 with CFG/STG guidance, distilled-LoRA
6
- stage 2 + x2 spatial upsampler) with the Cinemagraph LoRA fused into stage 1.
7
-
8
- Text encoding (positive + negative, for CFG) is offloaded to the Gemma encoder Space
9
- (TEXT_ENCODER_SPACE) via gradio_client `encode_prompts` is monkeypatched with the
10
- precomputed [ctx_p, ctx_n], so this Space never loads Gemma. Mirrors the working
11
- `linoyts/ltx23-dev-api` backend pattern.
 
 
 
 
 
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, handle_file
58
  from huggingface_hub import hf_hub_download
59
- from PIL import Image, ImageOps
60
 
61
- import ltx_pipelines.ti2vid_two_stages as ti2vid_module
62
  from ltx_core.components.guiders import MultiModalGuiderParams
63
- from ltx_core.loader import LoraPathStrengthAndSDOps, LTXV_LORA_COMFY_RENAMING_MAP
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.ti2vid_two_stages import TI2VidTwoStagesPipeline
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
- # LTX-2.3 guider defaults. Cinemagraph card recommends stg_v scale 1.0 @ block 29, guidance 4.0.
156
- VIDEO_STG, VIDEO_RESCALE, A2V_SCALE, STG_BLOCKS = 1.0, 0.7, 3.0, [29]
157
- AUDIO_CFG, AUDIO_STG, AUDIO_RESCALE, V2A_SCALE = 7.0, 1.0, 0.7, 3.0
158
 
159
  LTX_REPO = os.environ.get("LTX_REPO", "Lightricks/LTX-2.3")
160
- DEV_FILE = "ltx-2.3-22b-dev.safetensors"
161
- DISTILLED_LORA_FILE = "ltx-2.3-22b-distilled-lora-384-1.1.safetensors"
162
- UPSCALER_FILE = "ltx-2.3-spatial-upscaler-x2-1.1.safetensors"
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 checkpoints…")
170
  checkpoint_path = hf_hub_download(LTX_REPO, DEV_FILE, token=TOKEN)
171
- distilled_lora_path = hf_hub_download(LTX_REPO, DISTILLED_LORA_FILE, token=TOKEN)
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
- pipeline = TI2VidTwoStagesPipeline(
 
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=cinemagraph_lora_path, strength=DEFAULT_LORA_STRENGTH,
183
- sd_ops=LTXV_LORA_COMFY_RENAMING_MAP)],
184
- quantization=QuantizationPolicy.fp8_cast(),
 
 
185
  )
186
 
187
  print("Preloading models (ZeroGPU tensor packing)…")
188
- s1, s2 = pipeline.stage_1_model_ledger, pipeline.stage_2_model_ledger
189
- _cached_s1 = {n: getattr(s1, n)() for n in ("transformer", "video_encoder")}
190
- _cached_s2 = {n: getattr(s2, n)() for n in (
191
- "transformer", "video_decoder", "audio_decoder", "vocoder", "spatial_upsampler")}
192
- for name, model in _cached_s1.items():
193
- setattr(s1, name, (lambda m: (lambda: m))(model))
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
- enhance_prompt is disabled: cinemagraph prompting relies on an explicit
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, httpx_kwargs={"timeout": 300})
214
  emb_file, final_prompt, status = client.predict(
215
  prompt=prompt, negative_prompt=negative_prompt or "", encode_negative=True,
216
- enhance_prompt=False, seed=int(seed), api_name="/encode",
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 _prep_image(image_path, width, height):
235
- """Aspect-fit/crop the still to WxH and save a temp file the VAE encoder can read."""
236
- im = Image.open(image_path).convert("RGB")
237
- im = ImageOps.fit(im, (width, height), Image.LANCZOS)
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, duration, used_seed,
250
- num_inference_steps, video_cfg_scale, lora_strength, width, height,
 
251
  progress=gr.Progress(track_tqdm=True)):
252
- num_frames = ((int(duration * FRAME_RATE) + 1 - 1 + 7) // 8) * 8 + 1
253
- tiling_config = TilingConfig.default()
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=VIDEO_STG, rescale_scale=VIDEO_RESCALE,
275
- modality_scale=A2V_SCALE, skip_step=0, stg_blocks=STG_BLOCKS),
 
276
  audio_guider_params=MultiModalGuiderParams(
277
  cfg_scale=AUDIO_CFG, stg_scale=AUDIO_STG, rescale_scale=AUDIO_RESCALE,
278
- modality_scale=V2A_SCALE, skip_step=0, stg_blocks=STG_BLOCKS),
279
  images=images,
280
- tiling_config=tiling_config,
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, output_path=output_path,
288
- video_chunks_number=video_chunks_number)
289
  return output_path
290
 
291
 
292
- def _build_prompt(user_prompt: str) -> str:
293
- p = (user_prompt or "").strip()
294
- if TRIGGER.lower() in p.lower():
295
- return p
296
- return f"{TRIGGER}, tripod locked-off static camera, zero camera movement, {p}"
 
 
 
 
 
 
 
297
 
298
 
299
  def generate(
300
- image: str,
301
  prompt: str,
302
  negative_prompt: str = DEFAULT_NEGATIVE,
303
- duration: float = 4.0,
304
  seed: int = 42,
305
  randomize_seed: bool = True,
306
- num_inference_steps: int = 30,
307
- video_cfg_scale: float = 4.0,
308
- lora_strength: float = DEFAULT_LORA_STRENGTH,
309
- width: int = 704,
310
- height: int = 512,
 
 
311
  progress=gr.Progress(track_tqdm=True),
312
  ):
313
- """Turn a still image into a looping cinemagraph (selective motion, everything else frozen).
314
 
315
  Args:
316
- image: path to the still input image (i2v conditioning at frame 0).
317
- prompt: what should move (e.g. "only the ocean waves shimmer in his sunglasses").
318
- The CINEMAGRAPH_MOTION trigger + static-camera framing are added automatically.
319
- negative_prompt: things to suppress (camera motion, whole-image movement, artifacts).
320
- duration: clip length in seconds.
321
  seed: RNG seed.
322
- randomize_seed: draw a fresh random seed instead of `seed`.
323
- num_inference_steps: stage-1 diffusion steps.
324
- video_cfg_scale: classifier-free guidance scale (cinemagraph default 4.0).
325
- lora_strength: Cinemagraph LoRA strength note (fixed at load; shown for reference).
326
- width: output width (multiple of 64).
327
- height: output height (multiple of 64).
 
 
328
 
329
  Returns:
330
- (video_path, used_seed): the generated .mp4 and the seed actually used.
331
  """
332
- if image is None:
333
- raise gr.Error("Please upload a still image to animate.")
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
- full_prompt = _build_prompt(prompt)
338
- if TRIGGER.lower() not in full_prompt.lower():
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, used_seed)
 
344
  output_path = _generate_gpu(
345
- embeddings, image, full_prompt, negative_prompt, duration, used_seed,
346
- num_inference_steps, video_cfg_scale, lora_strength, width, height)
 
 
347
  return output_path, used_seed
348
 
349
 
350
  CSS = """
351
- #col-container { max-width: 1200px; margin: 0 auto; }
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
- [os.path.join(EX_DIR, "Glasses.jpeg"),
358
- "the man, face, hair, clothing, beach, sky, and background remain completely frozen, only the beach reflection inside his sunglasses moves, reflected time-lapse of ocean waves roll and shimmer in the lenses, everything outside the glasses stays still"],
359
- [os.path.join(EX_DIR, "Jump.jpeg"),
360
- "the man and cow remain completely frozen, only the clouds in the sky move in fast time-lapse, clouds drift and roll across the sky, grass and foreground remain still"],
361
- [os.path.join(EX_DIR, "Motel.jpeg"),
362
- "only the neon sign flickers, the starburst, Desert, MOTEL, and NO VACANCY neon tubes subtly pulse and flicker like a real vintage neon sign, everything else stays perfectly still"],
363
- [os.path.join(EX_DIR, "Tears.jpeg"),
364
- "the woman is frozen, her face, eyes, hair, clothing, seat, and airplane interior remain completely frozen, only the illustrated tear drops move downward along her cheeks like a cutout collage animation"],
 
 
 
 
 
 
 
 
 
 
365
  ]
366
 
367
- with gr.Blocks(title="LTX-2.3 Cinemagraph LoRA", theme=gr.themes.Citrus(), css=CSS) as demo:
368
- with gr.Column(elem_id="col-container"):
369
- gr.Markdown(
370
- "# 🎞️ LTX-2.3 Cinemagraph\n"
371
- "Turn a **still image** into a looping **cinemagraph** — only the element you "
372
- "describe moves (water, reflections, neon, clouds, rain) while the rest of the "
373
- "frame stays frozen. Built on [LTX-2.3](https://huggingface.co/Lightricks/LTX-2.3) "
374
- "with the [Cinemagraph LoRA](https://huggingface.co/Lightricks/LTX-2.3-22b-LoRA-Cinemagraph). "
375
- "Text encoding is offloaded to a remote Gemma encoder Space.\n\n"
376
- "**Tip:** be explicit — *\"only the [element] moves; everything else frozen.\"* "
377
- "The `CINEMAGRAPH_MOTION` trigger and static-camera framing are added for you."
378
- )
379
- with gr.Row():
380
- with gr.Column():
381
- image = gr.Image(label="Still image", type="filepath")
382
- prompt = gr.Textbox(
383
- label="What should move?", lines=3,
384
- placeholder="only the ocean waves reflected in his sunglasses shimmer; everything else stays frozen",
385
- )
386
- run = gr.Button("Animate", variant="primary")
387
- with gr.Accordion("Advanced settings", open=False):
388
- negative_prompt = gr.Textbox(label="Negative prompt", value=DEFAULT_NEGATIVE, lines=2)
389
- duration = gr.Slider(1, 8, value=4, step=0.5, label="Duration (s)")
390
- with gr.Row():
391
- seed = gr.Number(label="Seed", value=42, precision=0)
392
- randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
393
- with gr.Row():
394
- num_inference_steps = gr.Slider(10, 50, value=30, step=1, label="Steps")
395
- video_cfg_scale = gr.Slider(1, 8, value=4.0, step=0.1, label="Guidance (CFG)")
396
- lora_strength = gr.Slider(0.5, 3.0, value=DEFAULT_LORA_STRENGTH, step=0.1,
397
- label="LoRA strength (set at load)")
398
- with gr.Row():
399
- width = gr.Slider(384, 1024, value=704, step=64, label="Width")
400
- height = gr.Slider(384, 1024, value=512, step=64, label="Height")
401
- with gr.Column():
402
- video = gr.Video(label="Cinemagraph", autoplay=True, loop=True)
403
- used_seed = gr.Number(label="Used seed", precision=0)
404
-
405
- inputs = [image, prompt, negative_prompt, duration, seed, randomize_seed,
406
- num_inference_steps, video_cfg_scale, lora_strength, width, height]
407
- run.click(generate, inputs, [video, used_seed], api_name="generate")
408
-
409
- gr.Examples(
410
- examples=EXAMPLES,
411
- inputs=[image, prompt],
412
- outputs=[video, used_seed],
413
- fn=generate,
414
- cache_examples=True,
415
- cache_mode="lazy",
416
- )
417
 
418
  if __name__ == "__main__":
419
- demo.launch(mcp_server=True, show_error=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)