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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""H3 Script Studio — a structured prompt-builder and shot pipeline for MiniMax-H3.
|
| 2 |
+
|
| 3 |
+
The writing pipeline (concept -> characters -> locations -> beats -> shots -> prompts)
|
| 4 |
+
is entirely structured: no LLM dependency, every field is yours. Character appearance
|
| 5 |
+
strings are "locked" — reused word-for-word in every prompt they appear in — because
|
| 6 |
+
that is what keeps a character on-model across shots.
|
| 7 |
+
|
| 8 |
+
Rendering and image generation are delegated:
|
| 9 |
+
* video clips -> any Space exposing the ShotCraft-style `/generate` API
|
| 10 |
+
(default: swimmerzeromaybe/ShotCraft-Movie-Production) via gradio_client
|
| 11 |
+
* stills -> FLUX.1-schnell through the HF Inference router (needs the HF_TOKEN secret)
|
| 12 |
+
* assembly -> the backend's `/stitch` ffmpeg concat endpoint
|
| 13 |
+
|
| 14 |
+
Canvas table, duration snapping and LoRA choices mirror the backend exactly; a canvas
|
| 15 |
+
label the conditioner does not know is rejected over there, so they must stay identical.
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
from __future__ import annotations
|
| 19 |
+
|
| 20 |
+
import json
|
| 21 |
+
import os
|
| 22 |
+
import tempfile
|
| 23 |
+
import time
|
| 24 |
+
|
| 25 |
+
import gradio as gr
|
| 26 |
+
import requests
|
| 27 |
+
|
| 28 |
+
# ---------------------------------------------------------------------------
|
| 29 |
+
# Constants mirrored from the backend Spaces (must stay identical)
|
| 30 |
+
# ---------------------------------------------------------------------------
|
| 31 |
+
|
| 32 |
+
CANVASES = {
|
| 33 |
+
"960x544 · 16:9 fast": (544, 960),
|
| 34 |
+
"1024x576 · 16:9 fast": (576, 1024),
|
| 35 |
+
"1152x640 · 16:9": (640, 1152),
|
| 36 |
+
"1280x704 · 16:9": (704, 1280),
|
| 37 |
+
"1344x768 · 16:9 full": (768, 1344),
|
| 38 |
+
"544x960 · 9:16 fast": (960, 544),
|
| 39 |
+
"640x1152 · 9:16": (1152, 640),
|
| 40 |
+
"768x1344 · 9:16 full": (1344, 768),
|
| 41 |
+
"544x544 · 1:1 fast": (544, 544),
|
| 42 |
+
"768x768 · 1:1 full": (768, 768),
|
| 43 |
+
"768x576 · 4:3 fast": (576, 768),
|
| 44 |
+
"1024x768 · 4:3 full": (768, 1024),
|
| 45 |
+
"576x768 · 3:4 fast": (768, 576),
|
| 46 |
+
"768x1024 · 3:4 full": (1024, 768),
|
| 47 |
+
"1152x512 · 21:9 fast": (512, 1152),
|
| 48 |
+
"1536x672 · 21:9 full": (672, 1536),
|
| 49 |
+
}
|
| 50 |
+
DEFAULT_CANVAS = "960x544 · 16:9 fast"
|
| 51 |
+
FPS, FRAMES_PER_CHUNK, LATENTS_PER_CHUNK = 24, 17, 5
|
| 52 |
+
MIN_UI_DURATION, MAX_UI_DURATION = 2, 14
|
| 53 |
+
STEPS_FOR_LORA = {"larry": 6, "lightx": 4, "off": 28}
|
| 54 |
+
|
| 55 |
+
BACKEND_DEFAULT = "swimmerzeromaybe/ShotCraft-Movie-Production"
|
| 56 |
+
IMAGE_MODEL = "black-forest-labs/FLUX.1-schnell"
|
| 57 |
+
|
| 58 |
+
SHOT_SIZES = ["extreme wide", "wide", "medium", "medium close-up", "close-up", "extreme close-up", "over-the-shoulder", "insert"]
|
| 59 |
+
ANGLES = ["eye level", "low angle", "high angle", "dutch angle", "overhead", "aerial"]
|
| 60 |
+
MOVEMENTS = ["static", "slow push in", "slow pull out", "pan left", "pan right", "tilt up", "tilt down",
|
| 61 |
+
"handheld follow", "dolly left", "dolly right", "crane up", "orbit around subject"]
|
| 62 |
+
LENSES = ["14mm wide", "24mm", "35mm", "50mm", "85mm portrait", "135mm telephoto", "anamorphic 40mm"]
|
| 63 |
+
STYLES = ["photorealistic cinematic", "35mm film", "16mm documentary", "modern anime", "3D animation",
|
| 64 |
+
"noir black-and-white", "vintage 1970s film", "clean commercial", "dreamlike soft focus", "gritty realistic"]
|
| 65 |
+
GENRES = ["drama", "sci-fi", "thriller", "horror", "comedy", "romance", "action", "fantasy", "documentary", "music video"]
|
| 66 |
+
TONES = ["tense", "melancholic", "hopeful", "mysterious", "playful", "ominous", "triumphant", "intimate", "epic"]
|
| 67 |
+
PALETTES = ["neutral", "teal and orange", "warm golden hour", "cool blue", "neon cyberpunk", "desaturated",
|
| 68 |
+
"high contrast monochrome", "pastel soft"]
|
| 69 |
+
TIMES_OF_DAY = ["dawn", "morning", "midday", "afternoon", "golden hour", "dusk", "night", "late night"]
|
| 70 |
+
WEATHER = ["clear", "overcast", "light rain", "heavy rain", "snow", "fog", "storm", "windy"]
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def snap_frames(seconds: float) -> int:
|
| 74 |
+
"""Frame count the video VAE can decode: next `17 * n + 5` at 24 fps (mirrors the backend)."""
|
| 75 |
+
frames = max(1, round(float(seconds) * FPS))
|
| 76 |
+
while frames % FRAMES_PER_CHUNK != LATENTS_PER_CHUNK:
|
| 77 |
+
frames += 1
|
| 78 |
+
return frames
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def frames_label(seconds: float) -> str:
|
| 82 |
+
frames = snap_frames(seconds)
|
| 83 |
+
return f"→ snaps to **{frames} frames · {frames / FPS:.3f} s** at {FPS} fps (H3 VAE constraint: 17·n+5 frames)"
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def backend_base_url(space_id: str) -> str:
|
| 87 |
+
slug = space_id.strip("/").replace("/", "-").replace(".", "-").replace("_", "-").lower()
|
| 88 |
+
return f"https://{slug}.hf.space"
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
# ---------------------------------------------------------------------------
|
| 92 |
+
# Project state helpers
|
| 93 |
+
# ---------------------------------------------------------------------------
|
| 94 |
+
|
| 95 |
+
def new_project() -> dict:
|
| 96 |
+
return {
|
| 97 |
+
"concept": {"title": "", "logline": "", "genre": GENRES[0], "style": STYLES[0], "tone": TONES[0],
|
| 98 |
+
"era": "", "palette": PALETTES[0], "notes": ""},
|
| 99 |
+
"characters": {}, # id -> {name, appearance, wardrobe, voice, notes}
|
| 100 |
+
"locations": {}, # id -> {name, description, time, weather, notes}
|
| 101 |
+
"shots": {}, # id -> {name, beat, location, characters, size, angle, movement, lens,
|
| 102 |
+
# lighting, audio, duration, canvas, seed, prompt,
|
| 103 |
+
# first_image, last_image, clip_url}
|
| 104 |
+
"counters": {"character": 0, "location": 0, "shot": 0},
|
| 105 |
+
"sequence": [],
|
| 106 |
+
}
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def next_id(project: dict, kind: str) -> str:
|
| 110 |
+
project["counters"][kind] += 1
|
| 111 |
+
return f"{kind}-{project['counters'][kind]:03d}"
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def style_bible(concept: dict) -> str:
|
| 115 |
+
bits = []
|
| 116 |
+
if concept.get("era"):
|
| 117 |
+
bits.append(f"{concept['era']} setting")
|
| 118 |
+
bits.append(f"{concept.get('genre', '')} with a {concept.get('tone', '')} tone")
|
| 119 |
+
bits.append(f"visual style: {concept.get('style', '')}")
|
| 120 |
+
if concept.get("palette"):
|
| 121 |
+
bits.append(f"color palette: {concept.get('palette', '')}")
|
| 122 |
+
text = ", ".join(b for b in bits if b)
|
| 123 |
+
if concept.get("notes"):
|
| 124 |
+
text += f". {concept['notes'].strip()}"
|
| 125 |
+
return text
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def character_block(project: dict, names: list[str]) -> str:
|
| 129 |
+
"""Locked word-for-word appearance strings — the consistency mechanism."""
|
| 130 |
+
parts = []
|
| 131 |
+
for name in names:
|
| 132 |
+
name = name.strip()
|
| 133 |
+
char = next((c for c in project["characters"].values() if c["name"].strip().lower() == name.lower()), None)
|
| 134 |
+
if char is None:
|
| 135 |
+
parts.append(f"{name}")
|
| 136 |
+
continue
|
| 137 |
+
desc = char["appearance"].strip().rstrip(".")
|
| 138 |
+
if char.get("wardrobe", "").strip():
|
| 139 |
+
desc += f", wearing {char['wardrobe'].strip().rstrip('.')}"
|
| 140 |
+
parts.append(f"{char['name'].strip()} ({desc})")
|
| 141 |
+
return "; ".join(parts)
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def location_block(project: dict, name: str) -> str:
|
| 145 |
+
loc = next((l for l in project["locations"].values() if l["name"].strip().lower() == name.strip().lower()), None)
|
| 146 |
+
if loc is None:
|
| 147 |
+
return name.strip()
|
| 148 |
+
bits = [loc["description"].strip().rstrip(".")]
|
| 149 |
+
if loc.get("time"):
|
| 150 |
+
bits.append(loc["time"])
|
| 151 |
+
if loc.get("weather") and loc["weather"] != "clear":
|
| 152 |
+
bits.append(loc["weather"])
|
| 153 |
+
text = ", ".join(bits)
|
| 154 |
+
if loc.get("notes", "").strip():
|
| 155 |
+
text += f". {loc['notes'].strip()}"
|
| 156 |
+
return text
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def compose_shot_prompt(project: dict, shot: dict) -> str:
|
| 160 |
+
sentences = []
|
| 161 |
+
beat = shot.get("beat", "").strip()
|
| 162 |
+
if beat:
|
| 163 |
+
sentences.append(beat if beat.endswith((".", "!", "?")) else beat + ".")
|
| 164 |
+
names = [c for c in shot.get("characters", "").split(",") if c.strip()]
|
| 165 |
+
if names:
|
| 166 |
+
sentences.append(f"Featuring {character_block(project, names)}.")
|
| 167 |
+
if shot.get("location", "").strip():
|
| 168 |
+
sentences.append(f"Setting: {location_block(project, shot['location'])}.")
|
| 169 |
+
camera = f"{shot.get('size', '')} shot, {shot.get('angle', '')}, {shot.get('movement', '')}"
|
| 170 |
+
if shot.get("lens", "").strip():
|
| 171 |
+
camera += f", {shot['lens']} lens"
|
| 172 |
+
sentences.append(f"Camera: {camera}.")
|
| 173 |
+
if shot.get("lighting", "").strip():
|
| 174 |
+
sentences.append(f"Lighting: {shot['lighting']}.")
|
| 175 |
+
bible = style_bible(project["concept"])
|
| 176 |
+
if bible:
|
| 177 |
+
sentences.append(f"Style: {bible}.")
|
| 178 |
+
if shot.get("audio", "").strip():
|
| 179 |
+
sentences.append(f"Audio: {shot['audio'].strip().rstrip('.')}.")
|
| 180 |
+
return " ".join(sentences)
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def compose_still_prompt(project: dict, shot: dict, which: str) -> str:
|
| 184 |
+
camera = f"{shot.get('size', '')} shot, {shot.get('angle', '')}"
|
| 185 |
+
if shot.get("lens", "").strip():
|
| 186 |
+
camera += f", {shot['lens']} lens"
|
| 187 |
+
names = [c for c in shot.get("characters", "").split(",") if c.strip()]
|
| 188 |
+
tail = ("The frame the shot opens on, before the action begins." if which == "first"
|
| 189 |
+
else "The frame the shot ends on, the moment just after the action resolves.")
|
| 190 |
+
return (f"Cinematic film still. {camera}. "
|
| 191 |
+
f"{'Featuring ' + character_block(project, names) + '.' if names else ''} "
|
| 192 |
+
f"{('Setting: ' + location_block(project, shot['location']) + '.') if shot.get('location', '').strip() else ''} "
|
| 193 |
+
f"{('Lighting: ' + shot['lighting'] + '.') if shot.get('lighting', '').strip() else ''} "
|
| 194 |
+
f"{('Style: ' + style_bible(project['concept']) + '.') if style_bible(project['concept']) else ''} "
|
| 195 |
+
f"{tail}")
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
def flux_size(canvas: str) -> tuple[int, int]:
|
| 199 |
+
h, w = CANVASES[canvas]
|
| 200 |
+
scale = 1024 / max(h, w)
|
| 201 |
+
fh, fw = int(round(h * scale / 16) * 16), int(round(w * scale / 16) * 16)
|
| 202 |
+
return fh, fw
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
# ---------------------------------------------------------------------------
|
| 206 |
+
# Backend calls
|
| 207 |
+
# ---------------------------------------------------------------------------
|
| 208 |
+
|
| 209 |
+
def render_clip(prompt, first_image, last_image, canvas, duration, steps, seed, lora, upsample, backend):
|
| 210 |
+
if not prompt or not prompt.strip():
|
| 211 |
+
raise gr.Error("Compose or write a shot prompt first — H3 always takes a prompt.")
|
| 212 |
+
if not backend or not backend.strip():
|
| 213 |
+
raise gr.Error("Set the backend Space id (owner/name).")
|
| 214 |
+
from gradio_client import Client, handle_file
|
| 215 |
+
|
| 216 |
+
try:
|
| 217 |
+
client = Client(backend.strip(), hf_token=os.environ.get("HF_TOKEN") or None)
|
| 218 |
+
except Exception as error:
|
| 219 |
+
raise gr.Error(f"Could not connect to `{backend.strip()}`: {error}") from error
|
| 220 |
+
|
| 221 |
+
kwargs = {
|
| 222 |
+
"prompt": prompt.strip(),
|
| 223 |
+
"image_path": handle_file(first_image) if first_image else None,
|
| 224 |
+
"last_image_path": handle_file(last_image) if last_image else None,
|
| 225 |
+
"canvas": canvas,
|
| 226 |
+
"duration": float(duration),
|
| 227 |
+
"steps": int(steps),
|
| 228 |
+
"seed": int(seed),
|
| 229 |
+
"upsample": bool(upsample),
|
| 230 |
+
}
|
| 231 |
+
try:
|
| 232 |
+
video, report, refined = client.predict(**kwargs, api_name="/generate")
|
| 233 |
+
except Exception as error:
|
| 234 |
+
message = str(error)
|
| 235 |
+
if "gpu limit" in message.lower() or "quota" in message.lower():
|
| 236 |
+
raise gr.Error("The backend's GPU quota is exhausted — wait a minute and retry.") from error
|
| 237 |
+
raise gr.Error(f"Backend `/generate` failed: {message[:500]}") from error
|
| 238 |
+
return video, report, refined
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
def add_to_sequence(sequence, backend, video):
|
| 242 |
+
url = video.get("url") if isinstance(video, dict) else None
|
| 243 |
+
if not url:
|
| 244 |
+
raise gr.Error("No clip URL returned — render a clip first.")
|
| 245 |
+
base = backend_base_url(backend)
|
| 246 |
+
sequence = list(sequence or [])
|
| 247 |
+
sequence.append({"url": url, "absolute": base + url, "at": time.strftime("%H:%M:%S")})
|
| 248 |
+
lines = [f"{i + 1}. [{entry['at']}]({entry['absolute']})" for i, entry in enumerate(sequence)]
|
| 249 |
+
return sequence, f"**Sequence ({len(sequence)} clips)** — in render order:\n" + "\n".join(lines)
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
def stitch_sequence(sequence, backend):
|
| 253 |
+
if not sequence or len(sequence) < 2:
|
| 254 |
+
raise gr.Error("Add at least 2 rendered clips to the sequence before stitching.")
|
| 255 |
+
base = backend_base_url(backend)
|
| 256 |
+
try:
|
| 257 |
+
response = requests.post(f"{base}/stitch", json={"paths": [e["url"] for e in sequence]}, timeout=180)
|
| 258 |
+
response.raise_for_status()
|
| 259 |
+
except Exception as error:
|
| 260 |
+
raise gr.Error(f"Stitching via `{backend}` failed (it needs the ShotCraft `/stitch` endpoint): {error}") from error
|
| 261 |
+
result = response.json()
|
| 262 |
+
url = result.get("url", "")
|
| 263 |
+
if not url:
|
| 264 |
+
raise gr.Error(f"Stitch endpoint returned no url: {result}")
|
| 265 |
+
return base + url
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
def generate_still(prompt, canvas):
|
| 269 |
+
if not prompt or not prompt.strip():
|
| 270 |
+
raise gr.Error("Write a frame prompt first.")
|
| 271 |
+
from huggingface_hub import InferenceClient
|
| 272 |
+
|
| 273 |
+
token = os.environ.get("HF_TOKEN")
|
| 274 |
+
if not token:
|
| 275 |
+
raise gr.Error("Add an HF_TOKEN secret to this Space (Settings → Variables and secrets) to call "
|
| 276 |
+
f"`{IMAGE_MODEL}` through the Inference router.")
|
| 277 |
+
client = InferenceClient(token=token)
|
| 278 |
+
height, width = flux_size(canvas)
|
| 279 |
+
try:
|
| 280 |
+
image = client.text_to_image(prompt.strip(), model=IMAGE_MODEL, width=width, height=height)
|
| 281 |
+
except Exception as error:
|
| 282 |
+
raise gr.Error(f"Image generation failed: {str(error)[:400]}") from error
|
| 283 |
+
path = os.path.join(tempfile.gettempdir(), f"still-{int(time.time() * 1000)}.png")
|
| 284 |
+
image.save(path)
|
| 285 |
+
return path
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
# ---------------------------------------------------------------------------
|
| 289 |
+
# State handlers
|
| 290 |
+
# ---------------------------------------------------------------------------
|
| 291 |
+
|
| 292 |
+
def save_concept(project, title, logline, genre, style, tone, era, palette, notes):
|
| 293 |
+
project["concept"] = {"title": title, "logline": logline, "genre": genre, "style": style, "tone": tone,
|
| 294 |
+
"era": era, "palette": palette, "notes": notes}
|
| 295 |
+
bible = style_bible(project["concept"])
|
| 296 |
+
return project, f"**Style bible** (reused in every prompt):\n\n> {bible or '_(empty — fill the Concept tab)_'}"
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
def roster_markdown(project) -> str:
|
| 300 |
+
if not project["characters"]:
|
| 301 |
+
return "_No characters yet._"
|
| 302 |
+
lines = ["**Character consistency blocks** (locked word-for-word into every shot prompt):"]
|
| 303 |
+
for char in project["characters"].values():
|
| 304 |
+
lines.append(f"- **{char['name']}** — {char['appearance']}"
|
| 305 |
+
+ (f", wearing {char['wardrobe']}" if char.get("wardrobe") else "")
|
| 306 |
+
+ (f" · voice: {char['voice']}" if char.get("voice") else ""))
|
| 307 |
+
return "\n".join(lines)
|
| 308 |
+
|
| 309 |
+
|
| 310 |
+
def new_character(project):
|
| 311 |
+
cid = next_id(project, "character")
|
| 312 |
+
project["characters"][cid] = {"name": f"Character {project['counters']['character']}", "appearance": "",
|
| 313 |
+
"wardrobe": "", "voice": "", "notes": ""}
|
| 314 |
+
return (project, gr.update(choices=sorted(project["characters"]), value=cid), project["characters"][cid]["name"],
|
| 315 |
+
"", "", "", "", roster_markdown(project))
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
def load_character(project, cid):
|
| 319 |
+
char = project["characters"].get(cid, {"name": "", "appearance": "", "wardrobe": "", "voice": "", "notes": ""})
|
| 320 |
+
return char["name"], char["appearance"], char["wardrobe"], char["voice"], char["notes"]
|
| 321 |
+
|
| 322 |
+
|
| 323 |
+
def save_character(project, cid, name, appearance, wardrobe, voice, notes):
|
| 324 |
+
if not cid:
|
| 325 |
+
raise gr.Error("Add a character first.")
|
| 326 |
+
project["characters"][cid] = {"name": name, "appearance": appearance, "wardrobe": wardrobe,
|
| 327 |
+
"voice": voice, "notes": notes}
|
| 328 |
+
return project, gr.update(choices=sorted(project["characters"])), roster_markdown(project)
|
| 329 |
+
|
| 330 |
+
|
| 331 |
+
def delete_character(project, cid):
|
| 332 |
+
if cid:
|
| 333 |
+
project["characters"].pop(cid, None)
|
| 334 |
+
return (project, gr.update(choices=sorted(project["characters"]), value=None), "", "", "", "", "",
|
| 335 |
+
roster_markdown(project))
|
| 336 |
+
|
| 337 |
+
|
| 338 |
+
def locations_markdown(project) -> str:
|
| 339 |
+
if not project["locations"]:
|
| 340 |
+
return "_No locations yet._"
|
| 341 |
+
lines = ["**Locations**:"]
|
| 342 |
+
for loc in project["locations"].values():
|
| 343 |
+
lines.append(f"- **{loc['name']}** — {loc['description']} ({loc['time']}, {loc['weather']})")
|
| 344 |
+
return "\n".join(lines)
|
| 345 |
+
|
| 346 |
+
|
| 347 |
+
def new_location(project):
|
| 348 |
+
lid = next_id(project, "location")
|
| 349 |
+
project["locations"][lid] = {"name": f"Location {project['counters']['location']}", "description": "",
|
| 350 |
+
"time": TIMES_OF_DAY[0], "weather": WEATHER[0], "notes": ""}
|
| 351 |
+
return (project, gr.update(choices=sorted(project["locations"]), value=lid),
|
| 352 |
+
project["locations"][lid]["name"], "", TIMES_OF_DAY[0], WEATHER[0], "", locations_markdown(project))
|
| 353 |
+
|
| 354 |
+
|
| 355 |
+
def load_location(project, lid):
|
| 356 |
+
loc = project["locations"].get(lid, {"name": "", "description": "", "time": TIMES_OF_DAY[0],
|
| 357 |
+
"weather": WEATHER[0], "notes": ""})
|
| 358 |
+
return loc["name"], loc["description"], loc["time"], loc["weather"], loc["notes"]
|
| 359 |
+
|
| 360 |
+
|
| 361 |
+
def save_location(project, lid, name, description, time_of_day, weather, notes):
|
| 362 |
+
if not lid:
|
| 363 |
+
raise gr.Error("Add a location first.")
|
| 364 |
+
project["locations"][lid] = {"name": name, "description": description, "time": time_of_day,
|
| 365 |
+
"weather": weather, "notes": notes}
|
| 366 |
+
return project, gr.update(choices=sorted(project["locations"])), locations_markdown(project)
|
| 367 |
+
|
| 368 |
+
|
| 369 |
+
def delete_location(project, lid):
|
| 370 |
+
if lid:
|
| 371 |
+
project["locations"].pop(lid, None)
|
| 372 |
+
return (project, gr.update(choices=sorted(project["locations"]), value=None), "", "", TIMES_OF_DAY[0],
|
| 373 |
+
WEATHER[0], "", locations_markdown(project))
|
| 374 |
+
|
| 375 |
+
|
| 376 |
+
def shots_markdown(project) -> str:
|
| 377 |
+
if not project["shots"]:
|
| 378 |
+
return "_No shots yet. Add one, or spawn shots from beats in the Story tab._"
|
| 379 |
+
lines = [f"**Shot list** ({len(project['shots'])} shots):"]
|
| 380 |
+
for sid in sorted(project["shots"]):
|
| 381 |
+
shot = project["shots"][sid]
|
| 382 |
+
dur = snap_frames(shot.get("duration", 5)) / FPS
|
| 383 |
+
lines.append(f"- **{shot.get('name', sid)}** — {shot.get('size', '')}, {shot.get('movement', '')} · "
|
| 384 |
+
f"{dur:.2f}s · {shot.get('canvas', DEFAULT_CANVAS)}"
|
| 385 |
+
+ (" · 🖼️ keyframes" if shot.get("first_image") or shot.get("last_image") else "")
|
| 386 |
+
+ (" · 🎬 rendered" if shot.get("clip_url") else ""))
|
| 387 |
+
return "\n".join(lines)
|
| 388 |
+
|
| 389 |
+
|
| 390 |
+
def shot_choices(project):
|
| 391 |
+
return sorted(project["shots"])
|
| 392 |
+
|
| 393 |
+
|
| 394 |
+
def new_shot(project):
|
| 395 |
+
sid = next_id(project, "shot")
|
| 396 |
+
project["shots"][sid] = {"name": f"Shot {project['counters']['shot']:02d}", "beat": "", "location": "",
|
| 397 |
+
"characters": "", "size": SHOT_SIZES[1], "angle": ANGLES[0], "movement": MOVEMENTS[0],
|
| 398 |
+
"lens": LENSES[2], "lighting": "", "audio": "", "duration": 5,
|
| 399 |
+
"canvas": DEFAULT_CANVAS, "seed": 42, "prompt": "", "first_image": None,
|
| 400 |
+
"last_image": None, "clip_url": None}
|
| 401 |
+
return (project, gr.update(choices=shot_choices(project), value=sid), project["shots"][sid]["name"], "",
|
| 402 |
+
"", "", SHOT_SIZES[1], ANGLES[0], MOVEMENTS[0], LENSES[2], "", "", 5, DEFAULT_CANVAS, 42, "",
|
| 403 |
+
None, None, shots_markdown(project))
|
| 404 |
+
|
| 405 |
+
|
| 406 |
+
def load_shot(project, sid):
|
| 407 |
+
shot = project["shots"].get(sid)
|
| 408 |
+
if shot is None:
|
| 409 |
+
shot = {"name": "", "beat": "", "location": "", "characters": "", "size": SHOT_SIZES[1],
|
| 410 |
+
"angle": ANGLES[0], "movement": MOVEMENTS[0], "lens": LENSES[2], "lighting": "", "audio": "",
|
| 411 |
+
"duration": 5, "canvas": DEFAULT_CANVAS, "seed": 42, "prompt": "", "first_image": None,
|
| 412 |
+
"last_image": None}
|
| 413 |
+
return (shot["name"], shot["beat"], shot["location"], shot["characters"], shot["size"], shot["angle"],
|
| 414 |
+
shot["movement"], shot["lens"], shot["lighting"], shot["audio"], shot["duration"], shot["canvas"],
|
| 415 |
+
shot["seed"], shot["prompt"], shot.get("first_image"), shot.get("last_image"))
|
| 416 |
+
|
| 417 |
+
|
| 418 |
+
def save_shot(project, sid, name, beat, location, characters, size, angle, movement, lens, lighting, audio,
|
| 419 |
+
duration, canvas, seed, prompt, first_image, last_image):
|
| 420 |
+
if not sid:
|
| 421 |
+
raise gr.Error("Add a shot first.")
|
| 422 |
+
project["shots"][sid] = {"name": name, "beat": beat, "location": location, "characters": characters,
|
| 423 |
+
"size": size, "angle": angle, "movement": movement, "lens": lens,
|
| 424 |
+
"lighting": lighting, "audio": audio, "duration": float(duration), "canvas": canvas,
|
| 425 |
+
"seed": int(seed), "prompt": prompt, "first_image": first_image,
|
| 426 |
+
"last_image": last_image, "clip_url": project["shots"].get(sid, {}).get("clip_url")}
|
| 427 |
+
return project, gr.update(choices=shot_choices(project)), shots_markdown(project)
|
| 428 |
+
|
| 429 |
+
|
| 430 |
+
def delete_shot(project, sid):
|
| 431 |
+
if sid:
|
| 432 |
+
project["shots"].pop(sid, None)
|
| 433 |
+
return (project, gr.update(choices=shot_choices(project), value=None), "", "", "", "", SHOT_SIZES[1],
|
| 434 |
+
ANGLES[0], MOVEMENTS[0], LENSES[2], "", "", 5, DEFAULT_CANVAS, 42, "", None, None,
|
| 435 |
+
shots_markdown(project))
|
| 436 |
+
|
| 437 |
+
|
| 438 |
+
def compose_prompt(project, name, beat, location, characters, size, angle, movement, lens, lighting, audio,
|
| 439 |
+
duration, canvas, seed):
|
| 440 |
+
shot = {"name": name, "beat": beat, "location": location, "characters": characters, "size": size,
|
| 441 |
+
"angle": angle, "movement": movement, "lens": lens, "lighting": lighting, "audio": audio}
|
| 442 |
+
return compose_shot_prompt(project, shot)
|
| 443 |
+
|
| 444 |
+
|
| 445 |
+
def spawn_shots_from_beats(project, beats_text):
|
| 446 |
+
lines = [line.strip(" -•\t") for line in (beats_text or "").splitlines() if line.strip(" -•\t")]
|
| 447 |
+
if not lines:
|
| 448 |
+
raise gr.Error("Write one beat per line in the Story tab first.")
|
| 449 |
+
for line in lines:
|
| 450 |
+
sid = next_id(project, "shot")
|
| 451 |
+
project["shots"][sid] = {"name": f"Shot {project['counters']['shot']:02d} · {line[:32]}", "beat": line,
|
| 452 |
+
"location": "", "characters": "", "size": SHOT_SIZES[1], "angle": ANGLES[0],
|
| 453 |
+
"movement": MOVEMENTS[0], "lens": LENSES[2], "lighting": "", "audio": "",
|
| 454 |
+
"duration": 5, "canvas": DEFAULT_CANVAS, "seed": 42, "prompt": "",
|
| 455 |
+
"first_image": None, "last_image": None, "clip_url": None}
|
| 456 |
+
return (project, gr.update(choices=shot_choices(project), value=sorted(project["shots"])[0]),
|
| 457 |
+
shots_markdown(project))
|
| 458 |
+
|
| 459 |
+
|
| 460 |
+
def load_render_fields(project, sid):
|
| 461 |
+
shot = project["shots"].get(sid, {})
|
| 462 |
+
return (shot.get("prompt", ""), shot.get("canvas", DEFAULT_CANVAS), shot.get("duration", 5),
|
| 463 |
+
STEPS_FOR_LORA.get("larry", 6), shot.get("seed", 42), shot.get("first_image"), shot.get("last_image"))
|
| 464 |
+
|
| 465 |
+
|
| 466 |
+
def steps_for_lora(lora):
|
| 467 |
+
return STEPS_FOR_LORA.get(lora, 6)
|
| 468 |
+
|
| 469 |
+
|
| 470 |
+
# ---------------------------------------------------------------------------
|
| 471 |
+
# Export / import
|
| 472 |
+
# ---------------------------------------------------------------------------
|
| 473 |
+
|
| 474 |
+
def export_project(project):
|
| 475 |
+
path = os.path.join(tempfile.gettempdir(), f"h3-project-{int(time.time())}.json")
|
| 476 |
+
with open(path, "w", encoding="utf-8") as handle:
|
| 477 |
+
json.dump(project, handle, indent=2, ensure_ascii=False)
|
| 478 |
+
return path
|
| 479 |
+
|
| 480 |
+
|
| 481 |
+
def project_markdown(project) -> str:
|
| 482 |
+
concept = project["concept"]
|
| 483 |
+
out = [f"# {concept.get('title') or 'Untitled project'}", "", f"**Logline:** {concept.get('logline', '')}", "",
|
| 484 |
+
f"**Style bible:** {style_bible(concept)}", "", "## Characters"]
|
| 485 |
+
out += [f"- **{c['name']}** — {c['appearance']}" for c in project["characters"].values()] or ["_(none)_"]
|
| 486 |
+
out += ["", "## Locations"]
|
| 487 |
+
out += [f"- **{l['name']}** — {l['description']} ({l['time']}, {l['weather']})"
|
| 488 |
+
for l in project["locations"].values()] or ["_(none)_"]
|
| 489 |
+
out += ["", "## Shots"]
|
| 490 |
+
if not project["shots"]:
|
| 491 |
+
out.append("_(none)_")
|
| 492 |
+
for sid in sorted(project["shots"]):
|
| 493 |
+
shot = project["shots"][sid]
|
| 494 |
+
out += [f"### {shot.get('name', sid)}", f"- Camera: {shot['size']}, {shot['angle']}, {shot['movement']}, {shot['lens']}",
|
| 495 |
+
f"- Setting: {shot.get('location', '')} · Lighting: {shot.get('lighting', '')}",
|
| 496 |
+
f"- Duration: {snap_frames(shot['duration']) / FPS:.2f}s · Canvas: {shot['canvas']} · Seed: {shot['seed']}",
|
| 497 |
+
f"- Prompt: `{shot.get('prompt', '')}`", ""]
|
| 498 |
+
return "\n".join(out)
|
| 499 |
+
|
| 500 |
+
|
| 501 |
+
def import_project(file):
|
| 502 |
+
if not file:
|
| 503 |
+
raise gr.Error("Choose a project JSON file to import.")
|
| 504 |
+
try:
|
| 505 |
+
with open(file, encoding="utf-8") as handle:
|
| 506 |
+
project = json.load(handle)
|
| 507 |
+
except Exception as error:
|
| 508 |
+
raise gr.Error(f"Could not read the project file: {error}") from error
|
| 509 |
+
base = new_project()
|
| 510 |
+
for key, value in project.items():
|
| 511 |
+
if key in base:
|
| 512 |
+
base[key].update(value)
|
| 513 |
+
updates = populate_updates(base)
|
| 514 |
+
return [base] + updates + [project_markdown(base), roster_markdown(base), locations_markdown(base),
|
| 515 |
+
shots_markdown(base)]
|
| 516 |
+
|
| 517 |
+
|
| 518 |
+
def populate_updates(project) -> list:
|
| 519 |
+
"""Gradio update lists for every editable component, in the order import_project returns them."""
|
| 520 |
+
concept = project["concept"]
|
| 521 |
+
first_char = sorted(project["characters"])[0] if project["characters"] else None
|
| 522 |
+
first_loc = sorted(project["locations"])[0] if project["locations"] else None
|
| 523 |
+
first_shot = sorted(project["shots"])[0] if project["shots"] else None
|
| 524 |
+
char = project["characters"].get(first_char, {"name": "", "appearance": "", "wardrobe": "", "voice": "", "notes": ""})
|
| 525 |
+
loc = project["locations"].get(first_loc, {"name": "", "description": "", "time": TIMES_OF_DAY[0],
|
| 526 |
+
"weather": WEATHER[0], "notes": ""})
|
| 527 |
+
shot = project["shots"].get(first_shot, {"name": "", "beat": "", "location": "", "characters": "",
|
| 528 |
+
"size": SHOT_SIZES[1], "angle": ANGLES[0], "movement": MOVEMENTS[0],
|
| 529 |
+
"lens": LENSES[2], "lighting": "", "audio": "", "duration": 5,
|
| 530 |
+
"canvas": DEFAULT_CANVAS, "seed": 42, "prompt": "",
|
| 531 |
+
"first_image": None, "last_image": None})
|
| 532 |
+
return [
|
| 533 |
+
concept["title"], concept["logline"], concept["genre"], concept["style"], concept["tone"],
|
| 534 |
+
concept["era"], concept["palette"], concept["notes"],
|
| 535 |
+
gr.update(choices=sorted(project["characters"]), value=first_char),
|
| 536 |
+
char["name"], char["appearance"], char["wardrobe"], char["voice"], char["notes"],
|
| 537 |
+
gr.update(choices=sorted(project["locations"]), value=first_loc),
|
| 538 |
+
loc["name"], loc["description"], loc["time"], loc["weather"], loc["notes"],
|
| 539 |
+
project.get("beats", "") if isinstance(project.get("beats"), str) else "",
|
| 540 |
+
gr.update(choices=shot_choices(project), value=first_shot),
|
| 541 |
+
shot["name"], shot["beat"],
|
| 542 |
+
gr.update(choices=sorted(project["locations"]), value=shot["location"]),
|
| 543 |
+
shot["characters"], shot["size"], shot["angle"],
|
| 544 |
+
shot["movement"], shot["lens"], shot["lighting"], shot["audio"], shot["duration"], shot["canvas"],
|
| 545 |
+
shot["seed"], shot["prompt"], shot.get("first_image"), shot.get("last_image"),
|
| 546 |
+
]
|
| 547 |
+
|
| 548 |
+
|
| 549 |
+
# ---------------------------------------------------------------------------
|
| 550 |
+
# UI
|
| 551 |
+
# ---------------------------------------------------------------------------
|
| 552 |
+
|
| 553 |
+
def build_ui():
|
| 554 |
+
project = gr.State(new_project())
|
| 555 |
+
sequence = gr.State([])
|
| 556 |
+
|
| 557 |
+
with gr.Blocks(title="H3 Script Studio") as demo:
|
| 558 |
+
gr.Markdown(
|
| 559 |
+
"# 🎬 H3 Script Studio\n"
|
| 560 |
+
"Structured pre-production → shot prompts → MiniMax-H3 clips, no LLM in the loop. "
|
| 561 |
+
f"Stills: [`{IMAGE_MODEL}`](https://huggingface.co/{IMAGE_MODEL}) via the HF router · "
|
| 562 |
+
f"clips: delegated to a backend Space exposing the ShotCraft `/generate` API "
|
| 563 |
+
"(default: [ShotCraft-Movie-Production](https://hf.co/spaces/swimmerzeromaybe/ShotCraft-Movie-Production))."
|
| 564 |
+
)
|
| 565 |
+
|
| 566 |
+
with gr.Tab("1 · Concept"):
|
| 567 |
+
c_title = gr.Textbox(label="Title")
|
| 568 |
+
c_logline = gr.Textbox(label="Logline", lines=2)
|
| 569 |
+
with gr.Row():
|
| 570 |
+
c_genre = gr.Dropdown(GENRES, value=GENRES[0], label="Genre")
|
| 571 |
+
c_style = gr.Dropdown(STYLES, value=STYLES[0], label="Visual style")
|
| 572 |
+
c_tone = gr.Dropdown(TONES, value=TONES[0], label="Tone")
|
| 573 |
+
c_palette = gr.Dropdown(PALETTES, value=PALETTES[0], label="Palette")
|
| 574 |
+
c_era = gr.Textbox(label="Era / setting", placeholder="e.g. near-future coastal city, 1987 rural Midwest")
|
| 575 |
+
c_notes = gr.Textbox(label="Style notes (free text, appended to every prompt)", lines=2)
|
| 576 |
+
b_save_concept = gr.Button("Save concept", variant="primary")
|
| 577 |
+
md_bible = gr.Markdown("_Save the concept to build the style bible._")
|
| 578 |
+
|
| 579 |
+
with gr.Tab("2 · Characters"):
|
| 580 |
+
gr.Markdown("The **appearance** field is the consistency mechanism: it is reused word-for-word in "
|
| 581 |
+
"every shot prompt the character appears in. Write it once, precisely.")
|
| 582 |
+
with gr.Row():
|
| 583 |
+
with gr.Column():
|
| 584 |
+
ch_selector = gr.Dropdown([], label="Character", interactive=True)
|
| 585 |
+
with gr.Row():
|
| 586 |
+
b_ch_new = gr.Button("➕ New")
|
| 587 |
+
b_ch_delete = gr.Button("🗑️ Delete")
|
| 588 |
+
with gr.Column():
|
| 589 |
+
ch_name = gr.Textbox(label="Name")
|
| 590 |
+
ch_appearance = gr.Textbox(label="Appearance (LOCKED — reused verbatim in every prompt)",
|
| 591 |
+
lines=3, placeholder="mid-30s woman, sharp cheekbones, short black bob with a silver streak, faint scar on left eyebrow")
|
| 592 |
+
ch_wardrobe = gr.Textbox(label="Wardrobe")
|
| 593 |
+
ch_voice = gr.Textbox(label="Voice / accent (for H3 audio direction)")
|
| 594 |
+
ch_notes = gr.Textbox(label="Backstory / notes (not sent to the model)")
|
| 595 |
+
b_ch_save = gr.Button("Save character", variant="primary")
|
| 596 |
+
md_roster = gr.Markdown(roster_markdown(new_project()))
|
| 597 |
+
|
| 598 |
+
with gr.Tab("3 · Locations"):
|
| 599 |
+
with gr.Row():
|
| 600 |
+
with gr.Column():
|
| 601 |
+
lo_selector = gr.Dropdown([], label="Location", interactive=True)
|
| 602 |
+
with gr.Row():
|
| 603 |
+
b_lo_new = gr.Button("➕ New")
|
| 604 |
+
b_lo_delete = gr.Button("🗑️ Delete")
|
| 605 |
+
with gr.Column():
|
| 606 |
+
lo_name = gr.Textbox(label="Name")
|
| 607 |
+
lo_desc = gr.Textbox(label="Description (reused verbatim in prompts)", lines=3,
|
| 608 |
+
placeholder="abandoned ferry terminal, rusted loading crane, peeling paint, water stains")
|
| 609 |
+
lo_time = gr.Dropdown(TIMES_OF_DAY, value=TIMES_OF_DAY[0], label="Time of day")
|
| 610 |
+
lo_weather = gr.Dropdown(WEATHER, value=WEATHER[0], label="Weather")
|
| 611 |
+
lo_notes = gr.Textbox(label="Notes (not sent to the model)", lines=2)
|
| 612 |
+
b_lo_save = gr.Button("Save location", variant="primary")
|
| 613 |
+
md_locations = gr.Markdown(locations_markdown(new_project()))
|
| 614 |
+
|
| 615 |
+
with gr.Tab("4 · Story beats"):
|
| 616 |
+
gr.Markdown("**One beat per line.** Each beat becomes one shot when you click *Spawn shots from "
|
| 617 |
+
"beats*. A beat that fits one H3 clip (2–14 s) names one place, one action, one moment.")
|
| 618 |
+
beats_text = gr.Textbox(label="Beats", lines=10,
|
| 619 |
+
placeholder="Maya pushes through the ferry terminal's rusted door, flashlight beam cutting the dark\nClose on the tape recorder, its reels turning, dust drifting through the beam\nVex steps out of the shadow behind the crane, hands raised")
|
| 620 |
+
b_spawn = gr.Button("🎬 Spawn shots from beats", variant="primary")
|
| 621 |
+
|
| 622 |
+
with gr.Tab("5 · Shots & prompts"):
|
| 623 |
+
with gr.Row():
|
| 624 |
+
sh_selector = gr.Dropdown([], label="Shot", interactive=True)
|
| 625 |
+
with gr.Row():
|
| 626 |
+
b_sh_new = gr.Button("➕ New shot")
|
| 627 |
+
b_sh_delete = gr.Button("🗑️ Delete")
|
| 628 |
+
sh_name = gr.Textbox(label="Shot name")
|
| 629 |
+
sh_beat = gr.Textbox(label="Action / beat (the first sentence of the prompt)", lines=2)
|
| 630 |
+
with gr.Row():
|
| 631 |
+
sh_location = gr.Dropdown([], label="Location (from tab 3)", interactive=True)
|
| 632 |
+
sh_characters = gr.Textbox(label="Characters (comma-separated, must match tab 2 names)")
|
| 633 |
+
with gr.Row():
|
| 634 |
+
sh_size = gr.Dropdown(SHOT_SIZES, value=SHOT_SIZES[1], label="Shot size")
|
| 635 |
+
sh_angle = gr.Dropdown(ANGLES, value=ANGLES[0], label="Angle")
|
| 636 |
+
sh_movement = gr.Dropdown(MOVEMENTS, value=MOVEMENTS[0], label="Camera movement")
|
| 637 |
+
sh_lens = gr.Dropdown(LENSES, value=LENSES[2], label="Lens")
|
| 638 |
+
sh_lighting = gr.Dropdown(["high-key", "low-key", "chiaroscuro", "backlit silhouette", "soft window light",
|
| 639 |
+
"hard noir venetian-blind shadows", "neon practicals", "firelight",
|
| 640 |
+
"overcast flat", "golden backlight"], label="Lighting",
|
| 641 |
+
allow_custom_value=False, interactive=True)
|
| 642 |
+
sh_audio = gr.Textbox(label="Audio (H3 generates a soundtrack)", lines=2,
|
| 643 |
+
placeholder="rain on corrugated iron, distant foghorn, low tense synth drone")
|
| 644 |
+
with gr.Row():
|
| 645 |
+
sh_duration = gr.Slider(MIN_UI_DURATION, MAX_UI_DURATION, value=5, step=0.01, label="Duration (s)")
|
| 646 |
+
sh_frames = gr.Markdown(frames_label(5))
|
| 647 |
+
sh_canvas = gr.Dropdown(list(CANVASES), value=DEFAULT_CANVAS, label="Canvas")
|
| 648 |
+
sh_seed = gr.Number(value=42, label="Seed", precision=0)
|
| 649 |
+
b_sh_compose = gr.Button("🧩 Compose H3 prompt", variant="primary")
|
| 650 |
+
sh_prompt = gr.Textbox(label="H3 prompt", lines=6)
|
| 651 |
+
b_sh_save = gr.Button("Save shot", variant="primary")
|
| 652 |
+
md_shots = gr.Markdown(shots_markdown(new_project()))
|
| 653 |
+
|
| 654 |
+
with gr.Accordion("🖼️ Keyframes for this shot (first / last frame)", open=False):
|
| 655 |
+
gr.Markdown("Generate a still with FLUX, or upload one you made elsewhere. First/last frames "
|
| 656 |
+
"steer the clip; the backend cover-crops them to the canvas.")
|
| 657 |
+
with gr.Row():
|
| 658 |
+
with gr.Column():
|
| 659 |
+
fr_first_prompt = gr.Textbox(label="First-frame image prompt", lines=3)
|
| 660 |
+
b_fr_first_prompt = gr.Button("Compose first-frame prompt")
|
| 661 |
+
with gr.Row():
|
| 662 |
+
b_fr_gen_first = gr.Button("🎨 Generate (FLUX)")
|
| 663 |
+
fr_first = gr.Image(label="First frame", type="filepath", height=256)
|
| 664 |
+
with gr.Column():
|
| 665 |
+
fr_last_prompt = gr.Textbox(label="Last-frame image prompt", lines=3)
|
| 666 |
+
b_fr_last_prompt = gr.Button("Compose last-frame prompt")
|
| 667 |
+
with gr.Row():
|
| 668 |
+
b_fr_gen_last = gr.Button("🎨 Generate (FLUX)")
|
| 669 |
+
fr_last = gr.Image(label="Last frame", type="filepath", height=256)
|
| 670 |
+
|
| 671 |
+
with gr.Tab("6 · Render & assemble"):
|
| 672 |
+
gr.Markdown("Clips render on the backend Space (its GPU quota applies). The official "
|
| 673 |
+
"[MiniMaxAI demo](https://hf.co/spaces/MiniMaxAI/MiniMax-H3-Turbo-Lora) now serves a "
|
| 674 |
+
"workflow canvas and no longer exposes `/generate` to clients, so the default backend "
|
| 675 |
+
"is your ShotCraft Space, which also provides `/stitch` for assembly.")
|
| 676 |
+
r_backend = gr.Textbox(value=BACKEND_DEFAULT, label="Backend Space (owner/name)")
|
| 677 |
+
b_load_shot = gr.Button("⬅️ Load selected shot into the renderer")
|
| 678 |
+
with gr.Row():
|
| 679 |
+
r_prompt = gr.Textbox(label="Prompt", lines=4)
|
| 680 |
+
with gr.Column():
|
| 681 |
+
r_canvas = gr.Dropdown(list(CANVASES), value=DEFAULT_CANVAS, label="Canvas")
|
| 682 |
+
with gr.Row():
|
| 683 |
+
r_duration = gr.Slider(MIN_UI_DURATION, MAX_UI_DURATION, value=5, step=0.01, label="Duration (s)")
|
| 684 |
+
r_steps = gr.Slider(2, 28, value=6, step=1, label="Steps")
|
| 685 |
+
with gr.Row():
|
| 686 |
+
r_lora = gr.Dropdown(["larry", "lightx", "off"],
|
| 687 |
+
value="larry", label="Turbo LoRA",
|
| 688 |
+
info="larry: 6 steps · lightx: 4 steps · off: base model, 28 steps")
|
| 689 |
+
r_seed = gr.Number(value=42, label="Seed", precision=0)
|
| 690 |
+
r_upsample = gr.Checkbox(value=False, label="Upsample prompt (conditioner rewrite)")
|
| 691 |
+
r_first = gr.Image(label="First frame (optional)", type="filepath", height=192)
|
| 692 |
+
r_last = gr.Image(label="Last frame (optional)", type="filepath", height=192)
|
| 693 |
+
b_render = gr.Button("🎥 Render clip", variant="primary")
|
| 694 |
+
r_video = gr.Video(label="Clip")
|
| 695 |
+
r_report = gr.Markdown()
|
| 696 |
+
r_refined = gr.Accordion("Conditioner's refined prompt", open=False)
|
| 697 |
+
with r_refined:
|
| 698 |
+
r_refined_md = gr.Markdown()
|
| 699 |
+
with gr.Row():
|
| 700 |
+
b_add_seq = gr.Button("➕ Add clip to sequence")
|
| 701 |
+
b_clear_seq = gr.Button("🗑️ Clear sequence")
|
| 702 |
+
md_sequence = gr.Markdown("**Sequence (0 clips)**")
|
| 703 |
+
b_stitch = gr.Button("🎞️ Stitch sequence (backend ffmpeg concat)", variant="primary")
|
| 704 |
+
r_stitched = gr.Video(label="Assembled sequence")
|
| 705 |
+
|
| 706 |
+
with gr.Tab("7 · Project"):
|
| 707 |
+
with gr.Row():
|
| 708 |
+
b_export = gr.Button("💾 Export project JSON")
|
| 709 |
+
export_file = gr.File(label="Project file")
|
| 710 |
+
import_file = gr.File(label="Import project JSON", file_types=[".json"])
|
| 711 |
+
md_project = gr.Markdown()
|
| 712 |
+
|
| 713 |
+
# ---------------- listeners ----------------
|
| 714 |
+
b_save_concept.click(save_concept,
|
| 715 |
+
[project, c_title, c_logline, c_genre, c_style, c_tone, c_era, c_palette, c_notes],
|
| 716 |
+
[project, md_bible])
|
| 717 |
+
|
| 718 |
+
b_ch_new.click(new_character, [project],
|
| 719 |
+
[project, ch_selector, ch_name, ch_appearance, ch_wardrobe, ch_voice, ch_notes, md_roster])
|
| 720 |
+
ch_selector.change(load_character, [project, ch_selector],
|
| 721 |
+
[ch_name, ch_appearance, ch_wardrobe, ch_voice, ch_notes])
|
| 722 |
+
b_ch_save.click(save_character, [project, ch_selector, ch_name, ch_appearance, ch_wardrobe, ch_voice, ch_notes],
|
| 723 |
+
[project, ch_selector, md_roster])
|
| 724 |
+
b_ch_delete.click(delete_character, [project, ch_selector],
|
| 725 |
+
[project, ch_selector, ch_name, ch_appearance, ch_wardrobe, ch_voice, ch_notes, md_roster])
|
| 726 |
+
|
| 727 |
+
b_lo_new.click(new_location, [project],
|
| 728 |
+
[project, lo_selector, lo_name, lo_desc, lo_time, lo_weather, lo_notes, md_locations])
|
| 729 |
+
lo_selector.change(load_location, [project, lo_selector], [lo_name, lo_desc, lo_time, lo_weather, lo_notes])
|
| 730 |
+
b_lo_save.click(save_location, [project, lo_selector, lo_name, lo_desc, lo_time, lo_weather, lo_notes],
|
| 731 |
+
[project, lo_selector, md_locations])
|
| 732 |
+
b_lo_delete.click(delete_location, [project, lo_selector],
|
| 733 |
+
[project, lo_selector, lo_name, lo_desc, lo_time, lo_weather, lo_notes, md_locations])
|
| 734 |
+
|
| 735 |
+
b_spawn.click(spawn_shots_from_beats, [project, beats_text],
|
| 736 |
+
[project, sh_selector, md_shots])
|
| 737 |
+
b_spawn.click(lambda p: "", [project], [beats_text])
|
| 738 |
+
|
| 739 |
+
sh_selector.change(load_shot, [project, sh_selector],
|
| 740 |
+
[sh_name, sh_beat, sh_location, sh_characters, sh_size, sh_angle, sh_movement, sh_lens,
|
| 741 |
+
sh_lighting, sh_audio, sh_duration, sh_canvas, sh_seed, sh_prompt, fr_first, fr_last])
|
| 742 |
+
sh_selector.change(lambda p: gr.update(choices=sorted(p["locations"])), [project], [sh_location])
|
| 743 |
+
b_sh_new.click(new_shot, [project],
|
| 744 |
+
[project, sh_selector, sh_name, sh_beat, sh_location, sh_characters, sh_size, sh_angle,
|
| 745 |
+
sh_movement, sh_lens, sh_lighting, sh_audio, sh_duration, sh_canvas, sh_seed, sh_prompt,
|
| 746 |
+
fr_first, fr_last, md_shots])
|
| 747 |
+
b_sh_new.click(lambda p: gr.update(choices=sorted(p["locations"])), [project], [sh_location])
|
| 748 |
+
sh_duration.change(lambda s: frames_label(s), [sh_duration], [sh_frames])
|
| 749 |
+
b_sh_compose.click(compose_prompt,
|
| 750 |
+
[project, sh_name, sh_beat, sh_location, sh_characters, sh_size, sh_angle, sh_movement,
|
| 751 |
+
sh_lens, sh_lighting, sh_audio, sh_duration, sh_canvas, sh_seed], [sh_prompt])
|
| 752 |
+
b_sh_save.click(save_shot,
|
| 753 |
+
[project, sh_selector, sh_name, sh_beat, sh_location, sh_characters, sh_size, sh_angle,
|
| 754 |
+
sh_movement, sh_lens, sh_lighting, sh_audio, sh_duration, sh_canvas, sh_seed, sh_prompt,
|
| 755 |
+
fr_first, fr_last],
|
| 756 |
+
[project, sh_selector, md_shots])
|
| 757 |
+
b_sh_delete.click(delete_shot, [project, sh_selector],
|
| 758 |
+
[project, sh_selector, sh_name, sh_beat, sh_location, sh_characters, sh_size, sh_angle,
|
| 759 |
+
sh_movement, sh_lens, sh_lighting, sh_audio, sh_duration, sh_canvas, sh_seed, sh_prompt,
|
| 760 |
+
fr_first, fr_last, md_shots])
|
| 761 |
+
|
| 762 |
+
shot_editor_inputs = [project, sh_name, sh_beat, sh_location, sh_characters, sh_size, sh_angle, sh_movement,
|
| 763 |
+
sh_lens, sh_lighting, sh_audio, sh_duration, sh_canvas, sh_seed]
|
| 764 |
+
b_fr_first_prompt.click(compose_prompt, shot_editor_inputs, [fr_first_prompt])
|
| 765 |
+
b_fr_last_prompt.click(compose_prompt, shot_editor_inputs, [fr_last_prompt])
|
| 766 |
+
b_fr_gen_first.click(generate_still, [fr_first_prompt, sh_canvas], [fr_first])
|
| 767 |
+
b_fr_gen_last.click(generate_still, [fr_last_prompt, sh_canvas], [fr_last])
|
| 768 |
+
|
| 769 |
+
b_load_shot.click(load_render_fields, [project, sh_selector],
|
| 770 |
+
[r_prompt, r_canvas, r_duration, r_steps, r_seed, r_first, r_last])
|
| 771 |
+
r_lora.change(steps_for_lora, [r_lora], [r_steps])
|
| 772 |
+
b_render.click(render_clip,
|
| 773 |
+
[r_prompt, r_first, r_last, r_canvas, r_duration, r_steps, r_seed, r_lora, r_upsample, r_backend],
|
| 774 |
+
[r_video, r_report, r_refined_md])
|
| 775 |
+
b_add_seq.click(add_to_sequence, [sequence, r_backend, r_video], [sequence, md_sequence])
|
| 776 |
+
b_clear_seq.click(lambda s: ([], "**Sequence (0 clips)**"), [sequence], [sequence, md_sequence])
|
| 777 |
+
b_stitch.click(stitch_sequence, [sequence, r_backend], [r_stitched])
|
| 778 |
+
|
| 779 |
+
b_export.click(export_project, [project], [export_file])
|
| 780 |
+
import_file.change(import_project, [import_file],
|
| 781 |
+
[project,
|
| 782 |
+
c_title, c_logline, c_genre, c_style, c_tone, c_era, c_palette, c_notes,
|
| 783 |
+
ch_selector, ch_name, ch_appearance, ch_wardrobe, ch_voice, ch_notes,
|
| 784 |
+
lo_selector, lo_name, lo_desc, lo_time, lo_weather, lo_notes,
|
| 785 |
+
beats_text,
|
| 786 |
+
sh_selector, sh_name, sh_beat, sh_location, sh_characters, sh_size, sh_angle,
|
| 787 |
+
sh_movement, sh_lens, sh_lighting, sh_audio, sh_duration, sh_canvas, sh_seed,
|
| 788 |
+
sh_prompt, fr_first, fr_last,
|
| 789 |
+
md_project, md_roster, md_locations, md_shots])
|
| 790 |
+
|
| 791 |
+
return demo
|
| 792 |
+
|
| 793 |
+
|
| 794 |
+
if __name__ == "__main__":
|
| 795 |
+
build_ui().launch(server_name="0.0.0.0", server_port=7860, show_error=True)
|