SBScriptBox docs

Design document

ScriptBox architecture — from screenplay to verified storyboard

This document is for engineers working on the system. If you direct, write, or produce, start with the filmmaker guide on the homepage instead. ScriptBox splits the workflow into two halves: writing turns a screenplay into structured beats, and pre-production plans those beats, renders stills, verifies the pixels, repairs defects, and assembles video.

Overview

ScriptBox keeps five steps in separate code paths: script parsing, per-beat planning, prompt assembly, reference selection, and image verification.
#RuleHow it is enforced
01Deterministic script breakdownScene boundaries, dialogue, character/location IDs, and beat order are parsed from PDF geometry and editor blocks in plain Python — no model calls, same output for the same input.
02Structured, cached beat plansPronouns, active cast, blocking, and reference choices come from a per-beat planner validated against a JSON schema. Every inference carries evidence, confidence, and an authority label, and plans are cached by a SHA-256 of their context.
03Verification before approvalAn image returned by a provider is saved as a candidate, not an approved still. A vision verifier inspects the pixels against a beat-specific checklist. Without a verifier the frame stays unverified and is never auto-accepted.

01System architecture

The project planner processes the full screenplay once per recompute. The beat planner plans one frame at generation time. Their outputs combine inside the prompt compiler.

Script parsing, per-beat planning, and pixel verification run as separate stages Deterministic Python Model call (optional, audited) Saved state / verified output Writing PDF importer layout geometry parser Browser editor beats & live PDF preview Structured draft typed screenplay blocks Shared playbooks camera, lens & rule data Project breakdown Project planner bible · beats · locks prompts · checklists Project bundle saved state on disk Wardrobe try-ons Movie look text notes Per-beat loop Beat planner schema-checked staging Prompt compiler brief + Image 1..N roles Image provider OpenAI · Grok · Pollinations Vision verifier checklist vs. pixels repair loop Outputs Accepted still image + signed receipt Video assembly animatic or motion MP4 Review queue human approval & notes pass review

The eight stages

#StageConsumesProduces
1IngestUploaded PDF or editor draftOrdered, typed screenplay elements (scene, action, character, parenthetical, dialogue, transition)
1bStory analysisDraft (+ optional LLM)Project story pack: world, locations, cast sheets and aliases, props, timeline, per-scene staging, per-beat shot plan, stage/state locks, mood, consistency review
2Project plannerDraft + shared playbooksCharacter/location bible, sequences, drawable beats, camera plan, continuity locks, source prompts, verify checklists, production board
3WardrobeBible + sequences (+ optional LLM)Wardrobe catalog, per-scene assignments, garment images, virtual try-ons
4Beat plannerOne beat + neighbours + bibles + locks + accepted framesValidated beat plan (active cast, intent, blocking, references, physics)
5Prompt compilerSource prompt + beat plan + reference rolesStructured brief + generation policy
6GenerateBrief + ordered reference imagesCandidate image
7VerifyCandidate + checklist + identity referencesPer-criterion pass/fail with notes
8RepairFailed candidate + named defectsEdited candidate, re-verified (bounded loop)

02Project state & story packs

Shared playbooks hold default rules that apply across any film. Project state holds everything parsed, inferred, edited, or approved for one screenplay, stored locally as plain JSON and media under the data directory (configurable via SCRIPTBOX_DATA_DIR).

RecordContentsCreated bySurvives recompute?
Cast & location bibleCharacters (IDs, aliases, dialogue counts, likeness refs, visual notes) and normalized locationsProject plannerManual likenesses, notes, visual descriptions, actor names, costume locks, and manually added cast are preserved
SequencesScenes, time of day, location, cast, custom headings, per-scene look and wardrobe fieldsProject planner + scene summariesCustom headings and scene look/wardrobe fields preserved
Shot planOne record per drawable beat: shot size, angle, movement, coverage, lens, blocking, action/dialogue/speaker, cast, lock IDs, statusProject plannerRegenerated; statuses reconciled with rendered stills on disk
Continuity locksBinding physical and spatial continuity rulesProject plannerRegenerated
Movie lookStyle template, color LUT, image provider choice, look text clausesStudio UI (Step 4)Preserved
Wardrobe catalogGlobal garment catalog, scene assignments, try-on plates, analysis statusWardrobe stepPreserved
Prompts & checklistsSource prompt, prompt hash, and verification checklist per beatProject plannerRebuilt so manual edits reach prompts
Verification historyAttempt records and criterion verdicts per beatGeneration loopPreserved
Production boardLocation blocks and actor blocks for shoot planningProject plannerRegenerated
Beat assets & receiptsCandidate attempts, pending and accepted stills, per-attempt receipts, cached beat plansGeneration loopPreserved on disk
Cost audit ledgerAppend-only log of every paid call with token/image usage and pricingCost auditorPreserved
Generation checkpointFirst unresolved beat plus accepted/pending/missing state per beatRecovery reconcilerRebuilt from disk

