Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files
app.py
CHANGED
|
@@ -6,6 +6,9 @@ import sys
|
|
| 6 |
os.environ["TORCH_COMPILE_DISABLE"] = "1"
|
| 7 |
os.environ["TORCHDYNAMO_DISABLE"] = "1"
|
| 8 |
|
|
|
|
|
|
|
|
|
|
| 9 |
# Clone LTX-2 repo and install packages
|
| 10 |
LTX_REPO_URL = "https://github.com/Lightricks/LTX-2.git"
|
| 11 |
LTX_REPO_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "LTX-2")
|
|
@@ -37,17 +40,24 @@ torch._dynamo.config.disable = True
|
|
| 37 |
import spaces
|
| 38 |
import gradio as gr
|
| 39 |
import numpy as np
|
| 40 |
-
from
|
| 41 |
-
from huggingface_hub import hf_hub_download
|
| 42 |
|
| 43 |
from ltx_core.model.video_vae import TilingConfig, get_video_chunks_number
|
| 44 |
from ltx_core.quantization import QuantizationPolicy
|
| 45 |
-
from ltx_core.text_encoders.gemma.embeddings_processor import EmbeddingsProcessorOutput
|
| 46 |
-
import ltx_pipelines.distilled as distilled_module
|
| 47 |
from ltx_pipelines.distilled import DistilledPipeline
|
| 48 |
from ltx_pipelines.utils.args import ImageConditioningInput
|
| 49 |
from ltx_pipelines.utils.media_io import encode_video
|
| 50 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
logging.getLogger().setLevel(logging.INFO)
|
| 52 |
|
| 53 |
MAX_SEED = np.iinfo(np.int32).max
|
|
@@ -55,68 +65,63 @@ DEFAULT_PROMPT = (
|
|
| 55 |
"An astronaut hatches from a fragile egg on the surface of the Moon, "
|
| 56 |
"the shell cracking and peeling apart in gentle low-gravity motion. "
|
| 57 |
"Fine lunar dust lifts and drifts outward with each movement, floating "
|
| 58 |
-
"in slow arcs before settling back onto the ground.
|
| 59 |
-
"free in a deliberate, weightless motion, small fragments of the egg "
|
| 60 |
-
"tumbling and spinning through the air."
|
| 61 |
)
|
| 62 |
-
DEFAULT_HEIGHT = 1024
|
| 63 |
-
DEFAULT_WIDTH = 1536
|
| 64 |
DEFAULT_FRAME_RATE = 24.0
|
| 65 |
|
| 66 |
-
#
|
| 67 |
-
|
|
|
|
|
|
|
|
|
|
| 68 |
|
| 69 |
-
#
|
| 70 |
-
|
|
|
|
| 71 |
|
| 72 |
# Download model checkpoints
|
| 73 |
print("=" * 80)
|
| 74 |
-
print("Downloading LTX-2.3 distilled model...")
|
| 75 |
print("=" * 80)
|
| 76 |
|
| 77 |
checkpoint_path = hf_hub_download(repo_id=LTX_MODEL_REPO, filename="ltx-2.3-22b-distilled.safetensors")
|
| 78 |
spatial_upsampler_path = hf_hub_download(repo_id=LTX_MODEL_REPO, filename="ltx-2.3-spatial-upscaler-x2-1.0.safetensors")
|
|
|
|
| 79 |
|
| 80 |
print(f"Checkpoint: {checkpoint_path}")
|
| 81 |
print(f"Spatial upsampler: {spatial_upsampler_path}")
|
|
|
|
| 82 |
|
| 83 |
-
# Initialize pipeline
|
| 84 |
-
# Text encoding will be done by external space
|
| 85 |
pipeline = DistilledPipeline(
|
| 86 |
distilled_checkpoint_path=checkpoint_path,
|
| 87 |
spatial_upsampler_path=spatial_upsampler_path,
|
| 88 |
-
gemma_root=
|
| 89 |
loras=[],
|
| 90 |
quantization=QuantizationPolicy.fp8_cast(),
|
| 91 |
)
|
| 92 |
|
| 93 |
-
# Preload
|
| 94 |
-
|
| 95 |
-
# it between stages (FP8 upcast doubles it to ~44GB during forward pass).
|
| 96 |
-
# Keeping it cached prevents cleanup_memory() from freeing it.
|
| 97 |
-
print("Preloading small models...")
|
| 98 |
ledger = pipeline.model_ledger
|
|
|
|
| 99 |
_video_encoder = ledger.video_encoder()
|
| 100 |
_video_decoder = ledger.video_decoder()
|
| 101 |
_audio_decoder = ledger.audio_decoder()
|
| 102 |
_vocoder = ledger.vocoder()
|
| 103 |
_spatial_upsampler = ledger.spatial_upsampler()
|
|
|
|
|
|
|
| 104 |
|
|
|
|
| 105 |
ledger.video_encoder = lambda: _video_encoder
|
| 106 |
ledger.video_decoder = lambda: _video_decoder
|
| 107 |
ledger.audio_decoder = lambda: _audio_decoder
|
| 108 |
ledger.vocoder = lambda: _vocoder
|
| 109 |
ledger.spatial_upsampler = lambda: _spatial_upsampler
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
print(f"Connecting to text encoder space: {TEXT_ENCODER_SPACE}")
|
| 114 |
-
try:
|
| 115 |
-
text_encoder_client = Client(TEXT_ENCODER_SPACE)
|
| 116 |
-
print("Text encoder client connected!")
|
| 117 |
-
except Exception as e:
|
| 118 |
-
print(f"Warning: Could not connect to text encoder space: {e}")
|
| 119 |
-
text_encoder_client = None
|
| 120 |
|
| 121 |
print("=" * 80)
|
| 122 |
print("Pipeline ready!")
|
|
@@ -124,20 +129,46 @@ print("=" * 80)
|
|
| 124 |
|
| 125 |
|
| 126 |
def log_memory(tag: str):
|
| 127 |
-
"""Log GPU memory usage at a given point."""
|
| 128 |
if torch.cuda.is_available():
|
| 129 |
allocated = torch.cuda.memory_allocated() / 1024**3
|
| 130 |
-
reserved = torch.cuda.memory_reserved() / 1024**3
|
| 131 |
peak = torch.cuda.max_memory_allocated() / 1024**3
|
| 132 |
free, total = torch.cuda.mem_get_info()
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 136 |
else:
|
| 137 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 138 |
|
| 139 |
|
| 140 |
-
@spaces.GPU(duration=
|
|
|
|
| 141 |
def generate_video(
|
| 142 |
input_image,
|
| 143 |
prompt: str,
|
|
@@ -145,11 +176,10 @@ def generate_video(
|
|
| 145 |
enhance_prompt: bool = True,
|
| 146 |
seed: int = 42,
|
| 147 |
randomize_seed: bool = True,
|
| 148 |
-
height: int =
|
| 149 |
-
width: int =
|
| 150 |
progress=gr.Progress(track_tqdm=True),
|
| 151 |
):
|
| 152 |
-
"""Generate a video based on the given parameters."""
|
| 153 |
try:
|
| 154 |
torch.cuda.reset_peak_memory_stats()
|
| 155 |
log_memory("start")
|
|
@@ -158,14 +188,11 @@ def generate_video(
|
|
| 158 |
|
| 159 |
frame_rate = DEFAULT_FRAME_RATE
|
| 160 |
num_frames = int(duration * frame_rate) + 1
|
| 161 |
-
# 8k+1 format
|
| 162 |
num_frames = ((num_frames - 1 + 7) // 8) * 8 + 1
|
| 163 |
|
| 164 |
print(f"Generating: {height}x{width}, {num_frames} frames ({duration}s), seed={current_seed}")
|
| 165 |
|
| 166 |
-
# Handle image input
|
| 167 |
images = []
|
| 168 |
-
temp_image_path = None
|
| 169 |
if input_image is not None:
|
| 170 |
output_dir = Path("outputs")
|
| 171 |
output_dir.mkdir(exist_ok=True)
|
|
@@ -176,103 +203,49 @@ def generate_video(
|
|
| 176 |
temp_image_path = Path(input_image)
|
| 177 |
images = [ImageConditioningInput(path=str(temp_image_path), frame_idx=0, strength=1.0)]
|
| 178 |
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
prompt=prompt,
|
| 195 |
-
enhance_prompt=enhance_prompt,
|
| 196 |
-
input_image=image_input,
|
| 197 |
-
seed=current_seed,
|
| 198 |
-
negative_prompt="",
|
| 199 |
-
api_name="/encode_prompt",
|
| 200 |
-
)
|
| 201 |
-
embedding_path = result[0]
|
| 202 |
-
print(f"Embeddings received from: {embedding_path}")
|
| 203 |
-
|
| 204 |
-
embeddings = torch.load(embedding_path)
|
| 205 |
-
video_context = embeddings["video_context"].to("cuda")
|
| 206 |
-
audio_context = embeddings["audio_context"]
|
| 207 |
-
if audio_context is not None:
|
| 208 |
-
audio_context = audio_context.to("cuda")
|
| 209 |
-
print("Embeddings loaded successfully")
|
| 210 |
-
log_memory("after embeddings loaded")
|
| 211 |
-
except Exception as e:
|
| 212 |
-
raise RuntimeError(
|
| 213 |
-
f"Failed to get embeddings from text encoder space: {e}\n"
|
| 214 |
-
f"Please ensure {TEXT_ENCODER_SPACE} is running properly."
|
| 215 |
-
)
|
| 216 |
-
|
| 217 |
-
# Monkey-patch encode_prompts on the distilled module directly
|
| 218 |
-
# (it imports encode_prompts from helpers, so we must patch the local reference)
|
| 219 |
-
precomputed = EmbeddingsProcessorOutput(
|
| 220 |
-
video_encoding=video_context,
|
| 221 |
-
audio_encoding=audio_context,
|
| 222 |
-
attention_mask=torch.ones(1, device="cuda"), # dummy mask
|
| 223 |
)
|
| 224 |
-
original_encode_prompts = distilled_module.encode_prompts
|
| 225 |
-
distilled_module.encode_prompts = lambda *args, **kwargs: [precomputed]
|
| 226 |
-
|
| 227 |
-
try:
|
| 228 |
-
tiling_config = TilingConfig.default()
|
| 229 |
-
video_chunks_number = get_video_chunks_number(num_frames, tiling_config)
|
| 230 |
-
|
| 231 |
-
log_memory("before pipeline call")
|
| 232 |
-
|
| 233 |
-
video, audio = pipeline(
|
| 234 |
-
prompt=prompt,
|
| 235 |
-
seed=current_seed,
|
| 236 |
-
height=height,
|
| 237 |
-
width=width,
|
| 238 |
-
num_frames=num_frames,
|
| 239 |
-
frame_rate=frame_rate,
|
| 240 |
-
images=images,
|
| 241 |
-
tiling_config=tiling_config,
|
| 242 |
-
enhance_prompt=False, # Already enhanced by text encoder space
|
| 243 |
-
)
|
| 244 |
|
| 245 |
-
|
| 246 |
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
log_memory("after encode_video")
|
| 257 |
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
# Restore original encode_prompts
|
| 261 |
-
distilled_module.encode_prompts = original_encode_prompts
|
| 262 |
|
| 263 |
except Exception as e:
|
| 264 |
import traceback
|
| 265 |
log_memory("on error")
|
| 266 |
-
|
| 267 |
-
print(error_msg)
|
| 268 |
return None, current_seed
|
| 269 |
|
| 270 |
|
| 271 |
with gr.Blocks(title="LTX-2.3 Distilled") as demo:
|
| 272 |
gr.Markdown("# LTX-2.3 Distilled (22B): Fast Audio-Video Generation")
|
| 273 |
gr.Markdown(
|
| 274 |
-
"Fast video + audio generation
|
| 275 |
-
"[[model]](https://huggingface.co/Lightricks/LTX-2) "
|
| 276 |
"[[code]](https://github.com/Lightricks/LTX-2)"
|
| 277 |
)
|
| 278 |
|
|
@@ -286,9 +259,12 @@ with gr.Blocks(title="LTX-2.3 Distilled") as demo:
|
|
| 286 |
lines=3,
|
| 287 |
placeholder="Describe the motion and animation you want...",
|
| 288 |
)
|
|
|
|
| 289 |
with gr.Row():
|
| 290 |
duration = gr.Slider(label="Duration (seconds)", minimum=1.0, maximum=10.0, value=3.0, step=0.1)
|
| 291 |
-
|
|
|
|
|
|
|
| 292 |
|
| 293 |
generate_btn = gr.Button("Generate Video", variant="primary", size="lg")
|
| 294 |
|
|
@@ -296,12 +272,26 @@ with gr.Blocks(title="LTX-2.3 Distilled") as demo:
|
|
| 296 |
seed = gr.Slider(label="Seed", minimum=0, maximum=MAX_SEED, value=10, step=1)
|
| 297 |
randomize_seed = gr.Checkbox(label="Randomize Seed", value=True)
|
| 298 |
with gr.Row():
|
| 299 |
-
width = gr.Number(label="Width", value=
|
| 300 |
-
height = gr.Number(label="Height", value=
|
| 301 |
|
| 302 |
with gr.Column():
|
| 303 |
output_video = gr.Video(label="Generated Video", autoplay=True)
|
| 304 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 305 |
generate_btn.click(
|
| 306 |
fn=generate_video,
|
| 307 |
inputs=[
|
|
@@ -313,7 +303,7 @@ with gr.Blocks(title="LTX-2.3 Distilled") as demo:
|
|
| 313 |
|
| 314 |
|
| 315 |
css = """
|
| 316 |
-
.
|
| 317 |
"""
|
| 318 |
|
| 319 |
if __name__ == "__main__":
|
|
|
|
| 6 |
os.environ["TORCH_COMPILE_DISABLE"] = "1"
|
| 7 |
os.environ["TORCHDYNAMO_DISABLE"] = "1"
|
| 8 |
|
| 9 |
+
# Install xformers for memory-efficient attention
|
| 10 |
+
subprocess.run([sys.executable, "-m", "pip", "install", "xformers==0.0.32.post2", "--no-build-isolation"], check=False)
|
| 11 |
+
|
| 12 |
# Clone LTX-2 repo and install packages
|
| 13 |
LTX_REPO_URL = "https://github.com/Lightricks/LTX-2.git"
|
| 14 |
LTX_REPO_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "LTX-2")
|
|
|
|
| 40 |
import spaces
|
| 41 |
import gradio as gr
|
| 42 |
import numpy as np
|
| 43 |
+
from huggingface_hub import hf_hub_download, snapshot_download
|
|
|
|
| 44 |
|
| 45 |
from ltx_core.model.video_vae import TilingConfig, get_video_chunks_number
|
| 46 |
from ltx_core.quantization import QuantizationPolicy
|
|
|
|
|
|
|
| 47 |
from ltx_pipelines.distilled import DistilledPipeline
|
| 48 |
from ltx_pipelines.utils.args import ImageConditioningInput
|
| 49 |
from ltx_pipelines.utils.media_io import encode_video
|
| 50 |
|
| 51 |
+
# Force-patch xformers attention into the LTX attention module.
|
| 52 |
+
from ltx_core.model.transformer import attention as _attn_mod
|
| 53 |
+
print(f"[ATTN] Before patch: memory_efficient_attention={_attn_mod.memory_efficient_attention}")
|
| 54 |
+
try:
|
| 55 |
+
from xformers.ops import memory_efficient_attention as _mea
|
| 56 |
+
_attn_mod.memory_efficient_attention = _mea
|
| 57 |
+
print(f"[ATTN] After patch: memory_efficient_attention={_attn_mod.memory_efficient_attention}")
|
| 58 |
+
except Exception as e:
|
| 59 |
+
print(f"[ATTN] xformers patch FAILED: {type(e).__name__}: {e}")
|
| 60 |
+
|
| 61 |
logging.getLogger().setLevel(logging.INFO)
|
| 62 |
|
| 63 |
MAX_SEED = np.iinfo(np.int32).max
|
|
|
|
| 65 |
"An astronaut hatches from a fragile egg on the surface of the Moon, "
|
| 66 |
"the shell cracking and peeling apart in gentle low-gravity motion. "
|
| 67 |
"Fine lunar dust lifts and drifts outward with each movement, floating "
|
| 68 |
+
"in slow arcs before settling back onto the ground."
|
|
|
|
|
|
|
| 69 |
)
|
|
|
|
|
|
|
| 70 |
DEFAULT_FRAME_RATE = 24.0
|
| 71 |
|
| 72 |
+
# Resolution presets: (width, height)
|
| 73 |
+
RESOLUTIONS = {
|
| 74 |
+
"high": {"16:9": (1536, 1024), "9:16": (1024, 1536), "1:1": (1024, 1024)},
|
| 75 |
+
"low": {"16:9": (768, 512), "9:16": (512, 768), "1:1": (768, 768)},
|
| 76 |
+
}
|
| 77 |
|
| 78 |
+
# Model repos
|
| 79 |
+
LTX_MODEL_REPO = "diffusers-internal-dev/ltx-23"
|
| 80 |
+
GEMMA_REPO = "google/gemma-3-12b-it-qat-q4_0-unquantized"
|
| 81 |
|
| 82 |
# Download model checkpoints
|
| 83 |
print("=" * 80)
|
| 84 |
+
print("Downloading LTX-2.3 distilled model + Gemma...")
|
| 85 |
print("=" * 80)
|
| 86 |
|
| 87 |
checkpoint_path = hf_hub_download(repo_id=LTX_MODEL_REPO, filename="ltx-2.3-22b-distilled.safetensors")
|
| 88 |
spatial_upsampler_path = hf_hub_download(repo_id=LTX_MODEL_REPO, filename="ltx-2.3-spatial-upscaler-x2-1.0.safetensors")
|
| 89 |
+
gemma_root = snapshot_download(repo_id=GEMMA_REPO)
|
| 90 |
|
| 91 |
print(f"Checkpoint: {checkpoint_path}")
|
| 92 |
print(f"Spatial upsampler: {spatial_upsampler_path}")
|
| 93 |
+
print(f"Gemma root: {gemma_root}")
|
| 94 |
|
| 95 |
+
# Initialize pipeline WITH text encoder
|
|
|
|
| 96 |
pipeline = DistilledPipeline(
|
| 97 |
distilled_checkpoint_path=checkpoint_path,
|
| 98 |
spatial_upsampler_path=spatial_upsampler_path,
|
| 99 |
+
gemma_root=gemma_root,
|
| 100 |
loras=[],
|
| 101 |
quantization=QuantizationPolicy.fp8_cast(),
|
| 102 |
)
|
| 103 |
|
| 104 |
+
# Preload all models for ZeroGPU tensor packing.
|
| 105 |
+
print("Preloading all models (including Gemma)...")
|
|
|
|
|
|
|
|
|
|
| 106 |
ledger = pipeline.model_ledger
|
| 107 |
+
_transformer = ledger.transformer()
|
| 108 |
_video_encoder = ledger.video_encoder()
|
| 109 |
_video_decoder = ledger.video_decoder()
|
| 110 |
_audio_decoder = ledger.audio_decoder()
|
| 111 |
_vocoder = ledger.vocoder()
|
| 112 |
_spatial_upsampler = ledger.spatial_upsampler()
|
| 113 |
+
_text_encoder = ledger.text_encoder()
|
| 114 |
+
_embeddings_processor = ledger.gemma_embeddings_processor()
|
| 115 |
|
| 116 |
+
ledger.transformer = lambda: _transformer
|
| 117 |
ledger.video_encoder = lambda: _video_encoder
|
| 118 |
ledger.video_decoder = lambda: _video_decoder
|
| 119 |
ledger.audio_decoder = lambda: _audio_decoder
|
| 120 |
ledger.vocoder = lambda: _vocoder
|
| 121 |
ledger.spatial_upsampler = lambda: _spatial_upsampler
|
| 122 |
+
ledger.text_encoder = lambda: _text_encoder
|
| 123 |
+
ledger.gemma_embeddings_processor = lambda: _embeddings_processor
|
| 124 |
+
print("All models preloaded (including Gemma text encoder)!")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 125 |
|
| 126 |
print("=" * 80)
|
| 127 |
print("Pipeline ready!")
|
|
|
|
| 129 |
|
| 130 |
|
| 131 |
def log_memory(tag: str):
|
|
|
|
| 132 |
if torch.cuda.is_available():
|
| 133 |
allocated = torch.cuda.memory_allocated() / 1024**3
|
|
|
|
| 134 |
peak = torch.cuda.max_memory_allocated() / 1024**3
|
| 135 |
free, total = torch.cuda.mem_get_info()
|
| 136 |
+
print(f"[VRAM {tag}] allocated={allocated:.2f}GB peak={peak:.2f}GB free={free / 1024**3:.2f}GB total={total / 1024**3:.2f}GB")
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def detect_aspect_ratio(image) -> str:
|
| 140 |
+
"""Detect the closest aspect ratio (16:9, 9:16, or 1:1) from an image."""
|
| 141 |
+
if image is None:
|
| 142 |
+
return "16:9"
|
| 143 |
+
if hasattr(image, "size"):
|
| 144 |
+
w, h = image.size
|
| 145 |
+
elif hasattr(image, "shape"):
|
| 146 |
+
h, w = image.shape[:2]
|
| 147 |
else:
|
| 148 |
+
return "16:9"
|
| 149 |
+
ratio = w / h
|
| 150 |
+
candidates = {"16:9": 16 / 9, "9:16": 9 / 16, "1:1": 1.0}
|
| 151 |
+
return min(candidates, key=lambda k: abs(ratio - candidates[k]))
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def on_image_upload(image, high_res):
|
| 155 |
+
"""Auto-set resolution when image is uploaded."""
|
| 156 |
+
aspect = detect_aspect_ratio(image)
|
| 157 |
+
tier = "high" if high_res else "low"
|
| 158 |
+
w, h = RESOLUTIONS[tier][aspect]
|
| 159 |
+
return gr.update(value=w), gr.update(value=h)
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def on_highres_toggle(image, high_res):
|
| 163 |
+
"""Update resolution when high-res toggle changes."""
|
| 164 |
+
aspect = detect_aspect_ratio(image)
|
| 165 |
+
tier = "high" if high_res else "low"
|
| 166 |
+
w, h = RESOLUTIONS[tier][aspect]
|
| 167 |
+
return gr.update(value=w), gr.update(value=h)
|
| 168 |
|
| 169 |
|
| 170 |
+
@spaces.GPU(duration=300, size="xlarge")
|
| 171 |
+
@torch.inference_mode()
|
| 172 |
def generate_video(
|
| 173 |
input_image,
|
| 174 |
prompt: str,
|
|
|
|
| 176 |
enhance_prompt: bool = True,
|
| 177 |
seed: int = 42,
|
| 178 |
randomize_seed: bool = True,
|
| 179 |
+
height: int = 1024,
|
| 180 |
+
width: int = 1536,
|
| 181 |
progress=gr.Progress(track_tqdm=True),
|
| 182 |
):
|
|
|
|
| 183 |
try:
|
| 184 |
torch.cuda.reset_peak_memory_stats()
|
| 185 |
log_memory("start")
|
|
|
|
| 188 |
|
| 189 |
frame_rate = DEFAULT_FRAME_RATE
|
| 190 |
num_frames = int(duration * frame_rate) + 1
|
|
|
|
| 191 |
num_frames = ((num_frames - 1 + 7) // 8) * 8 + 1
|
| 192 |
|
| 193 |
print(f"Generating: {height}x{width}, {num_frames} frames ({duration}s), seed={current_seed}")
|
| 194 |
|
|
|
|
| 195 |
images = []
|
|
|
|
| 196 |
if input_image is not None:
|
| 197 |
output_dir = Path("outputs")
|
| 198 |
output_dir.mkdir(exist_ok=True)
|
|
|
|
| 203 |
temp_image_path = Path(input_image)
|
| 204 |
images = [ImageConditioningInput(path=str(temp_image_path), frame_idx=0, strength=1.0)]
|
| 205 |
|
| 206 |
+
tiling_config = TilingConfig.default()
|
| 207 |
+
video_chunks_number = get_video_chunks_number(num_frames, tiling_config)
|
| 208 |
+
|
| 209 |
+
log_memory("before pipeline call")
|
| 210 |
+
|
| 211 |
+
video, audio = pipeline(
|
| 212 |
+
prompt=prompt,
|
| 213 |
+
seed=current_seed,
|
| 214 |
+
height=int(height),
|
| 215 |
+
width=int(width),
|
| 216 |
+
num_frames=num_frames,
|
| 217 |
+
frame_rate=frame_rate,
|
| 218 |
+
images=images,
|
| 219 |
+
tiling_config=tiling_config,
|
| 220 |
+
enhance_prompt=enhance_prompt,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 221 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 222 |
|
| 223 |
+
log_memory("after pipeline call")
|
| 224 |
|
| 225 |
+
output_path = tempfile.mktemp(suffix=".mp4")
|
| 226 |
+
encode_video(
|
| 227 |
+
video=video,
|
| 228 |
+
fps=frame_rate,
|
| 229 |
+
audio=audio,
|
| 230 |
+
output_path=output_path,
|
| 231 |
+
video_chunks_number=video_chunks_number,
|
| 232 |
+
)
|
|
|
|
|
|
|
| 233 |
|
| 234 |
+
log_memory("after encode_video")
|
| 235 |
+
return str(output_path), current_seed
|
|
|
|
|
|
|
| 236 |
|
| 237 |
except Exception as e:
|
| 238 |
import traceback
|
| 239 |
log_memory("on error")
|
| 240 |
+
print(f"Error: {str(e)}\n{traceback.format_exc()}")
|
|
|
|
| 241 |
return None, current_seed
|
| 242 |
|
| 243 |
|
| 244 |
with gr.Blocks(title="LTX-2.3 Distilled") as demo:
|
| 245 |
gr.Markdown("# LTX-2.3 Distilled (22B): Fast Audio-Video Generation")
|
| 246 |
gr.Markdown(
|
| 247 |
+
"Fast and high quality video + audio generation"
|
| 248 |
+
"[[model]](https://huggingface.co/Lightricks/LTX-2.3) "
|
| 249 |
"[[code]](https://github.com/Lightricks/LTX-2)"
|
| 250 |
)
|
| 251 |
|
|
|
|
| 259 |
lines=3,
|
| 260 |
placeholder="Describe the motion and animation you want...",
|
| 261 |
)
|
| 262 |
+
|
| 263 |
with gr.Row():
|
| 264 |
duration = gr.Slider(label="Duration (seconds)", minimum=1.0, maximum=10.0, value=3.0, step=0.1)
|
| 265 |
+
with gr.Column():
|
| 266 |
+
enhance_prompt = gr.Checkbox(label="Enhance Prompt", value=False)
|
| 267 |
+
high_res = gr.Checkbox(label="High Resolution", value=True)
|
| 268 |
|
| 269 |
generate_btn = gr.Button("Generate Video", variant="primary", size="lg")
|
| 270 |
|
|
|
|
| 272 |
seed = gr.Slider(label="Seed", minimum=0, maximum=MAX_SEED, value=10, step=1)
|
| 273 |
randomize_seed = gr.Checkbox(label="Randomize Seed", value=True)
|
| 274 |
with gr.Row():
|
| 275 |
+
width = gr.Number(label="Width", value=1536, precision=0)
|
| 276 |
+
height = gr.Number(label="Height", value=1024, precision=0)
|
| 277 |
|
| 278 |
with gr.Column():
|
| 279 |
output_video = gr.Video(label="Generated Video", autoplay=True)
|
| 280 |
|
| 281 |
+
# Auto-detect aspect ratio from uploaded image and set resolution
|
| 282 |
+
input_image.change(
|
| 283 |
+
fn=on_image_upload,
|
| 284 |
+
inputs=[input_image, high_res],
|
| 285 |
+
outputs=[width, height],
|
| 286 |
+
)
|
| 287 |
+
|
| 288 |
+
# Update resolution when high-res toggle changes
|
| 289 |
+
high_res.change(
|
| 290 |
+
fn=on_highres_toggle,
|
| 291 |
+
inputs=[input_image, high_res],
|
| 292 |
+
outputs=[width, height],
|
| 293 |
+
)
|
| 294 |
+
|
| 295 |
generate_btn.click(
|
| 296 |
fn=generate_video,
|
| 297 |
inputs=[
|
|
|
|
| 303 |
|
| 304 |
|
| 305 |
css = """
|
| 306 |
+
.fillable{max-width: 1200px !important}
|
| 307 |
"""
|
| 308 |
|
| 309 |
if __name__ == "__main__":
|