Spaces:
Running on Zero
Running on Zero
Vicente Alvarez commited on
Commit ·
9c32fea
0
Parent(s):
Initial commit: Element-8 (vanilla LTX pre-distilled)
Browse files- .gitattributes +35 -0
- README.md +23 -0
- app.py +547 -0
- pinkknit.jpg +0 -0
- 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,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: Element-8 Video
|
| 3 |
+
emoji: 🌬️
|
| 4 |
+
colorFrom: blue
|
| 5 |
+
colorTo: indigo
|
| 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 pre-distilled LTX
|
| 12 |
+
---
|
| 13 |
+
|
| 14 |
+
# Element-8 Video Generator
|
| 15 |
+
|
| 16 |
+
Fast video + audio generation with first and last frame conditioning. Uses pre-distilled LTX model for efficient inference.
|
| 17 |
+
|
| 18 |
+
## Features
|
| 19 |
+
- First/Last frame conditioning
|
| 20 |
+
- Auto-generated audio
|
| 21 |
+
- Gaussian blur (censoring)
|
| 22 |
+
- Music removal (Demucs)
|
| 23 |
+
- Pre-distilled for fast generation
|
app.py
ADDED
|
@@ -0,0 +1,547 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
progress=gr.Progress(track_tqdm=True),
|
| 348 |
+
):
|
| 349 |
+
try:
|
| 350 |
+
torch.cuda.reset_peak_memory_stats()
|
| 351 |
+
log_memory("start")
|
| 352 |
+
|
| 353 |
+
current_seed = random.randint(0, MAX_SEED) if randomize_seed else int(seed)
|
| 354 |
+
|
| 355 |
+
frame_rate = DEFAULT_FRAME_RATE
|
| 356 |
+
num_frames = int(duration * frame_rate) + 1
|
| 357 |
+
num_frames = ((num_frames - 1 + 7) // 8) * 8 + 1
|
| 358 |
+
|
| 359 |
+
print(f"Generating: {height}x{width}, {num_frames} frames ({duration}s), seed={current_seed}")
|
| 360 |
+
|
| 361 |
+
images = []
|
| 362 |
+
output_dir = Path("outputs")
|
| 363 |
+
output_dir.mkdir(exist_ok=True)
|
| 364 |
+
|
| 365 |
+
if first_image is not None:
|
| 366 |
+
temp_first_path = output_dir / f"temp_first_{current_seed}.jpg"
|
| 367 |
+
if hasattr(first_image, "save"):
|
| 368 |
+
first_image.save(temp_first_path)
|
| 369 |
+
else:
|
| 370 |
+
temp_first_path = Path(first_image)
|
| 371 |
+
images.append(ImageConditioningInput(path=str(temp_first_path), frame_idx=0, strength=1.0))
|
| 372 |
+
|
| 373 |
+
if last_image is not None:
|
| 374 |
+
temp_last_path = output_dir / f"temp_last_{current_seed}.jpg"
|
| 375 |
+
if hasattr(last_image, "save"):
|
| 376 |
+
last_image.save(temp_last_path)
|
| 377 |
+
else:
|
| 378 |
+
temp_last_path = Path(last_image)
|
| 379 |
+
images.append(ImageConditioningInput(path=str(temp_last_path), frame_idx=num_frames - 1, strength=1.0))
|
| 380 |
+
|
| 381 |
+
from ltx_core.model.video_vae import TilingConfig, get_video_chunks_number
|
| 382 |
+
|
| 383 |
+
tiling_config = TilingConfig.default()
|
| 384 |
+
video_chunks_number = get_video_chunks_number(num_frames, tiling_config)
|
| 385 |
+
|
| 386 |
+
log_memory("before pipeline call")
|
| 387 |
+
|
| 388 |
+
# Run inference - DistilledPipeline has simpler API
|
| 389 |
+
video_frames_iter, audio = pipeline(
|
| 390 |
+
prompt=prompt,
|
| 391 |
+
seed=current_seed,
|
| 392 |
+
height=int(height),
|
| 393 |
+
width=int(width),
|
| 394 |
+
num_frames=num_frames,
|
| 395 |
+
frame_rate=frame_rate,
|
| 396 |
+
images=images,
|
| 397 |
+
enhance_prompt=enhance_prompt,
|
| 398 |
+
)
|
| 399 |
+
|
| 400 |
+
# Collect video frames
|
| 401 |
+
frames = [frame for frame in video_frames_iter]
|
| 402 |
+
video_tensor = torch.cat(frames, dim=0) if len(frames) > 1 else frames[0]
|
| 403 |
+
|
| 404 |
+
log_memory("after pipeline call")
|
| 405 |
+
|
| 406 |
+
# Apply Gaussian blur if requested (for censoring/teaser effect)
|
| 407 |
+
if blur_amount > 0:
|
| 408 |
+
print(f"Applying Gaussian blur (amount={blur_amount})...")
|
| 409 |
+
video_tensor = apply_gaussian_blur(video_tensor, blur_amount)
|
| 410 |
+
log_memory("after blur")
|
| 411 |
+
|
| 412 |
+
output_path = tempfile.mktemp(suffix=".mp4")
|
| 413 |
+
encode_video(
|
| 414 |
+
video=video_tensor,
|
| 415 |
+
fps=frame_rate,
|
| 416 |
+
audio=audio,
|
| 417 |
+
output_path=output_path,
|
| 418 |
+
video_chunks_number=video_chunks_number,
|
| 419 |
+
)
|
| 420 |
+
|
| 421 |
+
log_memory("after encode_video")
|
| 422 |
+
|
| 423 |
+
# Remove background music if requested
|
| 424 |
+
if remove_music:
|
| 425 |
+
print(f"Removing background music with Demucs...")
|
| 426 |
+
processed_path = tempfile.mktemp(suffix=".mp4")
|
| 427 |
+
success = remove_music_demucs(output_path, processed_path)
|
| 428 |
+
if success:
|
| 429 |
+
output_path = processed_path
|
| 430 |
+
log_memory("after demucs")
|
| 431 |
+
else:
|
| 432 |
+
print(f"Warning: Music removal failed, using original video")
|
| 433 |
+
|
| 434 |
+
return str(output_path), current_seed
|
| 435 |
+
|
| 436 |
+
except Exception as e:
|
| 437 |
+
import traceback
|
| 438 |
+
log_memory("on error")
|
| 439 |
+
print(f"Error: {str(e)}\n{traceback.format_exc()}")
|
| 440 |
+
return None, current_seed
|
| 441 |
+
|
| 442 |
+
|
| 443 |
+
with gr.Blocks(title="Element-8 Video", delete_cache=(3600, 7200)) as demo: # cleanup: check every 1h, delete files >2h old
|
| 444 |
+
gr.Markdown("# Element-8: Fast Video Generation with Frame Conditioning")
|
| 445 |
+
gr.Markdown(
|
| 446 |
+
"High quality video + audio generation with first and last frame conditioning. "
|
| 447 |
+
"Pre-distilled LTX model for fast inference. "
|
| 448 |
+
"[[code]](https://github.com/Lightricks/LTX-2)"
|
| 449 |
+
)
|
| 450 |
+
|
| 451 |
+
with gr.Row():
|
| 452 |
+
with gr.Column():
|
| 453 |
+
with gr.Row():
|
| 454 |
+
first_image = gr.Image(label="First Frame (Optional)", type="pil")
|
| 455 |
+
last_image = gr.Image(label="Last Frame (Optional)", type="pil")
|
| 456 |
+
prompt = gr.Textbox(
|
| 457 |
+
label="Prompt",
|
| 458 |
+
info="for best results - make it as elaborate as possible",
|
| 459 |
+
value="Make this image come alive with cinematic motion, smooth animation",
|
| 460 |
+
lines=3,
|
| 461 |
+
placeholder="Describe the motion and animation you want...",
|
| 462 |
+
)
|
| 463 |
+
duration = gr.Slider(label="Duration (seconds)", minimum=1.0, maximum=10.0, value=3.0, step=0.1)
|
| 464 |
+
|
| 465 |
+
generate_btn = gr.Button("Generate Video", variant="primary", size="lg")
|
| 466 |
+
|
| 467 |
+
with gr.Accordion("Advanced Settings", open=False):
|
| 468 |
+
seed = gr.Slider(label="Seed", minimum=0, maximum=MAX_SEED, value=10, step=1)
|
| 469 |
+
randomize_seed = gr.Checkbox(label="Randomize Seed", value=True)
|
| 470 |
+
with gr.Row():
|
| 471 |
+
width = gr.Number(label="Width", value=512, precision=0)
|
| 472 |
+
height = gr.Number(label="Height", value=320, precision=0)
|
| 473 |
+
with gr.Row():
|
| 474 |
+
enhance_prompt = gr.Checkbox(label="Enhance Prompt", value=False)
|
| 475 |
+
high_res = gr.Checkbox(label="High Resolution", value=False)
|
| 476 |
+
with gr.Row():
|
| 477 |
+
blur_amount = gr.Number(label="Blur (0=off, 36=heavy)", value=0, precision=0)
|
| 478 |
+
remove_music = gr.Checkbox(label="Remove Music", value=False)
|
| 479 |
+
negative_prompt = gr.Textbox(
|
| 480 |
+
label="Negative Prompt",
|
| 481 |
+
value=DEFAULT_NEGATIVE_PROMPT,
|
| 482 |
+
lines=3,
|
| 483 |
+
placeholder="What to avoid in the generated video...",
|
| 484 |
+
)
|
| 485 |
+
|
| 486 |
+
with gr.Column():
|
| 487 |
+
output_video = gr.Video(label="Generated Video", autoplay=True)
|
| 488 |
+
|
| 489 |
+
gr.Examples(
|
| 490 |
+
examples=[
|
| 491 |
+
[
|
| 492 |
+
None,
|
| 493 |
+
"pinkknit.jpg",
|
| 494 |
+
"The camera falls downward through darkness as if dropped into a tunnel. "
|
| 495 |
+
"As it slows, five friends wearing pink knitted hats and sunglasses lean "
|
| 496 |
+
"over and look down toward the camera with curious expressions. The lens "
|
| 497 |
+
"has a strong fisheye effect, creating a circular frame around them. They "
|
| 498 |
+
"crowd together closely, forming a symmetrical cluster while staring "
|
| 499 |
+
"directly into the lens.",
|
| 500 |
+
3.0,
|
| 501 |
+
False,
|
| 502 |
+
42,
|
| 503 |
+
True,
|
| 504 |
+
1024,
|
| 505 |
+
1024,
|
| 506 |
+
],
|
| 507 |
+
],
|
| 508 |
+
inputs=[
|
| 509 |
+
first_image, last_image, prompt, duration,
|
| 510 |
+
enhance_prompt, seed, randomize_seed, height, width,
|
| 511 |
+
],
|
| 512 |
+
)
|
| 513 |
+
|
| 514 |
+
first_image.change(
|
| 515 |
+
fn=on_image_upload,
|
| 516 |
+
inputs=[first_image, last_image, high_res],
|
| 517 |
+
outputs=[width, height],
|
| 518 |
+
)
|
| 519 |
+
|
| 520 |
+
last_image.change(
|
| 521 |
+
fn=on_image_upload,
|
| 522 |
+
inputs=[first_image, last_image, high_res],
|
| 523 |
+
outputs=[width, height],
|
| 524 |
+
)
|
| 525 |
+
|
| 526 |
+
high_res.change(
|
| 527 |
+
fn=on_highres_toggle,
|
| 528 |
+
inputs=[first_image, last_image, high_res],
|
| 529 |
+
outputs=[width, height],
|
| 530 |
+
)
|
| 531 |
+
|
| 532 |
+
generate_btn.click(
|
| 533 |
+
fn=generate_video,
|
| 534 |
+
inputs=[
|
| 535 |
+
first_image, last_image, prompt, duration, enhance_prompt,
|
| 536 |
+
seed, randomize_seed, height, width, negative_prompt, blur_amount, remove_music,
|
| 537 |
+
],
|
| 538 |
+
outputs=[output_video, seed],
|
| 539 |
+
)
|
| 540 |
+
|
| 541 |
+
|
| 542 |
+
css = """
|
| 543 |
+
.fillable{max-width: 1200px !important}
|
| 544 |
+
"""
|
| 545 |
+
|
| 546 |
+
if __name__ == "__main__":
|
| 547 |
+
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
|