Story packs — keeping each screenplay out of the repository

Committed playbooks are generic: no character names, places, day arcs, or script lines. Anything specific to one screenplay lives in that project's private story pack inside the gitignored data directory (overridable with SCRIPTBOX_STORY_PACK_DIR). On hosted deploys it sits on the persistent volume.

Before each breakdown, story analysis reads the draft and builds generated story-pack overlays: extracted facts (scenes, places, cues, action-line names), a story bible (locations with space tags and floor plans, cast sheets, relationships, aliases, recurring props), a timeline (story days, resolved CONTINUOUS/LATER/SAME tags, scene types), per-scene staging (left/right positions, posture, facing, cue-anchored blocking moves, state changes), a per-beat shot plan (shot size, angle, movement, lens, performance notes, must-show/must-not-show items), and a whole-script consistency review surfaced on Step 6 and at GET /api/prepro/story-review.

Every step works offline using heuristics. With an OpenAI key (PREPRO_STORY_ANALYSIS_LLM, default on), an audited LLM chain refines the heuristics while local validation drops unknown character names, invalid cues, or out-of-vocabulary shot terms. Responses are cached by request and the pack is cached by script hash, so recomputing is free until the script changes.

On the writing side, Check import catches PDF-import typing mistakes (a heading typed as action, a character cue glued to dialogue, dialogue missing a cue). It only retypes elements or splits a glued cue — never rewrites words — and the writer accepts each fix individually.

At runtime, playbook loading merges three layers per project: shared base playbooks, generated story-pack rules, and optional hand edits. Objects merge key by key; lists and scalars in a later layer override earlier ones. Every active playbook is hashed into the instruction inventory of each generation receipt. All state writes use temp-file-then-rename atomic swaps so an interrupted process never leaves a half-written JSON document or image.

03Project planner vs. beat planner

Project plannerBeat planner
RunsOnce per recomputeOnce per beat, cached by a SHA-256 of its full context
ModelNone — deterministic PythonOne OpenAI chat call with a strict JSON schema (optional)
OwnsExact dialogue, stable IDs, shot vocabulary, lenses, blocking templates, initial continuity and checklistsPronoun resolution, on-camera cast, narrative intent, spatial blocking, minimal set dressing, action physics, which accepted frames are useful references
Failure modeN/ADisabled, missing key, or error → generation continues on the deterministic path

Boundary rule. The beat planner can fill in visual and staging choices left open by the script, but it may not invent a plot event, relationship, location, costume change, dialogue, or emotional reversal. Local normalization drops unknown character IDs and unavailable reference beats, coerces every note's authority to one of screenplay_fact, continuity_fact, inference, or visualization_choice, and rejects any plan without a resolved action. Both the PDF importer and the prompt compiler filter out all-caps action lines mistakenly parsed as character cues.

04Wardrobe catalog and try-ons

Wardrobe is planned on demand and, once reviewed, feeds directly into storyboard generation.

Costumes are cataloged once and reused across scenes 01 · deterministic Seed catalog dedupe + CONTINUED scene inheritance 02 · optional LLM Wardrobe analysis unique looks & continuity groups 03 · image Garment plate one clean image per reusable item 04 · image edit Virtual try-on cast face + garment reused per pairing 05 · generation Scene lock text → prompt try-on → Image N Explicit user clicks only — opening Step 5 makes 0 paid calls
  1. Deterministic seed — existing costume text becomes deduplicated catalog records, and CONTINUED / CONTINUOUS scenes inherit the previous assignment.
  2. Optional wardrobe LLM — finds unique looks, screenplay evidence, accessories, and cross-scene continuity groups.
  3. Catalog image — one clean garment image per reusable item.
  4. Virtual try-on — character likeness plus garment produces a reusable per-character wardrobe plate.
  5. Generation lock — the text description enters the prompt; the try-on enters the ordered reference images.

