motion_video_generator / reference.py
srijaydeshpande's picture
Isolate CPU image captioning from the ZeroGPU worker parent process
bb2eb84 verified
Raw History Blame Contribute Delete
6.6 kB
"""Prepare the two image inputs for LTX-2.5 Ingredients conditioning."""
from pathlib import Path
from functools import lru_cache
from PIL import Image, ImageOps
WIDTH = 768
HEIGHT = 448
NUM_FRAMES = 121
FPS = 24
DURATIONS = (5, 10, 15, 20)
def render_spec(duration_seconds: int = 5, quality: str = "detail") -> dict:
"""Validate output options and snap the denoising grid to 8k+1 frames."""
if isinstance(duration_seconds, bool) or duration_seconds not in DURATIONS:
raise ValueError("Choose a clip length of 5, 10, 15, or 20 seconds.")
if quality not in ("draft", "detail", "high"):
raise ValueError("Choose Draft, Detailed, or High detail rendering.")
seconds = int(duration_seconds)
output_frames = seconds * FPS
return {
"duration_seconds": seconds,
"quality": quality,
"num_frames": output_frames + 1,
"output_frames": output_frames,
"width": WIDTH * (2 if quality == "high" else 1),
"height": HEIGHT * (2 if quality == "high" else 1),
"experimental_duration": seconds > 5,
}
def estimated_gpu_duration(duration_seconds: int, quality: str) -> int:
"""Reservation estimate, separate from the requested clip's playback length."""
spec = render_spec(duration_seconds, quality)
base = {"draft": 45, "detail": 60, "high": 135}[quality]
return min(1200, int(base * (spec["duration_seconds"] / 5) ** 1.6))
def build_reference_sheet(person_path: str, reference_path: str) -> Image.Image:
"""Place the person on the left and the reference on the right, preserving both images."""
if not person_path or not reference_path:
raise ValueError("Upload both a person image and a reference image.")
sheet = Image.new("RGB", (WIDTH, HEIGHT), "black")
margin, gap = 8, 16
panel_width = (WIDTH - margin * 2 - gap) // 2
panel_height = HEIGHT - margin * 2
for index, path in enumerate((person_path, reference_path)):
with Image.open(Path(path)) as source:
image = ImageOps.exif_transpose(source).convert("RGB")
image = ImageOps.contain(image, (panel_width, panel_height), Image.Resampling.LANCZOS)
panel_x = margin + index * (panel_width + gap)
x = panel_x + (panel_width - image.width) // 2
y = margin + (panel_height - image.height) // 2
sheet.paste(image, (x, y))
return sheet
@lru_cache(maxsize=1)
def _caption_model():
"""Load a small vision captioner on CPU, outside any GPU reservation."""
import torch
from transformers import AutoModelForImageTextToText, AutoProcessor
model_id = "HuggingFaceTB/SmolVLM-500M-Instruct"
processor = AutoProcessor.from_pretrained(model_id, size={"longest_edge": 512})
model = AutoModelForImageTextToText.from_pretrained(
model_id, dtype=torch.float32, attn_implementation="sdpa",
).to("cpu").eval()
return processor, model
def _describe_references_in_process(person_image: str, reference_image: str) -> str:
"""Run only in the standalone CPU caption process, never the ZeroGPU parent."""
import torch
if not person_image or not reference_image:
raise ValueError("Upload both a person image and a reference image.")
processor, model = _caption_model()
descriptions = []
questions = [
"Describe the person's visible appearance, hairstyle, clothing and accessories in two concise sentences.",
"Describe the visible scene, objects, clothing, colors and lighting in this image in two concise sentences.",
]
for path, question in zip((person_image, reference_image), questions):
with Image.open(path) as source:
image = ImageOps.exif_transpose(source).convert("RGB")
image.thumbnail((512, 512), Image.Resampling.LANCZOS)
messages = [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": question}]}]
text = processor.apply_chat_template(messages, add_generation_prompt=True)
inputs = processor(text=text, images=[image], return_tensors="pt")
with torch.inference_mode():
generated = model.generate(**inputs, max_new_tokens=96, do_sample=False)
answer = processor.batch_decode(
generated[:, inputs["input_ids"].shape[1]:], skip_special_tokens=True,
)[0].strip()
if not answer:
raise ValueError("Unable to describe an image reference. Please try another image.")
descriptions.append(answer)
return f"Person reference: {descriptions[0]} Visual reference: {descriptions[1]}"
def describe_references(person_image: str, reference_image: str) -> str:
"""Keep CPU Transformers CUDA probes outside the parent that forks GPU workers."""
import json
import logging
import os
import subprocess
import sys
env = os.environ.copy()
env.pop("SPACES_ZERO_GPU", None)
env["CUDA_VISIBLE_DEVICES"] = ""
env["PYTORCH_NVML_BASED_CUDA_CHECK"] = "1"
result = subprocess.run(
[sys.executable, str(Path(__file__).with_name("caption_worker.py"))],
input=json.dumps([person_image, reference_image]), text=True,
capture_output=True, env=env, timeout=180,
)
if result.returncode:
safe_lines = [line for line in result.stderr.splitlines()
if "token=" not in line and "Bearer " not in line]
logging.getLogger("motion.caption").error("CPU caption worker failed: %s", "\n".join(safe_lines)[-3000:])
raise ValueError("Unable to describe the references. Please retry with clear images.")
description = json.loads(result.stdout.strip().splitlines()[-1])
if not isinstance(description, str) or not description.strip():
raise ValueError("Unable to describe the references.")
return description
def build_prompt(prompt: str, reference_description: str = "") -> str:
"""Use the Ingredients adapter's trained reference-sheet / generated-video prompt structure."""
prompt = prompt.strip()
if not prompt:
raise ValueError("Describe the video you want to generate.")
if len(prompt) > 6000:
raise ValueError("Keep the prompt under 6,000 characters.")
description = reference_description.strip() or (
"A person reference and a visual reference for the scene, clothing, objects, or style."
)
return (
f"Reference sheet: {description}\n\n"
f"Generated video: A single continuous full-frame cinematic shot. {prompt} "
"The person and the referenced elements share one coherent scene that fills the entire frame."
)