Agent skill for narrated cinematic films built entirely from code: one continuous camera over photos, maps and cards, timed to the voice. Claude Code, Codex, Cursor, Gemini CLI.
Cinematic Skill 1.0.0: narrated cinematic films built from code
Moh4696d59e465075cc
diff --git a/.agents/plugins/marketplace.json b/.agents/plugins/marketplace.jsonnew file mode 100644index 0000000..82d0f26--- /dev/null+++ b/.agents/plugins/marketplace.json@@ -0,0 +1,21 @@+{+ "name": "cinematic-skill",+ "interface": {+ "displayName": "Cinematic Skill"+ },+ "plugins": [+ {+ "name": "cinematic-skill",+ "source": {+ "source": "url",+ "url": "https://github.com/Moh4696/cinematic-skill.git",+ "ref": "main"+ },+ "policy": {+ "installation": "AVAILABLE",+ "authentication": "ON_INSTALL"+ },+ "category": "Design"+ }+ ]+}diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.jsonnew file mode 100644index 0000000..fda0dad--- /dev/null+++ b/.claude-plugin/marketplace.json@@ -0,0 +1,33 @@+{+ "name": "cinematic-skill",+ "description": "An agent skill for narrated cinematic films built entirely from code: one continuous camera over photos, documents, cards and maps, every stamp, highlight and number landing on the narrator's word. Documentaries, product launches, brand stories, explainers.",+ "owner": {+ "name": "exploraX",+ "url": "https://x.com/exploraX_"+ },+ "plugins": [+ {+ "name": "cinematic-skill",+ "description": "An agent skill for narrated cinematic films built entirely from code: one continuous camera over photos, documents, cards and maps, every stamp, highlight and number landing on the narrator's word. Documentaries, product launches, brand stories, explainers.",+ "version": "1.0.0",+ "source": "./",+ "author": {+ "name": "exploraX",+ "url": "https://x.com/exploraX_"+ },+ "homepage": "https://github.com/Moh4696/cinematic-skill",+ "repository": "https://github.com/Moh4696/cinematic-skill",+ "license": "MIT",+ "keywords": [+ "skills",+ "video",+ "film",+ "documentary",+ "explainer",+ "animation",+ "motion-graphics",+ "skia"+ ]+ }+ ]+}diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.jsonnew file mode 100644index 0000000..606182d--- /dev/null+++ b/.codex-plugin/plugin.json@@ -0,0 +1,37 @@+{+ "name": "cinematic-skill",+ "version": "1.0.0",+ "description": "An agent skill for narrated cinematic films built entirely from code: one continuous camera over photos, documents, cards and maps, every stamp, highlight and number landing on the narrator's word. Documentaries, product launches, brand stories, explainers.",+ "author": {+ "name": "exploraX",+ "url": "https://x.com/exploraX_"+ },+ "homepage": "https://github.com/Moh4696/cinematic-skill",+ "repository": "https://github.com/Moh4696/cinematic-skill",+ "license": "MIT",+ "keywords": [+ "skills",+ "video",+ "film",+ "documentary",+ "explainer",+ "animation",+ "motion-graphics",+ "skia"+ ],+ "skills": "./skills/",+ "interface": {+ "displayName": "Cinematic Skill",+ "shortDescription": "Narrated cinematic films built from code, timed to the voice.",+ "longDescription": "An agent skill for narrated cinematic films built entirely from code: one continuous camera over photos, documents, cards and maps, every stamp, highlight and number landing on the narrator's word. Documentaries, product launches, brand stories, explainers.",+ "developerName": "exploraX",+ "category": "Design",+ "capabilities": [],+ "websiteURL": "https://github.com/Moh4696/cinematic-skill",+ "defaultPrompt": [+ "Make a 90 second cinematic documentary about the Wright brothers.",+ "Turn this product launch into a 60 second narrated film.",+ "Make an explainer video about how coffee gets from cherry to cup."+ ]+ }+}diff --git a/.cursor-plugin/plugin.json b/.cursor-plugin/plugin.jsonnew file mode 100644index 0000000..664cc4f--- /dev/null+++ b/.cursor-plugin/plugin.json@@ -0,0 +1,21 @@+{+ "name": "cinematic-skill",+ "version": "1.0.0",+ "description": "An agent skill for narrated cinematic films built entirely from code: one continuous camera over photos, documents, cards and maps, every stamp, highlight and number landing on the narrator's word. Documentaries, product launches, brand stories, explainers.",+ "author": {+ "name": "exploraX"+ },+ "homepage": "https://github.com/Moh4696/cinematic-skill",+ "repository": "https://github.com/Moh4696/cinematic-skill",+ "license": "MIT",+ "keywords": [+ "skills",+ "video",+ "film",+ "documentary",+ "explainer",+ "animation",+ "motion-graphics",+ "skia"+ ]+}diff --git a/.gitattributes b/.gitattributesnew file mode 100644index 0000000..1bbd695--- /dev/null+++ b/.gitattributes@@ -0,0 +1,2 @@+*.sh text eol=lf+*.py text eol=lfdiff --git a/.github/workflows/check.yml b/.github/workflows/check.ymlnew file mode 100644index 0000000..7540291--- /dev/null+++ b/.github/workflows/check.yml@@ -0,0 +1,67 @@+name: Check skill++on:+ push:+ branches: [main]+ pull_request:++jobs:+ check:+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v4+ - uses: actions/setup-node@v4+ with:+ node-version: 22+ - uses: actions/setup-python@v5+ with:+ python-version: "3.12"+ - name: Skill loads in every agent, manifests agree, scripts parse+ run: |+ npm install --no-save --no-package-lock [email protected]+ node tests/check.mjs+ - name: Installer works in a clean home+ run: |+ export HOME="$RUNNER_TEMP/home" && mkdir -p "$HOME/.claude" "$HOME/.codex"+ bash install.sh+ test -L "$HOME/.claude/skills/cinematic-film" && test -L "$HOME/.codex/skills/cinematic-film"+ bash install.sh --uninstall --claude --codex+ test ! -e "$HOME/.claude/skills/cinematic-film"++ film:+ # makes a real film from the starter project on Linux: scratch voice, timing, stills, cues, sound, mix, video, captions+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v4+ - uses: actions/setup-python@v5+ with:+ python-version: "3.12"+ - name: Install ffmpeg, espeak-ng and the Python packages+ run: |+ sudo apt-get update -qq+ sudo apt-get install -y -qq ffmpeg espeak-ng fonts-dejavu-core libgl1 libegl1 libfontconfig1+ pip install -q -r requirements.txt+ - name: Setup check+ run: python skills/cinematic-film/scripts/check_setup.py+ - name: Starter film, end to end+ run: |+ S=skills/cinematic-film/scripts; P="$RUNNER_TEMP/film"+ python $S/new_project.py "$P"+ python $S/make_beats.py --project "$P"+ python $S/prep_assets.py --project "$P"+ python $S/tts_say.py --project "$P"+ python $S/split_takes.py --project "$P"+ python $S/build_narration.py --project "$P"+ python $S/render.py --project "$P" --probe 2,8,14 --size 640x360+ python $S/render.py --project "$P" --cues+ python $S/build_sfx.py --project "$P"+ python $S/mix_soundtrack.py --project "$P"+ python $S/render.py --project "$P" --t0 0 --t1 6 --size 640x360 --workers 2 --out out/ci.mp4 --audio audio/mix.m4a+ python $S/burn_captions.py --project "$P" --video out/ci.mp4 --audio audio/mix.m4a --style highlighter --workers 2 --out out/ci_captions.mp4+ python $S/burn_captions.py --project "$P" --srt-only --out out/ci.srt+ test -s "$P/out/ci_captions.mp4" && test -s "$P/out/ci.srt" && ls -la "$P/out" "$P/out/probe"+ - uses: actions/upload-artifact@v4+ if: always()+ with:+ name: starter-film+ path: ${{ runner.temp }}/film/outdiff --git a/.gitignore b/.gitignorenew file mode 100644index 0000000..9cf123a--- /dev/null+++ b/.gitignore@@ -0,0 +1,5 @@+node_modules/+.DS_Store+__pycache__/+*.pyc+shots/diff --git a/CHANGELOG.md b/CHANGELOG.mdnew file mode 100644index 0000000..940c17b--- /dev/null+++ b/CHANGELOG.md@@ -0,0 +1,18 @@+# Changelog++## 1.0.0 (2026-11-09)++First release: `cinematic-film`, narrated cinematic films drawn entirely in code, on any subject.++- **Engine.** One continuous camera with motion blur and handheld drift, a spotlight, shakes and auto sound cues.+ - Items: prints and torn clippings, typeset documents, cards, big type, counters, stamps, pen marks, string, maps with region fills, routes and markers.+ - Seven looks.+- **Voice.** Scratch voice for timing, any-TTS take splitting with flagged cuts, and a narration track with a timing file.+- **Story.** Beat table with a chronology lint.+- **Images.** Wikimedia Commons fetcher that records licences and refuses non-free files; a map builder for any country; one-look grading.+- **Sound and finish.**+ - Synthesised sound effects.+ - A ducked, loudness-normalised mix.+ - A memory-aware parallel render.+ - Four caption styles and SRT.+- **Projects.** "Twelve Seconds", a 90 second documentary from seven public-domain photos, and a starter explainer.diff --git a/LICENSE b/LICENSEnew file mode 100644index 0000000..bb43009--- /dev/null+++ b/LICENSE@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 exploraX++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/PROMPT.md b/PROMPT.mdnew file mode 100644index 0000000..c78913b--- /dev/null+++ b/PROMPT.md@@ -0,0 +1,61 @@+# How this was built++- **Built with:** Claude Opus 5.5 in Claude Code, by exploraX, on 2026-11-09.+- **Inputs:**+ - The code-built Al Capone documentary made earlier in the same session (5:22, Skia engine, Higgsfield voice, ElevenLabs score).+ - Zane Hoyer's tutorial on code-built documentaries.+ - The bugs met along the way.+- **Process.**+ - The skill was first written as `cinematic-doc` for history documentaries.+ - Mid-build it was opened up to any subject (`cinematic-film`).+ - It was tested end to end on both shipped projects: the Wright Flyer documentary at 1080p with captions, and the starter explainer.+- **Bugs fixed from rendered stills:** six real bugs. See the "Self-review" list in `skills/cinematic-film/SKILL.md`.++## Original prompts++Quoted as sent:++> hey I posted the video on X and people loved it. what skill do you think we can make to help them create a cinimatic documentary like this?++> okay great create it++> i want a general skill for cinematic films btw++On scope, the user chose: "Any subject (Recommended)". That meant the same code-built single-camera style for any story (product launch, brand story, science explainer, biography, history), with images from archives, your own photos or AI stills, and more looks than the evidence wall.++> can you open-source this skill in a seperate public repo and name it cinmatic skill++## Prompt to recreate this repo++> Build an open-source agent skill, `cinematic-film`, that makes narrated cinematic films entirely from code on any subject. Ship it as a standalone repo, installable with `npx skills add`, plus Claude Code, Codex, Cursor and Gemini manifests and a no-Node shell installer.+>+> **The method.** One continuous camera moves over one designed world: a board of photos, torn clippings, typeset documents, cards, big type, counters, stamps, pen marks, red string, and maps with region fills, routes and markers. Every visual hit is timed to the word the narrator says. Draw it with skia-python. World units are 4K pixels at zoom 1. The camera is a monotone cubic spline with a log-zoom channel and handheld drift, with motion-blur sub-frames on fast moves. Add a radial spotlight that dims everything but the hero, and a film finish: glow, S-curve, vignette, and half-resolution grain that changes every second frame.+>+> **Scripts** (all take `--project`):+> 1. A setup check.+> 2. A project scaffolder.+> 3. A beat table with a chronology lint.+> 4. A free scratch voice (macOS `say`, espeak-ng, or any TTS command).+> 5. A take splitter: ffmpeg silencedetect plus a segment-based dynamic program, letters-per-second flags, and forced-cut overrides.+> 6. A narration builder that writes `audio/timing.json` and allows only a 0.90 to 1.15x tempo fit.+> 7. A Wikimedia Commons fetcher that records licences, refuses non-free files and writes `credits.md`.+> 8. A map builder: TopoJSON or GeoJSON, with Albers, equirectangular and Mercator projections and Sutherland-Hodgman clipping.+> 9. Asset prep: duotone or natural grading, and generated textures.+> 10. A render driver: probes, contact strips, a cue list, and a parallel MP4 with a worker count that fits in memory.+> 11. A sound-effects synthesiser with no samples.+> 12. A sidechain-ducked, two-pass loudness mixer.+> 13. A caption burner with four styles and SRT output.+>+> **Engine details.** The scene API is `build_film(doc)`, with `doc.L(i)`, `doc.E(i)`, `doc.W(i, "spoken word")` and `doc.on(print, fx, fy)`, plus `film.shot()` to key the camera and spotlight together. Items cue their own sound effects, and fast moves get an automatic whoosh. Font roles fall back across platforms. There are seven looks: wall, slate, charcoal, paper, studio, blueprint and night.+>+> **Performance rules to bake in.**+> - Tile textures with drawImageRect; never use repeat shaders under rotation.+> - Give every item bounds for culling.+> - Cache big vectors as images, and draw them live when the camera is close.+> - Cap photo sizes, and cap x264 lookahead at 4K.+>+> **Docs.** A SKILL.md with seven rules, an 11-step workflow with four approval gates, and a self-review checklist. References on story shapes (documentary, launch, brand, explainer, biography), voice, images and rights, film, sound, and performance.+>+> **Projects to ship.** A runnable studio-look starter explainer that needs no photos, and a 90 second public-domain documentary about the Wright Flyer as the worked example.+>+> **Checks.** CI parses the skill and makes a real film on Linux. No em dashes anywhere.diff --git a/README.md b/README.mdnew file mode 100644index 0000000..2bfe342--- /dev/null+++ b/README.md@@ -0,0 +1,145 @@+<h1 align="center">Cinematic Skill</h1>++<p align="center">Narrated cinematic films, built entirely from code, by your coding agent.</p>++<p align="center">+ <a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-24292f?style=flat" alt="MIT License" /></a>+ + <img src="https://img.shields.io/badge/agents-Claude%20Code%20%C2%B7%20Codex%20%C2%B7%20Cursor%20%C2%B7%20Gemini%20%C2%B7%20OpenCode-24292f?style=flat" alt="Works with Claude Code, Codex, Cursor, Gemini CLI and OpenCode" />+ + <a href="https://github.com/Moh4696/cinematic-skill/actions/workflows/check.yml"><img src="https://github.com/Moh4696/cinematic-skill/actions/workflows/check.yml/badge.svg" alt="Checks" /></a>+</p>++<p align="center">+ <img src="examples/film-cold-open.webp" alt="The cold open of a code-built documentary about the first flight: the date set big on a yellow block, the camera pulls back to a map pin on the Outer Banks, then glides to the 1903 first-flight photograph pinned to a cork wall as counters roll up to 12 seconds and 120 feet." width="100%" />+</p>++Ask your agent for "a 90 second documentary about the Wright brothers" and it writes the script, records a voice, finds public-domain photos with their licences, and builds one continuous camera move over a single designed world. Stamps slam, highlighters swipe and numbers roll up on the exact word the narrator says. It finishes with sound effects, an optional score and burned-in captions.++Nothing is generated video. Every frame is drawn by code (Skia, in Python), so the film renders the same every time, changes are cheap, and a new voice re-times the whole film by itself.++<table>+ <tr>+ <td width="50%"><img src="examples/film-wall.webp" alt="The final pull-back of the documentary: a US map print with Ohio and North Carolina filled, a route from Dayton to Kill Devil Hills, portraits, a typeset letter, Langley's failed machine with two stamps, and the first-flight photo with its counters, all on one cork wall" /></td>+ <td width="50%"><img src="examples/film-explainer.webp" alt="The starter explainer in the light studio look: the title From Cherry to Cup over four cards, Grow, Pick, Roast and Brew, joined by arrows, with a 200 degree counter" /></td>+ </tr>+</table>++<sub>Left: the final frame of "Twelve Seconds", the 90 second documentary that ships as the worked example, made from seven public-domain photos. Right: the starter explainer that every new project begins as.</sub>++## Install++```bash+npx skills add Moh4696/cinematic-skill+```++That uses the [`npx skills`](https://github.com/vercel-labs/skills) CLI (Node 22.20+). It installs for Claude Code, Codex, Cursor, Gemini CLI, OpenCode and dozens more. Start a new agent session afterwards.++<details>+<summary>Claude Code plugin</summary>++```+/plugin marketplace add Moh4696/cinematic-skill+/plugin install cinematic-skill@cinematic-skill+```++</details>++<details>+<summary>Codex plugin</summary>++```bash+codex plugin marketplace add Moh4696/cinematic-skill+codex plugin add cinematic-skill@cinematic-skill+```++</details>++<details>+<summary>Gemini CLI</summary>++```bash+gemini extensions install https://github.com/Moh4696/cinematic-skill+```++</details>++<details>+<summary>Without Node: the shell installer</summary>++```bash+curl -fsSL https://raw.githubusercontent.com/Moh4696/cinematic-skill/main/install.sh | bash+```++It clones to `~/.cinematic-skill` and links the skill into every coding agent it finds. Run it again to update. From a clone: `./install.sh --claude --codex`, `./install.sh --dir path/to/skills`, `./install.sh --copy`, `./install.sh --uninstall`.++</details>++Then install what the scripts use:++```bash+pip install -r requirements.txt # skia-python, numpy, pillow (scipy optional)+```++ffmpeg must be on your PATH. The skill's `check_setup.py` checks everything and says what's missing.++## What it makes++| Kind | Look | Images |+| --- | --- | --- |+| Documentary, history, true crime | Cork evidence wall, slate | Archive photos and documents, black and white |+| Product launch, brand or founder story | Studio, charcoal | Your own product shots and photos, in colour |+| Science, engineering, how it works | Blueprint, paper | Diagrams, archive or AI stills |+| Tech, space, trailers | Night | Screenshots, renders, AI stills |++The items work on every look:++- photos and torn newspaper clippings+- typeset documents with real quotes+- clean cards+- big distressed type and rolling counters+- stamps, pen circles and highlighter swipes+- red string between prints+- maps of any country, with filled regions, routes and markers++A spotlight follows the camera so each line has one hero.++## How it works++1. **Story.** The agent researches, fact-checks and writes the script: one idea per line, and time only moves forward after the opening. Each line also says what the camera shows. A beat table with a chronology lint goes to you for approval.+2. **Voice.** A free scratch voice (macOS `say` or espeak-ng) times the film first. The final voice can be any TTS or a person, recorded one section at a time and split into timed lines automatically. Suspect cuts get flagged.+3. **Images.** Wikimedia Commons search and download, with each licence recorded. Non-free files are refused. You can also add your own photos or AI stills. `credits.md` is written for you.+4. **Scene.** A short Python file places items on the voice's timing (`doc.W(line, "word")`) and keys the camera.+5. **Review.** The agent renders stills and contact strips of every move and checks them for known mistakes before showing you a draft.+6. **Sound and finish.** It synthesises the sound effects (nothing to license) and mixes them with the voice and an optional score, ducked and loudness-normalised. A memory-aware parallel render follows, then four caption styles and an SRT.++The agent stops for your approval after the beat table, the look, and a 30 second draft.++## Try the example++```bash+cd skills/cinematic-film/scripts+python3 new_project.py ~/wright --example+python3 fetch_commons.py get --project ~/wright+python3 make_map.py --project ~/wright && python3 prep_assets.py --project ~/wright+python3 tts_say.py --project ~/wright && python3 split_takes.py --project ~/wright && python3 build_narration.py --project ~/wright+python3 render.py --project ~/wright --size 1280x720 --out out/draft.mp4 --audio audio/narration.m4a+```++On a 16 GB laptop the 92 second film renders at 1080p in about 6 minutes.++## Credits++Built from a 5 minute documentary about Al Capone that exploraX made with an agent, then opened up to any subject. The single-camera evidence-wall method follows [Zane Hoyer's tutorial on code-built documentaries](https://www.youtube.com/watch?v=e2Fykz51Nxg). The rules and code here are our own, written from what broke along the way. The example film uses public-domain photographs from Wikimedia Commons; see its `photos.json`.++## Works well with++- [Open 3D Skills](https://github.com/Moh4696/open-3d-skills): three.js scenes, scroll films and frame-exact recording, from the same author. Its `motion-assets` skill plans AI stills.++## Feedback++Open an issue or a pull request, or find me on X at [@exploraX_](https://x.com/exploraX_).++## License++[MIT License](LICENSE) · Copyright (c) 2026 exploraXdiff --git a/examples/film-cold-open.webp b/examples/film-cold-open.webpnew file mode 100644index 0000000..b1c4ce7Binary files /dev/null and b/examples/film-cold-open.webp differdiff --git a/examples/film-explainer.webp b/examples/film-explainer.webpnew file mode 100644index 0000000..67e8b5fBinary files /dev/null and b/examples/film-explainer.webp differdiff --git a/examples/film-wall.webp b/examples/film-wall.webpnew file mode 100644index 0000000..e6f2f7dBinary files /dev/null and b/examples/film-wall.webp differdiff --git a/gemini-extension.json b/gemini-extension.jsonnew file mode 100644index 0000000..659d0ef--- /dev/null+++ b/gemini-extension.json@@ -0,0 +1,5 @@+{+ "name": "cinematic-skill",+ "version": "1.0.0",+ "description": "An agent skill for narrated cinematic films built entirely from code: one continuous camera over photos, documents, cards and maps, every stamp, highlight and number landing on the narrator's word. Documentaries, product launches, brand stories, explainers."+}diff --git a/install.sh b/install.shnew file mode 100755index 0000000..34bc07e--- /dev/null+++ b/install.sh@@ -0,0 +1,139 @@+#!/usr/bin/env bash+# Install Cinematic Skill for every coding agent on this machine, without Node.+# (With Node 22.20+, `npx skills add Moh4696/cinematic-skill` does the same.)+#+# curl -fsSL https://raw.githubusercontent.com/Moh4696/cinematic-skill/main/install.sh | bash+#+# Run from the internet, it clones the repo to ~/.cinematic-skill (or updates it) and links the+# skills from there, so `bash ~/.cinematic-skill/install.sh` again (or a git pull) updates them.+# Run from a clone, it links from that clone.+#+# ./install.sh every agent found: Claude Code, Codex, Cursor, Gemini CLI, OpenCode+# ./install.sh --claude --codex only these (also --cursor --gemini --opencode --agents)+# ./install.sh --dir PATH into any skills folder+# ./install.sh --copy copy instead of symlink (Windows, synced folders)+# ./install.sh cinematic-film only this skill, by name+# ./install.sh --list show the skills+# ./install.sh --uninstall remove links and copies this script made+#+# Needs bash and git. Nothing else is installed; the skills' own scripts list what they use.++set -euo pipefail++REPO_URL="https://github.com/Moh4696/cinematic-skill.git"+HOME_CLONE="${CINEMATIC_HOME:-$HOME/.cinematic-skill}"+MARK=".cinematic-skill"++SELF="${BASH_SOURCE[0]:-}"+REPO=""+if [[ -n $SELF && -f $SELF ]]; then REPO="$(cd "$(dirname "$SELF")" && pwd)"; fi++# piped from curl (or run outside a clone): fetch the repo, then run the copy inside it+if [[ -z $REPO || ! -d $REPO/skills ]]; then+ command -v git >/dev/null || { echo "git is required" >&2; exit 1; }+ if [[ -d $HOME_CLONE/.git ]]; then+ echo "updating $HOME_CLONE"+ git -C "$HOME_CLONE" pull --ff-only --quiet+ else+ echo "cloning to $HOME_CLONE"+ git clone --depth 1 --quiet "$REPO_URL" "$HOME_CLONE"+ fi+ exec bash "$HOME_CLONE/install.sh" "$@"+fi++SKILLS_DIR="$REPO/skills"+targets=()+mode=install+copy=0+wanted=()++add_target() { targets+=("$1"); }+while [[ $# -gt 0 ]]; do+ case "$1" in+ --claude) add_target "$HOME/.claude/skills" ;;+ --codex) add_target "${CODEX_HOME:-$HOME/.codex}/skills" ;;+ --cursor) add_target "$HOME/.cursor/skills" ;;+ --gemini) add_target "$HOME/.gemini/skills" ;;+ --opencode) add_target "$HOME/.config/opencode/skills" ;;+ --agents) add_target "$HOME/.agents/skills" ;;+ --dir) shift; add_target "${1:?--dir needs a path}" ;;+ --copy) copy=1 ;;+ --list) mode=list ;;+ --uninstall) mode=uninstall ;;+ -h|--help) awk 'NR>1 { if ($0 !~ /^#/) exit; sub(/^# ?/, ""); print }' "$REPO/install.sh"; exit 0 ;;+ -*) echo "unknown flag: $1" >&2; exit 2 ;;+ *) wanted+=("$1") ;;+ esac+ shift+done++# no agent named: every agent whose home folder exists+if [[ ${#targets[@]} -eq 0 ]]; then+ [[ -d $HOME/.claude ]] && add_target "$HOME/.claude/skills"+ [[ -d ${CODEX_HOME:-$HOME/.codex} ]] && add_target "${CODEX_HOME:-$HOME/.codex}/skills"+ [[ -d $HOME/.cursor ]] && add_target "$HOME/.cursor/skills"+ [[ -d $HOME/.gemini ]] && add_target "$HOME/.gemini/skills"+ # OpenCode also reads ~/.claude/skills; linking both would list every skill twice+ [[ -d $HOME/.config/opencode && ! -d $HOME/.claude ]] && add_target "$HOME/.config/opencode/skills"+ if [[ ${#targets[@]} -eq 0 ]]; then+ echo "no coding agent found; installing to ~/.claude/skills (use --dir for another place)"+ add_target "$HOME/.claude/skills"+ fi+fi++# frontmatter name: of a SKILL.md, falling back to the folder name+skill_name() {+ awk 'NR==1 && $0!="---" { exit } NR>1 && /^---[[:space:]]*$/ { exit }+ NR>1 && /^name:/ { sub(/^name:[[:space:]]*/, ""); gsub(/^["'\'']|["'\'']$/, ""); print; exit }' "$1"+}+wants() {+ [[ ${#wanted[@]} -eq 0 ]] && return 0+ local w; for w in "${wanted[@]}"; do [[ $w == "$1" ]] && return 0; done+ return 1+}+# true if PATH is a link into this repo, or a copy this script made+ours() {+ local p="$1"+ if [[ -L $p ]]; then [[ "$(readlink "$p")" == "$SKILLS_DIR"/* ]]; return; fi+ [[ -f $p/$MARK ]]+}++if [[ $mode == uninstall ]]; then+ for t in "${targets[@]}"; do+ [[ -d $t ]] || continue+ for d in "$SKILLS_DIR"/*/; do+ n="$(skill_name "$d/SKILL.md")"; n="${n:-$(basename "$d")}"+ p="$t/$n"+ if [[ -e $p || -L $p ]] && ours "$p"; then rm -rf "$p"; echo "removed $p"; fi+ done+ done+ exit 0+fi++names=()+for d in "$SKILLS_DIR"/*/; do+ d="${d%/}"+ [[ -f $d/SKILL.md ]] || continue+ n="$(skill_name "$d/SKILL.md")"; n="${n:-$(basename "$d")}"+ names+=("$n")+ wants "$n" || continue+ if [[ $mode == list ]]; then printf '%-16s %s\n' "$n" "skills/$(basename "$d")"; continue; fi+ for t in "${targets[@]}"; do+ mkdir -p "$t"+ p="$t/$n"+ if [[ -e $p || -L $p ]]; then+ if ours "$p"; then rm -rf "$p"+ else echo "skip $p (something else is installed there; move it aside first)" >&2; continue; fi+ fi+ if [[ $copy == 1 ]]; then cp -R "$d" "$p"; touch "$p/$MARK"; echo "copied $p"+ else ln -s "$d" "$p"; echo "linked $p"; fi+ done+done++if [[ ${#wanted[@]} -gt 0 ]]; then+ for w in "${wanted[@]}"; do+ found=0; for n in "${names[@]}"; do [[ $n == "$w" ]] && found=1; done+ [[ $found == 1 ]] || { echo "no skill named '$w'; available: ${names[*]}" >&2; exit 1; }+ done+fi+[[ $mode == list ]] || echo "done. Start a new agent session to load the skills."diff --git a/requirements.txt b/requirements.txtnew file mode 100644index 0000000..560d0c1--- /dev/null+++ b/requirements.txt@@ -0,0 +1,7 @@+# Python packages the skill's scripts use:+# pip install -r requirements.txt+# ffmpeg and ffprobe must be on PATH as well.+skia-python>=87.6 # the film engine (tested with 144.1)+numpy>=1.24+pillow>=10+scipy>=1.10 # optional: faster sound-effects renderdiff --git a/skills/cinematic-film/SKILL.md b/skills/cinematic-film/SKILL.mdnew file mode 100644index 0000000..52a418c--- /dev/null+++ b/skills/cinematic-film/SKILL.md@@ -0,0 +1,100 @@+---+name: cinematic-film+description: Makes narrated cinematic films entirely from code, on any subject. One continuous camera glides over one designed world of photos, documents, cards, maps with routes and big numbers, with every stamp, highlight and number landing on the narrator's word, then sound effects, an optional score and burned-in captions. For documentaries and history, product launches, brand and founder stories, science and tech explainers, biographies and true crime. Covers the script, voiceover from any TTS split into timed lines, images (archives with their licences, your own photos, AI stills), a beat table, the scene, self-review stills and a memory-safe parallel render. Use for "make a cinematic video about", "documentary about", "explainer video", "launch film", "Vox-style video", "evidence board animation", or turning a story into a video for X, YouTube or TikTok.+---++# Cinematic film++A film made this way is one camera move over one world. Every photo, card, clipping, map and number lives on one big board, and the camera travels between them along string, routes and arrows as the story moves. Every visual hit is timed to the word the narrator says. It is all code (Skia in Python), so it renders the same every time, any topic fits, and a new voice re-times the whole film by itself.++Built from a 5:22 documentary about Al Capone, then opened up to any subject. The single-camera method follows Zane Hoyer's tutorial on code-built documentaries ([video](https://www.youtube.com/watch?v=e2Fykz51Nxg)); the rules here are written fresh from what broke while making it.++## Tools++| File | What it does |+| --- | --- |+| `scripts/check_setup.py` | Checks Python, skia-python, ffmpeg, fonts and memory; says what to install |+| `scripts/new_project.py` | Starts a project from `assets/template/` (a runnable explainer), or the documentary example with `--example` |+| `scripts/make_beats.py` | Writes `beats.md`, the table you approve; lints chronology, line length, digits in spoken text |+| `scripts/tts_say.py` | Free scratch voice (macOS `say`, espeak-ng, or any TTS command) to time the film before the final voice |+| `scripts/split_takes.py` | Cuts whole-section takes into one clip per line and flags suspect cuts |+| `scripts/build_narration.py` | Joins the lines into `audio/narration.m4a` and `audio/timing.json`, which the film is built on |+| `scripts/fetch_commons.py` | Searches Wikimedia Commons, downloads with licence and credit, refuses non-free files, writes `credits.md` |+| `scripts/make_map.py` | Projects public-domain boundaries (any country or region) for the map |+| `scripts/prep_assets.py` | Grades every image into one look (black and white, sepia or natural colour); generates the board textures |+| `scripts/engine.py` | The film engine: camera, spotlight, items, maps, looks, film finish |+| `scripts/render.py` | Stills, contact strips, the cue list, and the parallel MP4 render |+| `scripts/build_sfx.py` | Synthesises every sound effect from the cue list (no samples, nothing to license) |+| `scripts/mix_soundtrack.py` | Voice, effects and optional music, ducked and loudness-normalised |+| `scripts/burn_captions.py` | Burns one of four caption styles into the finished film and writes an SRT |++Needs Python 3.9+, `pip install skia-python numpy pillow` (scipy optional) and ffmpeg. Run `scripts/check_setup.py` first. All commands take `--project <folder>`.++## Pick the film++| Kind | Look | Images | Typical items |+| --- | --- | --- | --- |+| History, true crime, investigation | `wall`, `slate` | Archive photos and documents, graded `bw` | Prints, torn clippings, stamps, red string, map routes |+| Product launch, brand or founder story | `studio`, `charcoal` | Your product shots and team photos, graded `natural` | Cards, big numbers, counters, arrows |+| Science, engineering, how it works | `blueprint`, `paper` | Diagrams, archive or AI stills | Cards, counters, pen marks, maps |+| Tech, space, trailers | `night` | Screenshots, renders, AI stills | Big type, counters, routes, cards |++Mix freely: the looks are a board and a finish, and every item works on every look. `references/story.md` has a story shape for each kind.++## The rules++1. **One hero per line.** Each narration line has exactly one thing the camera is on. The spotlight dims everything else.+2. **Hits land on the spoken word.** A stamp slams on "charged", not on the line start. Time everything with `doc.W(line, "word")`.+3. **Show a phrase one way.** Either type it on screen or show it on a real document, never both. Body copy on documents is grey rows, never filler words.+4. **Time only moves forward after the opening.** A cold open may jump ahead. After one bridge line ("Four years earlier..."), story time only goes forward.+5. **Type you can read on a phone in one second.** Big condensed caps. A typed label on screen should be about 3% or more of frame height.+6. **Less is more.** Strings fade after their beat, and old items dim. The final pull-back should look composed, not cluttered.+7. **Nothing invented that looks real.** Real photos and documents get credits. A document drawn in code is labelled a recreation and quotes only words that were really written. AI images are fine for illustration, but never as evidence of a real event or a real person.++## Workflow++Stop for the user's approval at the four gates (marked **Gate**).++1. **Story.** Research, then write `script.json`: takes (sections) of lines, each with `text`, `spoken` (numbers as words), `hero` and `typed`. Keep fact notes alongside. 60 to 90 seconds is about 150 to 230 words. Details are in `references/story.md`.+2. **Beat table.** Run `scripts/make_beats.py` and fix every lint warning. **Gate:** the user approves `beats.md`, including the facts.+3. **Images.** List every image in `photos.json`: its id, kind and where it comes from.+ - Archive images: `fetch_commons.py search`, `category` and `get`.+ - The user's own files: drop them in `<project>/assets/photos/`.+ - AI stills: generate them in one style (the `motion-assets` skill plans and prices them).+ - `references/archive.md` covers other archives and the rights rules.+4. **Scratch voice.** Run `tts_say.py`, then `split_takes.py`, then `build_narration.py`. Listen to every line `split_takes.py` flags. Now the timings are real.+5. **Assets.** Run `make_map.py` if the story travels, then `prep_assets.py`.+6. **Scene.** Write `scene.py`: lay out the board in clusters per section, add items on `doc.L`/`doc.W` times, then camera and spotlight keys (`film.shot`). Read `references/film.md`. Both shipped projects show the patterns: `assets/template/scene.py` (explainer, studio look) and `assets/wright-flyer/scene.py` (documentary, every item type).+7. **Look test.** Run `render.py --probe` on one still per line at 1280x720 and look at all of them, then `--strip` on every big camera move. **Gate:** show the user stills of the opening and the look.+8. **Draft.** Render the first 30 seconds at 1280x720 with the scratch voice. **Gate:** the user watches it.+9. **Final voice.** Record it with any TTS or a person (`references/voice.md`). Run split, build, and probes again; nothing in the scene changes.+10. **Sound.** Run `render.py --cues`, then `build_sfx.py`, then `mix_soundtrack.py`, adding a score if wanted. Read `references/sound.md`.+11. **Finish.** Do the full render, then `burn_captions.py` and the SRT. Read `references/performance.md` before rendering at 1440p or 4K. Hand over `credits.md` with the film.++## Self-review, every time++Look at the stills before you claim anything works. These are the mistakes that showed up, every one in a real render:++- Dark ink on a dark board: invisible. Use light type on dark looks, or `bar_h=0.92` for a full label block behind dark type.+- The camera moved on but the spotlight stayed behind, leaving a dark frame. Use `film.shot()` unless they should part.+- Map scale too small: a whole coast smaller than one photo. Pick `K` so each place with prints gets its own room (`references/film.md`).+- Map labels colliding. Put the label on the side away from its neighbour.+- A cluster straddling the map's edge. Keep clusters either on the map or clearly off it.+- Highlights a few pixels off their words. Use `PaperDoc.phrase_spans`, and `doc.on(print, fx, fy)` with fractions read off a grid overlay of the image.++## Shipped projects++- `assets/template/`: "From Cherry to Cup", a 25 second explainer in the studio look, made of cards, arrows and a counter, with no images. `new_project.py my-film` copies it. Give it a scratch voice and it renders.+- `assets/wright-flyer/`: "Twelve Seconds", a 90 second documentary about the first flight and the $50,000 rival who crashed twice. It uses seven public-domain photos, the US map, two typeset documents and every item type.++```bash+python3 scripts/new_project.py wright --example+python3 scripts/fetch_commons.py get --project wright+python3 scripts/make_map.py --project wright && python3 scripts/prep_assets.py --project wright+python3 scripts/tts_say.py --project wright && python3 scripts/split_takes.py --project wright && python3 scripts/build_narration.py --project wright+python3 scripts/render.py --project wright --size 1280x720 --out out/draft.mp4 --audio audio/narration.m4a+```++## Related skills++From [Open 3D Skills](https://github.com/Moh4696/open-3d-skills): `motion-assets` plans and prices AI stills when a film needs illustration, and `frame-capture` records web pages instead of code-drawn films.diff --git a/skills/cinematic-film/agents/openai.yaml b/skills/cinematic-film/agents/openai.yamlnew file mode 100644index 0000000..207b58c--- /dev/null+++ b/skills/cinematic-film/agents/openai.yaml@@ -0,0 +1,3 @@+interface:+ display_name: "Cinematic Film"+ short_description: "Narrated films built from code: one camera over photos, maps and cards, timed to the voice"diff --git a/skills/cinematic-film/assets/template/map.json b/skills/cinematic-film/assets/template/map.jsonnew file mode 100644index 0000000..2717bc2--- /dev/null+++ b/skills/cinematic-film/assets/template/map.json@@ -0,0 +1,10 @@+{+ "maps": [{+ "name": "world",+ "source": "https://cdn.jsdelivr.net/npm/world-atlas@2/countries-50m.json",+ "object": "countries",+ "projection": {"type": "equirect", "lon0": 10, "lat0": 0},+ "drop": ["Antarctica"],+ "places": {"Addis Ababa": [9.03, 38.74], "Bogota": [4.71, -74.07], "Hanoi": [21.03, 105.85]}+ }]+}diff --git a/skills/cinematic-film/assets/template/photos.json b/skills/cinematic-film/assets/template/photos.jsonnew file mode 100644index 0000000..5d16949--- /dev/null+++ b/skills/cinematic-film/assets/template/photos.json@@ -0,0 +1,5 @@+{+ "grade": "natural",+ "photos": [],+ "recreations": []+}diff --git a/skills/cinematic-film/assets/template/scene.py b/skills/cinematic-film/assets/template/scene.pynew file mode 100644index 0000000..b451083--- /dev/null+++ b/skills/cinematic-film/assets/template/scene.py@@ -0,0 +1,46 @@+"""Starter scene: a short explainer in the studio look, built only from code (no photos needed).++Runs as soon as the project has a voice:+ tts_say.py -> split_takes.py -> build_narration.py -> render.py --probe / --out++Replace it with your film. The pattern stays the same: lay the world out in clusters, add items on+voiceover times (doc.L line start, doc.W spoken word), then camera keys with film.shot().+World units are 4K pixels at zoom 1 (zoom 0.5 shows 7680 x 4320).+"""+from engine import BigText, Card, Counter, Film, PenMark, Route++ACCENT = (198, 92, 46)+INK = (34, 32, 30)+CARD_W, CARD_H, GAP = 3200, 1800, 4400 # four cards in a row, one per step+XS = [i * GAP for i in range(4)]+MID = (XS[0] + XS[-1]) / 2+++def build_film(doc):+ L, E, W = doc.L, doc.E, doc.W+ film = Film(doc.duration, fps=30, look="studio")++ # 1 the title, then an underline on the word that matters+ film.add(BigText("FROM CHERRY TO CUP", MID, -2300, 760, L(1) - 0.1, rgb=INK, shadow=False, grunge=False, type_on=0.7))+ film.add(PenMark("underline", MID, -2080, 5800, 60, t_in=W(1, "cherry") - 0.2, dur=0.5, width=34, rgb=ACCENT))++ # 2-5 a card per step appears as its line starts; arrows draw on between them+ steps = [("GROW", ["On a shrub, in the Coffee Belt"], 2),+ ("PICK", ["Ripe cherries only", "Fruit washed or dried away"], 3),+ ("ROAST", ["The green seed turns brown"], 4),+ ("BREW", ["Ground, brewed, poured"], 5)]+ for (title, lines, line), x in zip(steps, XS):+ film.add(Card(x, 0, CARD_W, CARD_H, L(line) + 0.05, title=title, lines=lines, accent=ACCENT, title_size=300, body_size=150))+ for a, b, line in zip(XS, XS[1:], (3, 4, 5)):+ film.add(Route((a + CARD_W / 2 + 80, 0), (b - CARD_W / 2 - 80, 0), t_in=L(line) - 0.2, dur=0.5, bend=-0.3, width=24, rgb=INK))+ film.add(Counter(XS[2], 2150, 600, 200, W(4, "two") - 0.1, dur=1.0, suffix="°C", caption="ROAST", rgb=ACCENT))++ # camera: the title, then along the row (landing on each card just after it appears), then the whole journey+ film.shot(0.0, MID, -2250, 0.52)+ film.shot(E(1) + 0.3, MID, -1100, 0.34) # wide: the title and the empty row the cards will fill+ for (title, lines, line), x in zip(steps, XS):+ film.shot(L(line) + 0.45, x, 350, 0.62, rot=-0.4 if line % 2 else 0.4)+ film.shot(E(line) - 0.1, x + 350, 500 if line != 4 else 600, 0.58)+ film.shot(L(6) + 0.6, MID, 0, 0.27)+ film.shot(film.duration, MID, -200, 0.205, radius=20000, strength=0.1)+ return filmdiff --git a/skills/cinematic-film/assets/template/script.json b/skills/cinematic-film/assets/template/script.jsonnew file mode 100644index 0000000..60062ef--- /dev/null+++ b/skills/cinematic-film/assets/template/script.json@@ -0,0 +1,30 @@+{+ "title": "From Cherry to Cup",+ "takes": [+ {"take": "T01_open", "lines": [+ {"id": 1, "text": "Every cup of coffee starts as a cherry.",+ "spoken": "Every cup of coffee starts as a cherry.",+ "hero": "the title, set big", "typed": "FROM CHERRY TO CUP", "gap_after": 0.8}+ ]},+ {"take": "T02_journey", "lines": [+ {"id": 2, "text": "It grows on a shrub, in a band around the equator called the Coffee Belt.",+ "spoken": "It grows on a shrub, in a band around the equator called the Coffee Belt.",+ "hero": "card GROW", "typed": "GROW"},+ {"id": 3, "text": "Pickers take the ripe cherries, and the fruit is washed or dried away.",+ "spoken": "Pickers take the ripe cherries, and the fruit is washed or dried away.",+ "hero": "card PICK", "typed": "PICK"},+ {"id": 4, "text": "The green seed inside is roasted at around 200 degrees.",+ "spoken": "The green seed inside is roasted at around two hundred degrees.",+ "hero": "card ROAST; the number rolls up", "typed": "ROAST · 200°C"},+ {"id": 5, "text": "Then it is ground, brewed, and poured.",+ "spoken": "Then it is ground, brewed, and poured.",+ "hero": "card BREW", "typed": "BREW"}+ ]},+ {"take": "T03_close", "lines": [+ {"id": 6, "text": "Months of work, for a few minutes in a cup.",+ "spoken": "Months of work, for a few minutes in a cup.",+ "hero": "pull back: the whole journey", "typed": ""}+ ]}+ ],+ "fact_notes": ["Replace this template with your own story; keep one note per claim with its source."]+}diff --git a/skills/cinematic-film/assets/wright-flyer/map.json b/skills/cinematic-film/assets/wright-flyer/map.jsonnew file mode 100644index 0000000..42cedf2--- /dev/null+++ b/skills/cinematic-film/assets/wright-flyer/map.json@@ -0,0 +1,12 @@+{+ "maps": [{+ "name": "us",+ "source": "https://cdn.jsdelivr.net/npm/us-atlas@3/states-10m.json",+ "object": "states",+ "projection": {"type": "albers", "lon0": -96, "lat0": 37.5, "p1": 29.5, "p2": 45.5},+ "drop": ["Alaska", "Hawaii", "Puerto Rico", "Guam", "American Samoa", "United States Virgin Islands", "Commonwealth of the Northern Mariana Islands"],+ "neighbors": {"source": "https://cdn.jsdelivr.net/npm/world-atlas@2/countries-50m.json", "object": "countries",+ "keep": ["Canada", "Mexico", "Cuba", "Bahamas"], "dark": ["Canada", "Mexico"], "clip": [-135, 14, -55, 58]},+ "places": {"Dayton": [39.76, -84.19], "Kill Devil Hills": [36.02, -75.67], "Washington": [38.90, -77.04]}+ }]+}diff --git a/skills/cinematic-film/assets/wright-flyer/photos.json b/skills/cinematic-film/assets/wright-flyer/photos.jsonnew file mode 100644index 0000000..d7a01b8--- /dev/null+++ b/skills/cinematic-film/assets/wright-flyer/photos.json@@ -0,0 +1,19 @@+{+ "grade": "bw",+ "photos": [+ {"id": "P01", "what": "First flight, Dec 17 1903", "kind": "photo", "commons": "File:First flight2.jpg"},+ {"id": "P02", "what": "Orville Wright in the Wright Cycle Company shop, 1890s", "kind": "photo",+ "commons": "File:Orville Wright in a work apron standing behind equipment at the Wright Cycle Company, c. 1890s. (a1895985-1dd8-b71b-0bd7-087631da420f).jpg"},+ {"id": "P03", "what": "Wilbur Wright, 1905", "kind": "photo", "commons": "File:Wilbur Wright-crop.jpg", "crop": [0.04, 0.02, 0.96, 0.86]},+ {"id": "P04", "what": "Orville Wright, 1905", "kind": "photo", "commons": "File:Orville Wright 1905-crop.jpg", "crop": [0.04, 0.02, 0.96, 0.86]},+ {"id": "P05", "what": "Samuel P. Langley", "kind": "photo", "commons": "File:Samuel Pierpont Langley SI-87-17019h original.jpg", "crop": [0.0, 0.04, 1.0, 0.72]},+ {"id": "P06", "what": "Langley's Aerodrome A on its houseboat, Oct 7 1903", "kind": "photo",+ "commons": "File:Attempted Flight of Langley's Full Sized Plane, being readied for Launching, October 7th 1903. (50255040742).jpg",+ "credit": "Photographer unknown (Commons upload via Flickr user tormentor4555)"},+ {"id": "P07", "what": "Orville's telegram to his father, Dec 17 1903", "kind": "doc", "commons": "File:Telegram Orville Wright 17 dec 1903.jpg"}+ ],+ "recreations": [+ "Wilbur Wright's letter of May 30, 1899 to the Smithsonian: the sentence shown is quoted from the letter; the page is typeset in code.",+ "New York Times editorial 'Flying Machines Which Do Not Fly', Oct 9, 1903: the quoted sentence is real; the page is typeset in code."+ ]+}diff --git a/skills/cinematic-film/assets/wright-flyer/scene.py b/skills/cinematic-film/assets/wright-flyer/scene.pynew file mode 100644index 0000000..087172b--- /dev/null+++ b/skills/cinematic-film/assets/wright-flyer/scene.py@@ -0,0 +1,181 @@+"""TWELVE SECONDS: the Wright Flyer, about 90 s. The worked example for cinematic-film.++One continuous camera over one wall: a US map print in the middle, the cold open (the first-flight+photograph) out on the cork past North Carolina, Dayton's prints above the Great Lakes, Langley's+prints to the north-east. Every time comes from the voiceover: doc.L(i) is when line i starts,+doc.W(i, "word") when a spoken word lands, so a new voice re-times the whole film by itself.++World units are 4K pixels at zoom 1 (zoom 0.5 shows 7680 x 4320 world px).+"""+from engine import (HILITE, MUSTARD, RUST, WHITE, BigText, Counter, Film, GeoMap, PaperDoc, PenMark, Print,+ RegionFill, Route, Stamp, StringLine, XMarker)++CX = 27800 # the cold-open cluster, out on the cork past the coast+K = 60000 # map scale: big enough that Dayton, Washington and the Outer Banks each get room+LBL = dict(size=3.0, label_size=150)+++def build_film(doc):+ L, E, W = doc.L, doc.E, doc.W+ res = doc.res()+ film = Film(doc.duration, fps=30, look="wall")+ cam, foc, cue = film.cam, film.focus, film.cue++ us = film.add(GeoMap(doc.map("us"), K, look="explainer"))+ kdh, dayton, dc = us.place("Kill Devil Hills"), us.place("Dayton"), us.place("Washington")++ # ============================================================ COLD OPEN (1-4)+ # 1 the date, then the pin on the Outer Banks+ film.add(BigText("DECEMBER 17, 1903", CX, -2350, 520, L(1) - 0.1, t_out=L(3), type_on=0.6, bar=HILITE, bar_h=0.92, rgb=(30, 26, 22), shadow=False))+ film.add(RegionFill(us, ["North Carolina"], RUST, W(1, "beach"), to_rgb=MUSTARD, t_change=L(5) + 0.5))+ film.add(XMarker(*kdh, "KILL DEVIL HILLS, N.C.", t_in=W(1, "North"), side="left", **LBL))++ # 2 the photograph lands out past the coast, tied to the pin+ photo = film.add(Print("P01", CX, 300, 2600, rot=-1.2, t_in=L(2) + 0.1, label="PHOTO: JOHN T. DANIELS", label_t=W(4, "took")))+ film.add(StringLine(kdh, (CX - 1250, -560), t_in=L(2) + 0.2, dur=0.7, sag=0.03, width=16, persist=True))++ # 3 two counters roll up under it+ c12 = film.add(Counter(CX - 1100, 2950, 760, 12, W(3, "Twelve") - 0.05, dur=0.8, caption="SECONDS"))+ film.add(Counter(CX + 1250, 2950, 760, 120, W(3, "hundred") - 0.15, dur=1.0, caption="FEET"))++ # 4 the photographer's name bar (Print label), then the title+ title_t = E(4) + 0.45+ film.add(BigText("TWELVE SECONDS", CX, -2300, 860, title_t, rgb=(244, 240, 232), hit=None))+ ring = film.add(PenMark("ellipse", CX, -2560, 7600, 1500, t_in=title_t + 0.35, dur=0.8, width=26, seed=4, rot=-2, rgb=(236, 230, 220)))+ cue("boom", title_t, 0.55)++ cam(0.0, CX, -2150, 1.0, -1.0)+ cam(W(1, "windy") - 0.3, CX - 600, -1900, 0.92, -0.6)+ cam(W(1, "North") + 0.4, 22300, -1100, 0.33, 0.0) # pull back: the pin and the date together+ cam(L(2) + 0.9, CX, 250, 1.12, -0.6)+ cam(L(3) + 0.3, CX + 50, 1300, 0.95, -0.3)+ cam(E(3) + 0.1, CX + 50, 1900, 0.88, 0.0)+ cam(L(4) + 0.6, CX, 900, 0.86, 0.2)+ cam(E(4) + 0.3, CX, -400, 0.52, 0.0)+ cam(title_t + 1.0, CX, -1100, 0.46, -0.2)+ foc(0.0, CX, -2300, 1700, 0.5)+ foc(W(1, "North") + 0.3, 22300, -1100, 7000, 0.3)+ foc(L(2) + 0.6, CX, 300, 1700, 0.6)+ foc(L(3) + 0.3, CX + 50, 2200, 1900, 0.55)+ foc(L(4) + 0.5, CX, 900, 2000, 0.55)+ foc(title_t + 0.2, CX, -1200, 4200, 0.5)++ # ============================================================ DAYTON (5-8)+ film.add(StringLine((CX - 1250, -560), dayton, t_in=L(5) + 0.15, dur=1.2, sag=0.02, width=22))+ film.add(RegionFill(us, ["Ohio"], RUST, W(5, "Dayton") - 0.2, to_rgb=MUSTARD, t_change=L(14) + 0.6))+ film.add(XMarker(*dayton, "DAYTON", t_in=W(5, "Dayton"), side="right", **LBL))+ shop = film.add(Print("P02", 9400, -7100, 2000, rot=1.5, t_in=W(5, "bicycle") - 0.1))+ wil = film.add(Print("P03", 6500, -7350, 1700, rot=-2.0, t_in=W(6, "Wilbur") - 0.1, label="WILBUR WRIGHT", label_t=W(6, "Wilbur") + 0.1))+ orv = film.add(Print("P04", 12350, -7350, 1700, rot=2.2, t_in=W(6, "Orville") - 0.1, label="ORVILLE WRIGHT", label_t=W(6, "Orville") + 0.1))+ letter = film.add(PaperDoc(15900, -7500, 2500, 3200, rot=1.6, t_in=W(7, "wrote") - 0.1, rows=16, sentence_row=5, sentence_size=96,+ header=(("WRIGHT CYCLE COMPANY", 130, "serif"), ("DAYTON, OHIO · MAY 30, 1899", 78, "mono")),+ sentence="I am an enthusiast, but not a crank in the sense that I have some pet theories as to the proper construction of a flying machine."))+ (ex, ey), ew = letter.phrase_pos(res, "I am an enthusiast,")+ (nx, ny), nw = letter.phrase_pos(res, "not a crank")+ film.add(PenMark("highlight", ex, ey - 30, ew + 60, 0, t_in=W(8, "enthusiast") - 0.35, dur=0.45, width=120, rot=1.6))+ film.add(PenMark("highlight", nx, ny - 30, nw + 60, 0, t_in=W(8, "crank") - 0.45, dur=0.4, width=120, rot=1.6, seed=3))++ cam(L(5) + 0.5, 17500, -2500, 0.26, 0.0) # wide: the string races to Dayton+ cam(W(5, "bicycle") + 0.2, 9600, -5000, 0.44, 0.3)+ cam(E(5) + 0.2, 9400, -6500, 0.6, 0.5)+ cam(L(6) + 0.5, 9400, -6900, 0.43, 0.0) # all three prints+ cam(E(6) + 0.1, 10200, -6900, 0.45, -0.2)+ cam(W(7, "wrote") + 0.4, 15600, -7500, 0.7, 0.6)+ cam(E(7) + 0.1, 15900, -7400, 0.8, 0.8)+ cam(W(8, "enthusiast"), ex + 300, ey + 150, 1.1, 1.0)+ cam(E(8) + 0.2, nx + 100, ny + 120, 1.12, 1.2)+ foc(L(5) + 0.4, 15000, -2500, 9000, 0.25)+ foc(W(5, "bicycle") + 0.1, 9400, -6000, 2600, 0.5)+ foc(L(6) + 0.4, 9400, -7000, 5200, 0.45)+ foc(W(7, "wrote") + 0.3, 15900, -7500, 2000, 0.6)+ foc(W(8, "enthusiast"), ex + 300, ey, 1300, 0.62)++ # ============================================================ THE RIVAL (9-13)+ cue("riser", L(9) - 1.3, 0.5, dur=1.2)+ lang = film.add(Print("P05", 20700, -7600, 1900, rot=-1.4, t_in=W(9, "Samuel") - 0.15, label="SAMUEL P. LANGLEY", label_t=W(9, "Samuel") + 0.1))+ film.add(StringLine((17000, -8900), (20700, -8620), t_in=W(9, "charge") - 0.1, dur=0.7, sag=0.06, width=16))+ film.add(Counter(20700, -4750, 800, 50000, W(10, "fifty") - 0.15, dur=1.2, prefix="$", caption="WAR DEPARTMENT"))+ boat = film.add(Print("P06", 25300, -7400, 2700, rot=1.2, t_in=W(11, "launched") - 0.15, label="OCTOBER 7, 1903", label_t=W(11, "October")))+ film.add(XMarker(*dc, "WASHINGTON", t_in=W(11, "Potomac") - 0.1, side="right", **LBL))+ film.add(StringLine(dc, (25300 - 900, -8350), t_in=W(11, "Potomac"), dur=0.8, sag=0.03, width=18))+ film.add(Stamp("FAILED", 25150, -7250, size=330, rot=-9, t_in=W(11, "river") - 0.1))+ nyt = film.add(PaperDoc(29700, -7600, 2400, 3150, rot=-1.5, t_in=W(12, "Times") - 0.2, rows=15, sentence_row=6, sentence_size=78,+ header=(("THE NEW YORK TIMES", 150, "serif"), ("FRIDAY, OCTOBER 9, 1903", 70, "mono"),+ ("FLYING MACHINES WHICH DO NOT FLY", 96, "cond")),+ sentence="...the flying machine which will really fly might be evolved by the combined and continuous efforts "+ "of mathematicians and mechanicians in from one million to ten million years."))+ spans = nyt.phrase_spans(res, "one million to ten million years.")+ for k, ((hx, hy), hw) in enumerate(spans):+ film.add(PenMark("highlight", hx, hy - 24, hw + 50, 0, t_in=W(12, "million") - 0.4 + 0.25 * k, dur=0.35, width=100, rot=-1.5, seed=7 + k))+ film.add(Stamp("FAILED AGAIN", 25500, -6500, size=270, rot=6, t_in=W(13, "result") - 0.1))+ for k in range(3):+ cue("heartbeat", L(13) + 0.1 + k * 0.95, 0.55)++ cam(L(9) + 0.6, 18300, -7600, 0.55, 0.6)+ cam(W(9, "Samuel") + 0.4, 20700, -7400, 0.78, 0.0)+ cam(E(9) + 0.1, 20750, -7000, 0.7, -0.3)+ cam(W(10, "fifty") + 0.1, 20700, -5800, 0.72, -0.4)+ cam(E(10) + 0.2, 21500, -6200, 0.55, 0.0)+ cam(W(11, "launched") + 0.3, 21800, -5600, 0.3, 0.2) # wide: Washington, Langley, the houseboat+ cam(W(11, "Potomac") + 0.4, 22200, -5300, 0.27, 0.2)+ cam(W(11, "river") - 0.3, 25300, -7300, 0.8, 0.6)+ cam(E(11) + 0.2, 25350, -7200, 0.86, 0.8)+ cam(W(12, "Times") + 0.3, 29700, -7700, 0.72, -0.6)+ hx0, hy0 = spans[0][0]+ cam(W(12, "million"), hx0 + 200, hy0 + 100, 1.0, -1.0)+ cam(E(12) + 0.2, hx0 + 260, hy0 + 140, 1.05, -1.2)+ cam(L(13) + 0.5, 25400, -7000, 0.74, 0.3)+ cam(E(13) + 0.3, 25450, -6900, 0.82, 0.5)+ foc(L(9) + 0.5, 19000, -7800, 2600, 0.5)+ foc(W(9, "Samuel") + 0.3, 20700, -7400, 1700, 0.62)+ foc(W(10, "fifty"), 20700, -5800, 1900, 0.6)+ foc(W(11, "launched") + 0.2, 21500, -5600, 7000, 0.3)+ foc(W(11, "river") - 0.2, 25300, -7300, 2000, 0.6)+ foc(W(12, "Times") + 0.2, 29700, -7600, 2000, 0.6)+ foc(W(12, "million"), hx0 + 200, hy0, 1300, 0.62)+ foc(L(13) + 0.4, 25400, -7000, 2100, 0.62)++ # ============================================================ KITTY HAWK (14-17)+ cue("riser", L(14) - 1.2, 0.45, dur=1.1)+ film.add(Route(dayton, kdh, t_in=L(14) + 0.4, dur=1.6, bend=0.18, width=55))+ film.add(RegionFill(us, ["North Carolina"], RUST, L(14) + 1.9, alpha=0.95))+ thousand = film.add(Counter(CX, 5000, 820, 1000, W(15, "less") - 0.1, dur=1.0, prefix="UNDER $", caption="1900 TO 1903, TRAVEL INCLUDED"))+ film.add(PenMark("underline", CX - 1100, 3200, 1500, 40, t_in=W(16, "Orville") - 0.1, dur=0.4, width=22, seed=12))+ film.add(Counter(CX + 4350, 2950, 760, 59, W(16, "fifty") - 0.1, dur=0.9, caption="SECONDS"))+ tele = film.add(Print("P07", CX + 4350, -150, 2600, rot=1.4, t_in=L(17) + 0.05))+ (sx, sy) = doc.on(tele, 0.08, 0.742)+ (cx, cy) = doc.on(tele, 0.17, 0.942)+ film.add(PenMark("highlight", sx, sy, 0.115 * 2600, 0, t_in=W(17, "Success") - 0.2, dur=0.3, width=95, rot=1.4))+ film.add(PenMark("highlight", cx, cy, 0.29 * 2600, 0, t_in=W(17, "Christmas") - 0.45, dur=0.45, width=95, rot=1.4, seed=5))++ cam(L(14) + 0.6, 17500, -2400, 0.19, 0.0) # wide: the route home to the beach+ cam(E(14) - 0.2, CX - 2500, -400, 0.34, -0.2)+ cam(W(15, "less") + 0.2, CX, 4000, 0.68, -0.4)+ cam(E(15) + 0.2, CX, 4400, 0.7, -0.2)+ cam(L(16) + 0.4, CX - 400, 2900, 0.72, 0.0)+ cam(W(16, "fifty") + 0.2, CX + 2400, 2500, 0.62, 0.3)+ cam(L(17) + 0.6, CX + 4350, -150, 0.92, 0.8)+ cam(W(17, "Success") + 0.3, sx + 650, sy - 50, 1.25, 1.0)+ cam(W(17, "Christmas"), cx + 300, cy - 200, 1.2, 1.2)+ film.shot(E(17) + 0.6, CX + 4100, 300, 0.85, 0.8)+ foc(L(14) + 0.5, 15000, -2500, 9500, 0.2)+ foc(W(15, "less"), CX, 4400, 1900, 0.58)+ foc(L(16) + 0.3, CX - 400, 3000, 2600, 0.5)+ foc(W(16, "fifty"), CX + 3000, 2600, 2600, 0.5)+ foc(L(17) + 0.5, CX + 4350, -150, 1900, 0.6)+ foc(W(17, "Success") + 0.2, sx + 500, sy, 1300, 0.6)++ # ============================================================ CLOSE (18-19)+ film.add(PenMark("ellipse", 20700, -5050, 3900, 1150, t_in=W(18, "fifty") - 0.1, dur=0.6, width=24, seed=21, rot=-2))+ film.add(PenMark("ellipse", CX, 4700, 6300, 1250, t_in=W(19, "thousand") - 0.2, dur=0.6, width=24, seed=22, rot=2))+ cam(L(18) + 0.9, 22800, -6100, 0.4, 0.0) # back across the wall to Langley+ cam(E(18), 22600, -5900, 0.42, -0.2)+ cam(W(19, "bicycle") + 0.4, 24500, 300, 0.21, 0.0)+ cam(W(19, "sky"), 21500, -1400, 0.16, 0.0)+ cam(film.duration, 18500, -1700, 0.122, 0.0) # the whole wall+ foc(L(18) + 0.8, 22800, -6100, 3800, 0.45)+ foc(W(19, "bicycle") + 0.3, 24500, 0, 9000, 0.3)+ foc(W(19, "sky"), 19000, -1500, 22000, 0.1)++ film.fade_in, film.fade_out = 0.9, 2.2+ return filmdiff --git a/skills/cinematic-film/assets/wright-flyer/script.json b/skills/cinematic-film/assets/wright-flyer/script.jsonnew file mode 100644index 0000000..c81e98f--- /dev/null+++ b/skills/cinematic-film/assets/wright-flyer/script.json@@ -0,0 +1,83 @@+{+ "title": "Twelve Seconds",+ "takes": [+ {"take": "T01_cold_open", "lines": [+ {"id": 1, "text": "December 17th, 1903. A windy beach in North Carolina.",+ "spoken": "December seventeenth, nineteen oh three. A windy beach in North Carolina.",+ "hero": "the date, set big; then the map pin on the Outer Banks", "typed": "DECEMBER 17, 1903 · KILL DEVIL HILLS, N.C."},+ {"id": 2, "text": "A machine of spruce and cloth leaves the sand.",+ "spoken": "A machine of spruce and cloth leaves the sand.",+ "hero": "the first-flight photograph lands", "typed": ""},+ {"id": 3, "text": "Twelve seconds. One hundred and twenty feet.",+ "spoken": "Twelve seconds. One hundred and twenty feet.",+ "hero": "two counters roll up under the photo", "typed": "12 SECONDS · 120 FEET"},+ {"id": 4, "text": "The man who took this picture had never taken one before.",+ "spoken": "The man who took this picture had never taken one before.",+ "hero": "pen circle round the photo; name bar under it; title after the line", "typed": "JOHN T. DANIELS · title TWELVE SECONDS", "gap_after": 1.2}+ ]},+ {"take": "T02_dayton", "lines": [+ {"id": 5, "text": "Four years earlier, two brothers ran a bicycle shop in Dayton, Ohio.",+ "spoken": "Four years earlier, two brothers ran a bicycle shop in Dayton, Ohio.",+ "hero": "string from the photo to Dayton on the map; the cycle-shop photo", "typed": "DAYTON"},+ {"id": 6, "text": "Wilbur and Orville Wright. Neither had a high school diploma.",+ "spoken": "Wilbur and Orville Wright. Neither had a high school diploma.",+ "hero": "two portraits, red name bars", "typed": "WILBUR WRIGHT · ORVILLE WRIGHT"},+ {"id": 7, "text": "In 1899, Wilbur wrote to the Smithsonian for everything it had on flight.",+ "spoken": "In eighteen ninety-nine, Wilbur wrote to the Smithsonian for everything it had on flight.",+ "hero": "his letter, typeset as a document", "typed": "letter header DAYTON, OHIO · MAY 30, 1899"},+ {"id": 8, "text": "I am an enthusiast, he wrote, but not a crank.",+ "spoken": "I am an enthusiast, he wrote, but not a crank.",+ "hero": "highlighter swipes the sentence on the letter", "typed": ""}+ ]},+ {"take": "T03_the_rival", "lines": [+ {"id": 9, "text": "The man in charge there, Samuel Langley, was building a flying machine of his own.",+ "spoken": "The man in charge there, Samuel Langley, was building a flying machine of his own.",+ "hero": "string from the letter to Langley's portrait", "typed": "SAMUEL P. LANGLEY"},+ {"id": 10, "text": "The War Department gave him fifty thousand dollars.",+ "spoken": "The War Department gave him fifty thousand dollars.",+ "hero": "counter rolls to $50,000", "typed": "$50,000"},+ {"id": 11, "text": "On October 7th, 1903, it launched from a houseboat on the Potomac, and dropped straight into the river.",+ "spoken": "On October seventh, nineteen oh three, it launched from a houseboat on the Potomac, and dropped straight into the river.",+ "hero": "the machine on its houseboat; stamp on 'river'", "typed": "label OCTOBER 7, 1903 · map WASHINGTON · stamp FAILED"},+ {"id": 12, "text": "Two days later, The New York Times said a real flying machine might take one to ten million years.",+ "spoken": "Two days later, The New York Times said a real flying machine might take one to ten million years.",+ "hero": "the editorial; highlighter on its prediction", "typed": "doc header THE NEW YORK TIMES · OCT. 9, 1903"},+ {"id": 13, "text": "On December 8th, Langley tried again. Same river. Same result.",+ "spoken": "On December eighth, Langley tried again. Same river. Same result.",+ "hero": "a second stamp beside the first", "typed": "stamp FAILED AGAIN"}+ ]},+ {"take": "T04_kitty_hawk", "lines": [+ {"id": 14, "text": "Nine days later, the Wright brothers were back on that beach.",+ "spoken": "Nine days later, the Wright brothers were back on that beach.",+ "hero": "route Dayton to the Outer Banks across the map", "typed": ""},+ {"id": 15, "text": "Their whole effort had cost less than a thousand dollars.",+ "spoken": "Their whole effort had cost less than a thousand dollars.",+ "hero": "counter rolls to $1,000", "typed": "UNDER $1,000"},+ {"id": 16, "text": "Orville flew first. By noon, Wilbur stayed up for fifty-nine seconds.",+ "spoken": "Orville flew first. By noon, Wilbur stayed up for fifty-nine seconds.",+ "hero": "counter 59 SECONDS beside the 12", "typed": "59 SECONDS"},+ {"id": 17, "text": "They wired their father: Success. Four flights. Home for Christmas.",+ "spoken": "They wired their father. Success. Four flights. Home for Christmas.",+ "hero": "the telegram; highlighter on 'Success'", "typed": "", "gap_after": 1.0}+ ]},+ {"take": "T05_close", "lines": [+ {"id": 18, "text": "The government spent fifty thousand dollars, and got a wreck in a river.",+ "spoken": "The government spent fifty thousand dollars, and got a wreck in a river.",+ "hero": "the camera crosses back to Langley's prints", "typed": ""},+ {"id": 19, "text": "Two bicycle mechanics spent less than a thousand, and got the sky.",+ "spoken": "Two bicycle mechanics spent less than a thousand, and got the sky.",+ "hero": "final pull-back: the whole wall", "typed": ""}+ ]}+ ],+ "fact_notes": [+ "Dec 17, 1903, Kill Devil Hills near Kitty Hawk: first flight 12 s, 120 ft, Orville at the controls; fourth flight (Wilbur, about noon) 59 s, 852 ft.",+ "John T. Daniels of the Kill Devil Hills lifesaving station squeezed the shutter bulb; he had never taken a photograph.",+ "Neither brother received a high-school diploma (Wilbur finished the course but the family moved before graduation; Orville left in his junior year).",+ "Wilbur's letter to the Smithsonian is dated May 30, 1899 and contains 'I am an enthusiast, but not a crank in the sense that I have some pet theories as to the proper construction of a flying machine.'",+ "Langley was Secretary of the Smithsonian; the War Department's Board of Ordnance and Fortification granted $50,000 (the Smithsonian added about $20,000).",+ "Aerodrome A failed on launch from a houseboat on the Potomac on Oct 7 and Dec 8, 1903; Dec 8 to Dec 17 is nine days.",+ "NYT editorial 'Flying Machines Which Do Not Fly', Oct 9, 1903: '...in from one million to ten million years.'",+ "Wright expenses 1900-1903 including travel: a little under $1,000 (commonly cited, McCullough; Orville later said about $1,000).",+ "Telegram text: 'Success four flights thursday morning ... longest 57 seconds inform Press home Christmas' (57 is the telegrapher's error for 59)."+ ]+}diff --git a/skills/cinematic-film/references/archive.md b/skills/cinematic-film/references/archive.mdnew file mode 100644index 0000000..7ef0682--- /dev/null+++ b/skills/cinematic-film/references/archive.md@@ -0,0 +1,65 @@+# Images: archives, your own, AI stills, and the rights++## Three sources++- **Archives** (history, real people, real events): the rest of this file.+- **Your own** (product shots, team photos, screenshots, renders): drop the files in `assets/photos/` and give them a `"file"` entry in `photos.json`. Grade them `natural` so they keep their colour under one shared balance. Anyone recognisable needs to have agreed to appear.+- **AI stills** (illustration, mood, things no camera saw): generate every still with one model and one style reference, so they read as a set. The `motion-assets` skill plans the prompts and the cost before spending anything. Never use AI images of real people, or as evidence of real events. Credit them in `credits.md` as AI-generated.++## What is free to use (archives)++- **Published in the US in 1930 or earlier**: public domain in the US (as of 2026; one more year enters each January).+- **Works of the US federal government** (Library of Congress staff photos, National Archives records made by federal agencies, NASA, military, FBI): public domain in the US.+- **CC0, CC BY, CC BY-SA**: free with credit. BY-SA asks that adaptations carry the same licence; credit it and say so in `credits.md`.+- **"No known copyright restrictions"** (Flickr Commons, LOC collections): usually fine. Record the institution's statement. `fetch_commons.py` marks these CHECK, and `get` refuses them unless you pass `--allow-nonfree` after checking.+- **Not free**: press agency photos after 1930 (AP, Getty, Corbis), film stills, most photos of living people, anything marked NC or ND, anything whose uploader is not the author with no source given.++A Commons page can be wrong. For anything that matters, check that the stated source (an LOC record, a museum page) really says so. Photos taken by the subjects themselves count as theirs: the Wright portraits are credited to the brothers.++## Where to look++| Archive | Good for | How |+| --- | --- | --- |+| Wikimedia Commons | Almost everything famous, with licence fields | `fetch_commons.py search` and `category`. Open the category of a good hit to see its siblings |+| Library of Congress (loc.gov) | US photos, newspapers (Chronicling America), maps | Add `?fo=json` to an item URL for its metadata and full-size image links |+| National Archives (catalog.archives.gov) | Federal records: court files, mugshots, letters, forms | Item JSON: `https://catalog.archives.gov/proxy/records/search?naId=<id>`. The page itself is a JavaScript app |+| State archives and memory projects | Regional history | Many sites load images by JavaScript: open the page in a headless browser and save the image responses |+| Internet Archive book images | Diagrams and engravings from old books | Usually "no known restrictions"; record the book |+| Smithsonian Open Access | Objects and portraits marked CC0 | Filter for CC0 |++Search with the archive's own words. Captions use period terms ("aeroplane", "liquor raid"), so try those as well as modern ones.++## photos.json++```json+{"grade": "bw",+ "photos": [+ {"id": "P01", "what": "First flight, Dec 17 1903", "kind": "photo", "commons": "File:First flight2.jpg"},+ {"id": "P07", "what": "Telegram", "kind": "doc", "url": "https://...", "credit": "...", "license": "Public domain", "source": "https://..."}+ ],+ "recreations": ["Wilbur Wright's 1899 letter: real sentence, page typeset in code."]}+```++- `kind` sets the grade: `photo` (one duotone across the film), `paper` (newsprint, used with `Print(paper=True)` torn edges), `doc` (records keep a hint of their paper colour), `color` (covers that must stay in colour).+- `crop` is `[left, top, right, bottom]` as fractions. Crop to the part that matters: a face on the top third, a headline block, without an uploader's border.+- `credit` overrides the Commons "Artist" field. That field is sometimes only the uploader.++## Rules that keep a film honest++- Never use a stand-in face. If no photo of a person exists, show a document with their name, a blank witness card, or a silhouette labelled as such.+- Never imply a photo shows something it does not. A photo of the machine being readied is not the crash; caption it with what it is.+- A recreated document says "recreation" in `credits.md` and quotes only real words. The narration may read them; the page must not add any.+- `fetch_commons.py credits` writes `credits.md`, ready to paste under a YouTube video or in a reply on X. It lists anything with unclear rights at the bottom. Clear those before anything monetised.++## Measuring positions on a photo++Highlights, circles and holes are placed by fractions of the image (`doc.on(print, fx, fy)`). To find them, draw a 10% grid over the graded image, view it, and read off the fractions:++```python+from PIL import Image, ImageDraw+im = Image.open("assets/prep/photos/P07.jpg"); d = ImageDraw.Draw(im)+for i in range(1, 10):+ x, y = im.width * i // 10, im.height * i // 10+ d.line([(x, 0), (x, im.height)], fill=(255, 0, 0)); d.line([(0, y), (im.width, y)], fill=(0, 0, 255))+im.save("grid.jpg")+```diff --git a/skills/cinematic-film/references/film.md b/skills/cinematic-film/references/film.mdnew file mode 100644index 0000000..ef99fe4--- /dev/null+++ b/skills/cinematic-film/references/film.md@@ -0,0 +1,111 @@+# Film: the wall, the camera, the items++## Units and the scene file++World units are 4K screen pixels at camera zoom 1. At zoom 1 the frame shows 3840 x 2160 world px; at zoom 0.5 it shows 7680 x 4320; at 0.13 a whole wall about 30,000 px wide.++```python+from engine import Film, GeoMap, Print, Stamp, StringLine, XMarker, RegionFill, RUST, MUSTARD++def build_film(doc):+ L, E, W = doc.L, doc.E, doc.W # line start, line end, when a spoken word lands+ film = Film(doc.duration, fps=30, look="wall")+ us = film.add(GeoMap(doc.map("us"), 60000))+ pr = film.add(Print("P01", 27800, 300, 2600, rot=-1.2, t_in=L(2) + 0.1, label="PHOTO: JOHN T. DANIELS", label_t=W(4, "took")))+ film.add(Stamp("FAILED", 25150, -7250, size=330, t_in=W(11, "river") - 0.1))+ film.shot(L(2) + 0.9, 27800, 250, 1.12, rot=-0.6)+ return film+```++- `doc.W(i, "word")` searches the **spoken** text: ask for "nineteen", not "1903". Use `nth=1` for a word's second occurrence.+- `doc.on(print, fx, fy)` gives the world point at a fraction of a print's image, rotation included.+- `doc.res()` measures text while laying out (`PaperDoc.phrase_spans(doc.res(), "not a crank")`).+- `film.add()` returns the item, so later lines can point strings, circles and the camera at it.++## Laying out the wall++1. Give each section a **cluster**: an area of the wall with its prints, documents and numbers. Leave about one print's width between clusters.+2. Put a map in the middle if the story travels. Hang clusters near the places they belong, on the map or out on the cork beside it, and tie them to their place with a `StringLine`.+3. Travel between clusters along a string (evidence: this leads to that) or a `Route` (people moving). The camera follows the line as it draws on.+4. Make the final pull-back a composition: everything still visible should read as one designed board.++**Map scale.** `GeoMap(data, K)`: K is world px per earth radius. At K=24000 the lower 48 states are about 17,000 px wide, which suits a story spread across the country. When several places a few hundred km apart each need their own prints (Dayton, Washington, the Outer Banks), use K=50000 to 70000 so each gets its own room. Close up, the map draws live vectors, so it stays sharp at any K.++## Camera++- One `film.shot(t, x, y, zoom, rot)` (or `cam` plus `focus`) every 0.6 to 3 seconds. The spline is monotone and keeps drifting through keys, so a hold is two keys close together, slightly apart.+- **Push in** to land on a hero: zoom from about 0.5 to 0.9 to 1.2 as the line reaches its key word.+- **Pull back** to show a connection or a place: zoom 0.2 to 0.35.+- **Whip** between clusters in 0.8 to 1.2 s. Motion blur and a whoosh are added on their own.+- Lean the roll a degree or two (`rot`) and let it change between keys. The handheld drift is built in.+- Land the camera on a hero about 0.3 s **after** it appears. It reads as the camera noticing it.+- Shakes: `Stamp` and `Ledger` shake the camera by themselves; `film.shake(t, amp, dur)` for anything else.++## Spotlight++`film.focus(t, x, y, radius, strength)` dims everything outside the hero. The hero is clear within about 0.7 x radius, and fully dim (strength) past 2.4 x radius. Use `film.shot()` so the light moves with the camera. For wide shots use a large radius and a low strength (0.15 to 0.3).++## Items++| Item | Use | Key arguments |+| --- | --- | --- |+| `Print(key, x, y, w, rot, t_in)` | A photo or document. `paper=True` makes a torn clipping that tears in | `label`, `label_t` (red name bar), `t_out`, `exit_vec` (slides off), `dim` |+| `PaperDoc(x, y, w, h, ...)` | A typeset document (a recreation): header lines, grey rows, one real sentence | `header=((text, size, font),)`, `sentence`, `phrase_spans()` |+| `Card(x, y, w, h, t_in, title, lines)` | A clean rounded panel for explainers and product stories; rises into place | `accent`, `rgb`, `text_rgb`, `title_size`, `body_size` |+| `Ledger`, `OpenLedger` | A closed ledger or file that slams down; an open spread with one handwritten entry | `label`, `entry`, `entry_mark()` |+| `BigText(text, x, y, size, t_in)` | Years, titles, numbers. Distressed by default | `bar=HILITE`, `bar_h` (0.92 for a full block), `type_on`, `hit` |+| `Counter(x, y, size, value, t_in)` | A number rolling up | `prefix`, `suffix`, `caption`, `dur` |+| `Stamp(text, x, y, size, rot, t_in)` | A verdict slammed onto a print | `rgb`, `shake` |+| `PenMark(kind, x, y, w, h, t_in)` | ellipse, underline, strike, arrow, highlight | `dur`, `width`, `rot`, `rgb` |+| `StringLine(a, b, t_in)` | Red string, pin to pin | `persist=True` to keep it; it fades after `hold` by default |+| `Chalk(x, y, times)` | Tally marks, one per time | `strike_t` |+| `Holes(print, pts, times)` | Holes punched into a print (shots, a punch card) | fractional `pts` |+| `FilmFrame(print, t_in)` | Film-strip bands around a print | |+| `DotField(points, t0, t1)` | Dots popping up (bars, stores, outbreaks) | `rgb`, `r` |+| `GeoMap(data, K)` | The map sheet | `look="explainer"` or `"period"`, `place(name)` |+| `RegionFill(map, names, rgb, t_in)` | Fill states or countries; `to_rgb`/`t_change` turns active RUST into visited MUSTARD | |+| `XMarker(x, y, label, t_in)` | A map marker with a typed-on label | `side`, `size`, `label_size` |+| `MapPin(x, y, label, t_in)` | A pulsing red pin with a typewriter label | |+| `Route(a, b, t_in)` | A white travel arc drawing on | `bend`, `width` |++Every item takes `t_out` (fade out), `z` (stacking order) and `sfx=False` (mute its own sounds). Write a new item by subclassing `Item`: give it `bounds()` for culling, `draw(c, res, t)`, and optionally `cues()` and `shakes()`. A big static drawing (a city street map, a floor plan) subclasses `Cached` too, so it is drawn once and reused.++## Looks and type++`Film(look=...)`:++- `wall`: dark cork, warm. True stories.+- `slate`: blue-grey. Business, politics.+- `charcoal`: neutral black. Lets colour photos lead.+- `paper`: light desk.+- `studio`: light seamless. Products, brands, explainers with cards.+- `blueprint`: deep blue with a grid. Engineering, science.+- `night`: dark navy with strong glow. Tech, space, trailers.++Change the finish with `film.look["grain"]`, `["glow"]`, `["vignette"]`, `["grade"]` and `["dim"]` (the spotlight colour; light looks dim towards grey, not black).++On light looks, use dark type and `BigText(grunge=False, shadow=False)` for a clean finish. Use `Print(pin=False)` for photos that should sit like prints on a table, not pinned evidence.++Font roles are `cond` (labels, numbers, stamps), `label` and `labelm` (map labels, captions), `serif` (documents), `mono` (typewriter), `hand` (handwriting). Each falls back through common fonts. Put a file at `fonts/<role>.ttf` in the project to force one, for example Oswald Bold (OFL) as `cond` on Linux. `check_setup.py` prints what each role resolves to.++Colour on dark looks: white or cream type. Dark ink goes only on paper, cards or a full yellow block (`bar_h=0.92`).++Pick one accent per film and keep it for the things that matter. In the documentary kit that is yellow for highlights and dates and red for verdicts and names; teal is water, and RUST then MUSTARD marks map regions (active, then visited). A brand film uses its own brand colour as the accent.++## Review loop++```bash+python3 scripts/render.py --project my-film --probe 2,5.5,9,12.5 --size 1280x720 # one still per line+python3 scripts/render.py --project my-film --strip 16.8:21.7:12 --size 1280x720 # a camera move as a contact sheet+```++Put the probe stills on one contact sheet and look at all of them. Check:++- the hero is lit and readable+- nothing important is cut by the frame edge+- type is not dark on dark+- labels don't collide+- the spotlight follows the camera+- no frame is empty mid-move++Fix, then probe again. Use a strip for each move between clusters.diff --git a/skills/cinematic-film/references/performance.md b/skills/cinematic-film/references/performance.mdnew file mode 100644index 0000000..91a63ff--- /dev/null+++ b/skills/cinematic-film/references/performance.md@@ -0,0 +1,48 @@+# Performance and delivery++## Render speed++Skia draws on the CPU. These rules took a 38 second draft from 22 minutes to 3:++- **Never fill with a repeating image shader under rotation.** It was about 70x slower than tiling the same image with `drawImageRect`. `tile_image()` does the tiling; use it for any texture.+- **Give every item `bounds()`.** Off-screen items are skipped. An item without bounds draws every frame, wherever the camera is.+- **Cache big static vector art** (`Cached`). Maps and street sheets draw once into an image and switch to live vectors only when the camera is close.+- **Profile one frame, not the run.** Time `Renderer.frame(n)` for a slow frame and comment items out until it is fast. A single slow item usually costs most of the time.+- Motion blur draws up to 8 sub-frames during fast moves. Whips cost more than holds; that is expected.++## Memory++Each render worker builds its own copy of the film and runs its own encoder.++| Size | Per worker (with encoder) | Workers on 16 GB |+| --- | --- | --- |+| 1280x720 | about 0.6 GB | 7 |+| 1920x1080 | about 0.9 GB | 6 to 7 |+| 2560x1440 | about 1.3 GB | 4 to 5 |+| 3840x2160 | about 2 GB | 3 to 4 |++`render.py` picks the worker count from total memory unless you pass `--workers`. Going past it puts the machine into swap, and then everything crawls. A 4K run with 15 GB of swap had to be killed. The other settings that keep a worker small:++- photos are capped at 2200 px times the render scale+- cache images are capped at 8192 px+- x264 runs with `-rc-lookahead 10 -threads 2` at 2000 px wide and up (its lookahead alone took about 2 GB at 4K)+- grain is half resolution and changes every second frame (full-resolution grain every frame made a 38 s clip 625 MB)++## Choosing a resolution++- **Drafts**: 1280x720.+- **X**: 1920x1080. X serves 1080p at most.+- **YouTube**: 2560x1440 is the sweet spot. It gets YouTube's better encode, at about a third of the cost of 4K.+- **4K**: only if asked. About 3 hours for 5 minutes on a 16 GB laptop.++## Captions++```bash+python3 scripts/burn_captions.py --project my-film --video out/final.mp4 --audio audio/mix.m4a --style highlighter --out out/final_captions.mp4+python3 scripts/burn_captions.py --project my-film --srt-only --out out/captions.srt+```++- **Styles**: `highlighter` (condensed caps, the current word swiped yellow), `clean` (classic subtitle), `paper` (typewriter on a torn strip), `redbar` (caps on a red bar). Render a still of each over the busiest shot and let the user pick.+- Captions occupy the bottom 26% of the frame. Keep big numbers and labels above it in the scene.+- **Deliver**: a captioned file for X and Instagram (they autoplay muted), and a clean file plus the SRT for YouTube.+- Also make a small phone preview (`ffmpeg -i final.mp4 -vf scale=960:-2 -crf 28 preview.mp4`), to send for review before the big upload.diff --git a/skills/cinematic-film/references/sound.md b/skills/cinematic-film/references/sound.mdnew file mode 100644index 0000000..7fa1933--- /dev/null+++ b/skills/cinematic-film/references/sound.md@@ -0,0 +1,57 @@+# Sound++Three layers: the narration, synthesised effects, and an optional score. Effects should be felt, not noticed; the voice always wins.++## Effects++```bash+python3 scripts/render.py --project my-film --cues # sfx_cues.json+python3 scripts/build_sfx.py --project my-film # audio/sfx.wav+```++Items cue their own sounds:++| Item | Sound |+| --- | --- |+| `Print` | pop (slide for torn clippings) |+| `Stamp` | stamp |+| `PenMark` | pencil (marker for highlights, snip for quick strikes) |+| `Chalk` | tick per mark |+| `Counter` | ticks |+| `Route` | whoosh |+| `StringLine` | slide |+| `XMarker`, `MapPin` | pop |+| `Ledger` | impact |++Fast camera moves get a whoosh. A cue the scene places by hand within 0.15 s replaces the automatic one, and `sfx=False` mutes an item.++Add the score-like moments by hand:++- `film.cue("boom", title_t, 0.55)`: the title or the biggest reveal. Use it once or twice per film.+- `film.cue("riser", L(9) - 1.3, 0.5, dur=1.2)`: a crescendo into a new section. It peaks at `t + dur`, so end it on the line start.+- `film.cue("heartbeat", t)` once a second, 3 to 6 beats, under the tensest line. Or `film.cue("clock", t, dur=4)`.+- `film.cue("impact", t, 0.4)`: a number or year landing. Also available as `BigText(hit=0.4)`.+- `film.room_tone = [[0, film.duration]]`: a quiet room bed. Leave gaps in it for deliberate silence.++## Score++Optional. A documentary bed works best when it is sparse:++- a low pulse+- a few held notes+- silences that line up with section changes++Generate one (ElevenLabs Music, or any music model whose terms allow it), use a licensed track, or skip it. Most tense true stories play better on effects alone, with the score very low. Check where the score's own breaks fall, and move it (or cut lines) so they hit section starts.++## Mix++```bash+python3 scripts/mix_soundtrack.py --project my-film # voice + effects+python3 scripts/mix_soundtrack.py --project my-film --music audio/score.mp3 \+ --music-db -4 --sfx-db -3 --duck-ratio 3 --duck-threshold 0.03 --music-level 0.07 --music-eq-dip 4+```++- The score ducks under the narration (sidechain), and a slow leveller stops a building score swamping the voice. A small dip at 2.4 kHz clears the voice's presence band.+- Two-pass loudness: -15 LUFS integrated, -1.5 dBTP. That suits X, YouTube and Instagram; YouTube turns louder files down anyway.+- Check the result by listening on phone speakers and on headphones. If you can follow the score's melody, it is too loud.+- `--stems` writes the ducked music alone, to measure it. Under -30 LUFS in a -15 mix reads as "felt, not followed".diff --git a/skills/cinematic-film/references/story.md b/skills/cinematic-film/references/story.mdnew file mode 100644index 0000000..5c2c57e--- /dev/null+++ b/skills/cinematic-film/references/story.md@@ -0,0 +1,84 @@+# Story: research, script, beat table++## Research++- Start from sources that would survive a fact-check: museum and archive pages (Smithsonian, Library of Congress, National Archives, national park sites), court records, contemporary newspapers, and good biographies. Use Wikipedia for leads only.+- Write `fact_notes` in `script.json` as you go: one line per claim, with the number, the date and where it came from. When sources disagree, say "about", "reported" or "commonly cited", or drop the claim.+- Quotes must be the person's real words. When you quote a document on screen, quote only what it says, and mark the page as a recreation in `photos.json` `recreations`.+- Check calendar facts: weekdays, intervals ("nine days later"), ages. The Wright example checks that Oct 9, 1903 was a Friday, because a typeset newspaper header shows it.++## Shapes++Every shape opens on a hook, moves forward, turns, and closes by paying off the hook while the camera pulls back to the whole board.++**Documentary, history, true crime**+- **Cold open** (2 to 5 lines): the most vivid moment, out of order. Then a title.+- **Bridge** (1 line): the only step back in time. "Four years earlier, ..." or "It started in Brooklyn, in 1899."+- **Sections** (3 to 6 lines each, one take each): strictly forward in time. Each section ends on a line that hands off to the next.+- **Turn**: the rival, the mistake, the price. Short punchy lines ("Same river. Same result.").+- **Close** (2 lines): pay off the cold open, then one line that lands the meaning.++**Product launch**+- **Problem** (2 lines): the pain, in the customer's words, with one number.+- **Reveal** (1 line): the product name, big. Then a title moment.+- **Three proofs** (2 or 3 lines each): what it does, shown, not claimed. Use one card or one product shot per proof, and a counter for each measurable claim.+- **Close**: the price or availability, and the line people will repeat.++**Brand or founder story**+- **Then**: where it started (a garage, a kitchen, a rejection letter).+- **The bet**: the risky decision.+- **The hard part**: what nearly ended it.+- **Now**: one number for scale.+- **Why**: the line that says what it was all for.++**Explainer (science, tech, how it works)**+- **The question** (1 line), asked the way a curious person would.+- **Steps** (one card or diagram each), in the order things happen. Arrows draw on between the steps.+- **The surprise**: the counter-intuitive fact.+- **Close**: the answer to the question in one sentence.++**Biography**: the same as a documentary. Open on the defining moment, bridge to childhood, then life in order.++Facts in a product or brand film are claims. Each still needs a source in `fact_notes` (a spec sheet, a press release, a dated report).++## Lines++- One idea per line, 4 to 18 words. A line is one hero on screen, so a 30-word line either holds one shot too long or crams in three heroes.+- Write for the ear: short words, concrete nouns, numbers people can picture ("less than a thousand dollars", not "under $1K").+- Put the key word last, so the visual hit lands near the end of the line where the pause follows.+- `spoken` is the same line in the form the voice reads. Write numbers as words ("nineteen oh three", "fifty thousand dollars", "fifty-nine seconds"). Spell names out phonetically if the voice stumbles on them. Leave abbreviations out. `make_beats.py` flags digits left in.+- `hero` says what the camera is on. `typed` lists any text drawn in code: labels, big numbers, stamps, document headers. Text on a document or photo is not typed.+- `gap_after` (seconds) adds room after a line: after the cold open, before a title, after a reveal. The default is 0.45, or 1.0 at the end of a take.++## script.json++```json+{"title": "Twelve Seconds",+ "takes": [{"take": "T01_cold_open", "lines": [+ {"id": 1, "text": "December 17th, 1903. A windy beach in North Carolina.",+ "spoken": "December seventeenth, nineteen oh three. A windy beach in North Carolina.",+ "hero": "the date, set big; then the map pin", "typed": "DECEMBER 17, 1903 · KILL DEVIL HILLS, N.C."}]}],+ "fact_notes": ["..."]}+```++Line ids are global and never reused. Takes are the units you record in one go, usually one per section.++## Length++| Length | Words | Lines | Takes |+| --- | --- | --- | --- |+| 60 s | about 150 | 12 to 15 | 3 to 4 |+| 90 s | about 230 | 18 to 20 | 4 to 5 |+| 5 min | about 750 | 70 | 10 |++A first film should be 60 to 90 seconds. The 5-minute version is the same method with more sections. Build and review it section by section, and look at a draft of each section before starting the next.++## Beat table++`make_beats.py` turns `script.json` (plus `audio/timing.json` when there is one) into `beats.md`. Show it to the user before any building. The lint catches:++- a year that steps back in time after the first take+- lines over 22 words+- lines with no hero+- a phrase that is typed and also spoken word for word+- digits in the spoken textdiff --git a/skills/cinematic-film/references/voice.md b/skills/cinematic-film/references/voice.mdnew file mode 100644index 0000000..df399a4--- /dev/null+++ b/skills/cinematic-film/references/voice.md@@ -0,0 +1,49 @@+# Voice++The film is timed to the voice, so the voice comes before the picture. Use a free scratch voice to build against, then swap in the final one. The scene asks for line starts and spoken words, never fixed seconds, so it re-times itself.++## Scratch voice++```bash+python3 scripts/tts_say.py --project my-film # macOS say, or espeak-ng on Linux+python3 scripts/tts_say.py --project my-film --voice Daniel --rate 165+```++It reads each take in one go, with a clear pause between lines, and writes `audio/takes/<take>.wav`.++## Final voice: any provider++Record **one take per section**, not one call per line. One call keeps the delivery even. Per-line calls change pace and pitch from line to line, which sounds stitched together.++- **A command-line TTS** (Piper, a provider's CLI, your own script): `tts_say.py --cmd 'tool --in {txt} --out {out}'`. `{txt}` is a file with the take's lines, one paragraph each.+- **An API or app** (ElevenLabs, OpenAI, Higgsfield, PlayHT): send each take's `spoken` lines joined with a paragraph break (or the provider's pause tag), and save the result as `audio/takes/<take>.wav`. Any format ffmpeg reads is fine.+- **A person**: one file per take, a beat of silence between lines.++Then:++```bash+python3 scripts/split_takes.py --project my-film+python3 scripts/build_narration.py --project my-film # natural read+python3 scripts/build_narration.py --project my-film --target 88 # fit to 88 s (0.90 to 1.15x only)+```++## Checking the split++`split_takes.py` measures every line's speaking rate in letters per second of actual speech, and flags lines more than 35% off the median. A flag nearly always means one of three things:++- **Two lines run together.** The voice did not pause, so the cut landed a sentence late. Force the boundary in `audio/overrides.json`: `{"cut_before": {"53": 26.80}}`, the line id and the seconds into its take where that line starts. Find the spot by listening, or with `ffmpeg -i take.wav -af silencedetect=noise=-40dB:d=0.1 -f null -`.+- **A dramatic pause inside a line** ("He was... thirty-two") got taken for a boundary. Force the real one the same way.+- **A dropped or doubled word.** Re-record that take.++Listen to every flagged line. A cut in the wrong place shifts every visual hit after it.++## Re-recording++Re-record a whole take, never a single line: one line patched in from another call stands out. After any change, run `split_takes.py` and `build_narration.py` again, then `render.py --probe` on the affected lines. If a line got noticeably longer, check its camera keys still have time.++## Delivery notes++- Ask for a measured documentary read. A pace of 150 to 170 words a minute suits these films.+- Numbers and names go in `spoken` exactly as they should be said.+- A tempo fit beyond 0.90 to 1.15x sounds wrong. `build_narration.py` refuses it: cut or add lines instead.+- The narration lands at -16 LUFS. `mix_soundtrack.py` sets the final loudness.diff --git a/skills/cinematic-film/scripts/build_narration.py b/skills/cinematic-film/scripts/build_narration.pynew file mode 100644index 0000000..302c6f0--- /dev/null+++ b/skills/cinematic-film/scripts/build_narration.py@@ -0,0 +1,97 @@+#!/usr/bin/env python3+"""Assemble the per-line clips into one narration track and the timing file the film is built on.++ python3 build_narration.py --project my-film # natural read (tempo 1.0)+ python3 build_narration.py --project my-film --target 75 # fit the whole film to 75 s++Trims the silence off both ends of every clip, so pacing is set here (each line's gap_after from+split_takes.py) and not by whatever padding the voice engine added. --target solves for the one+tempo change (pitch kept) that lands the film on that length, and refuses anything outside+0.90-1.15x: beyond that the read sounds wrong, and the fix is a shorter or longer script.++Reads audio/segments.json, audio/lines/segNN.wav+Writes audio/narration.m4a (-16 LUFS), audio/timing.json+"""+import argparse+import json+import pathlib+import subprocess+import sys++TEMPO_LIMITS = (0.90, 1.15)+TRIM = ("silenceremove=start_periods=1:start_silence=0:start_threshold=-50dB,areverse,"+ "silenceremove=start_periods=1:start_silence=0:start_threshold=-50dB,areverse")+++def run(cmd):+ r = subprocess.run(cmd, capture_output=True, text=True)+ if r.returncode != 0:+ sys.exit(f"FAILED: {' '.join(map(str, cmd))}\n{r.stderr[-2000:]}")+ return r.stdout+++def duration(path):+ return float(run(["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", str(path)]).strip())+++def main():+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ ap.add_argument("--project", required=True)+ ap.add_argument("--target", type=float, default=0.0, help="finished length in seconds; 0 keeps the natural read")+ ap.add_argument("--lead", type=float, default=0.9, help="silence before the first word (s)")+ ap.add_argument("--tail", type=float, default=3.0, help="hold after the last word, for the final pull-back (s)")+ a = ap.parse_args()+ proj = pathlib.Path(a.project)+ adir = proj / "audio"+ segments = json.loads((adir / "segments.json").read_text())["segments"]+ work = adir / "trimmed"; work.mkdir(exist_ok=True)++ for seg in segments:+ src = adir / "lines" / f"seg{seg['id']:02d}.wav"+ if not src.exists():+ sys.exit(f"missing line clip: {src} (run split_takes.py)")+ run(["ffmpeg", "-y", "-v", "error", "-i", str(src), "-af", TRIM, "-ar", "48000", "-ac", "1", str(work / f"raw{seg['id']:02d}.wav")])++ raw_speech = sum(duration(work / f"raw{s['id']:02d}.wav") for s in segments)+ fixed = a.lead + a.tail + sum(s["gap_after"] for s in segments[:-1])+ tempo = 1.0 if a.target <= 0 else raw_speech / (a.target - fixed)+ if not TEMPO_LIMITS[0] <= tempo <= TEMPO_LIMITS[1]:+ sys.exit(f"tempo {tempo:.3f} is outside {TEMPO_LIMITS} for a {a.target}s film ({raw_speech:.1f}s of speech + "+ f"{fixed:.1f}s of pauses). Rewrite the script shorter or longer instead of distorting the read.")+ print(f"speech {raw_speech:.2f}s + pauses {fixed:.2f}s, tempo {tempo:.4f}")++ timeline, parts, cursor = [], [], a.lead+ pdir = work / "parts"; pdir.mkdir(exist_ok=True)++ def silence(sec, tag):+ p = pdir / f"sil_{tag}.wav"+ run(["ffmpeg", "-y", "-v", "error", "-f", "lavfi", "-i", "anullsrc=r=48000:cl=mono", "-t", f"{sec:.3f}", str(p)])+ return p+ parts.append(silence(a.lead, "lead"))+ for i, seg in enumerate(segments):+ dst = work / f"seg{seg['id']:02d}.wav"+ run(["ffmpeg", "-y", "-v", "error", "-i", str(work / f"raw{seg['id']:02d}.wav"), "-af", f"atempo={tempo:.6f}",+ "-ar", "48000", "-ac", "1", str(dst)])+ d = duration(dst)+ timeline.append({"id": seg["id"], "scene": seg["scene"], "caption": seg["caption"], "vo": seg["vo"],+ "start": round(cursor, 3), "end": round(cursor + d, 3), "duration": round(d, 3)})+ parts.append(dst)+ cursor += d+ if i < len(segments) - 1:+ parts.append(silence(seg["gap_after"], f"g{seg['id']}")); cursor += seg["gap_after"]+ parts.append(silence(a.tail, "tail"))+ total = round(cursor + a.tail, 3)++ lst = pdir / "concat.txt"+ lst.write_text("".join(f"file '{p.resolve()}'\n" for p in parts))+ track = adir / "narration.m4a"+ # loudnorm resamples to 96 kHz internally; force 48 kHz back out (some players choke on 96 kHz AAC)+ run(["ffmpeg", "-y", "-v", "error", "-f", "concat", "-safe", "0", "-i", str(lst),+ "-af", "loudnorm=I=-16:TP=-1.5:LRA=11,aresample=48000", "-ar", "48000", "-c:a", "aac", "-b:a", "192k", str(track)])+ (adir / "timing.json").write_text(json.dumps({"total_duration": total, "lead_in": a.lead, "tail_out": a.tail,+ "tempo": round(tempo, 4), "segments": timeline}, indent=2))+ print(f"narration {track} ({duration(track):.2f}s), timeline {total:.2f}s, {len(timeline)} lines -> audio/timing.json")+++if __name__ == "__main__":+ main()diff --git a/skills/cinematic-film/scripts/build_sfx.py b/skills/cinematic-film/scripts/build_sfx.pynew file mode 100644index 0000000..c0b1b47--- /dev/null+++ b/skills/cinematic-film/scripts/build_sfx.py@@ -0,0 +1,320 @@+#!/usr/bin/env python3+"""Synthesise the sound-effects track from the film's cue list. No samples: every sound is built from+noise and partials with numpy, so there is nothing to license.++ python3 render.py --project my-film --cues # writes sfx_cues.json (items cue themselves)+ python3 build_sfx.py --project my-film # writes audio/sfx.wav (full level; mix_soundtrack.py sets levels)++Cue kinds (film.cue(kind, t, gain, dur=...); items add most of these on their own):+ pop print or card landing slide newspaper or string sliding in+ whoosh camera move, route drawing on marker highlighter stroke+ pencil pen circle or underline ("dur") tick pencil tick (tally marks)+ snip tiny cut, a hole punched click shutter or film-frame clamp+ stamp rubber stamp slam impact title or number landing, low thump+ boom big reveal, sub drop ticks a counter rolling up+ shimmer cluster of small blips (dots) drop falling swoop+ riser noise and tone crescendo into a section change ("dur"; peaks at t + dur)+ heartbeat low lub-dub thump (repeat once a second for a tension bed)+ clock dry clock ticks, one a second ("dur")+film.room_tone = [[start, end], ...] lays a quiet room tone under those spans (silence elsewhere is+a deliberate beat).+"""+from __future__ import annotations++import argparse+import inspect+import json+import pathlib+import subprocess+import sys++import numpy as np++SR = 48000+BLOCK = 4096+HOP = BLOCK // 2+++# ---------------------------------------------------------------- primitives+def n_of(sec):+ return int(sec * SR)+++def envelope(points, n):+ """Piecewise-linear envelope over n samples; points are (fraction 0..1, gain)."""+ return np.interp(np.linspace(0.0, 1.0, n), [p[0] for p in points], [p[1] for p in points])+++def sweep(a, b, n, curve=1.0):+ return a + (b - a) * np.linspace(0.0, 1.0, n) ** curve+++def _band_mask(freqs, lo, hi, tilt):+ mask = np.zeros_like(freqs)+ mask[(freqs >= lo) & (freqs <= hi)] = 1.0+ lower = (freqs < lo) & (freqs > lo / 2)+ if lower.any():+ mask[lower] = 0.5 - 0.5 * np.cos(np.pi * (freqs[lower] - lo / 2) / (lo / 2))+ upper = (freqs > hi) & (freqs < hi * 2)+ if upper.any():+ mask[upper] = 0.5 + 0.5 * np.cos(np.pi * (freqs[upper] - hi) / hi)+ if tilt:+ with np.errstate(divide="ignore"):+ mask *= np.where(freqs > 0, (np.maximum(freqs, 1.0) / 1000.0) ** tilt, 0.0)+ return mask+++def band_noise(n, lo, hi, amp, seed, tilt=0.0):+ """Noise confined to a band whose corners may move over time (overlap-add spectral masking)."""+ rng = np.random.default_rng(seed)+ source = rng.standard_normal(n + BLOCK)+ out = np.zeros(n + BLOCK)+ window = np.hanning(BLOCK)+ freqs = np.fft.rfftfreq(BLOCK, 1.0 / SR)+ lo_arr = np.full(n, lo, np.float64) if np.isscalar(lo) else np.asarray(lo, np.float64)+ hi_arr = np.full(n, hi, np.float64) if np.isscalar(hi) else np.asarray(hi, np.float64)+ for start in range(0, n, HOP):+ c = min(start + HOP, n - 1)+ spec = np.fft.rfft(source[start:start + BLOCK] * window)+ spec *= _band_mask(freqs, max(lo_arr[c], 1.0), max(hi_arr[c], 2.0), tilt)+ out[start:start + BLOCK] += np.fft.irfft(spec, BLOCK)+ out = out[:n]+ peak = np.max(np.abs(out))+ return (out / peak if peak > 0 else out) * amp+++def tone(n, freq, decay, partials=(1.0, 2.01, 3.03)):+ t = np.arange(n) / SR+ return sum((0.6 ** i) * np.sin(2 * np.pi * freq * r * t) for i, r in enumerate(partials)) * np.exp(-t / decay)+++def hit(n, lo, hi, decay, seed):+ return band_noise(n, lo, hi, np.exp(-(np.arange(n) / SR) / decay), seed=seed)+++def fade(x, a, b):+ """De-click: short linear fades at both ends (a truncated tail would otherwise be a step, and a step is a click)."""+ out = x.copy()+ na, nb = min(int(a * SR), len(out)), min(int(b * SR), len(out))+ if na > 0:+ out[:na] *= np.linspace(0, 1, na)+ if nb > 0:+ out[-nb:] *= np.linspace(1, 0, nb)+ return out+++class Bed:+ def __init__(self, duration):+ self.n = int(duration * SR)+ self.buf = np.zeros((2, self.n))++ def add(self, sig, at, gain=1.0, pan=0.0):+ s = int(at * SR)+ if s >= self.n or len(sig) == 0:+ return+ sig = fade(sig[: self.n - s], 0.02, 0.02)+ e = s + len(sig)+ self.buf[0, s:e] += sig * gain * np.sqrt((1.0 - pan) / 2.0) * np.sqrt(2.0)+ self.buf[1, s:e] += sig * gain * np.sqrt((1.0 + pan) / 2.0) * np.sqrt(2.0)++ def render(self, path, headroom_db=-1.0):+ a = self.buf+ b, a_ = _hp_coeffs(28.0)+ for ch in range(2):+ a[ch] = _iir(a[ch], b, a_)+ peak = np.max(np.abs(a))+ if peak > 0:+ a = a / peak * (10 ** (headroom_db / 20))+ pcm = (a.T.reshape(-1) * 32767).astype(np.int16)+ path.parent.mkdir(parents=True, exist_ok=True)+ subprocess.run(["ffmpeg", "-y", "-v", "error", "-f", "s16le", "-ar", str(SR), "-ac", "2", "-i", "pipe:0",+ "-c:a", "pcm_s24le", str(path)], input=pcm.tobytes(), check=True)+++def _hp_coeffs(fc):+ alpha = 1.0 / (1.0 + 2 * np.pi * fc / SR)+ return (alpha, -alpha), alpha+++def _iir(x, b, a):+ """y[n] = a*y[n-1] + b0*x[n] + b1*x[n-1] (one-pole high-pass), via scipy if present, else a loop."""+ try:+ from scipy.signal import lfilter+ return lfilter([b[0], b[1]], [1.0, -a], x)+ except ImportError:+ y = np.empty_like(x); yp = xp = 0.0+ for i, s in enumerate(x):+ yp = a * yp + b[0] * s + b[1] * xp; xp = s; y[i] = yp+ return y+++_LEAD = n_of(.025)+++def _lead(x):+ return np.concatenate([np.zeros(_LEAD), x])+++# ---------------------------------------------------------------- sounds+def whoosh(seed):+ n = n_of(.55)+ return band_noise(n, sweep(300, 1400, n), sweep(1800, 6000, n), envelope([(0, 0), (.45, 1), (1, 0)], n) ** 1.5, seed=seed, tilt=-.4)+++def pop(seed):+ n = n_of(.18); t = np.arange(n) / SR+ return np.sin(2 * np.pi * sweep(260, 150, n) * t) * np.exp(-t / .035) * .8 + hit(n, 1200, 5000, .01, seed) * .25+++def slide(seed):+ n = n_of(1.4)+ return band_noise(n, 250, 1800, envelope([(0, 0), (.15, .8), (.85, .8), (1, 0)], n), seed=seed, tilt=-.6) * .8+++def marker(seed):+ n = n_of(.45)+ amp = envelope([(0, 0), (.1, .9), (.8, .8), (1, 0)], n) * (1 + .25 * np.sin(2 * np.pi * 23 * np.arange(n) / SR))+ return band_noise(n, 1800, 5200, amp, seed=seed, tilt=.3) * .7+++def pencil(seed, dur=1.6):+ n = n_of(dur); t = np.arange(n) / SR+ rng = np.random.default_rng(seed)+ stroke = np.abs(np.sin(np.pi * (7 + rng.uniform(-1.5, 1.5)) * t + rng.uniform(0, 3))) ** .6+ amp = stroke * (1 + .3 * np.sin(2 * np.pi * rng.uniform(13, 19) * t)) * envelope([(0, 0), (.06, 1), (.9, .85), (1, 0)], n)+ return band_noise(n, 2400, 8500, amp, seed=seed, tilt=.2) * .55 + band_noise(n, 600, 1800, amp * .3, seed=seed + 1) * .3+++def tick(seed):+ n = n_of(.16)+ return _lead(band_noise(n, 2500, 9000, envelope([(0, 0), (.1, 1), (.35, .3), (.45, .9), (1, 0)], n), seed=seed, tilt=.2) * .7)+++def snip(seed):+ rng = np.random.default_rng(seed); n = n_of(.07)+ return _lead(tone(n, rng.uniform(2600, 3600), .006, (1.0, 1.52)) * .5 + hit(n, 3000, 10000, .004, seed) * .8)+++def click(seed):+ n = n_of(.11); out = np.zeros(n)+ a = hit(n_of(.012), 2500, 9000, .0018, seed) + tone(n_of(.012), 3400, .0015, (1.0,)) * .4+ out[:len(a)] += a+ b = hit(n_of(.01), 2000, 7000, .0015, seed + 1) * .6+ out[n_of(.075):n_of(.075) + len(b)] += b+ return _lead(out)+++def stamp(seed):+ n = n_of(.4); t = np.arange(n) / SR+ return np.sin(2 * np.pi * sweep(120, 55, n) * t) * np.exp(-t / .07) + hit(n, 400, 3500, .025, seed) * .8+++def impact(seed):+ n = n_of(1.2); t = np.arange(n) / SR+ return np.sin(2 * np.pi * sweep(90, 42, n, .6) * t) * np.exp(-t / .35) + band_noise(n, 200, 2500, np.exp(-t / .12), seed=seed) * .35+++def boom(seed):+ n = n_of(2.4); t = np.arange(n) / SR+ sub = np.sin(2 * np.pi * sweep(70, 30, n, .5) * t) * np.exp(-t / .8)+ return sub * 1.1 + hit(n, 500, 7000, .05, seed) * .5 + band_noise(n, 60, 400, np.exp(-t / .9), seed=seed + 3) * .4+++def ticks(seed):+ n = n_of(1.4); out = np.zeros(n); rng = np.random.default_rng(seed)+ for at in np.cumsum(np.linspace(.04, .11, 18)): # decelerating, like a counter settling+ s = n_of(at)+ if s >= n:+ break+ c = tone(n_of(.03), 2400 + rng.uniform(-150, 150), .004, (1.0, 2.3))+ out[s:s + len(c)] += c[: n - s]+ return out * .8+++def shimmer(seed):+ n = n_of(1.0); out = np.zeros(n); rng = np.random.default_rng(seed)+ for i in range(14):+ s = n_of(i * .05 + rng.uniform(0, .02)); c = tone(n_of(.12), rng.uniform(1600, 3400), .03, (1.0, 2.0))+ out[s:s + len(c)] += c[: n - s] * .5+ return out+++def drop(seed):+ n = n_of(.6)+ whistle = np.sin(2 * np.pi * np.cumsum(sweep(900, 120, n, .7)) / SR) * envelope([(0, .2), (.3, 1), (1, 0)], n)+ w = whoosh(seed); out = np.zeros(max(n, len(w)))+ out[:n] += whistle * .5; out[:len(w)] += w * .5+ return out+++def riser(seed, dur=2.0):+ """Noise band sweeping up plus a climbing low tone; starts at the cue, peaks at t + dur."""+ n = n_of(dur); t = np.arange(n) / SR+ env = (t / dur) ** 2.4+ out = band_noise(n, sweep(250, 1800, n), sweep(1200, 9000, n), env, seed=seed) * .7 + np.sin(2 * np.pi * np.cumsum(sweep(70, 260, n, 1.4)) / SR) * env * .5+ out[-n_of(.02):] *= np.linspace(1, 0, n_of(.02))+ return out+++def heartbeat(seed):+ n = n_of(.75); t = np.arange(n) / SR++ def thump(at, f0, amp):+ tt = np.clip(t - at, 0, None)+ return np.sin(2 * np.pi * sweep(f0, f0 * .55, n, .6) * tt) * np.exp(-tt / .09) * (t >= at) * amp+ return thump(.02, 62, 1.0) + thump(.24, 55, .7)+++def clock(seed, dur=4.0):+ n = n_of(dur); out = np.zeros(n)+ for k, at in enumerate(np.arange(.02, dur - .05, 1.0)):+ s = n_of(at); seg = hit(n_of(.05), 1800 if k % 2 == 0 else 1300, 5200, .012, seed + k)+ out[s:s + len(seg)] += seg[: n - s] * .8+ return out+++SOUNDS = dict(whoosh=whoosh, pop=pop, slide=slide, marker=marker, pencil=pencil, tick=tick, snip=snip, click=click,+ stamp=stamp, impact=impact, boom=boom, ticks=ticks, shimmer=shimmer, drop=drop, riser=riser,+ heartbeat=heartbeat, clock=clock)+++def room_tone(total, spans):+ """Quiet room: low filtered noise, faded in and out over each span."""+ n = n_of(total); gate = np.zeros(n)+ for a, b in spans:+ ia, ib = n_of(a), min(n_of(b), n)+ if ib <= ia:+ continue+ g = np.ones(ib - ia); fi, fo = min(n_of(1.2), len(g) // 3), min(n_of(.4), len(g) // 3)+ g[:fi] = np.linspace(0, 1, fi); g[len(g) - fo:] = np.linspace(1, 0, fo)+ gate[ia:ib] = g+ return band_noise(n, 70, 420, np.ones(n), seed=77) * .3 * gate+++def main():+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ ap.add_argument("--project", required=True)+ a = ap.parse_args()+ proj = pathlib.Path(a.project)+ cp = proj / "sfx_cues.json"+ if not cp.exists():+ sys.exit(f"{cp} not found: run render.py --project {proj} --cues first")+ cues = json.loads(cp.read_text())+ total = cues["duration"]+ unknown = sorted({c["type"] for c in cues["cues"]} - SOUNDS.keys())+ if unknown:+ sys.exit(f"unknown cue kinds: {unknown} (have {sorted(SOUNDS)})")+ bed = Bed(total)+ for i, c in enumerate(cues["cues"]):+ fn = SOUNDS[c["type"]]+ kw = {"dur": c["dur"]} if "dur" in c and "dur" in inspect.signature(fn).parameters else {}+ bed.add(fn(seed=100 + i, **kw), max(c["t"], 0), gain=c.get("gain", 1.0), pan=((i * 37) % 11 - 5) / 20)+ if cues.get("room_tone"):+ bed.add(room_tone(total, cues["room_tone"]), 0, gain=.22)+ out = proj / "audio" / "sfx.wav"+ bed.render(out)+ print(f"sfx: {out} ({len(cues['cues'])} cues, {total:.1f}s)")+++if __name__ == "__main__":+ main()diff --git a/skills/cinematic-film/scripts/burn_captions.py b/skills/cinematic-film/scripts/burn_captions.pynew file mode 100644index 0000000..897ab12--- /dev/null+++ b/skills/cinematic-film/scripts/burn_captions.py@@ -0,0 +1,123 @@+#!/usr/bin/env python3+"""Burn a caption style into a finished render (a second pass, no re-render) and write an SRT.++ python3 burn_captions.py --project my-film --video out/final.mp4 --audio audio/mix.m4a --style highlighter --out out/final_captions.mp4+ python3 burn_captions.py --project my-film --srt-only --out out/captions.srt++N workers each decode a time slice of the video, composite the caption layer onto the bottom+quarter of each frame and encode; the slices are joined losslessly and the audio is muxed.+Captions sit in the bottom 26% of the frame: keep big on-screen numbers out of that band.+Styles: highlighter, clean, paper, redbar (see captions.py). The SRT uses sentence-sized chunks+for players (upload it to YouTube with the clean, caption-free render).+"""+import argparse+import json+import multiprocessing as mp+import os+import pathlib+import subprocess+import sys+import time++HERE = pathlib.Path(__file__).resolve().parent+sys.path.insert(0, str(HERE))+++def probe(video):+ out = subprocess.run(["ffprobe", "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height,r_frame_rate,nb_frames",+ "-of", "json", str(video)], capture_output=True, text=True).stdout+ s = json.loads(out)["streams"][0]+ num, den = map(int, s["r_frame_rate"].split("/"))+ nb = int(s.get("nb_frames") or 0)+ if not nb:+ dur = float(subprocess.run(["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", str(video)],+ capture_output=True, text=True).stdout)+ nb = int(round(dur * num / den))+ return s["width"], s["height"], num / den, nb+++def worker(args):+ video, style, f0, f1, fps, w, h, out, crf, timing, fonts = args+ import numpy as np+ from captions import Captions+ cap = Captions(style, w, h, timing, fonts)+ y0 = int(h * 0.74)+ dec = subprocess.Popen(["ffmpeg", "-v", "error", "-ss", f"{f0 / fps:.4f}", "-i", str(video), "-frames:v", str(f1 - f0),+ "-f", "rawvideo", "-pix_fmt", "rgb24", "-"], stdout=subprocess.PIPE)+ enc = subprocess.Popen(["ffmpeg", "-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "rgb24", "-s", f"{w}x{h}", "-r", str(fps), "-i", "-",+ "-c:v", "libx264", "-preset", "medium", "-crf", str(crf), *(["-rc-lookahead", "10", "-threads", "2"] if w >= 2000 else []),+ "-pix_fmt", "yuv420p", str(out)], stdin=subprocess.PIPE)+ size = w * h * 3+ t0 = time.time()+ for n in range(f0, f1):+ buf = dec.stdout.read(size)+ if len(buf) < size:+ break+ frame = np.frombuffer(buf, np.uint8).reshape(h, w, 3)+ layer = cap.layer(n / fps)+ if layer is not None:+ frame = frame.copy()+ a = layer[y0:, :, 3:4].astype(np.float32) * (1 / 255.0)+ frame[y0:] = np.clip(frame[y0:].astype(np.float32) * (1 - a) + layer[y0:, :, :3], 0, 255).astype(np.uint8)+ enc.stdin.write(frame.tobytes())+ enc.stdin.close(); enc.wait(); dec.wait()+ return f0, f1, time.time() - t0+++def srt(timing, out):+ from captions import chunks_for+ total = timing["total_duration"]++ def ts(x):+ ms = int(round(x * 1000)); return f"{ms // 3600000:02d}:{ms // 60000 % 60:02d}:{ms // 1000 % 60:02d},{ms % 1000:03d}"+ rows = chunks_for(timing, "clean")+ lines = []+ for i, c in enumerate(rows, 1):+ lines += [str(i), f"{ts(c['t0'])} --> {ts(min(c['t1'], total))}", " ".join(w for w, _ in c["words"]), ""]+ pathlib.Path(out).write_text("\n".join(lines))+ print(f"srt: {out} ({len(rows)} cues)")+++def main():+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ ap.add_argument("--project", required=True)+ ap.add_argument("--video")+ ap.add_argument("--audio")+ ap.add_argument("--style", default="highlighter", choices=["highlighter", "clean", "paper", "redbar"])+ ap.add_argument("--out", required=True)+ ap.add_argument("--workers", type=int, default=max(1, min(6, (os.cpu_count() or 4) - 1)))+ ap.add_argument("--crf", type=int, default=18)+ ap.add_argument("--srt-only", action="store_true")+ a = ap.parse_args()+ proj = pathlib.Path(a.project).resolve()+ rel = lambda p: p if pathlib.Path(p).is_absolute() else proj / p+ timing = json.loads((proj / "audio" / "timing.json").read_text())+ out = rel(a.out); out.parent.mkdir(parents=True, exist_ok=True)+ if a.srt_only:+ srt(timing, out); return+ if not a.video:+ sys.exit("--video is required (or --srt-only)")+ video = rel(a.video)+ w, h, fps, nb = probe(video)+ work = proj / "out" / "burn"; work.mkdir(parents=True, exist_ok=True)+ for old in work.glob("*.mp4"):+ old.unlink()+ k = a.workers+ b = [nb * i // k for i in range(k + 1)]+ fonts = str(proj / "fonts")+ jobs = [(str(video), a.style, b[i], b[i + 1], fps, w, h, work / f"b{i:02d}.mp4", a.crf, timing, fonts) for i in range(k)]+ t0 = time.time()+ with mp.get_context("spawn").Pool(k) as pool:+ for f0, f1, dt in pool.imap_unordered(worker, jobs):+ print(f" frames {f0}-{f1}: {dt:.0f}s", flush=True)+ lst = work / "list.txt"; lst.write_text("".join(f"file '{j[7].resolve()}'\n" for j in jobs))+ cmd = ["ffmpeg", "-v", "error", "-y", "-f", "concat", "-safe", "0", "-i", str(lst)]+ if a.audio:+ cmd += ["-i", str(rel(a.audio)), "-map", "0:v", "-map", "1:a", "-c:a", "aac", "-b:a", "192k", "-shortest"]+ cmd += ["-c:v", "copy", "-movflags", "+faststart", str(out)]+ subprocess.run(cmd, check=True)+ print(f"wrote {out} in {time.time() - t0:.0f}s")+++if __name__ == "__main__":+ main()diff --git a/skills/cinematic-film/scripts/captions.py b/skills/cinematic-film/scripts/captions.pynew file mode 100644index 0000000..be7cdc7--- /dev/null+++ b/skills/cinematic-film/scripts/captions.py@@ -0,0 +1,163 @@+"""Burned-in caption styles, chunked from the voiceover timing. Used by burn_captions.py.++Captions are drawn in screen space on their own layer after the film finish, so they stay crisp.+Word times come from each line's letter share (the same estimate the scene uses for hits).++Styles:+ highlighter condensed caps on a dark band, the current word swiped in yellow (grunge newsprint)+ clean sentence case with a soft shadow over a bottom gradient (classic documentary subtitle)+ paper typewriter text typing onto a torn paper strip+ redbar white condensed caps on a red bar (matches name labels)+"""+import re++import numpy as np+import skia++from engine import HILITE, Res, ease_out_cubic, paint, ramp, text_width, draw_text++MAX_WORDS = {"highlighter": 6, "clean": 9, "paper": 8, "redbar": 5}+++def words_with_times(seg):+ """[(word as displayed, start time)] for one line: display text, spoken-text timing."""+ disp = seg["caption"].replace('"', "").split()+ lens = []+ for w in disp:+ letters = len(re.sub(r"[^A-Za-z]", "", w))+ if re.search(r"\d", w): # 1929 is long when spoken ("nineteen twenty-nine")+ letters = max(letters, 6 * len(re.sub(r"[^0-9]", "", w)) // 2 + 4)+ lens.append(max(1, letters))+ s = sum(lens); acc = 0; out = []+ dur = seg["end"] - seg["start"]+ for w, l in zip(disp, lens):+ out.append((w, seg["start"] + dur * acc / s)); acc += l+ return out+++def chunks_for(timing, style):+ """[{'words': [(w, t)], 't0', 't1'}], breaking at punctuation where possible."""+ mx = MAX_WORDS[style]+ out = []+ for seg in timing["segments"]:+ ws = words_with_times(seg)+ cur, line = [], []+ for i, (w, t) in enumerate(ws):+ cur.append((w, t))+ if len(cur) >= mx or (w[-1] in ".,?!;:" and len(cur) >= max(2, mx // 2)) or i == len(ws) - 1:+ line.append({"words": cur, "t0": cur[0][1]}); cur = []+ for a, b in zip(line, line[1:]):+ a["t1"] = b["t0"]+ line[-1]["t1"] = seg["end"] + 0.25+ out += line+ return out+++class Captions:+ def __init__(self, style, width, height, timing, fonts_dir=None):+ self.style, self.W, self.H = style, width, height+ self.k = width / 1920.0+ self.res = Res(width / 3840.0, None, fonts_dir)+ self.chunks = chunks_for(timing, style)+ self.surface = skia.Surface.MakeRaster(skia.ImageInfo.Make(width, height, skia.ColorType.kRGBA_8888_ColorType, skia.AlphaType.kPremul_AlphaType))++ def active(self, t):+ for c in self.chunks:+ if c["t0"] - 0.05 <= t < c["t1"]:+ return c+ return None++ def layer(self, t):+ """Premultiplied RGBA caption layer for time t, or None."""+ c = self.active(t)+ if c is None:+ return None+ with self.surface as cv:+ cv.clear(skia.Color(0, 0, 0, 0))+ getattr(self, "_" + self.style)(cv, c, t)+ return self.surface.makeImageSnapshot().toarray(colorType=skia.ColorType.kRGBA_8888_ColorType)++ def _text(self, c, upper=False):+ txt = " ".join(w for w, _ in c["words"])+ return txt.upper() if upper else txt++ def _highlighter(self, cv, c, t):+ k = self.k; size = 66 * k; y = self.H * 0.897; f = "cond"+ words = [w.upper() for w, _ in c["words"]]+ gap = size * 0.28+ widths = [text_width(self.res, w, size, f, 0.03) for w in words]+ total = sum(widths) + gap * (len(words) - 1)+ x = self.W / 2 - total / 2+ a = ramp(t, c["t0"] - 0.05, 0.12)+ cur = max(i for i, (_, wt) in enumerate(c["words"]) if wt <= t + 0.02) if t >= c["words"][0][1] else 0+ pad = 26 * k+ cv.drawRoundRect(skia.Rect.MakeXYWH(x - pad, y - size * 0.95, total + 2 * pad, size * 1.25), 6 * k, 6 * k, paint((10, 9, 8), 0.62 * a))+ for i, (w, wd) in enumerate(zip(words, widths)):+ if i == cur:+ # white word underneath; the yellow swipe reveals it in black only where the swipe has reached+ u = ease_out_cubic(ramp(t, c["words"][i][1], 0.12))+ box = skia.Rect.MakeXYWH(x - 10 * k, y - size * 0.78, (wd + 20 * k) * u, size * 0.92)+ draw_text(cv, self.res, w, x, y, size, f, (250, 247, 240), a, 0.03)+ cv.drawRect(box, paint(HILITE, 0.95 * a))+ cv.save(); cv.clipRect(box)+ draw_text(cv, self.res, w, x, y, size, f, (18, 16, 14), a, 0.03)+ cv.restore()+ else:+ cv.save(); cv.translate(3 * k, 4 * k)+ draw_text(cv, self.res, w, x, y, size, f, (0, 0, 0), 0.6 * a, 0.03)+ cv.restore()+ draw_text(cv, self.res, w, x, y, size, f, (250, 247, 240), a, 0.03)+ x += wd + gap++ def _clean(self, cv, c, t):+ k = self.k; size = 52 * k; f = "labelm"+ txt = self._text(c)+ a = ramp(t, c["t0"] - 0.05, 0.15) * (1 - ramp(t, c["t1"] - 0.12, 0.12))+ g = skia.GradientShader.MakeLinear([skia.Point(0, self.H * 0.68), skia.Point(0, self.H)], [skia.Color(0, 0, 0, 0), skia.Color(0, 0, 0, int(190 * a))])+ gp = skia.Paint(); gp.setShader(g); cv.drawRect(skia.Rect.MakeXYWH(0, self.H * 0.68, self.W, self.H * 0.32), gp)+ lines = [txt]+ if text_width(self.res, txt, size, f) > self.W * 0.7:+ ws = txt.split(); half = len(ws) // 2 + (len(ws) % 2)+ lines = [" ".join(ws[:half]), " ".join(ws[half:])]+ y0 = self.H * 0.885 - (len(lines) - 1) * size * 1.25+ for i, ln in enumerate(lines):+ y = y0 + i * size * 1.25+ cv.save(); cv.translate(0, 3 * k)+ tw = text_width(self.res, ln, size, f)+ cv.drawString(ln, self.W / 2 - tw / 2, y, self.res.font(f, size), paint((0, 0, 0), 0.85 * a, blur=6 * k))+ cv.restore()+ draw_text(cv, self.res, ln, self.W / 2, y, size, f, (252, 250, 245), a, 0.0, "center")++ def _paper(self, cv, c, t):+ k = self.k; size = 42 * k; f = "mono"+ txt = self._text(c)+ tw = text_width(self.res, txt, size, f, 0.02)+ a = ramp(t, c["t0"] - 0.05, 0.12)+ W, H = tw + 64 * k, size * 1.75+ cv.save(); cv.translate(self.W / 2, self.H * 0.865); cv.rotate(-0.8)+ rng = np.random.default_rng(int(c["t0"] * 10))+ p = skia.Path(); n = 28+ p.moveTo(-W / 2, -H / 2)+ for i in range(1, n + 1):+ p.lineTo(-W / 2 + W * i / n, -H / 2 + rng.uniform(-3, 3) * k)+ for i in range(n + 1):+ p.lineTo(W / 2 - W * i / n, H / 2 + rng.uniform(-3, 3) * k)+ p.close()+ cv.save(); cv.translate(6 * k, 8 * k); cv.drawPath(p, paint((0, 0, 0), 0.5 * a, blur=8 * k)); cv.restore()+ cv.drawPath(p, paint((240, 236, 226), 0.97 * a))+ n_chars = len(txt) * ramp(t, c["t0"], 0.035 * len(txt) + 0.05)+ draw_text(cv, self.res, txt, -tw / 2, size * 0.32, size, f, (24, 22, 20), a, 0.02, reveal=n_chars + 0.999)+ cv.restore()++ def _redbar(self, cv, c, t):+ k = self.k; size = 60 * k; f = "cond"+ txt = self._text(c, upper=True)+ tw = text_width(self.res, txt, size, f, 0.04)+ u = ease_out_cubic(ramp(t, c["t0"] - 0.05, 0.22)); a = ramp(t, c["t0"] - 0.05, 0.08)+ W, H = tw + 50 * k, size * 1.22+ x0, y0 = self.W / 2 - W / 2, self.H * 0.865 - H * 0.72+ cv.drawRect(skia.Rect.MakeXYWH(x0 + 6 * k, y0 + 8 * k, W * u, H), paint((0, 0, 0), 0.45 * a, blur=8 * k))+ cv.drawRect(skia.Rect.MakeXYWH(x0, y0, W * u, H), paint((176, 24, 20), 0.97 * a))+ cv.save(); cv.clipRect(skia.Rect.MakeXYWH(x0, y0, W * u, H))+ draw_text(cv, self.res, txt, self.W / 2, y0 + H * 0.8, size, f, (252, 249, 242), a, 0.04, "center")+ cv.restore()diff --git a/skills/cinematic-film/scripts/check_setup.py b/skills/cinematic-film/scripts/check_setup.pynew file mode 100644index 0000000..93bed8b--- /dev/null+++ b/skills/cinematic-film/scripts/check_setup.py@@ -0,0 +1,73 @@+#!/usr/bin/env python3+"""Check that this machine can build a cinematic-film project, and say exactly what to install if not.++ python3 check_setup.py++Checks Python, numpy, Pillow, skia-python, ffmpeg and ffprobe (with libx264), the fonts each text+role will use, a local voice for scratch tracks, and how many render workers fit in memory.+Exit code 1 when something required is missing.+"""+import importlib+import pathlib+import shutil+import subprocess+import sys++HERE = pathlib.Path(__file__).resolve().parent+ok = True+++def line(status, what, detail=""):+ print(f" [{status}] {what}" + (f" {detail}" if detail else ""))+++def need(cond, what, fix):+ global ok+ line("ok" if cond else "MISSING", what, "" if cond else fix)+ ok &= bool(cond)+++print("cinematic-film setup check")+need(sys.version_info >= (3, 9), f"Python {sys.version.split()[0]}", "needs Python 3.9 or newer")+mods = {}+for mod, pip in (("numpy", "numpy"), ("PIL", "pillow"), ("skia", "skia-python")):+ try:+ mods[mod] = importlib.import_module(mod)+ line("ok", f"{pip} {getattr(mods[mod], '__version__', '')}")+ except Exception as e:+ need(False, pip, f"pip install {pip} ({type(e).__name__})")+try:+ import scipy # noqa: F401+ line("ok", "scipy (optional: faster sound-effects render)")+except Exception:+ line("--", "scipy not installed (optional; build_sfx.py falls back to a slower filter)")++for tool in ("ffmpeg", "ffprobe"):+ need(shutil.which(tool), tool, "install ffmpeg: brew install ffmpeg / apt install ffmpeg / winget install ffmpeg")+if shutil.which("ffmpeg"):+ enc = subprocess.run(["ffmpeg", "-hide_banner", "-encoders"], capture_output=True, text=True).stdout+ need("libx264" in enc, "ffmpeg has libx264", "your ffmpeg build lacks libx264; install a full build")+ filt = subprocess.run(["ffmpeg", "-hide_banner", "-filters"], capture_output=True, text=True).stdout+ need("loudnorm" in filt and "sidechaincompress" in filt, "ffmpeg has loudnorm and sidechaincompress", "install a full ffmpeg build")++if "skia" in mods:+ sys.path.insert(0, str(HERE))+ from engine import FONT_ROLES, resolve_typeface+ print(" fonts (drop <project>/fonts/<role>.ttf to override any of them):")+ for role in FONT_ROLES:+ tf, desc = resolve_typeface(role)+ print(f" {role:<7} {desc}")++voice = "say" if shutil.which("say") else "espeak-ng" if shutil.which("espeak-ng") else None+line("ok" if voice else "--", f"scratch voice: {voice}" if voice else "no local voice for scratch tracks",+ "" if voice else "optional: apt install espeak-ng, or use any TTS and save takes as WAV")++sys.path.insert(0, str(HERE))+try:+ from render import auto_workers, total_ram_gb+ print(f" memory {total_ram_gb():.0f} GB: {auto_workers(1920, 1080)} workers at 1080p, "+ f"{auto_workers(2560, 1440)} at 1440p, {auto_workers(3840, 2160)} at 4K")+except Exception:+ pass+print("ready" if ok else "fix the MISSING items above, then run this again")+sys.exit(0 if ok else 1)diff --git a/skills/cinematic-film/scripts/engine.py b/skills/cinematic-film/scripts/engine.pynew file mode 100644index 0000000..a8ac47e--- /dev/null+++ b/skills/cinematic-film/scripts/engine.py@@ -0,0 +1,1566 @@+"""cinematic-film film engine: one continuous camera over one world, drawn with Skia.++World units are 4K screen pixels at camera zoom 1. A Film holds items (each knows how to draw+itself at time t), camera keys, spotlight keys, camera shakes and sound cues. A frame is:+camera transform -> items in z order -> spotlight dim -> film finish (glow, grade, vignette,+grain), with motion-blur sub-frames when the camera moves fast.++A project's scene.py imports from here and defines build_film(doc) -> Film. `doc` (a Doc) gives+the voiceover timing (doc.L, doc.E, doc.W), photo sizes and maps. render.py does the rest.++Performance rules baked in (each measured on the film this was built for):+ * images that repeat (cork, paper) are tiled with drawImageRect: a repeating image shader under+ rotation was about 70x slower in Skia's CPU raster+ * every item reports bounds() so off-screen items are skipped+ * static vector art (maps) is drawn once into an image (Cached) and reused+ * photos are capped at 2200 px (x render scale): full-size copies of ~30 photos pushed a 4K+ worker past 2 GB+"""+from __future__ import annotations++import bisect+import json+import math+import pathlib+import re++import numpy as np+import skia+from PIL import Image, ImageFilter++# ---------------------------------------------------------------- palette+TEAL = (112, 178, 182)+RUST = (186, 86, 52)+MUSTARD = (222, 176, 52)+HILITE = (246, 206, 46)+RED = (168, 28, 24)+INK = (40, 30, 22)+CREAM = (239, 230, 212)+WHITE = (246, 243, 236)++# Font roles -> candidates, tried in order (family, weight). Drop <project>/fonts/<role>.ttf (or .otf)+# to force a face, e.g. fonts/cond.ttf = Oswald Bold from Google Fonts (OFL).+FONT_ROLES = {+ "serif": [("Baskerville", 400), ("Libre Baskerville", 400), ("Georgia", 400), ("Times New Roman", 400), ("DejaVu Serif", 400)],+ "mono": [("Courier New", 700), ("Courier Prime", 700), ("Courier", 700), ("DejaVu Sans Mono", 700), ("Menlo", 700)],+ "hand": [("Snell Roundhand", 400), ("Homemade Apple", 400), ("Segoe Script", 400), ("Brush Script MT", 400), ("URW Chancery L", 400)],+ "cond": [("DIN Condensed", 700), ("Oswald", 700), ("Bebas Neue", 400), ("Roboto Condensed", 700), ("Arial Narrow", 700),+ ("DejaVu Sans Condensed", 700), ("Impact", 400)],+ "label": [("Avenir Next", 800), ("Montserrat", 800), ("Helvetica Neue", 700), ("Arial", 700), ("DejaVu Sans", 700)],+ "labelm": [("Avenir Next", 700), ("Montserrat", 600), ("Helvetica Neue", 500), ("Arial", 400), ("DejaVu Sans", 400)],+}++# Looks: the board under everything plus the film finish. A scene picks one with Film(look=...).+LOOKS = {+ # evidence wall: dark cork, warm grade (true stories, history, crime)+ "wall": dict(board="cork_dark.png", bg=(12, 9, 7), grade=(1.015, 1.0, 0.975), grain=0.026, glow=0.24, vignette=0.75, curve=0.25),+ # cool blue-grey board (politics, business, investigations)+ "slate": dict(board="slate.png", bg=(8, 10, 12), grade=(0.99, 1.0, 1.02), grain=0.024, glow=0.22, vignette=0.7, curve=0.25),+ # neutral black (anything; lets colour photos carry the frame)+ "charcoal": dict(board="charcoal.png", bg=(9, 9, 9), grade=(1.0, 1.0, 1.0), grain=0.03, glow=0.2, vignette=0.75, curve=0.3),+ # light paper desk (education, gentle stories)+ "paper": dict(board="paper.png", bg=(220, 216, 208), grade=(1.01, 1.0, 0.98), grain=0.022, glow=0.12, vignette=0.45, curve=0.2, dim=(70, 64, 58)),+ # light seamless studio (product launches, brand stories, explainers with cards)+ "studio": dict(board="studio.png", bg=(214, 212, 208), grade=(1.0, 1.0, 1.0), grain=0.012, glow=0.06, vignette=0.32, curve=0.12, dim=(96, 92, 88)),+ # deep blue drafting sheet with a grid (engineering, science, how things work)+ "blueprint": dict(board="blueprint.png", bg=(12, 30, 60), grade=(0.98, 1.0, 1.04), grain=0.02, glow=0.26, vignette=0.6, curve=0.2, dim=(4, 10, 24)),+ # dark navy, high glow (tech, space, night-time stories, trailers)+ "night": dict(board="night.png", bg=(7, 9, 15), grade=(0.97, 1.0, 1.06), grain=0.022, glow=0.32, vignette=0.8, curve=0.3, dim=(2, 3, 8)),+}+++# ---------------------------------------------------------------- easing / splines+def clamp(x, a=0.0, b=1.0):+ return a if x < a else b if x > b else x+++def ease_out_cubic(x):+ x = clamp(x); return 1 - (1 - x) ** 3+++def ease_in_out(x):+ x = clamp(x); return x * x * (3 - 2 * x)+++def ease_out_back(x, s=1.4):+ x = clamp(x) - 1; return 1 + x * x * ((s + 1) * x + s)+++def ramp(t, t0, dur):+ return clamp((t - t0) / dur) if dur > 0 else float(t >= t0)+++class Spline:+ """Monotone cubic (Fritsch-Carlson) through (t, value) keys: smooth, no overshoot, and it keeps+ moving through keys that sit on a monotone run, so a hold can drift instead of stopping dead."""++ def __init__(self, keys):+ keys = sorted(keys)+ self.t = [k[0] for k in keys]; self.v = [k[1] for k in keys]+ n = len(keys)+ d = [(self.v[i + 1] - self.v[i]) / max(1e-9, self.t[i + 1] - self.t[i]) for i in range(n - 1)]+ m = [0.0] * n+ if n > 1:+ m[0], m[-1] = d[0], d[-1]+ for i in range(1, n - 1):+ m[i] = 0.0 if d[i - 1] * d[i] <= 0 else (d[i - 1] + d[i]) / 2+ for i in range(n - 1):+ if d[i] == 0:+ m[i] = m[i + 1] = 0.0+ continue+ a, b = m[i] / d[i], m[i + 1] / d[i]+ s = a * a + b * b+ if s > 9:+ k = 3 / math.sqrt(s); m[i] = k * a * d[i]; m[i + 1] = k * b * d[i]+ self.m = m++ def __call__(self, t):+ T = self.t+ if t <= T[0]:+ return self.v[0]+ if t >= T[-1]:+ return self.v[-1]+ i = bisect.bisect_right(T, t) - 1+ h = T[i + 1] - T[i]; u = (t - T[i]) / h+ h00 = 2 * u ** 3 - 3 * u ** 2 + 1; h10 = u ** 3 - 2 * u ** 2 + u+ h01 = -2 * u ** 3 + 3 * u ** 2; h11 = u ** 3 - u ** 2+ return h00 * self.v[i] + h10 * h * self.m[i] + h01 * self.v[i + 1] + h11 * h * self.m[i + 1]+++# ---------------------------------------------------------------- project context+class Doc:+ """A project folder: voiceover timing, photo sizes, maps. Passed to scene.build_film(doc)."""++ def __init__(self, project):+ self.dir = pathlib.Path(project).resolve()+ self.prep = self.dir / "assets" / "prep"+ tp = self.dir / "audio" / "timing.json"+ if not tp.exists():+ raise SystemExit(f"{tp} not found: record a voice (or a scratch track with tts_say.py), "+ "then run split_takes.py and build_narration.py first")+ self.timing = json.loads(tp.read_text())+ self.seg = {s["id"]: s for s in self.timing["segments"]}+ self.duration = self.timing["total_duration"]+ mp = self.prep / "photos" / "meta.json"+ self.meta = json.loads(mp.read_text()) if mp.exists() else {}++ def L(self, i):+ """Start of narration line i (seconds)."""+ return self.seg[i]["start"]++ def E(self, i):+ """End of narration line i."""+ return self.seg[i]["end"]++ def W(self, i, word, nth=0):+ """When `word` is spoken in line i, by its letter share of the line (pauses spread evenly).+ Search the SPOKEN text: "1929" is spoken "nineteen twenty-nine", so ask for "nineteen"."""+ vo = self.seg[i]["vo"]+ letters = re.sub(r"[^a-z]", "", vo.lower())+ idx, start = -1, 0+ for _ in range(nth + 1):+ idx = vo.lower().find(word.lower(), start); start = idx + 1+ if idx < 0:+ break+ if idx < 0:+ raise ValueError(f"{word!r} (occurrence {nth}) is not in the spoken text of line {i}: {vo!r}")+ before = len(re.sub(r"[^a-z]", "", vo[:idx].lower()))+ return self.L(i) + (self.E(i) - self.L(i)) * before / max(1, len(letters)) + 0.04++ def on(self, pr, fx, fy):+ """World point at a fractional position (0..1, 0..1) inside a print's image area."""+ w, h = pr.size_from(self.meta)+ return rot_point(pr.x, pr.y, (fx - 0.5) * w, (fy - 0.5) * h, pr.rot)++ def res(self):+ """A Res at world scale, for measuring text while laying out (PaperDoc.phrase_pos and friends)."""+ if not hasattr(self, "_res"):+ self._res = Res(1.0, self.prep, self.dir / "fonts")+ return self._res++ def map(self, name):+ p = self.prep / f"map_{name}.json"+ if not p.exists():+ raise SystemExit(f"{p} not found: add the map to map.json and run make_map.py")+ return json.loads(p.read_text())+++# ---------------------------------------------------------------- resources+class Res:+ """Per-process cache of images and fonts. Images are downscaled to what the render size can show."""++ def __init__(self, scale, prep=None, fonts_dir=None):+ self.scale = scale+ self.prep = pathlib.Path(prep) if prep else None+ self.fonts_dir = pathlib.Path(fonts_dir) if fonts_dir else None+ self.imgs, self.tf, self.cache = {}, {}, {}+ self.screen_scale = 1.0+ self.view = skia.Rect.MakeXYWH(-80000, -60000, 160000, 120000)+ mp = self.prep / "photos" / "meta.json" if self.prep else None+ self.meta = json.loads(mp.read_text()) if mp and mp.exists() else {}++ def image(self, key, max_side=None):+ if key not in self.imgs:+ path = self.prep / key if "." in key else self.prep / "photos" / f"{key}.jpg"+ if not path.exists():+ raise SystemExit(f"image {key!r} not found at {path}: run prep_assets.py")+ im = Image.open(path).convert("RGBA")+ lim = int(min(max_side or 3200, 2200) * max(self.scale, 0.35))+ if max(im.size) > lim:+ im.thumbnail((lim, lim), Image.LANCZOS)+ arr = np.ascontiguousarray(np.asarray(im))+ self.imgs[key] = skia.Image.fromarray(arr, colorType=skia.ColorType.kRGBA_8888_ColorType).withDefaultMipmaps()+ return self.imgs[key]++ def typeface(self, name):+ if name not in self.tf:+ self.tf[name] = resolve_typeface(name, self.fonts_dir)[0]+ return self.tf[name]++ def wear(self):+ """Speckle mask that distresses type and stamps (alpha = where ink is knocked out)."""+ if "wear" not in self.imgs:+ rng = np.random.default_rng(7)+ n = rng.random((256, 768)) ** 7 * 255+ sm = np.asarray(Image.fromarray(n.astype(np.uint8)).filter(ImageFilter.GaussianBlur(0.6)), np.float32)+ arr = np.zeros((256, 768, 4), np.uint8); arr[..., 3] = np.clip(sm * 1.6, 0, 255).astype(np.uint8)+ self.imgs["wear"] = skia.Image.fromarray(arr, colorType=skia.ColorType.kRGBA_8888_ColorType)+ return self.imgs["wear"]++ def font(self, name, size):+ f = skia.Font(self.typeface(name), size)+ f.setSubpixel(True); f.setEdging(skia.Font.Edging.kAntiAlias)+ return f+++def resolve_typeface(role, fonts_dir=None):+ """(typeface, description) for a font role: project override file, then the candidates, then the default."""+ if fonts_dir:+ for ext in (".ttf", ".otf"):+ p = pathlib.Path(fonts_dir) / f"{role}{ext}"+ if p.exists():+ tf = skia.Typeface.MakeFromFile(str(p))+ if tf:+ return tf, f"{p.name} (project file)"+ mgr = skia.FontMgr.RefDefault()+ for fam, weight in FONT_ROLES.get(role, []):+ tf = mgr.matchFamilyStyle(fam, skia.FontStyle(weight, 5, skia.FontStyle.kUpright_Slant))+ if tf is not None and tf.getFamilyName().lower() == fam.lower():+ return tf, f"{fam} {weight}"+ tf = mgr.legacyMakeTypeface("", skia.FontStyle.Bold() if role in ("cond", "label", "mono") else skia.FontStyle.Normal())+ return tf, f"system default ({tf.getFamilyName() if tf else '?'}): install one of {[f for f, _ in FONT_ROLES.get(role, [])][:3]}"+++SAMPLING = skia.SamplingOptions(skia.FilterMode.kLinear, skia.MipmapMode.kLinear)+++def color(rgb, a=1.0):+ return skia.Color(int(rgb[0]), int(rgb[1]), int(rgb[2]), int(255 * clamp(a)))+++def paint(rgb=(0, 0, 0), a=1.0, stroke=None, blur=None, aa=True):+ p = skia.Paint(AntiAlias=aa, Color=color(rgb, a))+ if stroke is not None:+ p.setStyle(skia.Paint.kStroke_Style); p.setStrokeWidth(stroke)+ p.setStrokeCap(skia.Paint.kRound_Cap); p.setStrokeJoin(skia.Paint.kRound_Join)+ if blur:+ p.setMaskFilter(skia.MaskFilter.MakeBlur(skia.kNormal_BlurStyle, blur))+ return p+++def draw_text(c, res, text, x, y, size, font="serif", rgb=CREAM, a=1.0, track=0.0, align="left", reveal=None):+ """Draw text with letter tracking (em fraction). reveal=n draws only the first n characters."""+ f = res.font(font, size)+ widths = f.getWidths(f.textToGlyphs(text))+ gap = track * size+ total = sum(widths) + gap * (len(text) - 1)+ x0 = x - total / 2 if align == "center" else x - total if align == "right" else x+ p = paint(rgb, a)+ n = len(text) if reveal is None else int(reveal)+ cx = x0+ for i, ch in enumerate(text):+ if i >= n:+ break+ c.drawString(ch, cx, y, f, p)+ cx += widths[i] + gap+ return total+++def text_width(res, text, size, font="serif", track=0.0):+ f = res.font(font, size)+ return sum(f.getWidths(f.textToGlyphs(text))) + track * size * (len(text) - 1)+++def partial_path(path, p):+ """The first fraction p of a path, by length (for strokes that draw on)."""+ if p >= 1:+ return path+ pm = skia.PathMeasure(path, False)+ out = skia.Path()+ lengths = []+ while True:+ lengths.append(pm.getLength())+ if not pm.nextContour():+ break+ pm = skia.PathMeasure(path, False)+ want = sum(lengths) * clamp(p)+ for L in lengths:+ if want <= 0:+ break+ pm.getSegment(0, min(L, want), out, True)+ want -= L+ pm.nextContour()+ return out+++def rot_point(cx, cy, dx, dy, deg):+ r = math.radians(deg)+ return cx + dx * math.cos(r) - dy * math.sin(r), cy + dx * math.sin(r) + dy * math.cos(r)+++# ---------------------------------------------------------------- items+class Item:+ """Base item. t_in: when it appears; t_out: when it starts fading (None = stays). sfx=False mutes its auto cues."""+ z = 0++ def __init__(self, t_in=0.0, t_out=None, z=None, sfx=True):+ self.t_in, self.t_out, self.sfx = t_in, t_out, sfx+ if z is not None:+ self.z = z++ def visible(self, t):+ return t >= self.t_in - 0.01 and (self.t_out is None or t < self.t_out + 0.6)++ def bounds(self, res):+ return None++ def fade(self, t):+ return 1.0 if self.t_out is None else 1 - ramp(t, self.t_out, 0.6)++ def cues(self):+ """Sound cues this item makes on its own: [(type, t, gain, extra kwargs)]."""+ return []++ def shakes(self):+ """Camera shakes this item causes: [(t, amplitude, duration)]."""+ return []++ def draw(self, c, res, t):+ raise NotImplementedError+++class Cached:+ """Draw a static item once into an image (per process) and reuse it while the camera is far away;+ once the camera is close enough that the image would go soft, draw the vectors live, clipped to+ the view. Big vector art (a map 40,000 px wide) cannot fit one image sharp enough for close-ups."""+ cache_res = 1.0++ def cached_draw(self, c, res, rect, draw_fn):+ cs = min(res.scale * self.cache_res, 8192 / max(rect.width(), rect.height()))+ if res.screen_scale > cs * 1.3:+ c.save(); c.clipRect(res.view, skia.ClipOp.kIntersect, False)+ draw_fn(c, res)+ c.restore()+ return+ key = id(self)+ if key not in res.cache:+ w, h = int(rect.width() * cs) + 2, int(rect.height() * cs) + 2+ surf = skia.Surface.MakeRaster(skia.ImageInfo.Make(w, h, skia.ColorType.kRGBA_8888_ColorType, skia.AlphaType.kPremul_AlphaType))+ with surf as cc:+ cc.clear(skia.Color(0, 0, 0, 0)); cc.scale(cs, cs); cc.translate(-rect.left(), -rect.top())+ draw_fn(cc, res)+ res.cache[key] = surf.makeImageSnapshot().withDefaultMipmaps()+ c.drawImageRect(res.cache[key], rect, SAMPLING, skia.Paint(AntiAlias=True))+++def tile_image(c, img, rect, tile, paint_=None, clip=True):+ """Cover `rect` with copies of `img`, each `tile` world px square (the fast path; see module notes)."""+ x0 = math.floor(rect.left() / tile) * tile; y0 = math.floor(rect.top() / tile) * tile+ if clip:+ c.save(); c.clipRect(rect, skia.ClipOp.kIntersect, True)+ y = y0+ while y < rect.bottom():+ x = x0+ while x < rect.right():+ c.drawImageRect(img, skia.Rect.MakeXYWH(x, y, tile + 0.5, tile + 0.5), SAMPLING, paint_)+ x += tile+ y += tile+ if clip:+ c.restore()+++def paper_fill(c, res, rect, a=1.0, scale=1.0, blend=None):+ p = skia.Paint(AntiAlias=True); p.setAlphaf(clamp(a))+ if blend is not None:+ p.setBlendMode(blend)+ tile_image(c, res.image("paper.png", 1024), rect, 1024 * scale, p)+++class Board(Item):+ """The endless surface under everything (cork, slate, charcoal or paper), tiled."""+ z = -100++ def __init__(self, texture="cork_dark.png", tile=2458):+ super().__init__(-1)+ self.texture, self.tile = texture, tile++ def draw(self, c, res, t):+ tile_image(c, res.image(self.texture, 1024), res.view, self.tile, clip=False)+++def drop_anim(t, t_in, dur=0.5):+ """Physical landing: (scale, alpha, lift) for a print dropping onto the board."""+ u = ramp(t, t_in, dur)+ return 1 + 0.16 * (1 - ease_out_cubic(u)), ramp(t, t_in, 0.12), 1 - ease_out_cubic(u)+++def draw_pin(c, x, y, r=34, rgb=(176, 30, 26), a=1.0):+ c.drawCircle(x + r * 0.35, y + r * 0.55, r * 0.95, paint((0, 0, 0), 0.45 * a, blur=r * 0.35))+ c.drawCircle(x, y, r, paint(rgb, a))+ c.drawCircle(x - r * 0.3, y - r * 0.3, r * 0.35, paint((255, 210, 200), 0.55 * a))+++def draw_label(c, res, text, x, y, a=1.0, size=128, rot=0.0, reveal=1.0, rgb=(176, 24, 20), text_rgb=(250, 246, 238)):+ """Name label: a colour bar with condensed caps; the bar wipes in left to right."""+ tw = text_width(res, text, size, "cond", 0.06)+ pad = size * 0.45+ W, H = tw + 2 * pad, size * 1.25+ c.save(); c.translate(x, y); c.rotate(rot)+ u = ease_out_cubic(clamp(reveal))+ c.drawRect(skia.Rect.MakeXYWH(-W / 2 + 8, 12, W * u, H), paint((0, 0, 0), 0.45 * a, blur=10))+ c.drawRect(skia.Rect.MakeXYWH(-W / 2, 0, W * u, H), paint(rgb, a))+ c.save(); c.clipRect(skia.Rect.MakeXYWH(-W / 2, 0, W * u, H))+ draw_text(c, res, text, 0, H * 0.8, size, "cond", text_rgb, a, 0.06, "center")+ c.restore(); c.restore()+++class Print(Item):+ """A photo or document on the board: paper border, shadow, pin, drop-in. paper=True makes a torn+ newspaper clipping that tears onto the board instead. label= adds a red name bar under it."""+ z = 10++ def __init__(self, key, x, y, w, rot=0.0, t_in=0.0, t_out=None, border=0.035, pin=True,+ paper=False, z=None, label=None, label_t=None, aspect=None, sfx=True, label_rgb=(176, 24, 20)):+ super().__init__(t_in, t_out, z, sfx)+ self.key, self.x, self.y, self.w, self.rot = key, x, y, w, rot+ self.border, self.pin, self.paper = border, pin, paper+ self.label, self.label_t, self.label_rgb = label, label_t, label_rgb+ self.aspect = aspect+ self.dim = None # optional callable t -> extra darkening 0..1+ self.exit_vec = None # (dx, dy): slide off while fading out++ def size_from(self, meta):+ if self.aspect:+ return self.w, self.w / self.aspect+ if self.key not in meta:+ raise SystemExit(f"photo {self.key!r} is not in assets/prep/photos/meta.json: add it to photos.json and run prep_assets.py")+ m = meta[self.key]+ return self.w, self.w * m["h"] / m["w"]++ def size(self, res):+ return self.size_from(res.meta)++ def outer(self, res):+ w, h = self.size(res)+ b = 0 if self.paper else self.border * min(w, h)+ return w + 2 * b, h + 2 * b++ def bounds(self, res):+ W, H = self.outer(res); r = max(W, H) * 0.8 + 400+ return skia.Rect.MakeLTRB(self.x - r, self.y - r, self.x + r, self.y + r + (300 if self.label else 0))++ def cues(self):+ return [("slide", self.t_in, 0.6, {})] if self.paper else [("pop", self.t_in, 0.8, {})]++ def torn_path(self, W, H, seed=None):+ if getattr(self, "_torn", None) is None:+ rng = np.random.default_rng(seed if seed is not None else sum(map(ord, self.key)) % 9999)+ p = skia.Path(); step = max(W, H) / 70++ def edge(x0, y0, x1, y1, nx, ny, first):+ L = math.hypot(x1 - x0, y1 - y0); n = max(2, int(L / step))+ for i in range(n):+ u = i / n; d = rng.uniform(0, 0.011) * min(W, H) + (rng.random() < 0.06) * rng.uniform(0.01, 0.02) * min(W, H)+ x, y = x0 + (x1 - x0) * u + nx * d, y0 + (y1 - y0) * u + ny * d+ (p.moveTo if (first and i == 0) else p.lineTo)(x, y)+ edge(-W / 2, -H / 2, W / 2, -H / 2, 0, 1, True); edge(W / 2, -H / 2, W / 2, H / 2, -1, 0, False)+ edge(W / 2, H / 2, -W / 2, H / 2, 0, -1, False); edge(-W / 2, H / 2, -W / 2, -H / 2, 1, 0, False)+ p.close(); self._torn = p+ return self._torn++ def draw(self, c, res, t):+ s, a, lift = drop_anim(t, self.t_in)+ tx = ty = tr = 0.0+ if self.paper: # clippings tear onto the board: fast slide and settle, no scale pop+ u = ease_out_back(ramp(t, self.t_in, 0.42), 1.1)+ s = 1.0; lift = 1 - ease_out_cubic(ramp(t, self.t_in, 0.42))+ tx, ty, tr = (1 - u) * 260, (1 - u) * 900, (1 - u) * 7+ a = ramp(t, self.t_in, 0.08)+ a *= self.fade(t)+ if a <= 0:+ return+ w, h = self.size(res)+ b = 0 if self.paper else self.border * min(w, h)+ W, H = w + 2 * b, h + 2 * b+ ox, oy = tx, ty+ if self.exit_vec and self.t_out is not None:+ u = ease_in_out(ramp(t, self.t_out, 0.6)); ox += self.exit_vec[0] * u; oy += self.exit_vec[1] * u+ c.save()+ c.translate(self.x + ox, self.y + oy); c.rotate(self.rot + 3.0 * lift + tr); c.scale(s, s)+ off = 18 + 70 * lift+ c.drawRect(skia.Rect.MakeXYWH(-W / 2 + off * 0.4, -H / 2 + off, W, H), paint((0, 0, 0), 0.55 * a, blur=22 + 50 * lift))+ if not self.paper:+ paper_fill(c, res, skia.Rect.MakeXYWH(-W / 2, -H / 2, W, H), a, 1.0)+ ip = skia.Paint(AntiAlias=True); ip.setAlphaf(a)+ if self.paper:+ torn = self.torn_path(W, H)+ c.drawPath(torn, paint((240, 237, 230), 0.9 * a, stroke=10))+ c.save(); c.clipPath(torn, skia.ClipOp.kIntersect, True)+ c.drawImageRect(res.image(self.key), skia.Rect.MakeXYWH(-w / 2, -h / 2, w, h), SAMPLING, ip)+ c.restore()+ else:+ c.drawImageRect(res.image(self.key), skia.Rect.MakeXYWH(-w / 2, -h / 2, w, h), SAMPLING, ip)+ if self.dim:+ d = self.dim(t)+ if d > 0:+ c.drawRect(skia.Rect.MakeXYWH(-W / 2, -H / 2, W, H), paint((0, 0, 0), d * a))+ if self.pin:+ if self.paper:+ draw_pin(c, -0.36 * W, -H / 2 + 0.012 * H, r=max(26, 0.02 * W), a=a)+ else:+ draw_pin(c, 0, -H / 2 + max(b * 0.5, 0.03 * H), r=max(26, 0.02 * W), a=a)+ c.restore()+ if self.label:+ lt = self.label_t if self.label_t is not None else self.t_in + 0.35+ la = ramp(t, lt, 0.15) * self.fade(t)+ if la > 0:+ draw_label(c, res, self.label, self.x + ox, self.y + oy + H / 2 * s + 30, la, size=max(120, 0.068 * W), rot=self.rot,+ reveal=ramp(t, lt, 0.4), rgb=self.label_rgb)+++class MapPin(Item):+ """Red map pin with a soft pulse and a typewriter label (case-board style)."""+ z = 30++ def __init__(self, x, y, label=None, t_in=0.0, t_out=None, label_side="right", size=1.0, label_size=70, z=None, sfx=True):+ super().__init__(t_in, t_out, z, sfx)+ self.x, self.y, self.label, self.side, self.k, self.ls = x, y, label, label_side, size, label_size++ def bounds(self, res):+ L = len(self.label or "") * self.ls * self.k * 0.75 + 400 * self.k+ return skia.Rect.MakeLTRB(self.x - L, self.y - 300 * self.k, self.x + L, self.y + 300 * self.k)++ def cues(self):+ return [("pop", self.t_in, 0.5, {})]++ def draw(self, c, res, t):+ u = ramp(t, self.t_in, 0.35)+ a = u * self.fade(t)+ if a <= 0:+ return+ k = self.k+ ph = (t - self.t_in) % 2.2 / 2.2+ c.drawCircle(self.x, self.y, 30 * k + 120 * k * ph, paint(RED, 0.35 * (1 - ph) * a, stroke=6 * k))+ c.drawCircle(self.x, self.y, 70 * k, paint((220, 40, 30), 0.25 * a, blur=40 * k))+ c.drawCircle(self.x, self.y, 22 * k * ease_out_back(u), paint((200, 34, 28), a))+ c.drawCircle(self.x, self.y, 9 * k, paint((255, 190, 170), a))+ if self.label:+ la = ramp(t, self.t_in + 0.2, 0.4) * self.fade(t)+ n = len(self.label) * ease_out_cubic(ramp(t, self.t_in + 0.2, 0.5))+ dx = 60 * k if self.side == "right" else -60 * k+ draw_text(c, res, self.label, self.x + dx, self.y + self.ls * 0.35, self.ls * k, "mono", (120, 22, 18), la,+ 0.14, "left" if self.side == "right" else "right", reveal=n + 0.999)+++class StringLine(Item):+ """Red string pulled from pin to pin, sagging; draws on over `dur`. Fades `hold` seconds after it+ lands unless persist=True: strings are for the beat, and a wall full of them reads as clutter."""+ z = 40++ def __init__(self, a, b, t_in, dur=1.0, sag=0.05, width=9, z=None, pins=True, t_out=None, persist=False, hold=5.0, sfx=True):+ if t_out is None and not persist:+ t_out = t_in + dur + hold+ super().__init__(t_in, t_out, z, sfx)+ self.a, self.b, self.dur, self.sag, self.wd, self.pins = a, b, dur, sag, width, pins++ def bounds(self, res):+ (x0, y0), (x1, y1) = self.a, self.b+ d = math.hypot(x1 - x0, y1 - y0) * self.sag + 200+ return skia.Rect.MakeLTRB(min(x0, x1) - 200, min(y0, y1) - 200, max(x0, x1) + 200, max(y0, y1) + d)++ def cues(self):+ return [("slide", self.t_in, 0.5, {})]++ def path(self):+ (x0, y0), (x1, y1) = self.a, self.b+ d = math.hypot(x1 - x0, y1 - y0)+ p = skia.Path(); p.moveTo(x0, y0); p.quadTo((x0 + x1) / 2, (y0 + y1) / 2 + d * self.sag, x1, y1)+ return p++ def draw(self, c, res, t):+ u = ease_in_out(ramp(t, self.t_in, self.dur))+ a = self.fade(t)+ if u <= 0 or a <= 0:+ return+ seg = partial_path(self.path(), u)+ c.save(); c.translate(10, 22)+ c.drawPath(seg, paint((0, 0, 0), 0.4 * a, stroke=self.wd, blur=6))+ c.restore()+ c.drawPath(seg, paint((150, 24, 20), a, stroke=self.wd))+ c.drawPath(seg, paint((210, 70, 60), 0.35 * a, stroke=self.wd * 0.35))+ if self.pins:+ draw_pin(c, *self.a, r=26, a=a)+ if u >= 0.999:+ draw_pin(c, *self.b, r=26, a=a)+++class PenMark(Item):+ """Hand-drawn mark revealed as it is drawn, timed to land on the spoken word.+ kind: ellipse | underline | strike | arrow | highlight (yellow marker, multiply blend)."""+ z = 50++ def __init__(self, kind, x, y, w, h=0, t_in=0.0, dur=0.6, width=12, seed=1, rot=0.0, t_out=None, z=None, rgb=(160, 22, 20), sfx=True):+ super().__init__(t_in, t_out, z, sfx)+ self.kind, self.x, self.y, self.w, self.h, self.dur, self.wd, self.rot, self.rgb = kind, x, y, w, h, dur, width, rot, rgb+ rng = np.random.default_rng(seed)+ p = skia.Path()+ if kind == "ellipse":+ a0 = rng.uniform(-2.4, -1.8); turns = 1.12; n = 80+ for i in range(n + 1):+ th = a0 + 2 * math.pi * turns * i / n+ wob = 1 + 0.035 * math.sin(3 * th + rng.uniform(0, 6)) + 0.03 * (i / n)+ (p.moveTo if i == 0 else p.lineTo)(math.cos(th) * w / 2 * wob, math.sin(th) * h / 2 * wob)+ elif kind == "highlight":+ p.moveTo(-w / 2, rng.uniform(-3, 3)); p.cubicTo(-w / 6, rng.uniform(-6, 6), w / 6, rng.uniform(-6, 6), w / 2, rng.uniform(-4, 4))+ elif kind == "arrow":+ p.moveTo(-w / 2, 0); p.cubicTo(-w / 4, -h, w / 4, -h, w / 2, 0)+ elif kind == "strike":+ p.moveTo(-w / 2, h / 2 * rng.uniform(-0.2, 0.2)); p.quadTo(0, -h * 0.25, w / 2, h / 2 * rng.uniform(-0.3, 0.3))+ else: # underline+ p.moveTo(-w / 2, 0); p.cubicTo(-w / 6, h * 0.25 + 4, w / 6, -h * 0.2 - 4, w / 2, h * 0.15 + 2)+ self.p = p++ def cues(self):+ if self.kind == "highlight":+ return [("marker", self.t_in, 0.8, {})]+ if self.kind == "strike" and self.dur < 0.3:+ return [("snip", self.t_in, 0.7, {})]+ return [("pencil", self.t_in, 0.6, {"dur": round(max(0.3, self.dur), 2)})]++ def draw(self, c, res, t):+ u = ease_out_cubic(ramp(t, self.t_in, self.dur))+ a = self.fade(t)+ if u <= 0 or a <= 0:+ return+ c.save(); c.translate(self.x, self.y); c.rotate(self.rot)+ seg = partial_path(self.p, u)+ if self.kind == "highlight":+ hp = paint(HILITE, 0.62 * a, stroke=self.wd); hp.setStrokeCap(skia.Paint.kButt_Cap)+ hp.setBlendMode(skia.BlendMode.kMultiply)+ c.drawPath(seg, hp)+ else:+ c.drawPath(seg, paint(self.rgb, 0.9 * a, stroke=self.wd))+ if self.kind == "arrow" and u > 0.92:+ k = self.wd * 3.4; th = math.atan2(self.h, self.w / 4)+ for sgn in (-1, 1):+ c.drawLine(self.w / 2, 0, self.w / 2 - k * math.cos(th + sgn * 0.5), -k * math.sin(th + sgn * 0.5),+ paint(self.rgb, 0.9 * a, stroke=self.wd))+ c.restore()+++class Chalk(Item):+ """Tally marks, one stroke per time in `times`; optional red strike through them at strike_t."""+ z = 45++ def __init__(self, x, y, times, height=170, gap=62, strike_t=None, t_out=None, seed=3, rgb=INK, width=18, sfx=True):+ super().__init__(min(times), t_out, None, sfx)+ self.rgb, self.width = rgb, width+ self.x, self.y, self.times, self.hh, self.gap, self.strike_t = x, y, times, height, gap, strike_t+ rng = np.random.default_rng(seed)+ self.jit = [(rng.uniform(-8, 8), rng.uniform(-10, 10), rng.uniform(-6, 6)) for _ in times]++ def cues(self):+ out = [("tick", tt, 0.6, {}) for tt in self.times]+ if self.strike_t is not None:+ out.append(("pencil", self.strike_t, 0.7, {"dur": 0.4}))+ return out++ def draw(self, c, res, t):+ a = self.fade(t)+ for i, ti in enumerate(self.times):+ u = ease_out_cubic(ramp(t, ti, 0.12))+ if u <= 0:+ continue+ jx, jy, js = self.jit[i]+ x = self.x + i * self.gap + jx+ c.drawLine(x, self.y + jy, x + js, self.y + jy + self.hh * u, paint(self.rgb, 0.88 * a, stroke=self.width))+ if self.strike_t is not None:+ u = ease_out_cubic(ramp(t, self.strike_t, 0.35))+ if u > 0:+ x0 = self.x - 50; x1 = self.x + (len(self.times) - 1) * self.gap + 50+ c.drawLine(x0, self.y + self.hh * 0.62, x0 + (x1 - x0) * u, self.y + self.hh * 0.38, paint((170, 24, 20), 0.95 * a, stroke=self.width + 2))+++class Stamp(Item):+ """Rubber stamp: slams down with overshoot, ink with worn edges, a small camera shake."""+ z = 60++ def __init__(self, text, x, y, size=150, rot=-8.0, t_in=0.0, t_out=None, z=None, rgb=(168, 26, 22), shake=True, sfx=True):+ super().__init__(t_in, t_out, z, sfx)+ self.text, self.x, self.y, self.size, self.rot, self.rgb, self.shake = text, x, y, size, rot, rgb, shake++ def bounds(self, res):+ r = len(self.text) * self.size * 1.2+ return skia.Rect.MakeLTRB(self.x - r, self.y - r, self.x + r, self.y + r)++ def cues(self):+ return [("stamp", self.t_in, 1.0, {})]++ def shakes(self):+ return [(self.t_in + 0.1, 10, 0.3)] if self.shake else []++ def draw(self, c, res, t):+ u = ramp(t, self.t_in, 0.14)+ if u <= 0:+ return+ a = self.fade(t) * min(1, u * 3)+ s = 1.7 - 0.7 * ease_out_cubic(u)+ tw = text_width(res, self.text, self.size, "cond", 0.05)+ pad = self.size * 0.42+ W, H = tw + 2 * pad, self.size * 1.55+ c.save(); c.translate(self.x, self.y); c.rotate(self.rot); c.scale(s, s)+ c.saveLayerAlpha(None, int(235 * a))+ r = skia.RRect.MakeRectXY(skia.Rect.MakeXYWH(-W / 2, -H / 2, W, H), 18, 18)+ c.drawRRect(r, paint(self.rgb, 1, stroke=self.size * 0.09))+ draw_text(c, res, self.text, 0, self.size * 0.36, self.size, "cond", self.rgb, 1, 0.05, "center")+ wp = skia.Paint(); wp.setBlendMode(skia.BlendMode.kDstOut)+ c.drawImageRect(res.wear(), skia.Rect.MakeXYWH(-W / 2, -H / 2, W, H), SAMPLING, wp)+ c.restore(); c.restore()+++class BigText(Item):+ """Large words in world space (years, titles, numbers). grunge=True distresses the ink; bar=rgb wipes+ a colour block in behind it (highlighter yellow or a red bar), bar_h its height as a fraction of the+ size (0.42 = a marker streak through the lower half; 0.92 = a full label block, needed for dark ink+ on a dark board); type_on=seconds types it letter by letter; hit=gain plays an impact on arrival."""+ z = 70++ def __init__(self, text, x, y, size, t_in, t_out=None, font="cond", rgb=WHITE, track=0.04, rules=False,+ type_on=0.0, z=None, shadow=True, grunge=True, bar=None, bar_h=0.42, hit=None, sfx=True):+ super().__init__(t_in, t_out, z, sfx)+ self.text, self.x, self.y, self.size, self.font = text, x, y, size, font+ self.rgb, self.track, self.rules, self.type_on, self.shadow = rgb, track, rules, type_on, shadow+ self.grunge, self.bar, self.bar_h, self.hit = grunge, bar, bar_h, hit++ def bounds(self, res):+ r = len(self.text) * self.size * 0.8 + self.size * 3+ return skia.Rect.MakeLTRB(self.x - r, self.y - self.size * 2, self.x + r, self.y + self.size)++ def cues(self):+ return [("impact", self.t_in, self.hit, {})] if self.hit else []++ def draw(self, c, res, t):+ a = ramp(t, self.t_in, 0.5) * self.fade(t)+ if a <= 0:+ return+ reveal = len(self.text) * ramp(t, self.t_in, self.type_on) + 0.999 if self.type_on > 0 else None+ drift = 1 - ease_out_cubic(ramp(t, self.t_in, 1.2))+ tr = self.track + 0.06 * drift+ tw0 = text_width(res, self.text, self.size, self.font, tr)+ if self.bar is not None:+ bu = ease_out_cubic(ramp(t, self.t_in - 0.1, 0.35))+ bh = self.size * self.bar_h+ c.drawRect(skia.Rect.MakeXYWH(self.x - tw0 / 2 - self.size * 0.15, self.y + self.size * 0.063 - bh, (tw0 + self.size * 0.3) * bu, bh),+ paint(self.bar, 0.92 * self.fade(t)))+ if self.grunge:+ c.saveLayerAlpha(None, 255)+ if self.shadow:+ c.save(); c.translate(6, 14)+ draw_text(c, res, self.text, self.x, self.y, self.size, self.font, (0, 0, 0), 0.55 * a, tr, "center", reveal)+ c.restore()+ tw = draw_text(c, res, self.text, self.x, self.y, self.size, self.font, self.rgb, a, tr, "center", reveal)+ if self.grunge:+ wp = skia.Paint(); wp.setBlendMode(skia.BlendMode.kDstOut)+ c.drawImageRect(res.wear(), skia.Rect.MakeXYWH(self.x - tw / 2 - 20, self.y - self.size, tw + 40, self.size * 1.15), SAMPLING, wp)+ c.restore()+ if self.rules:+ ru = ease_out_cubic(ramp(t, self.t_in + 0.2, 0.9))+ yy = self.y - self.size * 0.33+ L = self.size * 2.2 * ru+ gap = tw / 2 + self.size * 0.45+ p = paint(self.rgb, 0.65 * a, stroke=max(3, self.size * 0.018))+ c.drawLine(self.x - gap, yy, self.x - gap - L, yy, p)+ c.drawLine(self.x + gap, yy, self.x + gap + L, yy, p)+++class Counter(Item):+ """A number that rolls up to its value, distressed, with an optional caption under it."""+ z = 70++ def __init__(self, x, y, size, value, t_in, dur=1.3, prefix="", suffix="", caption=None, rgb=WHITE, t_out=None,+ font="cond", start=0, sfx=True):+ super().__init__(t_in, t_out, None, sfx)+ self.x, self.y, self.size, self.value, self.dur = x, y, size, value, dur+ self.prefix, self.suffix, self.caption, self.rgb, self.font, self.start = prefix, suffix, caption, rgb, font, start++ def bounds(self, res):+ r = self.size * 6+ return skia.Rect.MakeLTRB(self.x - r, self.y - r, self.x + r, self.y + r)++ def cues(self):+ return [("ticks", self.t_in, 0.6, {})]++ def draw(self, c, res, t):+ a = ramp(t, self.t_in, 0.3) * self.fade(t)+ if a <= 0:+ return+ u = ease_out_cubic(ramp(t, self.t_in, self.dur))+ v = int(round(self.start + (self.value - self.start) * u))+ txt = f"{self.prefix}{v:,}{self.suffix}"+ c.saveLayerAlpha(None, 255)+ tw = draw_text(c, res, txt, self.x, self.y, self.size, self.font, self.rgb, a, 0.03, "center")+ wp = skia.Paint(); wp.setBlendMode(skia.BlendMode.kDstOut)+ c.drawImageRect(res.wear(), skia.Rect.MakeXYWH(self.x - tw / 2 - 20, self.y - self.size, tw + 40, self.size * 1.15), SAMPLING, wp)+ c.restore()+ if self.caption:+ ca = ramp(t, self.t_in + self.dur * 0.6, 0.4) * self.fade(t)+ draw_text(c, res, self.caption, self.x, self.y + self.size * 0.42, self.size * 0.24, "cond", self.rgb, 0.85 * ca, 0.12, "center")+++class PaperDoc(Item):+ """A typeset paper document drawn in code (a recreation): header lines, soft grey body rows (never+ filler words), and an optional block of real, legible text you can mark with a PenMark."""+ z = 12++ def __init__(self, x, y, w, h, rot=0.0, t_in=0.0, t_out=None, header=(), rows=18, sentence=None,+ sentence_row=8, sentence_size=58, row_gap=None, seed=21, pin=True, z=None, exit_vec=None, row_start=0.3, sfx=True):+ super().__init__(t_in, t_out, z, sfx)+ self.x, self.y, self.w, self.h, self.rot = x, y, w, h, rot+ self.header, self.rows, self.sentence, self.srow, self.ssize = header, rows, sentence, sentence_row, sentence_size+ self.row_gap = row_gap or (h * (0.92 - row_start)) / max(1, rows)+ self.row_start, self.pin, self.exit_vec = row_start, pin, exit_vec+ rng = np.random.default_rng(seed)+ self.lens = [rng.uniform(0.55, 0.97) for _ in range(rows)]+ self.sent_lines = []++ def bounds(self, res):+ r = max(self.w, self.h) * 0.8 + 300+ return skia.Rect.MakeLTRB(self.x - r, self.y - r, self.x + r, self.y + r)++ def cues(self):+ return [("pop", self.t_in, 0.8, {})]++ def wrap(self, res):+ if self.sentence and not self.sent_lines:+ line = ""; maxw = self.w * 0.8+ for wd in self.sentence.split():+ trial = (line + " " + wd).strip()+ if text_width(res, trial, self.ssize, "serif") > maxw and line:+ self.sent_lines.append(line); line = wd+ else:+ line = trial+ self.sent_lines.append(line)+ return self.sent_lines++ def line_pos(self, res, i):+ """(world point at the left of sentence line i, its width) for placing pen marks."""+ lines = self.wrap(res)+ y = -self.h / 2 + self.h * self.row_start + (self.srow + i) * self.row_gap+ return rot_point(self.x, self.y, -self.w * 0.4, y, self.rot), text_width(res, lines[i], self.ssize, "serif")++ def phrase_spans(self, res, phrase):+ """[(world centre, width)] of `phrase` in the sentence block, one span per wrapped line it covers:+ place one highlight per span (a phrase often wraps). y is the text's x-height middle."""+ lines = self.wrap(res)+ full = " ".join(lines)+ k = full.find(phrase)+ if k < 0:+ raise ValueError(f"{phrase!r} is not in the document text {full!r}")+ spans, pos = [], 0+ for i, ln in enumerate(lines):+ a, b = max(k, pos), min(k + len(phrase), pos + len(ln))+ if a < b:+ x0 = -self.w * 0.4 + text_width(res, ln[:a - pos], self.ssize, "serif")+ pw = text_width(res, ln[a - pos:b - pos].strip(), self.ssize, "serif")+ y = -self.h / 2 + self.h * self.row_start + (self.srow + i) * self.row_gap+ spans.append((rot_point(self.x, self.y, x0 + pw / 2, y, self.rot), pw))+ pos += len(ln) + 1+ return spans++ def phrase_pos(self, res, phrase):+ """(world centre, width) of the first span of `phrase`: for a circle or underline."""+ return self.phrase_spans(res, phrase)[0]++ def draw(self, c, res, t):+ s, a, lift = drop_anim(t, self.t_in)+ a *= self.fade(t)+ if a <= 0:+ return+ ox = oy = 0.0+ if self.exit_vec and self.t_out is not None:+ u = ease_in_out(ramp(t, self.t_out, 0.6)); ox, oy = self.exit_vec[0] * u, self.exit_vec[1] * u+ W, H = self.w, self.h+ c.save(); c.translate(self.x + ox, self.y + oy); c.rotate(self.rot + 3 * lift); c.scale(s, s)+ off = 18 + 70 * lift+ c.drawRect(skia.Rect.MakeXYWH(-W / 2 + off * 0.4, -H / 2 + off, W, H), paint((0, 0, 0), 0.55 * a, blur=22 + 50 * lift))+ paper_fill(c, res, skia.Rect.MakeXYWH(-W / 2, -H / 2, W, H), a, 1.0)+ y = -H / 2 + H * 0.09+ for txt, size, font in self.header:+ draw_text(c, res, txt, 0, y + size, size, font, INK, a, 0.08 if font == "mono" else 0.04, "center")+ y += size * 1.45+ lines = self.wrap(res) if self.sentence else []+ for i in range(self.rows):+ yy = -H / 2 + H * self.row_start + i * self.row_gap+ if lines and self.srow <= i < self.srow + len(lines):+ draw_text(c, res, lines[i - self.srow], -W * 0.4, yy + self.ssize * 0.3, self.ssize, "serif", INK, a)+ continue+ c.drawLine(-W * 0.4, yy, -W * 0.4 + W * 0.8 * self.lens[i], yy, paint((150, 140, 124), 0.55 * a, stroke=self.row_gap * 0.22))+ if self.pin:+ draw_pin(c, 0, -H / 2 + H * 0.035, r=max(26, 0.02 * W), a=a)+ c.restore()+++class Card(Item):+ """A clean panel for explainers and product stories: rounded, flat colour, an optional accent bar,+ a title and a few short lines of real text. Rises into place with a soft shadow."""+ z = 12++ def __init__(self, x, y, w, h, t_in, title="", lines=(), rgb=(250, 248, 244), text_rgb=(34, 32, 30), accent=None,+ rot=0.0, t_out=None, radius=36, title_size=None, body_size=None, z=None, sfx=True):+ super().__init__(t_in, t_out, z, sfx)+ self.x, self.y, self.w, self.h, self.rot = x, y, w, h, rot+ self.title, self.lines, self.rgb, self.text_rgb, self.accent, self.radius = title, list(lines), rgb, text_rgb, accent, radius+ self.ts = title_size or h * 0.16+ self.bs = body_size or h * 0.085++ def bounds(self, res):+ r = max(self.w, self.h) * 0.8 + 300+ return skia.Rect.MakeLTRB(self.x - r, self.y - r, self.x + r, self.y + r)++ def cues(self):+ return [("pop", self.t_in, 0.6, {})]++ def draw(self, c, res, t):+ u = ease_out_back(ramp(t, self.t_in, 0.45), 1.2)+ a = ramp(t, self.t_in, 0.15) * self.fade(t)+ if a <= 0:+ return+ s = 0.92 + 0.08 * u+ W, H = self.w, self.h+ c.save(); c.translate(self.x, self.y + (1 - u) * 120); c.rotate(self.rot); c.scale(s, s)+ rr = skia.RRect.MakeRectXY(skia.Rect.MakeXYWH(-W / 2, -H / 2, W, H), self.radius, self.radius)+ c.save(); c.translate(0, 26); c.drawRRect(rr, paint((0, 0, 0), 0.3 * a, blur=40)); c.restore()+ c.drawRRect(rr, paint(self.rgb, a))+ pad = W * 0.08+ if self.accent:+ c.save(); c.clipRRect(rr, skia.ClipOp.kIntersect, True)+ c.drawRect(skia.Rect.MakeXYWH(-W / 2, -H / 2, W * 0.035, H), paint(self.accent, a))+ c.restore()+ y = -H / 2 + pad + self.ts * 0.85+ if self.title:+ draw_text(c, res, self.title, -W / 2 + pad, y, self.ts, "label", self.text_rgb, a, 0.0)+ y += self.ts * 0.55+ for i, ln in enumerate(self.lines):+ la = a * ramp(t, self.t_in + 0.25 + 0.12 * i, 0.3)+ y += self.bs * 1.45+ draw_text(c, res, ln, -W / 2 + pad, y, self.bs, "labelm", self.text_rgb, la * 0.85, 0.0)+ c.restore()+++class Ledger(Item):+ """Closed ledger or case file drawn in code: cloth cover, leather spine and corners, paper label.+ Slams onto the board with a camera shake."""+ z = 20++ def __init__(self, x, y, w, rot=0.0, t_in=0.0, t_out=None, z=None, label="LEDGER", cloth=(44, 58, 46), sfx=True):+ super().__init__(t_in, t_out, z, sfx)+ self.x, self.y, self.w, self.rot, self.label, self.cloth = x, y, w, rot, label, cloth++ def bounds(self, res):+ r = self.w * 1.4+ return skia.Rect.MakeLTRB(self.x - r, self.y - r, self.x + r, self.y + r)++ def cues(self):+ return [("impact", self.t_in + 0.3, 1.0, {})]++ def shakes(self):+ return [(self.t_in + 0.3, 18, 0.4)]++ def draw(self, c, res, t):+ u = ramp(t, self.t_in, 0.32)+ if u <= 0:+ return+ a = min(1, u * 4) * self.fade(t)+ s = 1 + 0.35 * (1 - ease_out_cubic(u))+ w = self.w; h = w * 1.32+ c.save(); c.translate(self.x, self.y); c.rotate(self.rot + 5 * (1 - u)); c.scale(s, s)+ off = 30 + 120 * (1 - u)+ c.drawRect(skia.Rect.MakeXYWH(-w / 2 + off * 0.3, -h / 2 + off, w, h), paint((0, 0, 0), 0.6 * a, blur=30 + 60 * (1 - u)))+ c.drawRect(skia.Rect.MakeXYWH(-w / 2 + 10, -h / 2 + 8, w - 4, h - 4), paint((214, 204, 184), a))+ c.drawRect(skia.Rect.MakeXYWH(-w / 2, -h / 2, w - 14, h - 12), paint(self.cloth, a))+ paper_fill(c, res, skia.Rect.MakeXYWH(-w / 2, -h / 2, w - 14, h - 12), 0.5 * a, 0.5, skia.BlendMode.kMultiply)+ c.drawRect(skia.Rect.MakeXYWH(-w / 2, -h / 2, w * 0.17, h - 12), paint((74, 40, 26), a))+ for k in (0.12, 0.26, 0.74, 0.88):+ c.drawRect(skia.Rect.MakeXYWH(-w / 2, -h / 2 + h * k, w * 0.17, h * 0.018), paint((150, 112, 60), 0.8 * a))+ cs = w * 0.2+ for sy in (-1, 1):+ p = skia.Path(); cx = w / 2 - 14; cy = sy * (h / 2) - (12 if sy > 0 else 0)+ p.moveTo(cx, cy); p.lineTo(cx - cs, cy); p.lineTo(cx, cy - sy * cs); p.close()+ c.drawPath(p, paint((74, 40, 26), a))+ lw, lh = w * 0.42, w * 0.2+ lx, ly = w * 0.06, -h * 0.22+ paper_fill(c, res, skia.Rect.MakeXYWH(lx - lw / 2, ly - lh / 2, lw, lh), a, 0.6)+ c.drawRect(skia.Rect.MakeXYWH(lx - lw / 2 + 10, ly - lh / 2 + 10, lw - 20, lh - 20), paint(INK, 0.7 * a, stroke=4))+ draw_text(c, res, self.label, lx, ly + lh * 0.14, lh * 0.36 * min(1, 6 / max(1, len(self.label))), "serif", INK, a, 0.2, "center")+ c.restore()+++class OpenLedger(Item):+ """Open ledger, two-page spread: ruled columns, grey ink rows and one legible handwritten entry+ (a recreation: credit it as one). entry_mark() gives where to circle the last words."""+ z = 22++ def __init__(self, x, y, w, rot=0.0, t_in=0.0, entry="", entry_row=9, t_out=None, seed=31, sfx=True):+ super().__init__(t_in, t_out, None, sfx)+ self.x, self.y, self.w, self.rot, self.entry, self.erow = x, y, w, rot, entry, entry_row+ self.h = w * 0.66; self.rows = 16+ rng = np.random.default_rng(seed)+ self.scrib = [(rng.uniform(0.05, 0.12), rng.uniform(0.25, 0.62), rng.uniform(0.72, 0.9)) for _ in range(self.rows)]++ def bounds(self, res):+ r = self.w * 0.8+ return skia.Rect.MakeLTRB(self.x - r, self.y - r, self.x + r, self.y + r)++ def cues(self):+ return [("pop", self.t_in, 0.9, {})]++ def row_y(self, i):+ return -self.h / 2 + self.h * 0.16 + i * (self.h * 0.78 / self.rows)++ def entry_mark(self, res, words):+ """(world centre of the trailing `words` of the entry, their width) for a pen circle."""+ size = self.h * 0.072+ x0 = self.w / 2 * 0.06; y = self.row_y(self.erow) + size * 0.1+ full = text_width(res, self.entry, size, "hand")+ tail = text_width(res, words, size, "hand")+ return rot_point(self.x, self.y, x0 + full - tail / 2, y - size * 0.25, self.rot), tail++ def draw(self, c, res, t):+ u = ramp(t, self.t_in, 0.45)+ if u <= 0:+ return+ a = min(1, u * 3) * self.fade(t)+ s = 1 + 0.12 * (1 - ease_out_cubic(u))+ W, H = self.w, self.h+ c.save(); c.translate(self.x, self.y); c.rotate(self.rot); c.scale(s, s)+ c.drawRect(skia.Rect.MakeXYWH(-W / 2 + 20, -H / 2 + 40, W, H), paint((0, 0, 0), 0.6 * a, blur=40))+ c.drawRect(skia.Rect.MakeXYWH(-W / 2 - 30, -H / 2 - 20, W + 60, H + 40), paint((44, 58, 46), a))+ paper_fill(c, res, skia.Rect.MakeXYWH(-W / 2, -H / 2, W, H), a, 0.8)+ c.drawRect(skia.Rect.MakeXYWH(-W / 2, -H / 2, W, H), paint((214, 200, 170), 0.18 * a))+ g = skia.GradientShader.MakeLinear([skia.Point(-W * 0.06, 0), skia.Point(W * 0.06, 0)],+ [skia.Color(0, 0, 0, 0), skia.Color(40, 30, 20, int(90 * a)), skia.Color(0, 0, 0, 0)])+ gp = skia.Paint(); gp.setShader(g); c.drawRect(skia.Rect.MakeXYWH(-W * 0.06, -H / 2, W * 0.12, H), gp)+ for side in (-1, 1):+ px0 = -W / 2 if side < 0 else 0+ pw = W / 2+ for i in range(self.rows + 1):+ yy = self.row_y(i) + H * 0.02+ c.drawLine(px0 + pw * 0.05, yy, px0 + pw * 0.95, yy, paint((120, 140, 160), 0.35 * a, stroke=3))+ for fx in (0.17, 0.66, 0.82):+ c.drawLine(px0 + pw * fx, -H / 2 + H * 0.1, px0 + pw * fx, H / 2 - H * 0.04, paint((170, 60, 50), 0.45 * a, stroke=3))+ for i in range(self.rows):+ if side > 0 and i == self.erow:+ continue+ yy = self.row_y(i); d0, d1, d2 = self.scrib[i]+ c.drawLine(px0 + pw * d0, yy, px0 + pw * (d0 + 0.07), yy, paint((70, 60, 50), 0.35 * a, stroke=7))+ c.drawLine(px0 + pw * 0.2, yy, px0 + pw * d1, yy, paint((70, 60, 50), 0.32 * a, stroke=7))+ c.drawLine(px0 + pw * 0.69, yy, px0 + pw * d2, yy, paint((70, 60, 50), 0.32 * a, stroke=7))+ size = H * 0.072+ draw_text(c, res, self.entry, W / 2 * 0.06, self.row_y(self.erow) + size * 0.1, size, "hand", (22, 20, 40), a)+ c.restore()+++class FilmFrame(Item):+ """Film-strip bands with sprocket holes clamped around a print (for anything that became a movie)."""+ z = 15++ def __init__(self, pr, t_in, t_out=None, sfx=True):+ super().__init__(t_in, t_out, None, sfx)+ self.pr = pr++ def bounds(self, res):+ W, H = self.pr.outer(res); r = max(W, H) * 0.9+ return skia.Rect.MakeLTRB(self.pr.x - r, self.pr.y - r, self.pr.x + r, self.pr.y + r)++ def cues(self):+ return [("click", self.t_in, 0.6, {})]++ def draw(self, c, res, t):+ u = ease_out_cubic(ramp(t, self.t_in, 0.45)); a = u * self.fade(t)+ if a <= 0:+ return+ W, H = self.pr.outer(res); band = H * 0.16+ c.save(); c.translate(self.pr.x, self.pr.y); c.rotate(self.pr.rot)+ for sgn in (-1, 1):+ y = sgn * (H / 2 + band / 2 - band * 0.25) + sgn * (1 - u) * band * 1.5+ r = skia.Rect.MakeXYWH(-W / 2 - band * 0.3, y - band / 2, W + band * 0.6, band)+ c.drawRect(r.makeOffset(10, 18), paint((0, 0, 0), 0.5 * a, blur=14))+ c.drawRect(r, paint((18, 15, 13), 0.96 * a))+ n = int(W / (band * 0.62))+ for i in range(n):+ hx = -W / 2 + (i + 0.5) * W / n+ c.drawRoundRect(skia.Rect.MakeXYWH(hx - band * 0.14, y - band * 0.18, band * 0.28, band * 0.36), band * 0.06, band * 0.06,+ paint((196, 186, 168), 0.9 * a))+ c.restore()+++class Holes(Item):+ """Holes punched into a print at given times (dark core, torn light rim, short cracks).+ pts are fractional (fx, fy) positions inside the print's image."""+ z = 16++ def __init__(self, pr, pts, times, seed=5, sound="snip", sfx=True):+ super().__init__(min(times), None, None, sfx)+ self.pr, self.pts, self.times, self.sound = pr, pts, times, sound+ rng = np.random.default_rng(seed)+ self.cracks = [[(rng.uniform(0, 6.28), rng.uniform(0.6, 1.0)) for _ in range(5)] for _ in pts]++ def bounds(self, res):+ r = max(self.pr.size(res))+ return skia.Rect.MakeLTRB(self.pr.x - r, self.pr.y - r, self.pr.x + r, self.pr.y + r)++ def cues(self):+ return [(self.sound, tt, 0.7, {}) for tt in self.times]++ def draw(self, c, res, t):+ a = self.fade(t)+ w, h = self.pr.size(res)+ c.save(); c.translate(self.pr.x, self.pr.y); c.rotate(self.pr.rot)+ r0 = w * 0.012+ for (fx, fy), ti, cr in zip(self.pts, self.times, self.cracks):+ if ramp(t, ti, 0.06) <= 0:+ continue+ x, y = (fx - 0.5) * w, (fy - 0.5) * h+ for ang, ln in cr:+ c.drawLine(x, y, x + math.cos(ang) * r0 * 3.2 * ln, y + math.sin(ang) * r0 * 3.2 * ln, paint((230, 222, 205), 0.55 * a, stroke=r0 * 0.18))+ c.drawCircle(x, y, r0 * 1.35, paint((235, 228, 210), 0.7 * a))+ c.drawCircle(x, y, r0, paint((8, 6, 5), a))+ c.restore()+++class DotField(Item):+ """Dots popping up over an area between t0 and t1 (bars, branches, outbreaks, stores): give world points."""+ z = 8++ def __init__(self, points, t0, t1, seed=11, t_out=None, rgb=(176, 28, 22), r=30, sfx=True):+ super().__init__(t0, t_out, None, sfx)+ rng = np.random.default_rng(seed)+ self.pts, self.rgb, self.r = list(points), rgb, r+ self.times = sorted(rng.uniform(t0, t1, len(self.pts)))+ x = [p[0] for p in self.pts]; y = [p[1] for p in self.pts]+ self.box = skia.Rect.MakeLTRB(min(x) - 200, min(y) - 200, max(x) + 200, max(y) + 200)++ def bounds(self, res):+ return self.box++ def cues(self):+ return [("shimmer", self.t_in, 0.5, {})]++ def draw(self, c, res, t):+ a = self.fade(t)+ for (x, y), ti in zip(self.pts, self.times):+ u = ramp(t, ti, 0.25)+ if u <= 0:+ continue+ r = self.r * ease_out_back(u)+ c.drawCircle(x, y, r * 2.2, paint(self.rgb, 0.18 * a, blur=20))+ c.drawCircle(x, y, r, paint(self.rgb, 0.95 * a))+++# ---------------------------------------------------------------- maps+MAP_LOOKS = {+ # teal water, pale relief land, light borders, dark neighbours (modern explainer map)+ "explainer": dict(sheet=(236, 233, 226), water=TEAL, land=(188, 184, 176), border=(178, 170, 158), relief=0.24,+ neighbor=(222, 218, 210), neighbor_line=(170, 162, 150), dark=(84, 80, 77), dark_line=(60, 58, 56), frame=(60, 58, 56)),+ # parchment sheet, tan land, brown borders (old printed map)+ "period": dict(sheet=(232, 224, 204), water=(196, 206, 196), land=(222, 206, 172), border=(128, 96, 64), relief=0.18,+ neighbor=(214, 204, 182), neighbor_line=(150, 124, 92), dark=(176, 160, 132), dark_line=(120, 96, 70), frame=(110, 86, 60)),+}+++def _rings_path(rings, w):+ p = skia.Path()+ for r_ in rings:+ p.moveTo(*w(r_[0]))+ for pt in r_[1:]:+ p.lineTo(*w(pt))+ p.close()+ return p+++class GeoMap(Cached, Item):+ """A printed map sheet from make_map.py output: regions (states, countries) and neighbours.+ K = world px per projection unit (about one earth radius); origin = where unit (0, 0) lands."""+ z = 0++ def __init__(self, data, K, origin=(0, 0), look="explainer", t_in=-1, margin=0.03, relief_tile=9000):+ super().__init__(t_in)+ self.K, self.ox, self.oy, self.relief_tile = K, *origin, relief_tile+ self.look = MAP_LOOKS[look] if isinstance(look, str) else look+ self.data = data+ regions = data["regions"]+ xs = [p[0] for rings in regions.values() for r in rings for p in r]+ ys = [p[1] for rings in regions.values() for r in rings for p in r]+ b = data.get("frame") or [min(xs) - margin, min(ys) - margin * 1.4, max(xs) + margin, max(ys) + margin]+ self.frame = b+ self.region_paths = {n: _rings_path(r, self.w) for n, r in regions.items()}+ self.path = skia.Path()+ for p in self.region_paths.values():+ self.path.addPath(p)+ self.nb_paths = {n: _rings_path(r, self.w) for n, r in data.get("neighbors", {}).items()}+ self.dark = set(data.get("dark", []))++ def w(self, p):+ return self.ox + p[0] * self.K, self.oy + p[1] * self.K++ def place(self, name):+ """World position of a named place from map.json."""+ if name not in self.data.get("places", {}):+ raise KeyError(f"place {name!r} not in the map; add it under places in map.json and rerun make_map.py")+ return self.w(self.data["places"][name])++ def sheet(self):+ x0, y0 = self.w(self.frame[:2]); x1, y1 = self.w(self.frame[2:])+ return skia.Rect.MakeLTRB(x0, y0, x1, y1)++ def bounds(self, res):+ return self.sheet().makeOutset(500, 500)++ def draw(self, c, res, t):+ self.cached_draw(c, res, self.sheet().makeOutset(400, 400), self._draw)++ def _draw(self, c, res):+ L = self.look+ r = self.sheet()+ c.drawRect(r.makeOffset(30, 50), paint((0, 0, 0), 0.6, blur=60))+ c.drawRect(r, paint(L["sheet"]))+ inner = r.makeInset(70, 70)+ c.save(); c.clipRect(inner)+ c.drawRect(inner, paint(L["water"]))+ paper_fill(c, res, inner, 0.22, 2.0, skia.BlendMode.kMultiply)+ for name, path in self.nb_paths.items():+ dark = name in self.dark+ c.drawPath(path, paint(L["dark"] if dark else L["neighbor"], 0.96))+ c.drawPath(path, paint(L["dark_line"] if dark else L["neighbor_line"], 0.7, stroke=4))+ c.drawPath(self.path, paint(L["land"]))+ c.save(); c.clipPath(self.path, skia.ClipOp.kIntersect, True)+ rp = skia.Paint(AntiAlias=True); rp.setBlendMode(skia.BlendMode.kOverlay); rp.setAlphaf(L["relief"])+ # tiled at a fixed world size, so the terrain grain looks the same whatever the map scale+ tile_image(c, res.image("relief.png", 1024), inner, self.relief_tile, rp)+ c.restore()+ c.drawPath(self.path, paint(L["border"], 0.95, stroke=5))+ c.restore()+ c.drawRect(inner, paint(L["frame"], 0.5, stroke=4))+++class RegionFill(Item):+ """Fill one or more map regions; can change colour later (active RUST -> visited MUSTARD)."""+ z = 1++ def __init__(self, geomap, names, rgb, t_in, t_out=None, alpha=0.95, to_rgb=None, t_change=None, sfx=True):+ super().__init__(t_in, t_out, None, sfx)+ self.m, self.names, self.rgb, self.alpha, self.to_rgb, self.t_change = geomap, names, rgb, alpha, to_rgb, t_change+ missing = [n for n in names if n not in geomap.region_paths]+ if missing:+ raise KeyError(f"regions {missing} not in the map (have e.g. {sorted(geomap.region_paths)[:8]})")+ b = None+ for n in names:+ r = geomap.region_paths[n].getBounds()+ b = r if b is None else skia.Rect.MakeLTRB(min(b.left(), r.left()), min(b.top(), r.top()), max(b.right(), r.right()), max(b.bottom(), r.bottom()))+ self.box = b.makeOutset(300, 300)++ def bounds(self, res):+ return self.box++ def draw(self, c, res, t):+ a = ease_in_out(ramp(t, self.t_in, 0.6)) * self.fade(t)+ if a <= 0:+ return+ rgb = self.rgb+ if self.to_rgb and self.t_change is not None:+ u = ease_in_out(ramp(t, self.t_change, 0.7))+ rgb = tuple(self.rgb[i] + (self.to_rgb[i] - self.rgb[i]) * u for i in range(3))+ for n in self.names:+ p = self.m.region_paths[n]+ c.drawPath(p, paint(rgb, self.alpha * a))+ c.drawPath(p, paint((250, 246, 238), 0.55 * a, stroke=6))+++class Route(Item):+ """White travel line arcing between two points, drawn on with a small leading dot."""+ z = 28++ def __init__(self, a, b, t_in, dur=1.2, bend=0.16, width=10, t_out=None, rgb=(252, 250, 245), sfx=True):+ super().__init__(t_in, t_out, None, sfx)+ (x0, y0), (x1, y1) = a, b+ d = math.hypot(x1 - x0, y1 - y0)+ nx, ny = -(y1 - y0) / max(d, 1), (x1 - x0) / max(d, 1)+ self.p = skia.Path(); self.p.moveTo(x0, y0)+ self.p.quadTo((x0 + x1) / 2 + nx * d * bend, (y0 + y1) / 2 + ny * d * bend, x1, y1)+ self.dur, self.wd, self.rgb = dur, width, rgb+ self.box = self.p.getBounds().makeOutset(300, 300)++ def bounds(self, res):+ return self.box++ def cues(self):+ return [("whoosh", self.t_in, 0.4, {})]++ def draw(self, c, res, t):+ u = ease_in_out(ramp(t, self.t_in, self.dur)); a = self.fade(t)+ if u <= 0 or a <= 0:+ return+ seg = partial_path(self.p, u)+ c.save(); c.translate(6, 12); c.drawPath(seg, paint((0, 0, 0), 0.35 * a, stroke=self.wd, blur=5)); c.restore()+ c.drawPath(seg, paint(self.rgb, 0.95 * a, stroke=self.wd))+ if u < 1:+ pm = skia.PathMeasure(self.p, False); pos = pm.getPosTan(pm.getLength() * u)+ if pos:+ c.drawCircle(pos[0].x(), pos[0].y(), self.wd * 2.2, paint(self.rgb, a))+++class XMarker(Item):+ """Explainer map marker: white ring with a red centre, a thin leader line, a bold label that types on."""+ z = 32++ def __init__(self, x, y, label=None, t_in=0.0, t_out=None, side="right", size=1.0, label_size=90,+ label_rgb=(252, 250, 245), shadow=True, z=None, sfx=True):+ super().__init__(t_in, t_out, z, sfx)+ self.x, self.y, self.label, self.side, self.k, self.ls = x, y, label, side, size, label_size+ self.lrgb, self.shadow = label_rgb, shadow++ def bounds(self, res):+ L = len(self.label or "") * self.ls * self.k * 0.8 + 500 * self.k+ return skia.Rect.MakeLTRB(self.x - L, self.y - 400 * self.k, self.x + L, self.y + 400 * self.k)++ def cues(self):+ return [("pop", self.t_in, 0.6, {})]++ def draw(self, c, res, t):+ u = ramp(t, self.t_in, 0.35); a = u * self.fade(t)+ if a <= 0:+ return+ k = self.k; e = ease_out_back(u)+ c.drawCircle(self.x + 4 * k, self.y + 8 * k, 30 * k * e, paint((0, 0, 0), 0.35 * a, blur=8 * k))+ c.drawCircle(self.x, self.y, 26 * k * e, paint((252, 250, 245), a, stroke=9 * k))+ c.drawCircle(self.x, self.y, 13 * k * e, paint((200, 28, 24), a))+ if not self.label:+ return+ s = 1 if self.side == "right" else -1+ lu = ease_out_cubic(ramp(t, self.t_in + 0.15, 0.35))+ p = skia.Path(); x0, y0 = self.x + s * 34 * k, self.y+ p.moveTo(x0, y0); p.quadTo(x0 + s * 70 * k, y0 - 4 * k, x0 + s * 150 * k, y0 - 46 * k)+ c.drawPath(partial_path(p, lu), paint(self.lrgb, 0.9 * a, stroke=5 * k))+ n = len(self.label) * ramp(t, self.t_in + 0.3, 0.05 * len(self.label) + 0.1)+ tx = x0 + s * 165 * k; ty = y0 - 46 * k + self.ls * k * 0.36+ if self.shadow:+ c.save(); c.translate(4 * k, 7 * k)+ draw_text(c, res, self.label, tx, ty, self.ls * k, "label", (0, 0, 0), 0.5 * a, 0.04, "left" if s > 0 else "right", reveal=n + 0.999)+ c.restore()+ draw_text(c, res, self.label, tx, ty, self.ls * k, "label", self.lrgb, a, 0.04, "left" if s > 0 else "right", reveal=n + 0.999)+++# ---------------------------------------------------------------- film+class Film:+ """Everything that happens: items, camera keys, spotlight keys, shakes, sound cues and the look."""++ def __init__(self, duration, fps=30, look="wall"):+ self.duration, self.fps = duration, fps+ self.look = dict(LOOKS[look]) if isinstance(look, str) else dict(look)+ self.board = Board(self.look["board"])+ self.items: list[Item] = [self.board]+ self.cam_keys, self.focus_keys, self.shakes, self.sfx = [], [], [], []+ self.room_tone = [] # [[start, end]] spans of quiet room tone under everything (optional)+ self.fade_in, self.fade_out = 0.9, 2.2+ self.auto_cues, self.auto_whoosh = True, True+ self._cam = self._foc = None++ def add(self, item):+ self.items.append(item)+ for sh in item.shakes():+ self.shake(*sh)+ return item++ def cam(self, t, x, y, zoom, rot=0.0):+ """Camera key: look at world (x, y) at time t. zoom 1 = 4K pixels 1:1; 0.15 shows a whole wall."""+ self.cam_keys.append((t, x, y, zoom, rot)); self._cam = None++ def focus(self, t, x, y, radius, strength=0.55):+ """Spotlight key: everything outside `radius` of (x, y) dims by `strength` (the hero rule)."""+ self.focus_keys.append((t, x, y, radius, strength)); self._foc = None++ def shot(self, t, x, y, zoom, rot=0.0, radius=None, strength=0.55):+ """Camera key and spotlight key on the same point (radius defaults to about 60% of the frame):+ keeps the light on what the camera looks at. Set them apart only on purpose."""+ self.cam(t, x, y, zoom, rot)+ self.focus(t, x, y, radius or 1600 / zoom, strength)++ def shake(self, t, amp=14.0, dur=0.35):+ self.shakes.append((t, amp, dur))++ def cue(self, kind, t, gain=1.0, **kw):+ """A sound effect at time t (see build_sfx.py for the kinds)."""+ self.sfx.append({"type": kind, "t": round(t, 3), "gain": gain, **kw})++ def _build(self):+ if not self.cam_keys:+ raise SystemExit("the film has no camera keys: add film.cam(t, x, y, zoom) calls")+ k = sorted(self.cam_keys)+ self._cam = [Spline([(a[0], a[i]) for a in k]) for i in (1, 2)] + \+ [Spline([(a[0], math.log(a[3])) for a in k]), Spline([(a[0], a[4]) for a in k])]+ f = sorted(self.focus_keys)+ self._foc = [Spline([(a[0], a[i]) for a in f]) for i in (1, 2, 3, 4)] if f else None++ def camera(self, t):+ if self._cam is None:+ self._build()+ x, y, lz, r = (s(t) for s in self._cam)+ z = math.exp(lz)+ # handheld: slow incommensurate wobble in 4K screen px, converted to world units+ hx = 7 * math.sin(t * 0.83 + 1.3) + 4 * math.sin(t * 1.71 + 0.2) + 2.5 * math.sin(t * 3.3)+ hy = 6 * math.sin(t * 0.67 + 2.1) + 3.5 * math.sin(t * 1.93 + 1.1) + 2 * math.sin(t * 2.9 + 0.5)+ hr = 0.12 * math.sin(t * 0.51 + 0.4) + 0.05 * math.sin(t * 1.37)+ for (ts, amp, dur) in self.shakes:+ if ts <= t < ts + dur:+ u = (t - ts) / dur; e = amp * (1 - u) ** 2+ hx += e * math.sin(u * 60); hy += e * math.cos(u * 47)+ return x + hx / z, y + hy / z, z, r + hr++ def focus_at(self, t):+ if self._cam is None:+ self._build()+ return tuple(s(t) for s in self._foc) if self._foc else None++ def screen_speed(self, t):+ """Approximate camera speed in 4K screen px per frame (pan + zoom + roll)."""+ dt = 1 / self.fps+ a = self.camera(t); b = self.camera(t + dt)+ return (math.hypot(b[0] - a[0], b[1] - a[1]) * a[2] + abs(math.log(b[2] / a[2])) * 1920+ + abs(b[3] - a[3]) * math.pi / 180 * 1920)++ def all_cues(self):+ """Explicit cues, plus each item's own cues and a whoosh on every fast camera move (unless the+ scene placed a cue of the same kind within 0.15 s, or the item has sfx=False)."""+ cues = list(self.sfx)+ def near(kind, t):+ return any(c["type"] == kind and abs(c["t"] - t) < 0.15 for c in cues)+ if self.auto_cues:+ for it in self.items:+ if not it.sfx:+ continue+ for kind, t, gain, kw in it.cues():+ if 0 <= t <= self.duration and not near(kind, t):+ cues.append({"type": kind, "t": round(t, 3), "gain": gain, **kw})+ if self.auto_whoosh and self.cam_keys:+ n = int(self.duration * self.fps); last = -9.0; i = 0+ while i < n:+ t = i / self.fps+ if self.screen_speed(t) > 90 and t - last > 1.4:+ j = i+ peak = 0.0+ while j < n and self.screen_speed(j / self.fps) > 60:+ peak = max(peak, self.screen_speed(j / self.fps)); j += 1+ if not near("whoosh", t):+ cues.append({"type": "whoosh", "t": round(max(0, t - 0.1), 3), "gain": round(min(0.8, 0.3 + peak / 600), 2)})+ last = t; i = j+ i += 1+ return sorted(cues, key=lambda c: c["t"])+++class Renderer:+ def __init__(self, film: Film, width=1920, height=1080, doc: Doc | None = None):+ self.film, self.W, self.H = film, width, height+ self.s = width / 3840.0+ self.res = Res(self.s, doc.prep if doc else None, (doc.dir / "fonts") if doc else None)+ self.surface = skia.Surface.MakeRaster(skia.ImageInfo.Make(width, height, skia.ColorType.kRGBA_8888_ColorType, skia.AlphaType.kPremul_AlphaType))+ L = film.look+ yy, xx = np.mgrid[0:height, 0:width].astype(np.float32)+ d = np.sqrt(((xx - width / 2) / (width / 2)) ** 2 + ((yy - height / 2) / (height / 2)) ** 2) / math.sqrt(2)+ self.vignette = (1 - L["vignette"] * np.clip(d - 0.28, 0, 1) ** 1.5 * 1.9).clip(0.22, 1)[..., None].astype(np.float32)+ self.items = sorted(film.items, key=lambda i: i.z)++ def draw_world(self, t):+ f = self.film+ cx, cy, z, rot = f.camera(t)+ k = z * self.s+ self.res.screen_scale = k+ hw, hh = self.W / 2 / k * 1.25, self.H / 2 / k * 1.25+ self.res.view = view = skia.Rect.MakeLTRB(cx - hw, cy - hh, cx + hw, cy + hh)+ with self.surface as c:+ c.clear(color(f.look["bg"]))+ c.save()+ c.translate(self.W / 2, self.H / 2); c.scale(k, k); c.rotate(rot); c.translate(-cx, -cy)+ for it in self.items:+ if it.visible(t):+ b = it.bounds(self.res)+ if b is None or skia.Rect.Intersects(b, view):+ it.draw(c, self.res, t)+ foc = f.focus_at(t)+ if foc:+ fx, fy, fr, fs = foc+ dr, dg, db = f.look.get("dim", (6, 4, 3))+ g = skia.GradientShader.MakeRadial(skia.Point(fx, fy), max(10, fr * 2.4),+ [skia.Color(0, 0, 0, 0), skia.Color(0, 0, 0, 0), skia.Color(dr, dg, db, int(255 * clamp(fs))),+ skia.Color(dr, dg, db, int(255 * min(0.92, fs + 0.25)))], [0.0, 0.3, 0.68, 1.0])+ p = skia.Paint(); p.setShader(g)+ c.drawRect(skia.Rect.MakeXYWH(cx - 60000, cy - 60000, 120000, 120000), p)+ c.restore()+ return self.surface.makeImageSnapshot().toarray(colorType=skia.ColorType.kRGBA_8888_ColorType)[..., :3]++ def frame(self, n):+ f = self.film; t = n / f.fps+ sp = f.screen_speed(t) * self.s+ k = int(clamp(math.ceil(sp / (6 * max(self.s, 0.5))), 1, 8)) # motion-blur sub-frames+ if k == 1:+ img = self.draw_world(t).astype(np.float32)+ else:+ acc = np.zeros((self.H, self.W, 3), np.float32)+ for i in range(k):+ acc += self.draw_world(t + (i / k - 0.5) * 0.5 / f.fps)+ img = acc / k+ return self.post(img, n)++ def post(self, img, n):+ """Film finish: glow, S-curve, grade, vignette, grain, fades."""+ L = self.film.look+ if not hasattr(self, "_grain"):+ # half-resolution grain that changes every 2nd frame: reads as film grain and survives+ # re-encoding (full-resolution per-frame noise made a 38 s clip 625 MB)+ rng = np.random.default_rng(99)+ self._grain = [Image.fromarray(np.clip(128 + rng.standard_normal((self.H // 2, self.W // 2)) * 42, 0, 255).astype(np.uint8))+ for _ in range(10)]+ self._tint = (self.vignette * np.array(L["grade"], np.float32)).astype(np.float32)+ u8 = img.astype(np.uint8) if img.dtype != np.uint8 else img+ f = u8.astype(np.float32); f *= 1 / 255.0+ if L["glow"] > 0:+ small = Image.fromarray(u8).reduce(8)+ hi = np.asarray(small, np.float32) * (1.6 / 255.0) - 0.62 * 1.6+ np.clip(hi, 0, 1, out=hi)+ hi = Image.fromarray((hi * 255).astype(np.uint8)).filter(ImageFilter.GaussianBlur(6)).resize((self.W, self.H), Image.BILINEAR)+ f += np.asarray(hi, np.float32) * (L["glow"] / 255.0)+ np.clip(f, 0, 1, out=f)+ cv = L["curve"]+ f *= (1 - cv) + cv * f * (3 - 2 * f)+ f *= self._tint+ tt = n / self.film.fps+ if self.film.fade_in > 0 and tt < self.film.fade_in:+ f *= ease_in_out(tt / self.film.fade_in)+ fo = self.film.fade_out+ if fo > 0 and tt > self.film.duration - fo:+ f *= 1 - ease_in_out((tt - (self.film.duration - fo)) / fo)+ if L["grain"] > 0:+ g = np.asarray(self._grain[((n // 2) * 7) % len(self._grain)].resize((self.W, self.H), Image.BILINEAR), np.float32) - 128.0+ f += g[..., None] * (L["grain"] / 42.0)+ np.clip(f, 0, 1, out=f)+ f *= 255+ return f.astype(np.uint8)diff --git a/skills/cinematic-film/scripts/fetch_commons.py b/skills/cinematic-film/scripts/fetch_commons.pynew file mode 100644index 0000000..8082cc6--- /dev/null+++ b/skills/cinematic-film/scripts/fetch_commons.py@@ -0,0 +1,173 @@+#!/usr/bin/env python3+"""Find and download archival images from Wikimedia Commons with their licence, and keep the credits.++ python3 fetch_commons.py search "wright brothers first flight 1903" --limit 12+ python3 fetch_commons.py category "Category:Wright Flyer" --limit 40+ python3 fetch_commons.py get --project my-film # download every photos.json entry that has no file yet+ python3 fetch_commons.py credits --project my-film # write credits.md from photos.json++photos.json entries name their source one of two ways:+ {"id": "P01", "kind": "photo", "commons": "File:Wright First Flight 1903Dec17.jpg"}+ {"id": "P07", "kind": "doc", "url": "https://.../full.jpg", "credit": "...", "license": "Public domain", "source": "..."}++For "commons" entries, `get` fills file, source, credit, license and license_ok from the file page's+metadata. It refuses a licence that is not public domain, CC0, CC BY or CC BY-SA unless you pass+--allow-nonfree (and then you own the rights question). "url" entries download as given: fill in+credit and licence yourself from the archive's record page (Library of Congress, National Archives).++Search tips: Commons search matches file names and descriptions, so search the archive's words+("first flight", "Kitty Hawk 1903"), then open the category of a good hit to see its siblings.+Large originals are fetched as 3200 px renders, which is more than a print on screen ever needs.+"""+import argparse+import html+import json+import pathlib+import re+import sys+import time+import urllib.parse+import urllib.request++API = "https://commons.wikimedia.org/w/api.php"+UA = "cinematic-film/1.0 (+https://github.com/Moh4696/open-3d-skills)"+FREE = re.compile(r"public domain|^pd\b|^pd-|cc0|cc[- ]by(?!.*\bnc\b)(?!.*\bnd\b)", re.I)+++def api(**params):+ params.update(format="json", formatversion="2")+ req = urllib.request.Request(API + "?" + urllib.parse.urlencode(params), headers={"User-Agent": UA})+ for attempt in range(4):+ try:+ with urllib.request.urlopen(req, timeout=40) as r:+ return json.loads(r.read())+ except urllib.error.HTTPError as e:+ if e.code in (429, 503) and attempt < 3:+ time.sleep(3 * (attempt + 1)); continue+ raise+++def text(v):+ return html.unescape(re.sub(r"<[^>]+>", "", v or "")).strip()+++def info(page):+ ii = (page.get("imageinfo") or [{}])[0]+ md = ii.get("extmetadata", {})+ g = lambda k: text(md.get(k, {}).get("value", ""))+ return {"title": page.get("title"), "w": ii.get("width"), "h": ii.get("height"), "mime": ii.get("mime"),+ "url": ii.get("url"), "thumb": ii.get("thumburl"), "source": ii.get("descriptionurl"),+ "license": g("LicenseShortName") or g("UsageTerms"), "license_url": g("LicenseUrl"),+ "credit": g("Artist") or g("Credit"), "date": g("DateTimeOriginal") or g("DateTime"),+ "desc": g("ImageDescription")[:160]}+++IIPROP = dict(prop="imageinfo", iiprop="url|size|mime|extmetadata", iiurlwidth=3200)+++def show(pages):+ for p in pages:+ d = info(p)+ ok = "free " if FREE.search(d["license"] or "") else "CHECK"+ print(f"[{ok}] {d['title']}\n {d['w']}x{d['h']} {d['license'] or 'no licence field'} {d['credit'][:60]} {d['date'][:20]}\n {d['desc'][:120]}")+++def cmd_search(a):+ r = api(action="query", generator="search", gsrsearch=a.query, gsrnamespace=6, gsrlimit=a.limit, **IIPROP)+ show(sorted((r.get("query") or {}).get("pages", []), key=lambda p: p.get("index", 0)))+++def cmd_category(a):+ cat = a.category if a.category.startswith("Category:") else "Category:" + a.category+ r = api(action="query", generator="categorymembers", gcmtitle=cat, gcmtype="file", gcmlimit=a.limit, **IIPROP)+ show((r.get("query") or {}).get("pages", []))+++def download(url, dst):+ req = urllib.request.Request(url, headers={"User-Agent": UA})+ for attempt in range(4):+ try:+ with urllib.request.urlopen(req, timeout=120) as r:+ dst.write_bytes(r.read()); return+ except urllib.error.HTTPError as e:+ if e.code in (429, 503) and attempt < 3:+ time.sleep(5 * (attempt + 1)); continue+ raise+++def cmd_get(a):+ proj = pathlib.Path(a.project)+ spec = json.loads((proj / "photos.json").read_text())+ dst_dir = proj / "assets" / "photos"; dst_dir.mkdir(parents=True, exist_ok=True)+ refused = 0+ for p in spec["photos"]:+ have = bool(p.get("file")) and (dst_dir / p["file"]).exists()+ if have and not a.force and (p.get("license") or not p.get("commons")):+ continue # downloaded and credited (or a local/url file the user credits by hand)+ if p.get("commons"):+ title = p["commons"] if p["commons"].startswith("File:") else "File:" + p["commons"]+ pages = (api(action="query", titles=title, **IIPROP).get("query") or {}).get("pages", [])+ if not pages or pages[0].get("missing"):+ print(f"{p['id']}: {title} not found on Commons"); refused += 1; continue+ d = info(pages[0])+ ok = bool(FREE.search(d["license"] or ""))+ if not ok and not a.allow_nonfree:+ print(f"{p['id']}: REFUSED, licence {d['license']!r} is not free ({d['source']})"); refused += 1; continue+ url = d["thumb"] if d["thumb"] and (d["w"] or 0) > 3200 and "svg" not in (d["mime"] or "") else d["url"]+ if "svg" in (d["mime"] or ""):+ url = d["thumb"]+ ext = pathlib.Path(urllib.parse.urlparse(url).path).suffix.lower() or ".jpg"+ fname = p["file"] if have and not a.force else f"{p['id']}_{re.sub(r'[^A-Za-z0-9]+', '_', title[5:].rsplit('.', 1)[0])[:48]}{ext}"+ if not have or a.force:+ download(url, dst_dir / fname) # an existing file only gets its credit and licence filled in+ p.update(file=fname, source=d["source"], credit=p.get("credit") or d["credit"], license=d["license"],+ license_url=d["license_url"], date=d["date"], license_ok=ok)+ print(f"{p['id']}: {fname} [{d['license']}] {p['credit'][:50]}")+ time.sleep(0.5)+ elif p.get("url"):+ ext = pathlib.Path(urllib.parse.urlparse(p["url"]).path).suffix.lower() or ".jpg"+ fname = f"{p['id']}{ext}"+ download(p["url"], dst_dir / fname)+ p["file"] = fname+ p.setdefault("license_ok", bool(FREE.search(p.get("license", ""))))+ print(f"{p['id']}: {fname} [{p.get('license') or 'LICENCE NOT RECORDED'}]")+ else:+ print(f"{p['id']}: no 'commons' or 'url' and no file in assets/photos/; add one")+ (proj / "photos.json").write_text(json.dumps(spec, indent=1, ensure_ascii=False) + "\n")+ if refused:+ sys.exit(f"{refused} image(s) not downloaded; replace them or decide on the rights yourself")+++def cmd_credits(a):+ proj = pathlib.Path(a.project)+ spec = json.loads((proj / "photos.json").read_text())+ rows, unclear = [], []+ for p in spec["photos"]:+ lic = p.get("license") or "NOT RECORDED"+ if not p.get("license_ok", bool(FREE.search(lic))):+ unclear.append(p["id"])+ rows.append(f"| {p['id']} | {p.get('what', '')} | {p.get('credit', '')} | {lic} | {p.get('source', '')} |")+ md = ("# Image credits\n\n| ID | What | Credit | Licence | Source |\n|---|---|---|---|---|\n" + "\n".join(rows) + "\n")+ recs = [l for l in spec.get("recreations", [])]+ if recs:+ md += "\n## Recreations drawn in code\n\n" + "\n".join(f"- {r}" for r in recs) + "\n"+ if unclear:+ md += f"\n**Rights unclear:** {', '.join(unclear)}. Verify or replace before publishing anything monetised.\n"+ (proj / "credits.md").write_text(md)+ print(f"credits.md: {len(rows)} images" + (f", rights unclear for {', '.join(unclear)}" if unclear else ", all free"))+++def main():+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ sub = ap.add_subparsers(dest="cmd", required=True)+ s = sub.add_parser("search"); s.add_argument("query"); s.add_argument("--limit", type=int, default=12)+ c = sub.add_parser("category"); c.add_argument("category"); c.add_argument("--limit", type=int, default=40)+ g = sub.add_parser("get"); g.add_argument("--project", required=True); g.add_argument("--force", action="store_true")+ g.add_argument("--allow-nonfree", action="store_true")+ k = sub.add_parser("credits"); k.add_argument("--project", required=True)+ a = ap.parse_args()+ {"search": cmd_search, "category": cmd_category, "get": cmd_get, "credits": cmd_credits}[a.cmd](a)+++if __name__ == "__main__":+ main()diff --git a/skills/cinematic-film/scripts/make_beats.py b/skills/cinematic-film/scripts/make_beats.pynew file mode 100644index 0000000..04533b6--- /dev/null+++ b/skills/cinematic-film/scripts/make_beats.py@@ -0,0 +1,85 @@+#!/usr/bin/env python3+"""Write beats.md, the beat table you approve before building: one row per narration line with its+start, length, the one hero on screen and any typed text. Also lints the script.++ python3 make_beats.py --project my-film++Uses audio/timing.json when there is one; before any voice exists it estimates times from the+letters (about 14.5 letters per second plus pauses), so the table can be reviewed first.++Lint (warnings, not errors):+ * chronology: after the cold open (the first take), a year lower than one already reached+ * a line over 22 words (one idea per line; long lines get cut in half by the camera anyway)+ * a line with no hero+ * a phrase typed on screen that is also spoken word for word in the same line+ * digits left in the spoken text (voices misread "1903"; write "nineteen oh three")+"""+import argparse+import json+import pathlib+import re++LPS = 14.5+++def mmss(s):+ return f"{int(s // 60)}:{s % 60:04.1f}"+++def main():+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ ap.add_argument("--project", required=True)+ a = ap.parse_args()+ proj = pathlib.Path(a.project)+ script = json.loads((proj / "script.json").read_text())+ tp = proj / "audio" / "timing.json"+ timing = {s["id"]: s for s in json.loads(tp.read_text())["segments"]} if tp.exists() else {}+ lines = [(t["take"], l) for t in script["takes"] for l in t["lines"]]++ warn, rows, cursor, max_year = [], [], 0.9, None+ first_take = script["takes"][0]["take"]+ for take, l in lines:+ i = l["id"]+ if i in timing:+ start, dur = timing[i]["start"], timing[i]["duration"]+ else:+ dur = len(re.sub(r"[^A-Za-z]", "", l["spoken"])) / LPS+ start = cursor+ cursor += dur + l.get("gap_after", 0.45)+ typed = l.get("typed", "") or "--"+ hero = l.get("hero", "")+ rows.append(f"| {i} | {mmss(start)} | {dur:.1f}s | {l['text']} | {hero or '(previous hero holds)'} | {typed} |")+ words = len(l["text"].split())+ if words > 22:+ warn.append(f"line {i}: {words} words; split it (one idea per line)")+ if not hero:+ warn.append(f"line {i}: no hero (say what the camera is on, even if the previous one holds)")+ if re.search(r"\d", l["spoken"]):+ warn.append(f"line {i}: digits in the spoken text {l['spoken']!r}; write numbers as words")+ for ph in [p.strip() for p in re.split(r"[+·,;]", typed) if len(p.strip().split()) >= 3]: # name bars are fine+ if ph.lower() in l["text"].lower():+ warn.append(f"line {i}: {ph!r} is typed AND spoken word for word; show it one way")+ years = [int(y) for y in re.findall(r"\b(1[0-9]{3}|20[0-9]{2})\b", l["text"])]+ if take != first_take:+ for y in years:+ if max_year is not None and y < max_year:+ warn.append(f"line {i}: {y} steps back in time after {max_year}; after the cold open, story time only moves forward")+ max_year = y if max_year is None else max(max_year, y)+ total = json.loads(tp.read_text())["total_duration"] if tp.exists() else cursor + 3.0+ src = "timed to audio/timing.json" if timing else "ESTIMATED from letter counts (no voice yet)"+ head = (f"# {script.get('title', proj.name)}: beat table\n\n"+ f"{len(lines)} lines, {mmss(total)} total, {src}.\n\n"+ "Hero = the one thing the camera is on (everything else dims). Typed = text drawn in code; "+ "a phrase is either typed or shown on a real document, never both.\n\n"+ "| # | Start | Len | Narration | Hero on screen | Typed |\n|---|---|---|---|---|---|\n")+ body = "\n".join(rows) + "\n"+ if warn:+ body += "\n## Lint\n\n" + "\n".join(f"- {w}" for w in warn) + "\n"+ (proj / "beats.md").write_text(head + body)+ print(f"beats.md: {len(lines)} beats, {mmss(total)} ({'timed' if timing else 'estimated'}), {len(warn)} warning(s)")+ for w in warn:+ print(" " + w)+++if __name__ == "__main__":+ main()diff --git a/skills/cinematic-film/scripts/make_map.py b/skills/cinematic-film/scripts/make_map.pynew file mode 100644index 0000000..37018d6--- /dev/null+++ b/skills/cinematic-film/scripts/make_map.py@@ -0,0 +1,209 @@+#!/usr/bin/env python3+"""Build the projected map data for GeoMap from public-domain boundaries (TopoJSON or GeoJSON).++ python3 make_map.py --project my-film++Reads map.json in the project:+ {"maps": [{+ "name": "us",+ "source": "https://cdn.jsdelivr.net/npm/us-atlas@3/states-10m.json", # TopoJSON or GeoJSON, URL or path+ "object": "states", # TopoJSON object (ignored for GeoJSON)+ "projection": {"type": "albers", "lon0": -96, "lat0": 37.5, "p1": 29.5, "p2": 45.5},+ "drop": ["Alaska", "Hawaii", "Puerto Rico"], # or "keep": [...]+ "neighbors": {"source": "https://cdn.jsdelivr.net/npm/world-atlas@2/countries-50m.json", "object": "countries",+ "keep": ["Canada", "Mexico", "Cuba"], "dark": ["Canada", "Mexico"], "clip": [-140, 12, -55, 62]},+ "frame": [-125, 24, -66, 50], # optional sheet bounds: lon_min, lat_min, lon_max, lat_max+ "places": {"Dayton": [39.76, -84.19], "Kitty Hawk": [36.06, -75.70]} # [lat, lon]+ }]}++Projections: albers (equal-area conic; good for one country), equirect (lon0, lat0; fine for a region),+mercator (lon0). Units are earth radii, so GeoMap(K=24000) gives a country about 20,000 world px wide.+Boundaries are kept at full detail: thinning them opened slivers between neighbouring regions.++Good free sources (Natural Earth data is public domain; the atlas packages are ISC-licensed):+ us-atlas@3/states-10m.json (objects: states, nation) world-atlas@2/countries-50m.json (object: countries)+ both on https://cdn.jsdelivr.net/npm/ Natural Earth GeoJSON: github.com/nvkelso/natural-earth-vector++Downloads are cached in assets/data/. Writes assets/prep/map_<name>.json.+"""+import argparse+import json+import math+import pathlib+import sys+import urllib.request++UA = "cinematic-film/1.0 (+https://github.com/Moh4696/open-3d-skills)"+++def load(src, cache):+ if str(src).startswith(("http://", "https://")):+ p = cache / pathlib.Path(src.split("?")[0]).name+ if not p.exists():+ cache.mkdir(parents=True, exist_ok=True)+ req = urllib.request.Request(src, headers={"User-Agent": UA})+ with urllib.request.urlopen(req, timeout=60) as r:+ p.write_bytes(r.read())+ print(f"downloaded {src} -> {p}")+ return json.loads(p.read_text())+ return json.loads(pathlib.Path(src).read_text())+++def name_of(props):+ props = props or {}+ for k in ("name", "NAME", "ADMIN", "name_en", "NAME_EN"):+ if props.get(k):+ return props[k]+ return None+++def features(data, obj=None):+ """[(name, [ring lon/lat lists])] from TopoJSON or GeoJSON."""+ out = []+ if data.get("type") == "Topology":+ tr = data.get("transform")+ arcs = []+ for arc in data["arcs"]:+ x = y = 0; pts = []+ for p in arc:+ if tr:+ x += p[0]; y += p[1]+ pts.append((x * tr["scale"][0] + tr["translate"][0], y * tr["scale"][1] + tr["translate"][1]))+ else:+ pts.append((p[0], p[1]))+ arcs.append(pts)++ def ring(idx):+ pts = []+ for i in idx:+ a = arcs[i] if i >= 0 else arcs[~i][::-1]+ pts.extend(a if not pts else a[1:])+ return pts+ if obj not in data["objects"]:+ sys.exit(f"object {obj!r} not in TopoJSON; have {list(data['objects'])}")+ for g in data["objects"][obj]["geometries"]:+ polys = g["arcs"] if g["type"] == "MultiPolygon" else [g["arcs"]] if g["type"] == "Polygon" else []+ out.append((name_of(g.get("properties")) or str(g.get("id")), [ring(r) for poly in polys for r in poly]))+ else:+ feats = data["features"] if data.get("type") == "FeatureCollection" else [data]+ for f in feats:+ geo = f.get("geometry") or {}+ polys = geo.get("coordinates", []) if geo.get("type") == "MultiPolygon" else [geo.get("coordinates", [])] if geo.get("type") == "Polygon" else []+ out.append((name_of(f.get("properties")) or str(f.get("id")), [r for poly in polys for r in poly]))+ return out+++def projector(spec):+ t = spec.get("type", "albers")+ r = math.radians+ if t == "albers":+ lon0, lat0, p1, p2 = spec.get("lon0", -96.0), spec.get("lat0", 37.5), spec.get("p1", 29.5), spec.get("p2", 45.5)+ n = (math.sin(r(p1)) + math.sin(r(p2))) / 2+ c = math.cos(r(p1)) ** 2 + 2 * n * math.sin(r(p1))+ rho0 = math.sqrt(c - 2 * n * math.sin(r(lat0))) / n++ def f(lon, lat):+ rho = math.sqrt(max(0.0, c - 2 * n * math.sin(r(lat)))) / n+ th = n * r(lon - lon0)+ return rho * math.sin(th), -(rho0 - rho * math.cos(th)) # y down+ return f+ if t == "equirect":+ lon0, lat0 = spec.get("lon0", 0.0), spec.get("lat0", 0.0)+ k = math.cos(r(lat0))+ return lambda lon, lat: (r(lon - lon0) * k, -r(lat - lat0))+ if t == "mercator":+ lon0 = spec.get("lon0", 0.0)+ return lambda lon, lat: (r(lon - lon0), -math.log(math.tan(math.pi / 4 + r(max(-85, min(85, lat))) / 2)))+ sys.exit(f"unknown projection {t!r} (albers, equirect, mercator)")+++def clip_ring(ring, box):+ """Sutherland-Hodgman clip of a lon/lat ring to [lon0, lat0, lon1, lat1]."""+ x0, y0, x1, y1 = box+ def clip(pts, inside, cross):+ out = []+ for i, cur in enumerate(pts):+ prev = pts[i - 1]+ if inside(cur):+ if not inside(prev):+ out.append(cross(prev, cur))+ out.append(cur)+ elif inside(prev):+ out.append(cross(prev, cur))+ return out+ def lerp_x(a, b, x):+ u = (x - a[0]) / (b[0] - a[0]); return (x, a[1] + (b[1] - a[1]) * u)+ def lerp_y(a, b, y):+ u = (y - a[1]) / (b[1] - a[1]); return (a[0] + (b[0] - a[0]) * u, y)+ pts = [tuple(p[:2]) for p in ring]+ for inside, cross in ((lambda p: p[0] >= x0, lambda a, b: lerp_x(a, b, x0)), (lambda p: p[0] <= x1, lambda a, b: lerp_x(a, b, x1)),+ (lambda p: p[1] >= y0, lambda a, b: lerp_y(a, b, y0)), (lambda p: p[1] <= y1, lambda a, b: lerp_y(a, b, y1))):+ if not pts:+ break+ pts = clip(pts, inside, cross)+ return pts+++def project_rings(rings, proj, box=None):+ out = []+ for rg in rings:+ pts = clip_ring(rg, box) if box else [tuple(p[:2]) for p in rg]+ if len(pts) > 2:+ out.append([[round(x, 5), round(y, 5)] for x, y in (proj(lon, lat) for lon, lat in pts)])+ return out+++def build(m, cache):+ proj = projector(m.get("projection", {}))+ feats = features(load(m["source"], cache), m.get("object"))+ names = [n for n, _ in feats]+ keep, drop = set(m.get("keep") or []), set(m.get("drop") or [])+ for n in keep | drop:+ if n not in names:+ print(f" warning: {n!r} not found in {m['source']} (names look like {names[:6]})")+ regions = {}+ for n, rings in feats:+ if (keep and n not in keep) or n in drop:+ continue+ pr = project_rings(rings, proj, m.get("clip"))+ if pr:+ regions.setdefault(n, []).extend(pr)+ out = {"regions": regions, "neighbors": {}, "dark": [], "places": {}, "projection": m.get("projection", {})}+ nb = m.get("neighbors")+ if nb:+ nfeats = features(load(nb["source"], cache), nb.get("object"))+ want = set(nb.get("keep") or [])+ found = set()+ for n, rings in nfeats:+ if want and n not in want:+ continue+ pr = project_rings(rings, proj, nb.get("clip"))+ if pr:+ out["neighbors"].setdefault(n, []).extend(pr); found.add(n)+ for n in want - found:+ print(f" warning: neighbour {n!r} not found")+ out["dark"] = nb.get("dark", [])+ for name, (lat, lon) in (m.get("places") or {}).items():+ x, y = proj(lon, lat); out["places"][name] = [round(x, 6), round(y, 6)]+ if m.get("frame"):+ a, b, c, d = m["frame"]+ corners = [proj(a, b), proj(a, d), proj(c, b), proj(c, d), proj((a + c) / 2, b), proj((a + c) / 2, d)]+ out["frame"] = [min(p[0] for p in corners), min(p[1] for p in corners), max(p[0] for p in corners), max(p[1] for p in corners)]+ return out+++def main():+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ ap.add_argument("--project", required=True)+ a = ap.parse_args()+ proj = pathlib.Path(a.project)+ spec = json.loads((proj / "map.json").read_text())+ prep = proj / "assets" / "prep"; prep.mkdir(parents=True, exist_ok=True)+ for m in spec["maps"]:+ out = build(m, proj / "assets" / "data")+ (prep / f"map_{m['name']}.json").write_text(json.dumps(out))+ print(f"map_{m['name']}.json: {len(out['regions'])} regions, {len(out['neighbors'])} neighbours, {len(out['places'])} places")+++if __name__ == "__main__":+ main()diff --git a/skills/cinematic-film/scripts/mix_soundtrack.py b/skills/cinematic-film/scripts/mix_soundtrack.pynew file mode 100644index 0000000..824c866--- /dev/null+++ b/skills/cinematic-film/scripts/mix_soundtrack.py@@ -0,0 +1,95 @@+#!/usr/bin/env python3+"""Mix narration, sound effects and an optional music bed into the film's soundtrack.++ python3 mix_soundtrack.py --project my-film # voice + sfx+ python3 mix_soundtrack.py --project my-film --music audio/score.mp3 # + score, ducked under the voice+ python3 mix_soundtrack.py --project my-film --music audio/score.mp3 --music-db -4 --music-level 0.07 --music-eq-dip 4++The music is side-chain compressed by the narration (it dips while the narrator speaks and swells in+the gaps); the effects ride on top; the whole mix is normalised in two passes (measure, then apply)+to the target loudness with a -1.5 dBTP ceiling, so nothing pumps.++Levels that worked for a tense documentary where the music should be felt, not followed:+ --music-db -4 --sfx-db -3 --duck-ratio 3 --duck-threshold 0.03 --music-level 0.07 --music-eq-dip 4+(music lands near -30 LUFS under a -15 LUFS mix). Writes audio/mix.m4a; --stems also writes the+ducked music alone so you can check its level.+"""+import argparse+import json+import pathlib+import re+import subprocess+import sys+++def run(cmd):+ r = subprocess.run(cmd, capture_output=True, text=True)+ if r.returncode != 0:+ sys.exit(f"FAILED: {' '.join(map(str, cmd))}\n{r.stderr[-2500:]}")+ return r+++def resolve(proj, p):+ p = pathlib.Path(p)+ return p if p.is_absolute() else proj / p+++def main():+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ ap.add_argument("--project", required=True)+ ap.add_argument("--voice", default="audio/narration.m4a")+ ap.add_argument("--sfx", default="audio/sfx.wav")+ ap.add_argument("--music", default=None)+ ap.add_argument("--out", default="audio/mix.m4a")+ ap.add_argument("--music-db", type=float, default=-6.0, help="music gain before ducking")+ ap.add_argument("--sfx-db", type=float, default=-7.0, help="effects bus gain")+ ap.add_argument("--lufs", type=float, default=-15.0)+ ap.add_argument("--fade-in", type=float, default=1.2)+ ap.add_argument("--fade-out", type=float, default=3.5)+ ap.add_argument("--duck-threshold", type=float, default=0.025)+ ap.add_argument("--duck-ratio", type=float, default=4.0)+ ap.add_argument("--music-level", type=float, default=None, help="slow leveller threshold for a score that builds (0.1 = -20 dBFS)")+ ap.add_argument("--music-eq-dip", type=float, default=0.0, help="dB cut in the music around 2.4 kHz, where the voice lives")+ ap.add_argument("--stems", action="store_true")+ a = ap.parse_args()+ proj = pathlib.Path(a.project)+ dur = json.loads((proj / "audio" / "timing.json").read_text())["total_duration"]+ voice, sfx = resolve(proj, a.voice), resolve(proj, a.sfx)+ inputs = ["-i", str(voice)]+ graph = "[0:a]aformat=sample_rates=48000:channel_layouts=stereo,asplit=2[v][vk];"+ mix = ["[v]"]+ if sfx.exists():+ inputs += ["-i", str(sfx)]+ graph += f"[1:a]aformat=sample_rates=48000:channel_layouts=stereo,volume={a.sfx_db}dB[s];"+ mix.append("[s]")+ else:+ print(f"no {sfx}: mixing without effects")+ if a.music:+ mi = len(inputs) // 2+ inputs += ["-i", str(resolve(proj, a.music))]+ lev = f"acompressor=threshold={a.music_level}:ratio=3:attack=1500:release=3500:makeup=1," if a.music_level else ""+ lev += f"equalizer=f=2400:t=q:w=1.1:g={-abs(a.music_eq_dip)}," if a.music_eq_dip else ""+ graph += (f"[{mi}:a]atrim=0:{dur:.3f},asetpts=PTS-STARTPTS,aformat=sample_rates=48000:channel_layouts=stereo,{lev}"+ f"afade=t=in:d={a.fade_in},afade=t=out:st={dur - a.fade_out:.3f}:d={a.fade_out},volume={a.music_db}dB[m];"+ f"[m][vk]sidechaincompress=threshold={a.duck_threshold}:ratio={a.duck_ratio}:attack=35:release=550:makeup=1:knee=4[md];")+ mix.append("[md]")+ else:+ graph += "[vk]anullsink;"+ premix = graph + "".join(mix) + f"amix=inputs={len(mix)}:duration=first:normalize=0,alimiter=limit=0.9:level=disabled"++ r = run(["ffmpeg", "-v", "info", "-y", *inputs, "-filter_complex", premix + f",loudnorm=I={a.lufs}:TP=-1.5:LRA=11:print_format=json", "-f", "null", "-"])+ m = json.loads(re.search(r"\{[^{}]*\"input_i\"[^{}]*\}", r.stderr, re.S).group(0))+ ln = (f"loudnorm=I={a.lufs}:TP=-1.5:LRA=11:measured_I={m['input_i']}:measured_TP={m['input_tp']}:"+ f"measured_LRA={m['input_lra']}:measured_thresh={m['input_thresh']}:offset={m['target_offset']}:linear=true")+ out = resolve(proj, a.out)+ run(["ffmpeg", "-v", "error", "-y", *inputs, "-filter_complex", premix + "," + ln + ",aresample=48000", "-c:a", "aac", "-b:a", "256k", str(out)])+ print(f"mix: {out} (measured {m['input_i']} LUFS -> {a.lufs})")+ if a.stems and a.music:+ stem = out.with_name(out.stem + "_music.wav")+ sinks = "[v]anullsink;" + ("[s]anullsink;" if "[s]" in mix else "")+ run(["ffmpeg", "-v", "error", "-y", *inputs, "-filter_complex", graph + sinks.rstrip(";"), "-map", "[md]", str(stem)])+ print(f"ducked music stem: {stem}")+++if __name__ == "__main__":+ main()diff --git a/skills/cinematic-film/scripts/new_project.py b/skills/cinematic-film/scripts/new_project.pynew file mode 100644index 0000000..a36a7b4--- /dev/null+++ b/skills/cinematic-film/scripts/new_project.py@@ -0,0 +1,45 @@+#!/usr/bin/env python3+"""Start a cinematic-film project folder from the template (or copy the worked example).++ python3 new_project.py my-film --title "The Great Molasses Flood"+ python3 new_project.py wright-demo --example # the Wright Flyer film, ready to fetch, voice and render++Layout:+ script.json narration, one entry per line (text, spoken, hero, typed), grouped into takes+ photos.json every image: id, kind, crop, source, credit, licence+ map.json optional maps (make_map.py)+ scene.py the film: build_film(doc) places items and camera keys on the voiceover timing+ assets/photos (downloads) assets/prep (graded, generated) audio/ out/ fonts/ (optional overrides)+"""+import argparse+import json+import pathlib+import shutil+import sys++SKILL = pathlib.Path(__file__).resolve().parent.parent+++def main():+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ ap.add_argument("folder")+ ap.add_argument("--title", default=None)+ ap.add_argument("--example", action="store_true", help="copy the Wright Flyer example instead of the blank template")+ a = ap.parse_args()+ dst = pathlib.Path(a.folder)+ if dst.exists() and any(dst.iterdir()):+ sys.exit(f"{dst} exists and is not empty")+ src = SKILL / "assets" / ("wright-flyer" if a.example else "template")+ shutil.copytree(src, dst, dirs_exist_ok=True)+ for sub in ("assets/photos", "assets/prep", "audio/takes", "out"):+ (dst / sub).mkdir(parents=True, exist_ok=True)+ if a.title:+ sp = dst / "script.json"+ s = json.loads(sp.read_text()); s["title"] = a.title+ sp.write_text(json.dumps(s, indent=1, ensure_ascii=False) + "\n")+ print(f"created {dst} from {src.name}")+ print("next: write script.json, then make_beats.py -> tts_say.py -> split_takes.py -> build_narration.py")+++if __name__ == "__main__":+ main()diff --git a/skills/cinematic-film/scripts/prep_assets.py b/skills/cinematic-film/scripts/prep_assets.pynew file mode 100644index 0000000..d7890a8--- /dev/null+++ b/skills/cinematic-film/scripts/prep_assets.py@@ -0,0 +1,198 @@+#!/usr/bin/env python3+"""Grade the project's images into one look and generate the board textures (no downloaded textures).++ python3 prep_assets.py --project my-film+ python3 prep_assets.py --project my-film --grade natural # override photos.json "grade"++photos.json:+ {"grade": "bw",+ "photos": [{"id": "P01", "file": "first_flight.jpg", "kind": "photo", "crop": [0.1, 0, 0.9, 1], ...}]}++grade: bw = neutral high-contrast black and white (archive), sepia = warm monochrome,+ natural = keep colour with one shared balance (your own photos, product shots, AI stills)+kind: photo -> one duotone (or natural colour)+ paper -> newsprint: blacks lifted a little so it reads as ink on paper+ doc -> records and forms: most colour removed, a hint of the paper kept+ color -> kept in colour, only warmed (magazine covers)+crop: optional [left, top, right, bottom] as fractions, to cut to the part that matters++Writes assets/prep/photos/<id>.jpg, assets/prep/photos/meta.json and, if missing, the textures+cork.png, cork_dark.png, slate.png, charcoal.png, paper.png, studio.png, night.png, blueprint.png+and relief.png (the boards behind the looks in engine.LOOKS).+"""+import argparse+import json+import math+import pathlib+import sys++import numpy as np+from PIL import Image, ImageFilter, ImageOps++MAX_SIDE = 3200+GRADES = {+ "bw": ((15, 15, 16), (238, 236, 231), (234, 231, 224)),+ "sepia": ((28, 20, 14), (240, 226, 200), (236, 226, 204)),+ "natural": None, # keep colour: product shots, brand photos, AI stills, modern stories+}+++def duotone(gray, shadow, light):+ g = np.asarray(gray, np.float32)[..., None] / 255.0+ shadow = np.array(shadow, np.float32); light = np.array(light, np.float32)+ return (shadow + (light - shadow) * g).clip(0, 255).astype(np.uint8)+++def grade(im, kind, look):+ if GRADES[look] is None: # natural: gentle contrast and a shared, slightly warm balance+ a = np.asarray(ImageOps.autocontrast(im.convert("RGB"), cutoff=0.5), np.float32)+ lum = a.mean(axis=2, keepdims=True)+ a = (lum + (a - lum) * 0.92) * np.array([1.01, 1.0, 0.98])+ return Image.fromarray(a.clip(0, 255).astype(np.uint8))+ shadow, light, paper_light = GRADES[look]+ if kind == "color":+ a = np.asarray(im.convert("RGB"), np.float32) * np.array([1.0, 0.97, 0.9]) + np.array([4, 2, 0])+ return Image.fromarray(a.clip(0, 255).astype(np.uint8))+ g = ImageOps.grayscale(im)+ if kind == "photo":+ a = np.asarray(ImageOps.autocontrast(g, cutoff=1.0), np.float32) / 255.0+ a = np.clip((a - 0.5) * 1.12 + 0.5, 0, 1)+ return Image.fromarray(duotone((a * 255).astype(np.uint8), shadow, light))+ if kind == "paper":+ return Image.fromarray(duotone(ImageOps.autocontrast(g, cutoff=0.4), shadow, paper_light))+ a = np.asarray(im.convert("RGB"), np.float32)+ lum = a.mean(axis=2, keepdims=True)+ a = (lum + (a - lum) * 0.45) * np.array([1.0, 0.99, 0.97])+ return Image.fromarray(a.clip(0, 255).astype(np.uint8))+++def prep_photos(proj, look):+ spec = json.loads((proj / "photos.json").read_text())+ look = look or spec.get("grade", "bw")+ out = proj / "assets" / "prep" / "photos"; out.mkdir(parents=True, exist_ok=True)+ meta, missing = {}, []+ for p in spec["photos"]:+ src = proj / "assets" / "photos" / p["file"] if p.get("file") else None+ if not src or not src.exists():+ missing.append(f"{p['id']} ({p.get('file') or 'no file yet'})"); continue+ im = Image.open(src)+ im = im.convert("RGBA") if im.mode in ("P", "LA", "PA") else im+ if im.mode == "RGBA":+ bg = Image.new("RGB", im.size, (235, 228, 214)); bg.paste(im, mask=im.split()[3]); im = bg+ if p.get("crop"):+ w, h = im.size; c = p["crop"]+ im = im.crop((int(c[0] * w), int(c[1] * h), int(c[2] * w), int(c[3] * h)))+ if max(im.size) > MAX_SIDE:+ im.thumbnail((MAX_SIDE, MAX_SIDE), Image.LANCZOS)+ g = grade(im, p.get("kind", "photo"), look)+ g.save(out / f"{p['id']}.jpg", quality=93)+ meta[p["id"]] = {"w": g.width, "h": g.height, "kind": p.get("kind", "photo")}+ (out / "meta.json").write_text(json.dumps(meta, indent=1))+ print(f"photos: {len(meta)} graded ({look})" + (f"; missing {', '.join(missing)}" if missing else ""))+ return not missing+++def tile_noise(size, scale, seed):+ """Tileable value noise from FFT-filtered white noise."""+ rng = np.random.default_rng(seed)+ n = rng.standard_normal((size, size))+ fx = np.fft.fftfreq(size)[:, None]; fy = np.fft.fftfreq(size)[None, :]+ f = np.sqrt(fx ** 2 + fy ** 2) * size / scale+ out = np.real(np.fft.ifft2(np.fft.fft2(n) * np.exp(-f ** 2)))+ return (out - out.mean()) / (out.std() + 1e-9)+++def make_cork(size=1024):+ base = np.array([92, 62, 38], np.float32)+ n = 0.55 * tile_noise(size, 40, 1) + 0.35 * tile_noise(size, 12, 2) + 0.25 * tile_noise(size, 3, 3)+ speck = np.random.default_rng(4).random((size, size))+ dark = (speck > 0.985).astype(np.float32) * -0.9 + (speck < 0.012).astype(np.float32) * 0.5+ dark = np.asarray(Image.fromarray(((dark + 1) * 127).astype(np.uint8)).filter(ImageFilter.GaussianBlur(0.7)), np.float32) / 127 - 1+ v = n * 0.16 + dark * 0.35+ return (base[None, None, :] * (1 + v[..., None])).clip(0, 255)+++def make_paper(size=1024):+ base = np.array([232, 229, 222], np.float32)+ n = 0.5 * tile_noise(size, 60, 11) + 0.3 * tile_noise(size, 8, 12) + 0.2 * tile_noise(size, 2, 13)+ rng = np.random.default_rng(14)+ fib = np.zeros((size, size), np.float32)+ for _ in range(900): # short paper fibres+ x, y = rng.integers(0, size, 2); ang = rng.random() * math.pi; ln = rng.integers(6, 22)+ for k in range(ln):+ fib[int(y + k * math.sin(ang)) % size, int(x + k * math.cos(ang)) % size] += 1+ fib = np.asarray(Image.fromarray((fib.clip(0, 1) * 255).astype(np.uint8)).filter(ImageFilter.GaussianBlur(0.6)), np.float32) / 255+ v = n * 0.035 - fib * 0.05+ return (base[None, None, :] * (1 + v[..., None])).clip(0, 255)+++def make_flat(rgb, seed, size=1024, amount=0.08):+ n = 0.6 * tile_noise(size, 50, seed) + 0.3 * tile_noise(size, 10, seed + 1) + 0.2 * tile_noise(size, 2, seed + 2)+ return (np.array(rgb, np.float32)[None, None, :] * (1 + n[..., None] * amount)).clip(0, 255)+++def make_blueprint(size=1024):+ """Deep blue drafting sheet with a fine grid every 64 px and a heavier line every 256 (tileable)."""+ a = make_flat((22, 52, 98), 71, size, amount=0.06)+ grid = np.zeros((size, size), np.float32)+ for k in range(0, size, 64):+ w = 0.5 if k % 256 == 0 else 0.22+ grid[:, k:k + 2] = np.maximum(grid[:, k:k + 2], w); grid[k:k + 2, :] = np.maximum(grid[k:k + 2, :], w)+ return (a + grid[..., None] * np.array([120, 160, 200], np.float32)).clip(0, 255)+++def make_relief(size=1024):+ """Faux terrain relief for map land: tileable multi-octave noise, hill-shaded, soft."""+ n = 0.6 * tile_noise(size, 90, 41) + 0.3 * tile_noise(size, 30, 42) + 0.15 * tile_noise(size, 8, 43)+ gy = (np.roll(n, -1, 0) - np.roll(n, 1, 0)) / 2; gx = (np.roll(n, -1, 1) - np.roll(n, 1, 1)) / 2 # wraps, so it tiles+ shade = np.clip(0.5 + (gx * -1.0 + gy * -1.0) * 1.6, 0, 1)+ return Image.fromarray((shade * 255).astype(np.uint8))+++def textures(prep, force=False):+ def save(name, arr):+ p = prep / name+ if force or not p.exists():+ (arr if isinstance(arr, Image.Image) else Image.fromarray(arr.astype(np.uint8))).save(p)+ return name+ made = []+ cork = make_cork() if force or not (prep / "cork.png").exists() or not (prep / "cork_dark.png").exists() else None+ if cork is not None:+ made.append(save("cork.png", cork))+ lum = cork.mean(axis=2, keepdims=True)+ dark = (lum + (cork - lum) * 0.55) * 0.45 + np.array([12, 10, 9]) * 0.55 # calmer cork so colour reads on top+ made.append(save("cork_dark.png", dark))+ if force or not (prep / "paper.png").exists():+ made.append(save("paper.png", make_paper()))+ if force or not (prep / "slate.png").exists():+ made.append(save("slate.png", make_flat((34, 40, 46), 21)))+ if force or not (prep / "charcoal.png").exists():+ made.append(save("charcoal.png", make_flat((30, 29, 28), 31, amount=0.12)))+ if force or not (prep / "relief.png").exists():+ made.append(save("relief.png", make_relief()))+ if force or not (prep / "studio.png").exists():+ made.append(save("studio.png", make_flat((222, 220, 216), 51, amount=0.025)))+ if force or not (prep / "night.png").exists():+ made.append(save("night.png", make_flat((16, 20, 32), 61, amount=0.1)))+ if force or not (prep / "blueprint.png").exists():+ made.append(save("blueprint.png", make_blueprint()))+ made = [m for m in made if m]+ print("textures:", ", ".join(made) if made else "up to date")+++def main():+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ ap.add_argument("--project", required=True)+ ap.add_argument("--grade", choices=sorted(GRADES), default=None)+ ap.add_argument("--textures", action="store_true", help="regenerate textures even if present")+ a = ap.parse_args()+ proj = pathlib.Path(a.project)+ prep = proj / "assets" / "prep"; prep.mkdir(parents=True, exist_ok=True)+ textures(prep, a.textures)+ ok = prep_photos(proj, a.grade) if (proj / "photos.json").exists() else True+ if not ok:+ sys.exit(1)+++if __name__ == "__main__":+ main()diff --git a/skills/cinematic-film/scripts/render.py b/skills/cinematic-film/scripts/render.pynew file mode 100644index 0000000..6299e6a--- /dev/null+++ b/skills/cinematic-film/scripts/render.py@@ -0,0 +1,170 @@+#!/usr/bin/env python3+"""Render a cinematic-film project (its scene.py) to stills, contact strips, a cue list or an MP4.++ python3 render.py --project my-film --probe 1.0,6.2,11.5 --size 1280x720 # stills -> out/probe/+ python3 render.py --project my-film --strip 17.9:21.6:12 --size 1280x720 # 12-frame contact sheet of a move+ python3 render.py --project my-film --cues # sfx_cues.json for build_sfx.py+ python3 render.py --project my-film --t0 0 --t1 30 --size 1280x720 --out out/draft.mp4 --audio audio/narration.m4a+ python3 render.py --project my-film --size 1920x1080 --out out/final.mp4 --audio audio/mix.m4a++Each worker builds the film, renders a contiguous range of frames and pipes raw RGB into its own+ffmpeg; the chunks are joined losslessly, then the soundtrack is muxed. --workers defaults to what+fits in memory (a 4K worker plus its encoder needs about 2 GB; past that the machine swaps and+everything slows to a crawl).+"""+import argparse+import importlib.util+import json+import multiprocessing as mp+import os+import pathlib+import subprocess+import sys+import time++HERE = pathlib.Path(__file__).resolve().parent+sys.path.insert(0, str(HERE))+++def load_scene(project):+ path = pathlib.Path(project) / "scene.py"+ if not path.exists():+ sys.exit(f"{path} not found (new_project.py makes one)")+ spec = importlib.util.spec_from_file_location("scene", path)+ mod = importlib.util.module_from_spec(spec)+ sys.path.insert(0, str(path.parent))+ spec.loader.exec_module(mod)+ return mod+++def make(project, size):+ from engine import Doc, Renderer+ w, h = map(int, size.lower().split("x"))+ doc = Doc(project)+ film = load_scene(project).build_film(doc)+ return film, Renderer(film, w, h, doc), doc+++def total_ram_gb():+ try:+ if sys.platform == "darwin":+ return int(subprocess.run(["sysctl", "-n", "hw.memsize"], capture_output=True, text=True).stdout) / 2 ** 30+ with open("/proc/meminfo") as f:+ return int(f.readline().split()[1]) / 2 ** 20+ except Exception:+ return 8.0+++def auto_workers(w, h):+ px = w * h+ per = 0.55 + 1.5 * px / (3840 * 2160) # GB per worker + encoder, measured: ~0.9 at 1080p, ~2 at 4K+ by_ram = int(total_ram_gb() * 0.6 / per)+ by_cpu = max(1, (os.cpu_count() or 4) - 1)+ return max(1, min(by_ram, by_cpu, 8))+++def encoder_args(w, crf):+ # x264 lookahead buffers ran ~2 GB per encoder at 4K; capping them keeps parallel workers in RAM+ lean = ["-rc-lookahead", "10", "-threads", "2"] if w >= 2000 else []+ return ["-c:v", "libx264", "-preset", "medium", "-crf", str(crf), *lean, "-pix_fmt", "yuv420p"]+++def worker(args):+ project, size, f0, f1, out, crf = args+ film, r, _ = make(project, size)+ ff = subprocess.Popen(["ffmpeg", "-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "rgb24", "-s", f"{r.W}x{r.H}",+ "-r", str(film.fps), "-i", "-", *encoder_args(r.W, crf), str(out)], stdin=subprocess.PIPE)+ t0 = time.time()+ for n in range(f0, f1):+ ff.stdin.write(r.frame(n).tobytes())+ ff.stdin.close()+ if ff.wait() != 0:+ raise RuntimeError(f"ffmpeg failed for chunk {out}")+ return f0, f1, time.time() - t0+++def main():+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ ap.add_argument("--project", required=True)+ ap.add_argument("--size", default="1920x1080")+ ap.add_argument("--probe", default="", help="comma-separated times: one PNG still each")+ ap.add_argument("--strip", default="", help="t0:t1:n contact sheet of n frames between t0 and t1")+ ap.add_argument("--t0", type=float, default=0.0)+ ap.add_argument("--t1", type=float, default=None)+ ap.add_argument("--out", default="")+ ap.add_argument("--audio", default="")+ ap.add_argument("--workers", type=int, default=0, help="0 = as many as fit in memory")+ ap.add_argument("--crf", type=int, default=16)+ ap.add_argument("--cues", action="store_true")+ a = ap.parse_args()+ proj = pathlib.Path(a.project).resolve()++ if a.cues:+ from engine import Doc+ film = load_scene(proj).build_film(Doc(proj))+ cues = film.all_cues()+ (proj / "sfx_cues.json").write_text(json.dumps({"duration": film.duration, "cues": cues, "room_tone": film.room_tone}, indent=1))+ kinds = {}+ for c in cues:+ kinds[c["type"]] = kinds.get(c["type"], 0) + 1+ print(f"sfx_cues.json: {len(cues)} cues " + ", ".join(f"{k} {v}" for k, v in sorted(kinds.items())))+ return++ if a.probe or a.strip:+ from PIL import Image+ film, r, _ = make(proj, a.size)+ pdir = proj / "out" / "probe"; pdir.mkdir(parents=True, exist_ok=True)+ if a.probe:+ for ts in [float(x) for x in a.probe.split(",") if x.strip()]:+ t0 = time.time(); img = r.frame(round(ts * film.fps))+ p = pdir / f"t{ts:07.2f}.png"; Image.fromarray(img).save(p)+ print(f"{p} ({time.time() - t0:.2f}s)")+ if a.strip:+ s0, s1, n = a.strip.split(":"); s0, s1, n = float(s0), float(s1), int(n)+ frames = [Image.fromarray(r.frame(round((s0 + (s1 - s0) * i / max(1, n - 1)) * film.fps))) for i in range(n)]+ cols = 4; rows = (n + cols - 1) // cols+ tw, th = frames[0].width // 2, frames[0].height // 2+ sheet = Image.new("RGB", (cols * tw, rows * th), "white")+ for i, f in enumerate(frames):+ sheet.paste(f.resize((tw, th)), ((i % cols) * tw, (i // cols) * th))+ p = pdir / f"strip_{s0:06.2f}_{s1:06.2f}.jpg"; sheet.save(p, quality=85); print(p)+ return++ if not a.out:+ sys.exit("--out is required for a video render (or use --probe, --strip, --cues)")+ from engine import Doc+ film = load_scene(proj).build_film(Doc(proj))+ fps = film.fps+ t1 = a.t1 if a.t1 is not None else film.duration+ f0, f1 = round(a.t0 * fps), round(t1 * fps)+ n = f1 - f0+ w, h = map(int, a.size.lower().split("x"))+ k = max(1, min(a.workers or auto_workers(w, h), n // 30 or 1))+ work = proj / "out" / "chunks"; work.mkdir(parents=True, exist_ok=True)+ for old in work.glob("*.mp4"):+ old.unlink()+ bounds = [f0 + n * i // k for i in range(k + 1)]+ jobs = [(str(proj), a.size, bounds[i], bounds[i + 1], work / f"c{i:03d}.mp4", a.crf) for i in range(k)]+ print(f"rendering {n} frames ({n / fps:.1f}s) at {a.size} on {k} workers")+ t0 = time.time()+ with mp.get_context("spawn").Pool(k) as pool:+ for b0, b1, dt in pool.imap_unordered(worker, jobs):+ print(f" frames {b0}-{b1}: {dt:.0f}s ({(b1 - b0) / dt:.1f} fps/worker)", flush=True)+ lst = work / "list.txt"+ lst.write_text("".join(f"file '{j[4].resolve()}'\n" for j in jobs))+ out = pathlib.Path(a.out)+ out = (out if out.is_absolute() else proj / out).resolve()+ out.parent.mkdir(parents=True, exist_ok=True)+ cmd = ["ffmpeg", "-v", "error", "-y", "-f", "concat", "-safe", "0", "-i", str(lst)]+ if a.audio:+ audio = pathlib.Path(a.audio)+ audio = audio if audio.is_absolute() else proj / audio+ cmd += ["-ss", f"{a.t0:.3f}", "-t", f"{t1 - a.t0:.3f}", "-i", str(audio.resolve()),+ "-map", "0:v", "-map", "1:a", "-c:a", "aac", "-b:a", "192k", "-shortest"]+ cmd += ["-c:v", "copy", "-movflags", "+faststart", str(out)]+ subprocess.run(cmd, check=True)+ print(f"wrote {out} ({n} frames in {time.time() - t0:.0f}s)")+++if __name__ == "__main__":+ main()diff --git a/skills/cinematic-film/scripts/split_takes.py b/skills/cinematic-film/scripts/split_takes.pynew file mode 100644index 0000000..5524b83--- /dev/null+++ b/skills/cinematic-film/scripts/split_takes.py@@ -0,0 +1,168 @@+#!/usr/bin/env python3+"""Split whole-section voice takes into one clip per narration line.++Reading a whole section in one TTS call keeps the delivery consistent, but the film needs the+timing of every line. This finds the pauses in each take (ffmpeg silencedetect) and picks the ones+that best match where each line boundary should fall, by each line's share of the letters, with a+small dynamic program so the cuts stay in order and one bad guess cannot shift every later line.++ python3 split_takes.py --project my-film++Reads script.json and audio/takes/<take>.wav+Writes audio/lines/segNN.wav, audio/lines/split_report.json, audio/segments.json++Sanity check: speaking rate is measured in letters per second of actual speech. A line more than+35% off the median is flagged; that is nearly always a misplaced cut or a word the voice dropped.+Listen to every flagged line.++When a voice runs two lines together with no pause (or pauses dramatically inside a line), force+the boundary in audio/overrides.json: {"cut_before": {"14": 26.80}} (line id: seconds into its take).+A line can set "gap_after" (seconds of silence after it in the finished track) in script.json.+"""+import argparse+import json+import pathlib+import re+import subprocess+import sys++NOISE_DB = -40 # silence threshold+MIN_SIL = 0.16 # shortest pause considered a candidate cut (s)+LPS_TOL = 0.35 # flag a line whose letters/sec is more than 35% off the median+++def run(cmd):+ r = subprocess.run(cmd, capture_output=True, text=True)+ if r.returncode != 0:+ sys.exit(f"FAILED: {' '.join(map(str, cmd))}\n{r.stderr[-1500:]}")+ return r+++def duration(path):+ return float(run(["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", str(path)]).stdout.strip())+++def silences(path):+ err = run(["ffmpeg", "-v", "info", "-i", str(path), "-af", f"silencedetect=noise={NOISE_DB}dB:d={MIN_SIL}", "-f", "null", "-"]).stderr+ starts = [float(x) for x in re.findall(r"silence_start: ([\d.]+)", err)]+ ends = [float(x) for x in re.findall(r"silence_end: ([\d.]+)", err)]+ total = duration(path)+ if len(ends) < len(starts):+ ends.append(total)+ return list(zip(starts, ends)), total+++def weight(text):+ """Rough speaking-time weight: letters, plus allowances for commas and sentence breaks inside the line."""+ return len(re.sub(r"[^A-Za-z]", "", text)) + 6 * text.count(",") + 14 * len(re.findall(r"[.!?](?=\s+\S)", text.strip()))+++def choose_cuts(cands, w, start, end, p0=0.55):+ """Pick len(w)-1 pauses so each line's length matches its expected length (segment-based DP).+ Longer pauses get a small bonus: sentence ends pause longer than commas."""+ k, n = len(w), len(cands)+ if k == 1:+ return []+ if n < k - 1:+ return None+ rate = max(1e-6, (end - start - k * p0)) / sum(w)+ exp = [wi * rate + p0 for wi in w]+ mids = [(s + e) / 2 for s, e in cands]++ def seg(i, a, b):+ return (((b - a) - exp[i]) / (0.22 * exp[i] + 0.3)) ** 2++ def bonus(j):+ return 1.2 * min(cands[j][1] - cands[j][0], 0.8)+ INF = float("inf")+ cost = [[INF] * n for _ in range(k - 1)]+ back = [[-1] * n for _ in range(k - 1)]+ for j in range(n):+ cost[0][j] = seg(0, start, mids[j]) - bonus(j)+ for i in range(1, k - 1):+ for j in range(n):+ best, arg = INF, -1+ for jp in range(j):+ if cost[i - 1][jp] < INF:+ v = cost[i - 1][jp] + seg(i, mids[jp], mids[j])+ if v < best:+ best, arg = v, jp+ if arg >= 0:+ cost[i][j] = best - bonus(j); back[i][j] = arg+ final = [cost[k - 2][j] + seg(k - 1, mids[j], end) if cost[k - 2][j] < INF else INF for j in range(n)]+ j = min(range(n), key=lambda x: final[x])+ if final[j] == INF:+ return None+ picks = [j]+ for i in range(k - 2, 0, -1):+ j = back[i][j]; picks.append(j)+ return [cands[x] for x in reversed(picks)]+++def main():+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ ap.add_argument("--project", required=True)+ ap.add_argument("--gap", type=float, default=0.45, help="default silence after a line in the finished track (s)")+ ap.add_argument("--take-gap", type=float, default=1.0, help="silence after the last line of a take (s)")+ a = ap.parse_args()+ proj = pathlib.Path(a.project)+ script = json.loads((proj / "script.json").read_text())+ tdir, odir = proj / "audio" / "takes", proj / "audio" / "lines"+ odir.mkdir(parents=True, exist_ok=True)+ ov = proj / "audio" / "overrides.json"+ cut_before = json.loads(ov.read_text()).get("cut_before", {}) if ov.exists() else {}++ report, segments = [], []+ for take in script["takes"]:+ wav = tdir / f"{take['take']}.wav"+ if not wav.exists():+ sys.exit(f"missing take: {wav}")+ sil, total = silences(wav)+ speech_start = sil[0][1] if sil and sil[0][0] < 0.05 else 0.0+ speech_end = sil[-1][0] if sil and sil[-1][1] >= total - 0.05 else total+ inner = [(s, e) for s, e in sil if s > speech_start + 0.05 and e < speech_end - 0.05]+ lines = take["lines"]+ w = [weight(l["spoken"]) for l in lines]+ forced = {i: float(cut_before[str(l["id"])]) for i, l in enumerate(lines) if i > 0 and str(l["id"]) in cut_before}+ edges = [0] + sorted(forced) + [len(lines)]+ bounds = [speech_start - 0.05]+ for a_i, b_i in zip(edges, edges[1:]):+ g0 = speech_start if a_i == 0 else forced[a_i]+ g1 = speech_end if b_i == len(lines) else forced[b_i]+ cands = [(s, e) for s, e in inner if s > g0 + 0.05 and e < g1 - 0.05]+ cuts = choose_cuts(cands, w[a_i:b_i], g0, g1)+ if cuts is None:+ sys.exit(f"{take['take']}: only {len(cands)} pauses for {b_i - a_i} lines; re-record with clearer pauses "+ "or add a cut_before override in audio/overrides.json")+ bounds += [(s + e) / 2 for s, e in cuts]+ if b_i < len(lines):+ bounds.append(forced[b_i])+ bounds.append(speech_end + 0.05)+ for i, line in enumerate(lines):+ t0, t1 = max(0.0, bounds[i]), min(total, bounds[i + 1])+ run(["ffmpeg", "-y", "-v", "error", "-ss", f"{t0:.3f}", "-to", f"{t1:.3f}", "-i", str(wav),+ "-ar", "48000", "-ac", "1", str(odir / f"seg{line['id']:02d}.wav")])+ pause = sum(min(e, t1) - max(s, t0) for s, e in sil if e > t0 and s < t1)+ speech = max(0.01, (t1 - t0) - pause)+ letters = len(re.sub(r"[^A-Za-z]", "", line["spoken"]))+ report.append({"id": line["id"], "take": take["take"], "start": round(t0, 3), "end": round(t1, 3),+ "speech_s": round(speech, 2), "letters": letters, "lps": round(letters / speech, 2), "text": line["text"]})+ last = i == len(lines) - 1+ segments.append({"id": line["id"], "scene": take["take"], "caption": line["text"], "vo": line["spoken"],+ "gap_after": line.get("gap_after", a.take_gap if last else a.gap)})+ print(f"{take['take']:<20} {len(lines)} lines, {len(inner)} pauses, {speech_end - speech_start:5.1f}s of speech")++ med = sorted(r["lps"] for r in report)[len(report) // 2]+ flagged = 0+ for r in report:+ r["flag"] = abs(r["lps"] / med - 1) > LPS_TOL+ flagged += r["flag"]+ (odir / "split_report.json").write_text(json.dumps(report, indent=1))+ (proj / "audio" / "segments.json").write_text(json.dumps({"segments": segments}, indent=1))+ for r in report:+ print(f" {r['id']:>3} {r['lps']:5.2f} l/s {r['speech_s']:5.2f}s {r['text'][:64]}{' <-- CHECK' if r['flag'] else ''}")+ print(f"{len(report)} lines, median {med:.2f} letters/s, {flagged} flagged")+++if __name__ == "__main__":+ main()diff --git a/skills/cinematic-film/scripts/tts_say.py b/skills/cinematic-film/scripts/tts_say.pynew file mode 100644index 0000000..8889f8b--- /dev/null+++ b/skills/cinematic-film/scripts/tts_say.py@@ -0,0 +1,83 @@+#!/usr/bin/env python3+"""Record every take in script.json with a local voice: a free scratch track to time the film against.++The film is timed to the voiceover, so the picture cannot be built before there is a voice. A+scratch track from the system voice costs nothing, gives real timings, and is replaced later by+the final voice (any TTS or a human): the scene re-times itself because it asks for line starts+and spoken words, never fixed seconds.++ python3 tts_say.py --project my-film # macOS `say`, or espeak-ng on Linux+ python3 tts_say.py --project my-film --voice Daniel --rate 165+ python3 tts_say.py --project my-film --cmd 'piper -m en_US-lessac-medium.onnx -f {out} < {txt}'++--cmd runs any command-line TTS once per take: {txt} is a text file with the take's lines (one per+paragraph), {out} the WAV it must write. Each take is read in one go so the delivery stays even;+split_takes.py then cuts it into lines. Writes audio/takes/<take>.wav.+"""+import argparse+import json+import pathlib+import shutil+import subprocess+import sys+import tempfile+++def run(cmd, shell=False):+ r = subprocess.run(cmd, capture_output=True, text=True, shell=shell)+ if r.returncode != 0:+ sys.exit(f"FAILED: {cmd if shell else ' '.join(map(str, cmd))}\n{r.stderr[-1500:]}")+ return r.stdout+++def to_wav(src, dst):+ run(["ffmpeg", "-y", "-v", "error", "-i", str(src), "-ar", "48000", "-ac", "1", str(dst)])+++def main():+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ ap.add_argument("--project", required=True)+ ap.add_argument("--voice", default=None, help="say / espeak-ng voice name")+ ap.add_argument("--rate", type=int, default=165, help="words per minute (documentary pace is 150-170)")+ ap.add_argument("--pause", type=int, default=650, help="pause between lines, ms (split_takes.py cuts there)")+ ap.add_argument("--cmd", default=None, help="any TTS command with {txt} and {out} placeholders")+ ap.add_argument("--only", default="", help="comma-separated take names to (re)record")+ a = ap.parse_args()++ proj = pathlib.Path(a.project)+ script = json.loads((proj / "script.json").read_text())+ tdir = proj / "audio" / "takes"; tdir.mkdir(parents=True, exist_ok=True)+ only = {x.strip() for x in a.only.split(",") if x.strip()}+ engine = "cmd" if a.cmd else "say" if shutil.which("say") else "espeak-ng" if shutil.which("espeak-ng") else None+ if engine is None:+ sys.exit("no local voice: install espeak-ng (apt install espeak-ng), or pass --cmd for your TTS, "+ "or record takes elsewhere and save them as audio/takes/<take>.wav")+ with tempfile.TemporaryDirectory() as tmp:+ tmp = pathlib.Path(tmp)+ for take in script["takes"]:+ name = take["take"]+ if only and name not in only:+ continue+ lines = [l["spoken"].strip() for l in take["lines"]]+ out = tdir / f"{name}.wav"+ if engine == "say":+ text = f" [[slnc {a.pause}]] ".join(lines)+ raw = tmp / f"{name}.aiff"+ cmd = ["say", "-r", str(a.rate), "-o", str(raw)] + (["-v", a.voice] if a.voice else []) + [text]+ run(cmd); to_wav(raw, out)+ elif engine == "espeak-ng":+ ssml = "<speak>" + f"<break time='{a.pause}ms'/>".join(lines) + "</speak>"+ raw = tmp / f"{name}.wav"+ cmd = ["espeak-ng", "-m", "-s", str(a.rate), "-w", str(raw)] + (["-v", a.voice] if a.voice else []) + [ssml]+ run(cmd); to_wav(raw, out)+ else:+ txt = tmp / f"{name}.txt"; txt.write_text("\n\n".join(lines) + "\n")+ raw = tmp / f"{name}_raw.wav"+ run(a.cmd.format(txt=str(txt), out=str(raw)), shell=True)+ to_wav(raw, out)+ dur = float(run(["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", str(out)]))+ print(f"{name:<20} {len(lines)} lines {dur:5.1f}s -> {out}")+++if __name__ == "__main__":+ main()diff --git a/tests/check.mjs b/tests/check.mjsnew file mode 100644index 0000000..d83f257--- /dev/null+++ b/tests/check.mjs@@ -0,0 +1,109 @@+#!/usr/bin/env node+// Every skill must load in every agent, and every script must at least parse.+//+// Claude Code, Codex, Cursor and Gemini CLI read SKILL.md frontmatter with strict YAML parsers+// and silently skip a skill whose frontmatter fails (an unquoted "word: word" in a description+// is enough), so this parses each one the same way and fails loudly. It also checks the plugin+// manifests point at real skills, every JavaScript file passes `node --check`, and every Python+// script compiles.+//+// npm install --no-save --no-package-lock [email protected] (once; CI does this)+// node tests/check.mjs+import { readFileSync, readdirSync, existsSync, statSync } from 'node:fs';+import { join, dirname, relative } from 'node:path';+import { fileURLToPath } from 'node:url';+import { execFileSync } from 'node:child_process';++let YAML;+try { YAML = await import('yaml'); } catch {+ console.error('needs the "yaml" package: npm install --no-save --no-package-lock [email protected]');+ process.exit(2);+}++const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');+const SKILLS = join(ROOT, 'skills');+const errors = [];+const fail = (where, msg) => errors.push(`${where}: ${msg}`);+const parse = (text, where) => {+ const doc = YAML.parseDocument(text, { strict: true, uniqueKeys: true, prettyErrors: true });+ for (const e of [...doc.errors, ...doc.warnings]) fail(where, `YAML ${e.name}: ${e.message.split('\n')[0]}`);+ return doc.errors.length ? null : doc.toJS();+};+const walk = (dir) => readdirSync(dir).flatMap((f) => {+ const p = join(dir, f);+ return statSync(p).isDirectory() ? (f === 'node_modules' ? [] : walk(p)) : [p];+});++// skills: frontmatter, names, descriptions, Codex metadata+const names = new Map();+for (const dir of readdirSync(SKILLS)) {+ const file = join(SKILLS, dir, 'SKILL.md');+ if (!statSync(join(SKILLS, dir)).isDirectory()) continue;+ const where = `skills/${dir}/SKILL.md`;+ if (!existsSync(file)) { fail(`skills/${dir}`, 'no SKILL.md'); continue; }+ const src = readFileSync(file, 'utf8');+ const m = src.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n/);+ if (!m) { fail(where, 'no frontmatter block at the top'); continue; }+ const fm = parse(m[1], where);+ if (!fm) continue;+ if (typeof fm.name !== 'string' || !/^[a-z0-9]+(-[a-z0-9]+)*$/.test(fm.name) || fm.name.length > 64) fail(where, `name must be kebab-case, 64 characters at most (got ${JSON.stringify(fm.name)})`);+ if (fm.name !== dir) fail(where, `name "${fm.name}" should match its folder "${dir}" (Gemini CLI and Cursor key skills by folder)`);+ if (typeof fm.description !== 'string' || !fm.description.trim()) fail(where, 'description must be a non-empty string');+ else if (fm.description.length > 1024) fail(where, `description is ${fm.description.length} characters; agents allow 1024 at most`);+ if (names.has(fm.name)) fail(where, `name "${fm.name}" is also used by ${names.get(fm.name)}`); else names.set(fm.name, where);+ if (/—/.test(src)) fail(where, 'contains an em dash');+ // every file the skill mentions under scripts/, assets/ or references/ must exist+ for (const [, ref] of src.matchAll(/`((?:scripts|assets|references)\/[^`\s]+?)`/g)) {+ if (!existsSync(join(SKILLS, dir, ref))) fail(where, `mentions ${ref}, which does not exist`);+ }+ const openai = join(SKILLS, dir, 'agents', 'openai.yaml');+ if (existsSync(openai)) {+ const o = parse(readFileSync(openai, 'utf8'), `skills/${dir}/agents/openai.yaml`);+ if (o && !o.interface?.display_name) fail(`skills/${dir}/agents/openai.yaml`, 'interface.display_name missing');+ }+}++// plugin manifests: valid JSON, names agree, and every skill path they list exists+const manifests = ['.claude-plugin/marketplace.json', '.codex-plugin/plugin.json', '.agents/plugins/marketplace.json', '.cursor-plugin/plugin.json', 'gemini-extension.json'];+const versions = new Set();+for (const rel of manifests) {+ const p = join(ROOT, rel);+ if (!existsSync(p)) { fail(rel, 'missing'); continue; }+ let j; try { j = JSON.parse(readFileSync(p, 'utf8')); } catch (e) { fail(rel, 'invalid JSON: ' + e.message); continue; }+ if (j.name !== 'cinematic-skill') fail(rel, `name is ${JSON.stringify(j.name)}, expected "cinematic-skill"`);+ for (const plugin of j.plugins || []) {+ if (plugin.version) versions.add(plugin.version);+ for (const s of [].concat(plugin.skills || [])) if (!existsSync(join(ROOT, s, 'SKILL.md'))) fail(rel, `lists ${s}, which has no SKILL.md`);+ }+ if (j.version) versions.add(j.version);+ if (typeof j.skills === 'string' && !existsSync(join(ROOT, j.skills))) fail(rel, `skills path ${j.skills} does not exist`);+ if (j.logo && !existsSync(join(ROOT, j.logo))) fail(rel, `logo ${j.logo} does not exist`);+}+if (versions.size > 1) fail('manifests', `versions disagree: ${[...versions].join(', ')}`);+// Claude Code already discovers skills/ under a plugin's source; listing them as well loads+// every skill twice (seen in `claude plugin details`), so the entry must not list them+for (const plugin of JSON.parse(readFileSync(join(ROOT, '.claude-plugin/marketplace.json'), 'utf8')).plugins) {+ if (plugin.source === './' && plugin.skills) fail('.claude-plugin/marketplace.json', `plugin "${plugin.name}" lists skills that skills/ already provides; each would load twice`);+}++// scripts parse+const files = walk(SKILLS);+for (const f of files.filter((f) => f.endsWith('.js') || f.endsWith('.mjs'))) {+ try { execFileSync(process.execPath, ['--check', f], { stdio: 'pipe' }); } catch (e) { fail(relative(ROOT, f), String(e.stderr || e).split('\n').slice(0, 3).join(' ')); }+}+const py = files.filter((f) => f.endsWith('.py'));+if (py.length) {+ const python = ['python3', 'python'].find((p) => { try { execFileSync(p, ['--version'], { stdio: 'pipe' }); return true; } catch { return false; } });+ if (!python) fail('python', 'python3 not found; cannot check scripts');+ else for (const f of py) {+ try { execFileSync(python, ['-c', 'import ast,sys; ast.parse(open(sys.argv[1]).read())', f], { stdio: 'pipe' }); }+ catch (e) { fail(relative(ROOT, f), String(e.stderr || e).split('\n').slice(-3).join(' ')); }+ }+}++if (errors.length) {+ console.error(`not ok - ${errors.length} problem(s):`);+ for (const e of errors) console.error(' ' + e);+ process.exit(1);+}+console.log(`ok - ${names.size} skills load, ${manifests.length} manifests agree, ${files.filter((f) => /\.(m?js|py)$/.test(f)).length} scripts parse`);