Cost control. Planning, catalog images, and try-ons are separate explicit actions. Opening the Wardrobe step makes no paid call. Mutations are serialized per project so double clicks cannot charge twice or lose state.

05Runtime — the lifecycle of one beat

Generation runs sequentially per beat so the accepted result of one beat can carry continuity into the next.

Lifecycle of one beat during generation Sequential per beat so accepted frames can carry continuity into the next shot 01 · reconcile Load beat state assets & locks 02 · LLM (cached) Beat planner plan cached by hash 03 · deterministic Prompt compiler brief + Image 1..N 04 · image API Image provider candidate pixels 05 · vision check Vision verifier checklist + faces stop for human Pending review flag in /feedback bounded repair Targeted edit failed = Image 1 all checks pass Accepted still promoted with receipt pass critical defect re-verify cap atomic disk writes & provenance (never stores API keys) Candidate image per attempt Signed attempt receipt Append-only cost ledger (fsync) Resumable beat checkpoint

Generation policy

Every prompt includes a shared policy block covering beat scope, single instant, exact dialogue, identity and wardrobe locks, plausible anatomy and physics, no future action, and no unverified acceptance. A validated flashback, insert, or sub-location overrides a coarse scene tag so the prompt never mixes contradictory backdrops.

Ordered references — every image has one declared job

Reference images are assembled in priority order and capped by PREPRO_MAX_IMAGE_REFS (default 5):

  1. Repair source, when repairing
  2. Active-character virtual try-on plates
  3. Uploaded cast likeness portraits
  4. Explicit geography plates
  5. Accepted same-sequence continuity frames (scored for active cast, immediate action, and establishing geography), then location references

Each reference's role is written into the prompt (Image 1: …) and the receipt. Movie-look stills compile to text clauses by default so reference actors never replace your cast; set PREPRO_LOOK_REFS_AS_IMAGES=1 to also pass them as image inputs. For crowded repairs where a target plus four or more face references exceed the provider cap, one accepted multi-character continuity frame is retained to preserve group layout, wardrobe, scale, and geography while remaining slots go to identities needing correction.

Bounded repair

Repair runs inside Generate, not as a separate job. Only critical failures trigger it: wrong-beat or adjacent-beat staging, named-principal cast count, scripted speaker or silence rules, likeness, location, dialogue/action text, wardrobe, side-specific accessories, shot size/framing, hands/anatomy, world physics, single-frame composition, required prop count/state/ownership/placement, or a byte-identical duplicate of another beat's accepted still.

Cast scope checks every visible person including backgrounds, reflections, portraits, and screens (tracking required flat portraits/screens separately so they never turn into live duplicates). Performance checks permit an open speaking mouth only on the scripted on-camera speaker, keep visible listeners closed-mouth, and enforce closed mouths on silent beats without suppressing scripted laughter. Verifier image inputs default to detail: high (or original via OPENAI_VERIFY_IMAGE_DETAIL=original on models that support it). A likeness failure with no attached likeness photo stops for review instead of burning another call. Automatic attempts are capped by PREPRO_MAX_AUTOMATIC_ATTEMPTS (default 2, max 5).

A scene run does not abort later beats when one beat fails or stays pending review. It records that beat as unresolved, excludes its unverified pixels from continuity references, continues with accepted stills, and finishes the audit as completed_with_errors. When manual repair later resumes that beat, the prior failed verifier findings are restored as repair constraints. Local defects edit the failed candidate; full-frame reuse of another beat's staging switches to a fresh composition.

Second-pass review. Review completion is tracked independently from initial generation acceptance. An accepted still that passes a review pass is logged as verified_unchanged with its SHA-256 and dimensions — no image call runs and no pixels change. A focused repair preserves the original pre-review still as an immutable backup. Quality-first review batches cap at ten beats (shrinking to one when needed); independent read-only checks may fan out up to three lanes, while verification, installation, checkpoints, and ledger writes remain sequential.

Provider fallback

Generation walks PREPRO_IMAGE_FALLBACK_CHAIN (default openai,grok,pollinations,cursor):

