ajsbsd commited on
Commit
b432dcc
·
verified ·
1 Parent(s): 6e22c08

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -400
app.py CHANGED
@@ -34,404 +34,4 @@ if freshly_cloned:
34
  [sys.executable, "-m", "pip", "install", "--force-reinstall", "--no-deps", "-e",
35
  os.path.join(LTX_REPO_DIR, "packages", "ltx-core"),
36
  "-e", os.path.join(LTX_REPO_DIR, "packages", "ltx-pipelines")],
37
- check=True,
38
- )
39
-
40
- sys.path.insert(0, os.path.join(LTX_REPO_DIR, "packages", "ltx-pipelines", "src"))
41
- sys.path.insert(0, os.path.join(LTX_REPO_DIR, "packages", "ltx-core", "src"))
42
-
43
- import logging
44
- import random
45
- import tempfile
46
- from pathlib import Path
47
-
48
- import torch
49
- import torch._dynamo
50
-
51
- import spaces
52
- import gradio as gr
53
- import numpy as np
54
- import transformers
55
- from huggingface_hub import hf_hub_download, snapshot_download
56
-
57
- from ltx_core.model.video_vae import SpatialTilingConfig, TemporalTilingConfig, TilingConfig, get_video_chunks_number
58
- from ltx_core.quantization import QuantizationPolicy
59
- from ltx_pipelines.distilled import DistilledPipeline
60
- from ltx_pipelines.utils.args import ImageConditioningInput
61
- from ltx_pipelines.utils.media_io import encode_video
62
-
63
- # Force-patch xformers attention into the LTX attention module.
64
- from ltx_core.model.transformer import attention as _attn_mod
65
- print(f"[ATTN] Before patch: memory_efficient_attention={_attn_mod.memory_efficient_attention}")
66
- try:
67
- from xformers.ops import memory_efficient_attention as _mea
68
- _attn_mod.memory_efficient_attention = _mea
69
- print(f"[ATTN] After patch: memory_efficient_attention={_attn_mod.memory_efficient_attention}")
70
- except Exception as e:
71
- print(f"[ATTN] xformers patch FAILED: {type(e).__name__}: {e}")
72
-
73
- try:
74
- from xformers.ops.fmha import _set_use_fa3
75
- _set_use_fa3(False)
76
- print("[ATTN] xformers FA3 dispatch disabled (Blackwell-incompatible)")
77
- except Exception as e:
78
- print(f"[ATTN] FA3 disable FAILED: {type(e).__name__}: {e}")
79
-
80
- # --- PATCH 1: TRANSFORMERS 5.x COMPATIBILITY (SiglipVisionModel) ---
81
- # In transformers 5.x, the internal structure of SiglipVisionModel was flattened.
82
- try:
83
- from transformers.models.siglip import modeling_siglip
84
- if hasattr(modeling_siglip, 'SiglipVisionModel'):
85
- SiglipVisionModel = modeling_siglip.SiglipVisionModel
86
- if not hasattr(SiglipVisionModel, 'vision_model'):
87
- print("[PATCH 1] Adding missing 'vision_model' property to SiglipVisionModel for transformers 5.x...")
88
- SiglipVisionModel.vision_model = property(lambda self: self)
89
- except Exception as e:
90
- print(f"[PATCH 1] Could not patch SiglipVisionModel: {e}")
91
-
92
- # --- PATCH 2: TRANSFORMERS 5.x COMPATIBILITY (Gemma3TextConfig) ---
93
- # In transformers 5.x, 'rope_local_base_freq' was removed from Gemma3TextConfig.
94
- # LTX-2 expects this attribute to exist. We patch the __init__ to ensure it's always present.
95
- try:
96
- from transformers.models.gemma3.configuration_gemma3 import Gemma3TextConfig
97
- if not hasattr(Gemma3TextConfig, '_patched_rope_local'):
98
- original_gemma3_init = Gemma3TextConfig.__init__
99
- def patched_gemma3_init(self, *args, **kwargs):
100
- original_gemma3_init(self, *args, **kwargs)
101
- if not hasattr(self, 'rope_local_base_freq'):
102
- self.rope_local_base_freq = 10000.0 # Standard Gemma 3 local RoPE base frequency
103
- Gemma3TextConfig.__init__ = patched_gemma3_init
104
- Gemma3TextConfig._patched_rope_local = True
105
- print("[PATCH 2] Patched Gemma3TextConfig to include 'rope_local_base_freq' for transformers 5.x...")
106
- except Exception as e:
107
- print(f"[PATCH 2] Could not patch Gemma3TextConfig: {e}")
108
-
109
- import json
110
- import struct
111
-
112
- from ltx_core.loader.primitives import StateDict
113
- from ltx_core.loader.sft_loader import SafetensorsStateDictLoader
114
-
115
- _SAFETENSORS_DTYPE_MAP = {
116
- "F64": torch.float64, "F32": torch.float32, "F16": torch.float16, "BF16": torch.bfloat16,
117
- "F8_E5M2": torch.float8_e5m2, "F8_E4M3": torch.float8_e4m3fn, "I64": torch.int64,
118
- "I32": torch.int32, "I16": torch.int16, "I8": torch.int8, "U8": torch.uint8, "BOOL": torch.bool,
119
- }
120
-
121
- def _patched_load(self, path, sd_ops, device=None):
122
- sd = {}
123
- size = 0
124
- dtype = set()
125
- device = device or torch.device("cpu")
126
- model_paths = path if isinstance(path, list) else [path]
127
- for shard_path in model_paths:
128
- with open(shard_path, "rb") as f:
129
- header_len = struct.unpack("<Q", f.read(8))[0]
130
- header = json.loads(f.read(header_len).decode("utf-8"))
131
- data_base = 8 + header_len
132
- for name, meta in header.items():
133
- if name == "__metadata__": continue
134
- expected_name = name if sd_ops is None else sd_ops.apply_to_key(name)
135
- if expected_name is None: continue
136
- start, end = meta["data_offsets"]
137
- f.seek(data_base + start)
138
- buf = f.read(end - start)
139
- t = torch.frombuffer(bytearray(buf), dtype=_SAFETENSORS_DTYPE_MAP[meta["dtype"]]).reshape(meta["shape"])
140
- t = t.to(device=device, non_blocking=True, copy=False)
141
- kvs = (((expected_name, t),) if sd_ops is None else sd_ops.apply_to_key_value(expected_name, t))
142
- for key, v in kvs:
143
- size += v.nbytes
144
- dtype.add(v.dtype)
145
- sd[key] = v
146
- return StateDict(sd=sd, device=device, size=size, dtype=dtype)
147
-
148
- SafetensorsStateDictLoader.load = _patched_load
149
- print("[FUSE-PATCH] SafetensorsStateDictLoader.load replaced (chunked-read)")
150
-
151
- logging.getLogger().setLevel(logging.INFO)
152
-
153
- MAX_SEED = np.iinfo(np.int32).max
154
- DEFAULT_FRAME_RATE = 24.0
155
-
156
- RESOLUTIONS = {
157
- "high": {"16:9": (1536, 1024), "9:16": (1024, 1536), "1:1": (1024, 1024)},
158
- "low": {"16:9": (768, 512), "9:16": (512, 768), "1:1": (768, 768)},
159
- }
160
-
161
- BASE_DIR = os.path.dirname(os.path.abspath(__file__))
162
- LTX_MOUNT = os.path.join(BASE_DIR, "models_ltx")
163
- GEMMA_MOUNT = "/home/user/app/models_gemma"
164
-
165
- DISTILLED_FILENAME = "ltx-2.3-22b-distilled-1.1.safetensors"
166
- UPSCALER_FILENAME = "ltx-2.3-spatial-upscaler-x2-1.1.safetensors"
167
-
168
- def download_assets_safeguard():
169
- os.makedirs(GEMMA_MOUNT, exist_ok=True)
170
- os.makedirs(LTX_MOUNT, exist_ok=True)
171
-
172
- weights_present = bool(glob.glob(os.path.join(GEMMA_MOUNT, "model-*.safetensors")))
173
- if not weights_present:
174
- print("Downloading Gemma 3 12B weights (safetensors)...")
175
- try:
176
- snapshot_download(
177
- repo_id="google/gemma-3-12b-it",
178
- local_dir=GEMMA_MOUNT,
179
- ignore_patterns=["*.bin", "*.pt", "original/*"],
180
- token=HF_TOKEN
181
- )
182
- print("Gemma weights cached cleanly!")
183
- except Exception as e:
184
- print(f"Failed loading Gemma weights: {e}")
185
-
186
- distilled_path = os.path.join(LTX_MOUNT, DISTILLED_FILENAME)
187
- upscaler_path = os.path.join(LTX_MOUNT, UPSCALER_FILENAME)
188
-
189
- if not os.path.exists(distilled_path):
190
- print(f"Downloading {DISTILLED_FILENAME} into stable local mount...")
191
- hf_hub_download(
192
- repo_id="Lightricks/LTX-2.3",
193
- filename=DISTILLED_FILENAME,
194
- local_dir=LTX_MOUNT,
195
- token=HF_TOKEN
196
- )
197
-
198
- if not os.path.exists(upscaler_path):
199
- print(f"Downloading {UPSCALER_FILENAME} into stable local mount...")
200
- hf_hub_download(
201
- repo_id="Lightricks/LTX-2.3",
202
- filename=UPSCALER_FILENAME,
203
- local_dir=LTX_MOUNT,
204
- token=HF_TOKEN
205
- )
206
-
207
- print("[STARTUP] Warming up local asset registers...")
208
- download_assets_safeguard()
209
-
210
- pipeline = None
211
-
212
- def log_memory(tag: str):
213
- if torch.cuda.is_available():
214
- allocated = torch.cuda.memory_allocated() / 1024**3
215
- peak = torch.cuda.max_memory_allocated() / 1024**3
216
- free, total = torch.cuda.mem_get_info()
217
- print(f"[VRAM {tag}] allocated={allocated:.2f}GB peak={peak:.2f}GB free={free / 1024**3:.2f}GB total={total / 1024**3:.2f}GB")
218
-
219
- def detect_aspect_ratio(image) -> str:
220
- if image is None: return "16:9"
221
- if hasattr(image, "size"): w, h = image.size
222
- elif hasattr(image, "shape"): h, w = image.shape[:2]
223
- else: return "16:9"
224
- ratio = w / h
225
- candidates = {"16:9": 16 / 9, "9:16": 9 / 16, "1:1": 1.0}
226
- return min(candidates, key=lambda k: abs(ratio - candidates[k]))
227
-
228
- def safe_image_upload(image, high_res):
229
- if image is None: return gr.update(), gr.update()
230
- try:
231
- aspect = detect_aspect_ratio(image)
232
- tier = "high" if high_res else "low"
233
- w, h = RESOLUTIONS[tier][aspect]
234
- return gr.update(value=w), gr.update(value=h)
235
- except Exception as e:
236
- print(f"[Warning] Failed to preprocess image upload: {e}")
237
- return gr.update(value=1536), gr.update(value=1024)
238
-
239
- TILING_PRESETS = {
240
- "default": TilingConfig(
241
- spatial_config=SpatialTilingConfig(tile_size_in_pixels=768, tile_overlap_in_pixels=64),
242
- temporal_config=TemporalTilingConfig(tile_size_in_frames=80, tile_overlap_in_frames=24),
243
- ),
244
- "low-memory": TilingConfig(
245
- spatial_config=SpatialTilingConfig(tile_size_in_pixels=512, tile_overlap_in_pixels=64),
246
- temporal_config=TemporalTilingConfig(tile_size_in_frames=48, tile_overlap_in_frames=16),
247
- ),
248
- "high-quality": TilingConfig(
249
- spatial_config=SpatialTilingConfig(tile_size_in_pixels=1024, tile_overlap_in_pixels=128),
250
- temporal_config=TemporalTilingConfig(tile_size_in_frames=128, tile_overlap_in_frames=32),
251
- ),
252
- }
253
-
254
- @spaces.GPU(duration=180)
255
- @torch.inference_mode()
256
- def generate_video(
257
- input_image,
258
- prompt: str,
259
- duration: float,
260
- enhance_prompt: bool = True,
261
- seamless_loop: bool = False,
262
- seed: int = 42,
263
- randomize_seed: bool = True,
264
- height: int = 1024,
265
- width: int = 1536,
266
- tiling_preset: str = "default",
267
- progress=gr.Progress(track_tqdm=True),
268
- ):
269
- global pipeline
270
-
271
- if input_image is None:
272
- raise gr.Error("An Input Image is required for Image-to-Video generation!")
273
-
274
- try:
275
- torch.cuda.reset_peak_memory_stats()
276
- log_memory("start")
277
-
278
- if pipeline is None:
279
- print("Initializing DistilledPipeline on active ZeroGPU worker...")
280
- distilled_checkpoint_path = os.path.join(LTX_MOUNT, DISTILLED_FILENAME)
281
- spatial_upsampler_path = os.path.join(LTX_MOUNT, UPSCALER_FILENAME)
282
-
283
- pipeline = DistilledPipeline(
284
- distilled_checkpoint_path=distilled_checkpoint_path,
285
- spatial_upsampler_path=spatial_upsampler_path,
286
- gemma_root=GEMMA_MOUNT,
287
- loras=[],
288
- quantization=QuantizationPolicy.fp8_cast(),
289
- )
290
- print("Pipeline successfully configured!")
291
-
292
- current_seed = random.randint(0, MAX_SEED) if randomize_seed else int(seed)
293
- frame_rate = DEFAULT_FRAME_RATE
294
- num_frames = int(duration * frame_rate) + 1
295
- num_frames = ((num_frames - 1 + 7) // 8) * 8 + 1
296
-
297
- print(f"Generating I2V: {height}x{width}, {num_frames} frames ({duration}s), seed={current_seed}")
298
-
299
- images = []
300
- owned_temp_image = None
301
- output_dir = Path("outputs")
302
- output_dir.mkdir(exist_ok=True)
303
- temp_image_path = output_dir / f"temp_input_{current_seed}.jpg"
304
-
305
- if hasattr(input_image, "save"):
306
- input_image.save(temp_image_path)
307
- owned_temp_image = temp_image_path
308
- else:
309
- temp_image_path = Path(input_image)
310
-
311
- images = [ImageConditioningInput(path=str(temp_image_path), frame_idx=0, strength=1.0)]
312
-
313
- if seamless_loop:
314
- images.append(
315
- ImageConditioningInput(path=str(temp_image_path), frame_idx=num_frames - 1, strength=1.0)
316
- )
317
- print(f"[LOOP] Seamless loop enabled: conditioning frame 0 and frame {num_frames - 1}")
318
-
319
- try:
320
- tiling_config = TILING_PRESETS.get(tiling_preset, TILING_PRESETS["default"])
321
- video_chunks_number = get_video_chunks_number(num_frames, tiling_config)
322
-
323
- log_memory("before pipeline call")
324
-
325
- video, audio = pipeline(
326
- prompt=prompt,
327
- seed=current_seed,
328
- height=int(height),
329
- width=int(width),
330
- num_frames=num_frames,
331
- frame_rate=frame_rate,
332
- images=images,
333
- tiling_config=tiling_config,
334
- enhance_prompt=enhance_prompt,
335
- )
336
-
337
- log_memory("after pipeline call")
338
-
339
- output_path = tempfile.mktemp(suffix=".mp4")
340
- encode_video(
341
- video=video,
342
- fps=frame_rate,
343
- audio=audio,
344
- output_path=output_path,
345
- video_chunks_number=video_chunks_number,
346
- )
347
-
348
- log_memory("after encode_video")
349
- torch.cuda.empty_cache()
350
- return str(output_path), current_seed
351
- finally:
352
- if owned_temp_image is not None:
353
- Path(owned_temp_image).unlink(missing_ok=True)
354
-
355
- except Exception as e:
356
- import traceback
357
- log_memory("on error")
358
- torch.cuda.empty_cache()
359
- print(f"Error: {str(e)}\n{traceback.format_exc()}")
360
- raise gr.Error(f"Generation failed: {str(e)}")
361
-
362
- with gr.Blocks(title="LTX-2.3 I2V & Seamless Loops") as demo:
363
- gr.Markdown("# LTX-2.3 Distilled I2V: Image-to-Video & Seamless Loops")
364
- gr.Markdown(
365
- "High quality Image-to-Video generation with native **Seamless Looping** (First-Last Frame conditioning). "
366
- "[[model]](https://huggingface.co/Lightricks/LTX-2.3) "
367
- "[[code]](https://github.com/Lightricks/LTX-2)"
368
- )
369
-
370
- with gr.Row():
371
- with gr.Column():
372
- input_image = gr.Image(label="Input Image (Required)", type="pil")
373
- prompt = gr.Textbox(
374
- label="Motion Prompt",
375
- info="Describe how the image should move. For loops, mention 'seamless cyclic motion'.",
376
- value="Make this image come alive with cinematic motion, smooth animation",
377
- lines=3,
378
- placeholder="Describe the motion and animation you want...",
379
- )
380
-
381
- with gr.Row():
382
- duration = gr.Slider(label="Duration (seconds)", minimum=1.0, maximum=10.0, value=3.0, step=0.1)
383
- with gr.Column():
384
- enhance_prompt = gr.Checkbox(label="Enhance Prompt", value=False)
385
- high_res = gr.Checkbox(label="High Resolution", value=True)
386
- seamless_loop = gr.Checkbox(
387
- label="Seamless Loop",
388
- value=False,
389
- info="Forces the last frame to match the first frame for perfect looping."
390
- )
391
-
392
- generate_btn = gr.Button("Generate I2V", variant="primary", size="lg")
393
-
394
- with gr.Accordion("Advanced Settings", open=False):
395
- seed = gr.Slider(label="Seed", minimum=0, maximum=MAX_SEED, value=10, step=1)
396
- randomize_seed = gr.Checkbox(label="Randomize Seed", value=True)
397
- with gr.Row():
398
- width = gr.Number(label="Width", value=1536, precision=0)
399
- height = gr.Number(label="Height", value=1024, precision=0)
400
- tiling_preset = gr.Dropdown(
401
- label="Tiling Preset",
402
- choices=list(TILING_PRESETS.keys()),
403
- value="default",
404
- info="default: balanced · low-memory: smaller tiles, less VRAM · high-quality: larger tiles, fewer seam artefacts",
405
- )
406
-
407
- with gr.Column():
408
- output_video = gr.Video(label="Generated Video", autoplay=True, loop=True)
409
-
410
- input_image.change(
411
- fn=safe_image_upload,
412
- inputs=[input_image, high_res],
413
- outputs=[width, height],
414
- )
415
-
416
- high_res.change(
417
- fn=safe_image_upload,
418
- inputs=[input_image, high_res],
419
- outputs=[width, height],
420
- )
421
-
422
- generate_btn.click(
423
- fn=generate_video,
424
- inputs=[
425
- input_image, prompt, duration, enhance_prompt, seamless_loop,
426
- seed, randomize_seed, height, width, tiling_preset,
427
- ],
428
- outputs=[output_video, seed],
429
- )
430
-
431
- css = """
432
- .fillable{max-width: 1200px !important}
433
- .progress-text {color: white}
434
- """
435
-
436
- if __name__ == "__main__":
437
  demo.launch(theme=gr.themes.Citrus(), css=css, ssr_mode=False)
 
34
  [sys.executable, "-m", "pip", "install", "--force-reinstall", "--no-deps", "-e",
35
  os.path.join(LTX_REPO_DIR, "packages", "ltx-core"),
36
  "-e", os.path.join(LTX_REPO_DIR, "packages", "ltx-pipelines")],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
  demo.launch(theme=gr.themes.Citrus(), css=css, ssr_mode=False)