Overview
ScriptBox keeps five steps in separate code paths: script parsing, per-beat planning, prompt assembly, reference selection, and image verification.
| # | Rule | How it is enforced |
|---|---|---|
| 01 | Deterministic script breakdown | Scene 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. |
| 02 | Structured, cached beat plans | Pronouns, 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. |
| 03 | Verification before approval | An 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.
The eight stages
| # | Stage | Consumes | Produces |
|---|---|---|---|
| 1 | Ingest | Uploaded PDF or editor draft | Ordered, typed screenplay elements (scene, action, character, parenthetical, dialogue, transition) |
| 1b | Story analysis | Draft (+ 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 |
| 2 | Project planner | Draft + shared playbooks | Character/location bible, sequences, drawable beats, camera plan, continuity locks, source prompts, verify checklists, production board |
| 3 | Wardrobe | Bible + sequences (+ optional LLM) | Wardrobe catalog, per-scene assignments, garment images, virtual try-ons |
| 4 | Beat planner | One beat + neighbours + bibles + locks + accepted frames | Validated beat plan (active cast, intent, blocking, references, physics) |
| 5 | Prompt compiler | Source prompt + beat plan + reference roles | Structured brief + generation policy |
| 6 | Generate | Brief + ordered reference images | Candidate image |
| 7 | Verify | Candidate + checklist + identity references | Per-criterion pass/fail with notes |
| 8 | Repair | Failed candidate + named defects | Edited 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).
| Record | Contents | Created by | Survives recompute? |
|---|---|---|---|
| Cast & location bible | Characters (IDs, aliases, dialogue counts, likeness refs, visual notes) and normalized locations | Project planner | Manual likenesses, notes, visual descriptions, actor names, costume locks, and manually added cast are preserved |
| Sequences | Scenes, time of day, location, cast, custom headings, per-scene look and wardrobe fields | Project planner + scene summaries | Custom headings and scene look/wardrobe fields preserved |
| Shot plan | One record per drawable beat: shot size, angle, movement, coverage, lens, blocking, action/dialogue/speaker, cast, lock IDs, status | Project planner | Regenerated; statuses reconciled with rendered stills on disk |
| Continuity locks | Binding physical and spatial continuity rules | Project planner | Regenerated |
| Movie look | Style template, color LUT, image provider choice, look text clauses | Studio UI (Step 4) | Preserved |
| Wardrobe catalog | Global garment catalog, scene assignments, try-on plates, analysis status | Wardrobe step | Preserved |
| Prompts & checklists | Source prompt, prompt hash, and verification checklist per beat | Project planner | Rebuilt so manual edits reach prompts |
| Verification history | Attempt records and criterion verdicts per beat | Generation loop | Preserved |
| Production board | Location blocks and actor blocks for shoot planning | Project planner | Regenerated |
| Beat assets & receipts | Candidate attempts, pending and accepted stills, per-attempt receipts, cached beat plans | Generation loop | Preserved on disk |
| Cost audit ledger | Append-only log of every paid call with token/image usage and pricing | Cost auditor | Preserved |
| Generation checkpoint | First unresolved beat plus accepted/pending/missing state per beat | Recovery reconciler | Rebuilt 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 planner | Beat planner | |
|---|---|---|
| Runs | Once per recompute | Once per beat, cached by a SHA-256 of its full context |
| Model | None — deterministic Python | One OpenAI chat call with a strict JSON schema (optional) |
| Owns | Exact dialogue, stable IDs, shot vocabulary, lenses, blocking templates, initial continuity and checklists | Pronoun resolution, on-camera cast, narrative intent, spatial blocking, minimal set dressing, action physics, which accepted frames are useful references |
| Failure mode | N/A | Disabled, 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.
- Deterministic seed — existing costume text becomes deduplicated catalog records, and
CONTINUED/CONTINUOUSscenes inherit the previous assignment. - Optional wardrobe LLM — finds unique looks, screenplay evidence, accessories, and cross-scene continuity groups.
- Catalog image — one clean garment image per reusable item.
- Virtual try-on — character likeness plus garment produces a reusable per-character wardrobe plate.
- 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.
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):
- Repair source, when repairing
- Active-character virtual try-on plates
- Uploaded cast likeness portraits
- Explicit geography plates
- 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):
| Provider | Transport | Notes |
|---|---|---|
| OpenAI | OpenAI Images API (generate & edit) | Reference images use edit mode with high input fidelity |
| Grok (xAI) | OpenAI-compatible endpoint | Text-to-image fallback |
| Pollinations | Public HTTP, no key | Free text-to-image fallback (no reference images) |
| Cursor | Local handoff queue | Not an HTTP API; fulfilled locally by a Cursor agent when enabled |
| Gemini | Placeholder | Not 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.
| Pattern | How ScriptBox implements it |
|---|---|
| Bounded generator–verifier–repair loop | Each 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 grounding | Story 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-data | Prompts 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 caps | Image 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 harness | Every 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
| Path | Text / vision calls | Image calls | Total |
|---|---|---|---|
| First pass, plan cached or disabled | 1 (verify) | 1 | 2 |
| First pass, fresh plan | 2 (plan + verify) | 1 | 3 |
| With one automatic repair | 2–3 | 2 | 4–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
| Concern | Control |
|---|---|
| API keys in git | Local 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 git | Code 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 images | Container build ignores exclude environment files, drafts, exports, and PDFs. Hosted secrets come from platform environment variables. |
| API keys in logs/receipts | Receipts and audit events store request metadata, never keys. Keys are read from environment variables at call time only. |
| Public exposure | When 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 calls | No CORS by default (same-origin UI). Opt in with SCRIPTBOX_CORS_ORIGINS. |
| Path traversal | Project IDs are regex-validated; asset and guide routes resolve paths and reject anything outside their allowed directory. |
| SSRF | Cast image downloads allow only public HTTP(S) hosts and cap downloads at 12 MB. |
| Upload limits | PDF 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 spend | Starting 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.