ProviderTransportNotes
OpenAIOpenAI Images API (generate & edit)Reference images use edit mode with high input fidelity
Grok (xAI)OpenAI-compatible endpointText-to-image fallback
PollinationsPublic HTTP, no keyFree text-to-image fallback (no reference images)
CursorLocal handoff queueNot an HTTP API; fulfilled locally by a Cursor agent when enabled
GeminiPlaceholderNot wired yet

Placeholder or stub images are never accepted as real stills. A safety-moderated request is treated as terminal: its receipt records the moderation code, preserves any prior accepted still, and stops the fallback chain instead of routing around the safety block.

06Agentic engineering patterns

ScriptBox is built as a deterministic harness around narrow model calls rather than an open-ended autonomous loop. Each pattern below maps directly to a mechanism enforced at runtime.

Two nested loops: a bounded automatic repair loop inside a human review loop inner loop · automatic (capped at PREPRO_MAX_AUTOMATIC_ATTEMPTS, default 2, max 5) Structured retrieval beat, locks & refs Generate / edit brief + Image 1..N Vision critic strict JSON verdict local edit or fresh retry Stops early on: pass · moderation block · missing likeness photo · verifier unavailable · cap Accepted still enters continuity pool for next beat Human-in-the-loop review flag defects in /feedback, then re-run with restored constraints pass cap outer loop · manual repair only for flagged beat
PatternHow ScriptBox implements it
Bounded generator–verifier–repair loopEach beat runs an automatic inner loop (default 2 attempts, configurable up to 5): generate → vision critic → strategy switch (local edit keeping valid pixels vs. fresh generation on compositional reuse) → re-verify. Unresolved beats escalate to the outer human-in-the-loop review loop without regenerating accepted frames.
Context engineering & structured retrieval (not vector RAG)Continuity needs exact cast IDs, wardrobe locks, and scene state rather than fuzzy embedding chunks. Instead of a vector database, each beat assembles a tight, deterministic context window: current beat, immediate neighbors, active cast/wardrobe/physics locks, and scored, allow-listed prior accepted frames capped by PREPRO_MAX_IMAGE_REFS.
Strict structured outputs & local groundingStory analysis, per-beat planning, and vision verification use strict JSON Schema (response_format: json_schema). Local Python validation drops hallucinated character IDs, invalid cues, unavailable reference beats, and out-of-vocabulary shot sizes before prompt compilation.
Prompt compilation & rules-as-dataPrompts are compiled from versioned JSON playbooks, local project overlays, and the validated beat plan into a sectioned brief with explicit multimodal reference slots (Image 1..N) and look-still-to-text distillation. Every active playbook and compiled prompt is SHA-256 hashed into the attempt receipt.
Two-layer caching (content-hash + prompt caching)Locally, beat plans cache by SHA-256(model, system prompt, context), story-analysis calls cache by request hash, and whole story packs cache by script hash so unchanged recomputes cost $0. At the provider layer, stable system and playbook prefixes enable API prompt caching, and the cost auditor reads cached_tokens to price cached vs. uncached input tokens separately.
Model routing, guardrails & spend capsImage requests route across a configurable fallback chain (OpenAI → Grok → Pollinations → Cursor), stop immediately on safety moderation (never routing around blocks), fail closed if the audit ledger cannot flush, and enforce hard per-run USD caps on video generation jobs.
Observability & offline eval harnessEvery paid call logs to an fsynced append-only ledger; each attempt saves a full provenance receipt; opt-in execution dumps (SCRIPTBOX_EXECUTION_DUMPS=1) snapshot stage inputs and outputs locally; and 379 offline unit tests validate planning, prompt compilation, repair logic, and security against a fictional fixture.

07Calls per beat

PathText / vision callsImage callsTotal
First pass, plan cached or disabled1 (verify)12
First pass, fresh plan2 (plan + verify)13
With one automatic repair2–324–5

The studio shows this call budget before a run starts. Every call (including failed fallback requests) is fsynced to an append-only audit ledger with request metadata, token usage, and pricing from a dated snapshot. If the ledger cannot be written, paid calls stop immediately.

