Vicente Alvarez commited on
Commit
7971834
·
0 Parent(s):

Initial: Element-8-Video-Max (based on Element-16-Video-Max, uses LTX-2.3 distilled checkpoint)

Browse files
Files changed (5) hide show
  1. .gitattributes +35 -0
  2. README.md +22 -0
  3. app.py +610 -0
  4. pinkknit.jpg +0 -0
  5. requirements.txt +14 -0
.gitattributes ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Element-16 Video
3
+ emoji: 🧪
4
+ colorFrom: yellow
5
+ colorTo: yellow
6
+ sdk: gradio
7
+ sdk_version: 6.8.0
8
+ python_version: '3.12'
9
+ app_file: app.py
10
+ pinned: false
11
+ short_description: Fast video generation with bf16 model
12
+ ---
13
+
14
+ # Element-16 Video Generator
15
+
16
+ Fast video + audio generation with first and last frame conditioning. Uses an optimized fp8 model for efficient inference.
17
+
18
+ ## Features
19
+ - First/Last frame conditioning
20
+ - Auto-generated audio
21
+ - Customizable negative prompt
22
+ - fp8 quantized for speed
app.py ADDED
@@ -0,0 +1,610 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import subprocess
3
+ import sys
4
+ from concurrent.futures import ThreadPoolExecutor
5
+
6
+ # Enable fast downloads
7
+ os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = "1"
8
+ os.environ["HF_XET_HIGH_PERFORMANCE"] = "1"
9
+
10
+ # Disable torch.compile / dynamo before any torch import
11
+ os.environ["TORCH_COMPILE_DISABLE"] = "1"
12
+ os.environ["TORCHDYNAMO_DISABLE"] = "1"
13
+
14
+ # Install xformers for memory-efficient attention
15
+ subprocess.run([sys.executable, "-m", "pip", "install", "xformers==0.0.32.post2", "--no-build-isolation"], check=False)
16
+
17
+ # Clone LTX-2 repo at a pinned compatible commit and install packages
18
+ LTX_REPO_URL = "https://github.com/Lightricks/LTX-2.git"
19
+ LTX_REPO_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "LTX-2")
20
+ LTX_COMMIT = "ae855f8538843825f9015a419cf4ba5edaf5eec2"
21
+
22
+ if os.path.exists(LTX_REPO_DIR):
23
+ print(f"Removing existing repo at {LTX_REPO_DIR}...")
24
+ subprocess.run(["rm", "-rf", LTX_REPO_DIR], check=True)
25
+
26
+ print(f"Cloning {LTX_REPO_URL}...")
27
+ subprocess.run(["git", "clone", LTX_REPO_URL, LTX_REPO_DIR], check=True)
28
+
29
+ print(f"Checking out commit {LTX_COMMIT}...")
30
+ subprocess.run(["git", "-C", LTX_REPO_DIR, "checkout", LTX_COMMIT], check=True)
31
+
32
+ print("Installing ltx-core and ltx-pipelines from pinned repo commit...")
33
+ subprocess.run(
34
+ [
35
+ sys.executable, "-m", "pip", "install",
36
+ "--force-reinstall", "--no-deps",
37
+ "-e", os.path.join(LTX_REPO_DIR, "packages", "ltx-core"),
38
+ "-e", os.path.join(LTX_REPO_DIR, "packages", "ltx-pipelines"),
39
+ ],
40
+ check=True,
41
+ )
42
+
43
+ sys.path.insert(0, os.path.join(LTX_REPO_DIR, "packages", "ltx-pipelines", "src"))
44
+ sys.path.insert(0, os.path.join(LTX_REPO_DIR, "packages", "ltx-core", "src"))
45
+
46
+ import logging
47
+ import random
48
+ import tempfile
49
+ from pathlib import Path
50
+
51
+ import torch
52
+ torch._dynamo.config.suppress_errors = True
53
+ torch._dynamo.config.disable = True
54
+
55
+ # Critical workaround: Replace inference_mode with no_grad
56
+ # Avoids "inference tensor" failures in spatial upsampler and VAE decoder
57
+ torch.inference_mode = torch.no_grad
58
+
59
+ import spaces
60
+ import gradio as gr
61
+ import numpy as np
62
+ from huggingface_hub import hf_hub_download, snapshot_download
63
+
64
+ from ltx_pipelines.distilled import DistilledPipeline
65
+ from ltx_pipelines.utils.args import ImageConditioningInput
66
+ from ltx_pipelines.utils.media_io import encode_video
67
+
68
+ # Patch attention backend into the LTX attention module.
69
+ import torch.nn.functional as F
70
+ from ltx_core.model.transformer import attention as _attn_mod
71
+
72
+ def _sdpa_as_mea(query, key, value, attn_bias=None, scale=None, **kwargs):
73
+ # xformers memory_efficient_attention: (B, S, H, D) -> (B, S, H, D)
74
+ # torch SDPA: (B, H, S, D) -> (B, H, S, D)
75
+ q, k, v = query.transpose(1, 2), key.transpose(1, 2), value.transpose(1, 2)
76
+ return F.scaled_dot_product_attention(q, k, v, scale=scale).transpose(1, 2)
77
+
78
+ _cap = torch.cuda.get_device_capability() if torch.cuda.is_available() else (0, 0)
79
+ _use_xformers = False
80
+ if _cap < (12, 0):
81
+ try:
82
+ from xformers.ops import memory_efficient_attention as _mea
83
+ _attn_mod.memory_efficient_attention = _mea
84
+ _use_xformers = True
85
+ print(f"[ATTN] Using xformers memory_efficient_attention")
86
+ except Exception as e:
87
+ print(f"[ATTN] xformers unavailable ({e}), falling back to SDPA")
88
+
89
+ if not _use_xformers:
90
+ _attn_mod.memory_efficient_attention = _sdpa_as_mea
91
+ print(f"[ATTN] Using SDPA fallback (sm_{_cap[0]}{_cap[1]})")
92
+
93
+ logging.getLogger().setLevel(logging.INFO)
94
+
95
+ MAX_SEED = np.iinfo(np.int32).max
96
+ DEFAULT_PROMPT = (
97
+ "An astronaut hatches from a fragile egg on the surface of the Moon, "
98
+ "the shell cracking and peeling apart in gentle low-gravity motion. "
99
+ "Fine lunar dust lifts and drifts outward with each movement, floating "
100
+ "in slow arcs before settling back onto the ground."
101
+ )
102
+ DEFAULT_FRAME_RATE = 24.0
103
+
104
+ # Resolution presets: (width, height)
105
+ RESOLUTIONS = {
106
+ "high": {"16:9": (1536, 1024), "9:16": (1024, 1536), "1:1": (1024, 1024)},
107
+ "low": {"16:9": (512, 320), "9:16": (320, 512), "1:1": (512, 512)},
108
+ }
109
+
110
+
111
+ # Model repos
112
+ LTX_MODEL_REPO = "Lightricks/LTX-2.3"
113
+ GEMMA_REPO = "Lightricks/gemma-3-12b-it-qat-q4_0-unquantized"
114
+
115
+ # Download model checkpoints in parallel for speed
116
+ print("=" * 80)
117
+ print("Downloading Element-8 (pre-distilled LTX) + Gemma (parallel)...")
118
+ print("=" * 80)
119
+
120
+ def download_checkpoint():
121
+ # Use pre-distilled LTX checkpoint - no LoRA needed
122
+ return hf_hub_download(repo_id=LTX_MODEL_REPO, filename="ltx-2.3-22b-distilled.safetensors")
123
+
124
+ def download_upsampler():
125
+ return hf_hub_download(repo_id=LTX_MODEL_REPO, filename="ltx-2.3-spatial-upscaler-x2-1.0.safetensors")
126
+
127
+ def download_gemma():
128
+ return snapshot_download(repo_id=GEMMA_REPO)
129
+
130
+ with ThreadPoolExecutor(max_workers=3) as executor:
131
+ future_checkpoint = executor.submit(download_checkpoint)
132
+ future_upsampler = executor.submit(download_upsampler)
133
+ future_gemma = executor.submit(download_gemma)
134
+
135
+ checkpoint_path = future_checkpoint.result()
136
+ spatial_upsampler_path = future_upsampler.result()
137
+ gemma_root = future_gemma.result()
138
+
139
+ print(f"Checkpoint: {checkpoint_path}")
140
+ print(f"Spatial upsampler: {spatial_upsampler_path}")
141
+ print(f"Gemma root: {gemma_root}")
142
+
143
+ # Initialize pipeline with pre-distilled checkpoint (no LoRA needed)
144
+ pipeline = DistilledPipeline(
145
+ distilled_checkpoint_path=checkpoint_path,
146
+ spatial_upsampler_path=spatial_upsampler_path,
147
+ gemma_root=gemma_root,
148
+ loras=(),
149
+ )
150
+
151
+ # Preload all models for ZeroGPU tensor packing
152
+ print("Preloading all pipeline components via model_ledger...")
153
+
154
+ # DistilledPipeline uses model_ledger similar to other pipelines
155
+ ledger = pipeline.model_ledger
156
+ _transformer = ledger.transformer()
157
+ _video_encoder = ledger.video_encoder()
158
+ _video_decoder = ledger.video_decoder()
159
+ _spatial_upsampler = ledger.spatial_upsampler()
160
+ _text_encoder = ledger.text_encoder()
161
+ _embeddings_processor = ledger.gemma_embeddings_processor()
162
+ _audio_encoder = ledger.audio_encoder()
163
+ _audio_decoder = ledger.audio_decoder()
164
+ _vocoder = ledger.vocoder()
165
+
166
+ # Replace ledger methods with lambdas returning preloaded instances
167
+ ledger.transformer = lambda: _transformer
168
+ ledger.video_encoder = lambda: _video_encoder
169
+ ledger.video_decoder = lambda: _video_decoder
170
+ ledger.spatial_upsampler = lambda: _spatial_upsampler
171
+ ledger.text_encoder = lambda: _text_encoder
172
+ ledger.gemma_embeddings_processor = lambda: _embeddings_processor
173
+ ledger.audio_encoder = lambda: _audio_encoder
174
+ ledger.audio_decoder = lambda: _audio_decoder
175
+ ledger.vocoder = lambda: _vocoder
176
+
177
+ print("All models preloaded!")
178
+
179
+ print("=" * 80)
180
+ print("Pipeline ready!")
181
+ print("=" * 80)
182
+
183
+
184
+ def log_memory(tag: str):
185
+ if torch.cuda.is_available():
186
+ allocated = torch.cuda.memory_allocated() / 1024**3
187
+ peak = torch.cuda.max_memory_allocated() / 1024**3
188
+ free, total = torch.cuda.mem_get_info()
189
+ print(f"[VRAM {tag}] allocated={allocated:.2f}GB peak={peak:.2f}GB free={free / 1024**3:.2f}GB total={total / 1024**3:.2f}GB")
190
+
191
+
192
+ def detect_aspect_ratio(image) -> str:
193
+ if image is None:
194
+ return "16:9"
195
+ if hasattr(image, "size"):
196
+ w, h = image.size
197
+ elif hasattr(image, "shape"):
198
+ h, w = image.shape[:2]
199
+ else:
200
+ return "16:9"
201
+ ratio = w / h
202
+ candidates = {"16:9": 16 / 9, "9:16": 9 / 16, "1:1": 1.0}
203
+ return min(candidates, key=lambda k: abs(ratio - candidates[k]))
204
+
205
+
206
+ def on_image_upload(first_image, last_image, high_res):
207
+ ref_image = first_image if first_image is not None else last_image
208
+ aspect = detect_aspect_ratio(ref_image)
209
+ tier = "high" if high_res else "low"
210
+ w, h = RESOLUTIONS[tier][aspect]
211
+ return gr.update(value=w), gr.update(value=h)
212
+
213
+
214
+ def on_highres_toggle(first_image, last_image, high_res):
215
+ ref_image = first_image if first_image is not None else last_image
216
+ aspect = detect_aspect_ratio(ref_image)
217
+ tier = "high" if high_res else "low"
218
+ w, h = RESOLUTIONS[tier][aspect]
219
+ return gr.update(value=w), gr.update(value=h)
220
+
221
+
222
+ DEFAULT_NEGATIVE_PROMPT = "色调艳丽,过曝,静态,细节模糊不清,字幕,风格,作品,画作,画面,静止,整体发灰,最差质量,低质量,JPEG压缩残留,丑陋的,残缺的,多余的手指,画得不好的手部,画得不好的脸部,畸形的,毁容的,形态畸形的肢体,手指融合,静止不动的画面,杂乱的背景,三条腿,背景人很多,倒着走, blurry, glasses, deformed, subtitles, text, captions, worst quality, low quality, inconsistent motion, jittery, distorted"
223
+
224
+
225
+ def remove_music_demucs(input_video_path: str, output_video_path: str) -> bool:
226
+ """Remove background music from video using Demucs, keeping only vocals."""
227
+ import subprocess
228
+ import tempfile
229
+ from pathlib import Path
230
+
231
+ try:
232
+ with tempfile.TemporaryDirectory() as tmpdir:
233
+ tmpdir = Path(tmpdir)
234
+
235
+ # Extract audio from video
236
+ audio_in = tmpdir / "audio.wav"
237
+ extract_cmd = [
238
+ 'ffmpeg', '-y', '-i', input_video_path,
239
+ '-vn', '-acodec', 'pcm_s16le', '-ar', '44100', '-ac', '2',
240
+ str(audio_in)
241
+ ]
242
+ result = subprocess.run(extract_cmd, capture_output=True, text=True)
243
+ if result.returncode != 0:
244
+ print(f"[demucs] Failed to extract audio: {result.stderr[-200:]}")
245
+ return False
246
+
247
+ print(f"[demucs] Running music separation...")
248
+
249
+ import soundfile as sf
250
+ from demucs.pretrained import get_model
251
+ from demucs.apply import apply_model
252
+
253
+ # Load model (cached after first run)
254
+ model = get_model('htdemucs')
255
+ model.to('cuda')
256
+ model.eval()
257
+
258
+ # Load audio
259
+ data, sr = sf.read(str(audio_in))
260
+ wav = torch.from_numpy(data.T).float()
261
+ if wav.dim() == 1:
262
+ wav = wav.unsqueeze(0)
263
+
264
+ # Resample if needed
265
+ if sr != model.samplerate:
266
+ import torchaudio
267
+ wav = torchaudio.functional.resample(wav, sr, model.samplerate)
268
+
269
+ wav = wav.unsqueeze(0).to('cuda')
270
+
271
+ # Separate sources
272
+ with torch.no_grad():
273
+ sources = apply_model(model, wav, overlap=0.25, progress=False)
274
+
275
+ # Keep only vocals (index 3)
276
+ vocals = sources[0, 3].cpu()
277
+
278
+ # Save vocals
279
+ audio_out = tmpdir / "vocals.wav"
280
+ audio_np = vocals.numpy().T
281
+ sf.write(str(audio_out), audio_np, model.samplerate)
282
+
283
+ print(f"[demucs] Merging vocals back with video...")
284
+ merge_cmd = [
285
+ 'ffmpeg', '-y',
286
+ '-i', input_video_path,
287
+ '-i', str(audio_out),
288
+ '-c:v', 'copy',
289
+ '-map', '0:v:0', '-map', '1:a:0',
290
+ '-c:a', 'aac', '-b:a', '128k',
291
+ '-shortest',
292
+ output_video_path
293
+ ]
294
+ result = subprocess.run(merge_cmd, capture_output=True, text=True)
295
+ if result.returncode != 0:
296
+ print(f"[demucs] Failed to merge: {result.stderr[-200:]}")
297
+ return False
298
+
299
+ print(f"[demucs] Successfully removed music")
300
+ return True
301
+
302
+ except Exception as e:
303
+ print(f"[demucs] Error: {e}")
304
+ import traceback
305
+ traceback.print_exc()
306
+ return False
307
+
308
+
309
+ def apply_gaussian_blur(video_tensor: torch.Tensor, blur_amount: int) -> torch.Tensor:
310
+ """Apply Gaussian blur to video tensor. Video shape: [frames, H, W, C]"""
311
+ if blur_amount <= 0:
312
+ return video_tensor
313
+
314
+ from torchvision.transforms.functional import gaussian_blur
315
+
316
+ # Ensure kernel size is odd and at least 3
317
+ kernel_size = blur_amount * 2 + 1
318
+ sigma = blur_amount / 2.0
319
+
320
+ # Video tensor is [frames, H, W, C], but gaussian_blur expects [batch, C, H, W]
321
+ # Permute to [frames, C, H, W]
322
+ video_tensor = video_tensor.permute(0, 3, 1, 2)
323
+
324
+ blurred = gaussian_blur(video_tensor, kernel_size=[kernel_size, kernel_size], sigma=[sigma, sigma])
325
+
326
+ # Permute back to [frames, H, W, C]
327
+ blurred = blurred.permute(0, 2, 3, 1)
328
+
329
+ return blurred
330
+
331
+
332
+ @spaces.GPU(duration=90)
333
+ @torch.inference_mode()
334
+ def generate_video(
335
+ first_image,
336
+ last_image,
337
+ prompt: str,
338
+ duration: float,
339
+ enhance_prompt: bool = True,
340
+ seed: int = 42,
341
+ randomize_seed: bool = True,
342
+ height: int = 320,
343
+ width: int = 512,
344
+ negative_prompt: str = DEFAULT_NEGATIVE_PROMPT,
345
+ blur_amount: int = 0,
346
+ remove_music: bool = False,
347
+ prompt2: str = "",
348
+ prompt3: str = "",
349
+ progress=gr.Progress(track_tqdm=True),
350
+ ):
351
+ try:
352
+ torch.cuda.reset_peak_memory_stats()
353
+ log_memory("start")
354
+
355
+ current_seed = random.randint(0, MAX_SEED) if randomize_seed else int(seed)
356
+
357
+ frame_rate = DEFAULT_FRAME_RATE
358
+ num_frames = int(duration * frame_rate) + 1
359
+ num_frames = ((num_frames - 1 + 7) // 8) * 8 + 1
360
+
361
+ print(f"Generating: {height}x{width}, {num_frames} frames ({duration}s), seed={current_seed}")
362
+
363
+ images = []
364
+ output_dir = Path("outputs")
365
+ output_dir.mkdir(exist_ok=True)
366
+
367
+ if first_image is not None:
368
+ temp_first_path = output_dir / f"temp_first_{current_seed}.jpg"
369
+ if hasattr(first_image, "save"):
370
+ first_image.save(temp_first_path)
371
+ else:
372
+ temp_first_path = Path(first_image)
373
+ images.append(ImageConditioningInput(path=str(temp_first_path), frame_idx=0, strength=1.0))
374
+
375
+ if last_image is not None:
376
+ temp_last_path = output_dir / f"temp_last_{current_seed}.jpg"
377
+ if hasattr(last_image, "save"):
378
+ last_image.save(temp_last_path)
379
+ else:
380
+ temp_last_path = Path(last_image)
381
+ images.append(ImageConditioningInput(path=str(temp_last_path), frame_idx=num_frames - 1, strength=1.0))
382
+
383
+ from ltx_core.model.video_vae import TilingConfig, get_video_chunks_number
384
+
385
+ tiling_config = TilingConfig.default()
386
+ video_chunks_number = get_video_chunks_number(num_frames, tiling_config)
387
+
388
+ log_memory("before pipeline call")
389
+
390
+ # Run inference - DistilledPipeline has simpler API
391
+ video_frames_iter, audio = pipeline(
392
+ prompt=prompt,
393
+ seed=current_seed,
394
+ height=int(height),
395
+ width=int(width),
396
+ num_frames=num_frames,
397
+ frame_rate=frame_rate,
398
+ images=images,
399
+ enhance_prompt=enhance_prompt,
400
+ )
401
+
402
+ # Collect video frames
403
+ frames = [frame for frame in video_frames_iter]
404
+ video_tensor = torch.cat(frames, dim=0) if len(frames) > 1 else frames[0]
405
+
406
+ log_memory("after pipeline call")
407
+
408
+ # Apply Gaussian blur if requested (for censoring/teaser effect)
409
+ if blur_amount > 0:
410
+ print(f"Applying Gaussian blur (amount={blur_amount})...")
411
+ video_tensor = apply_gaussian_blur(video_tensor, blur_amount)
412
+ log_memory("after blur")
413
+
414
+ output_path = tempfile.mktemp(suffix=".mp4")
415
+ encode_video(
416
+ video=video_tensor,
417
+ fps=frame_rate,
418
+ audio=audio,
419
+ output_path=output_path,
420
+ video_chunks_number=video_chunks_number,
421
+ )
422
+
423
+ log_memory("after encode_video")
424
+
425
+ # Remove background music if requested
426
+ if remove_music:
427
+ print(f"Removing background music with Demucs...")
428
+ processed_path = tempfile.mktemp(suffix=".mp4")
429
+ success = remove_music_demucs(output_path, processed_path)
430
+ if success:
431
+ output_path = processed_path
432
+ log_memory("after demucs")
433
+ else:
434
+ print(f"Warning: Music removal failed, using original video")
435
+
436
+ # Generate additional clips if prompt2/prompt3 provided
437
+ video2_path = None
438
+ video3_path = None
439
+
440
+ if prompt2 and prompt2.strip():
441
+ print(f"[Clip 2] Generating with prompt2: {prompt2[:50]}...")
442
+ seed2 = current_seed + 1
443
+ video_frames_iter2, audio2 = pipeline(
444
+ prompt=prompt2.strip(),
445
+ seed=seed2,
446
+ height=int(height),
447
+ width=int(width),
448
+ num_frames=num_frames,
449
+ frame_rate=frame_rate,
450
+ images=images,
451
+ enhance_prompt=enhance_prompt,
452
+ )
453
+ frames2 = [frame for frame in video_frames_iter2]
454
+ video_tensor2 = torch.cat(frames2, dim=0) if len(frames2) > 1 else frames2[0]
455
+ if blur_amount > 0:
456
+ video_tensor2 = apply_gaussian_blur(video_tensor2, blur_amount)
457
+ video2_path = tempfile.mktemp(suffix=".mp4")
458
+ encode_video(video=video_tensor2, fps=frame_rate, audio=audio2, output_path=video2_path, video_chunks_number=video_chunks_number)
459
+ if remove_music:
460
+ processed2 = tempfile.mktemp(suffix=".mp4")
461
+ if remove_music_demucs(video2_path, processed2):
462
+ video2_path = processed2
463
+ log_memory("after clip 2")
464
+
465
+ if prompt3 and prompt3.strip():
466
+ print(f"[Clip 3] Generating with prompt3: {prompt3[:50]}...")
467
+ seed3 = current_seed + 2
468
+ video_frames_iter3, audio3 = pipeline(
469
+ prompt=prompt3.strip(),
470
+ seed=seed3,
471
+ height=int(height),
472
+ width=int(width),
473
+ num_frames=num_frames,
474
+ frame_rate=frame_rate,
475
+ images=images,
476
+ enhance_prompt=enhance_prompt,
477
+ )
478
+ frames3 = [frame for frame in video_frames_iter3]
479
+ video_tensor3 = torch.cat(frames3, dim=0) if len(frames3) > 1 else frames3[0]
480
+ if blur_amount > 0:
481
+ video_tensor3 = apply_gaussian_blur(video_tensor3, blur_amount)
482
+ video3_path = tempfile.mktemp(suffix=".mp4")
483
+ encode_video(video=video_tensor3, fps=frame_rate, audio=audio3, output_path=video3_path, video_chunks_number=video_chunks_number)
484
+ if remove_music:
485
+ processed3 = tempfile.mktemp(suffix=".mp4")
486
+ if remove_music_demucs(video3_path, processed3):
487
+ video3_path = processed3
488
+ log_memory("after clip 3")
489
+
490
+ return str(output_path), current_seed, video2_path, video3_path
491
+
492
+ except Exception as e:
493
+ import traceback
494
+ log_memory("on error")
495
+ print(f"Error: {str(e)}\n{traceback.format_exc()}")
496
+ return None, current_seed, None, None
497
+
498
+
499
+ with gr.Blocks(title="Element-8 Video", delete_cache=(3600, 7200)) as demo: # cleanup: check every 1h, delete files >2h old
500
+ gr.Markdown("# Element-8: Fast Video Generation with Frame Conditioning")
501
+ gr.Markdown(
502
+ "High quality video + audio generation with first and last frame conditioning. "
503
+ "Optimized fp8 model for faster inference. "
504
+ "[[code]](https://github.com/Lightricks/LTX-2)"
505
+ )
506
+
507
+ with gr.Row():
508
+ with gr.Column():
509
+ with gr.Row():
510
+ first_image = gr.Image(label="First Frame (Optional)", type="pil")
511
+ last_image = gr.Image(label="Last Frame (Optional)", type="pil")
512
+ prompt = gr.Textbox(
513
+ label="Prompt",
514
+ info="for best results - make it as elaborate as possible",
515
+ value="Make this image come alive with cinematic motion, smooth animation",
516
+ lines=3,
517
+ placeholder="Describe the motion and animation you want...",
518
+ )
519
+ duration = gr.Slider(label="Duration (seconds)", minimum=1.0, maximum=10.0, value=3.0, step=0.1)
520
+
521
+ generate_btn = gr.Button("Generate Video", variant="primary", size="lg")
522
+
523
+ with gr.Accordion("Advanced Settings", open=False):
524
+ seed = gr.Slider(label="Seed", minimum=0, maximum=MAX_SEED, value=10, step=1)
525
+ randomize_seed = gr.Checkbox(label="Randomize Seed", value=True)
526
+ with gr.Row():
527
+ width = gr.Number(label="Width", value=512, precision=0)
528
+ height = gr.Number(label="Height", value=320, precision=0)
529
+ with gr.Row():
530
+ enhance_prompt = gr.Checkbox(label="Enhance Prompt", value=False)
531
+ high_res = gr.Checkbox(label="High Resolution", value=False)
532
+ with gr.Row():
533
+ blur_amount = gr.Number(label="Blur (0=off, 36=heavy)", value=0, precision=0)
534
+ remove_music = gr.Checkbox(label="Remove Music", value=False)
535
+ negative_prompt = gr.Textbox(
536
+ label="Negative Prompt",
537
+ value=DEFAULT_NEGATIVE_PROMPT,
538
+ lines=3,
539
+ placeholder="What to avoid in the generated video...",
540
+ )
541
+
542
+ with gr.Column():
543
+ output_video = gr.Video(label="Generated Video", autoplay=True)
544
+ output_video2 = gr.Video(label="Generated Video 2", autoplay=True)
545
+ output_video3 = gr.Video(label="Generated Video 3", autoplay=True)
546
+
547
+ with gr.Row():
548
+ prompt2 = gr.Textbox(label="Prompt 2 (optional)", value="", lines=2)
549
+ prompt3 = gr.Textbox(label="Prompt 3 (optional)", value="", lines=2)
550
+
551
+ gr.Examples(
552
+ examples=[
553
+ [
554
+ None,
555
+ "pinkknit.jpg",
556
+ "The camera falls downward through darkness as if dropped into a tunnel. "
557
+ "As it slows, five friends wearing pink knitted hats and sunglasses lean "
558
+ "over and look down toward the camera with curious expressions. The lens "
559
+ "has a strong fisheye effect, creating a circular frame around them. They "
560
+ "crowd together closely, forming a symmetrical cluster while staring "
561
+ "directly into the lens.",
562
+ 3.0,
563
+ False,
564
+ 42,
565
+ True,
566
+ 1024,
567
+ 1024,
568
+ ],
569
+ ],
570
+ inputs=[
571
+ first_image, last_image, prompt, duration,
572
+ enhance_prompt, seed, randomize_seed, height, width,
573
+ ],
574
+ )
575
+
576
+ first_image.change(
577
+ fn=on_image_upload,
578
+ inputs=[first_image, last_image, high_res],
579
+ outputs=[width, height],
580
+ )
581
+
582
+ last_image.change(
583
+ fn=on_image_upload,
584
+ inputs=[first_image, last_image, high_res],
585
+ outputs=[width, height],
586
+ )
587
+
588
+ high_res.change(
589
+ fn=on_highres_toggle,
590
+ inputs=[first_image, last_image, high_res],
591
+ outputs=[width, height],
592
+ )
593
+
594
+ generate_btn.click(
595
+ fn=generate_video,
596
+ inputs=[
597
+ first_image, last_image, prompt, duration, enhance_prompt,
598
+ seed, randomize_seed, height, width, negative_prompt, blur_amount, remove_music,
599
+ prompt2, prompt3,
600
+ ],
601
+ outputs=[output_video, seed, output_video2, output_video3],
602
+ )
603
+
604
+
605
+ css = """
606
+ .fillable{max-width: 1200px !important}
607
+ """
608
+
609
+ if __name__ == "__main__":
610
+ demo.launch(theme=gr.themes.Citrus(), css=css)
pinkknit.jpg ADDED
requirements.txt ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ transformers==4.57.6
2
+ accelerate
3
+ torch==2.8.0
4
+ torchvision==0.23.0
5
+ hf_transfer
6
+ huggingface_hub[hf_xet]
7
+ einops
8
+ scipy
9
+ av
10
+ scikit-image>=0.25.2
11
+ flashpack==0.1.2
12
+ torchaudio==2.8.0
13
+ demucs
14
+ soundfile