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