08Runtime model, concurrency and recovery

  • Process model. A single FastAPI/Uvicorn process serves the browser UI and JSON API. Generation requests are synchronous per beat; the UI steps through scenes one beat at a time.
  • Single worker. Per-project generation and wardrobe locks, image-search sessions, and YouTube capture sessions live in process memory. Always run one worker (the container image enforces this).
  • Resumability. Every generate call reconciles files on disk with project metadata first. Orphaned candidates from interrupted runs recover as pending review, never silently accepted. New runs resume from the first unresolved beat. Every rendered image is flushed atomically and re-read for byte-count and SHA-256 verification before advancing the checkpoint.
  • Raster dimensions. Candidate dimensions are inspected before verification. A 1–2 px provider drift is normalized and logged; larger size or aspect-ratio mismatches are never silently stretched or cropped.
  • Accepted-still history & locks. Replacing an accepted still copies the previous bytes into content-addressed history first and records the backup hash in the receipt. Publication holds a per-beat cross-process lock and rejects late overlapping runs if another worker already updated the beat.
  • Motion jobs. Video tasks take minutes, so Motion runs in one persistent background worker thread. Jobs survive restarts; an interrupted beat re-polls its provider task instead of paying twice. Motion state is stored separately behind a per-project lock so UI saves never overwrite worker updates.
  • Provenance. Every attempt writes a receipt containing prompts, planner I/O, reference roles and hashes, provider parameters, checklist, verifier result, output hash, and an inventory hash of active playbooks. Credentials are never recorded.

09Security model

ConcernControl
API keys in gitLocal environment files, key files, screenplay files, media (except README demo screenshots), and project data directories are gitignored and blocked by the pre-push secret guard.
Screenplay content in gitCode and committed playbooks stay generic; per-film data lives in local gitignored project storage. The secret guard also blocks staged lines matching project-configured private terms. Automated tests use a fictional fixture only.
API keys in container imagesContainer build ignores exclude environment files, drafts, exports, and PDFs. Hosted secrets come from platform environment variables.
API keys in logs/receiptsReceipts and audit events store request metadata, never keys. Keys are read from environment variables at call time only.
Public exposureWhen hosted (Railway detected or SCRIPTBOX_REQUIRE_AUTH=1), the server refuses to start without SCRIPTBOX_AUTH_PASSWORD (12+ chars); every route except /healthz requires constant-time HTTP Basic auth.
Cross-origin callsNo CORS by default (same-origin UI). Opt in with SCRIPTBOX_CORS_ORIGINS.
Path traversalProject IDs are regex-validated; asset and guide routes resolve paths and reject anything outside their allowed directory.
SSRFCast image downloads allow only public HTTP(S) hosts and cap downloads at 12 MB.
Upload limitsPDF uploads cap at 35 MB. Voice samples cap at 25 MB (header and streaming), 10 s–5 min, five per character, validated with ffprobe and re-encoded to strip metadata.
Voice samples (biometric)Gitignored and blocked by the secret guard. Sent only to ElevenLabs. Cloning requires an explicit consent checkbox plus the attesting person's name and timestamp. Deleting a voice or character deletes the remote ElevenLabs voice first.
Motion spendStarting a motion job requires explicit estimate confirmation (HTTP 409 otherwise) and enforces a hard per-run cap (PREPRO_MOTION_MAX_USD_PER_RUN) checked before every beat against actual ledger spend.

10Voice and motion

After stills are approved, the Motion step turns each beat into a short clip with Seedance 2.5 (BytePlus ModelArk, image-to-video with native audio) and gives each speaking character an ElevenLabs voice.

  • Voices (Cast step). Per character: upload or record samples and clone them (consent required), design a voice from character notes, or choose a stock voice. Optional BytePlus portrait asset IDs enable a reference-mode fallback when moderation rejects a real-person first frame.
  • Clean plate. Dialogue stills carry a drawn lower-third caption. A masked image edit removes it (verified by vision); if that fails, the frame crops above the band. Exact subtitles are burned back in at assembly.
  • Audio routing per beat. Ambient without dialogue; swap when the speaker is on screen in a supported language (Seedance speaks for lip sync, then speech is converted to the character's voice); overlay for off-screen/V.O., wide shots, or unsupported languages (TTS sets clip duration, Seedance renders ambience); native when no character voice is configured; optional per-beat lipsync sends reference audio directly to Seedance.
  • Assembly. Cuts either an animatic (stills) or a motion cut (approved clip, else latest ready clip, else still), normalized to 1280×720 / 24 fps / 48 kHz with matched loudness.
  • Offline dry run. With SCRIPTBOX_OFFLINE=1, clips are local pan-and-zoom renders with placeholder tones so the full workflow can be tested without spending credits.