Skip to content

An AI skill that turns books into animated, narrated, interactive web experiences

feat(skill): picture books from a story, on top of the textbook pipeline

yzr021db9ea10bc
diff --git a/.claude/skills/papermorph/SKILL.md b/.claude/skills/papermorph/SKILL.md
index c515bb3..c6d227c 100644
--- a/.claude/skills/papermorph/SKILL.md
+++ b/.claude/skills/papermorph/SKILL.md
@@ -1,6 +1,6 @@
---
name: papermorph
-description: Make or edit animated, narrated, interactive web books from reference PDFs. Use for book planning, storyboards, chapter animation and exercises, narration, and cover and contents pages, including "make the next chapter" or "fix this animation". Deliver runnable static book files; bookshelf design, bookshelf registration and hosting are separate tasks.
+description: Make or edit animated, narrated, interactive web books from reference PDFs, and animated picture books (paper-puppet films) from a story, a joke or a fairy tale. Use for book planning, storyboards, chapter animation and exercises, narration, and cover and contents pages, including "make the next chapter", "turn this story into a picture book" or "fix this animation". Deliver runnable static book files; bookshelf design, bookshelf registration and hosting are separate tasks.
---
# Papermorph
@@ -9,6 +9,8 @@ Each chapter is a short animated lesson film: the picture carries the explanatio
What the picture should be depends on the book and on the user, so the work starts with a conversation ([intake.md](references/intake.md)) that ends in `style.json`, the book's agreed style. Every chapter is made against it. `style.json` fixes the atoms (palette and meanings, fonts, voice, cast, shared components, approved chapters); composition stays free, so how each beat is laid out and choreographed is yours to judge against it and the approved chapters. Then read the reference for the technique in use: [diagrams.md](references/diagrams.md) (symbols and diagrams that change), [scenes.md](references/scenes.md) (illustrated scenes, actors, camera), [assets.md](references/assets.md) (shared components, images, sprites), [authoring.md](references/authoring.md) (chapter shape, narration, questions), [engine.md](references/engine.md), [review.md](references/review.md), [site.md](references/site.md), [team.md](references/team.md) (making chapters with subagents).
+**Picture books** are the same machine pointed at a story: short films of paper puppets in front of sets, drawn in code or painted by an image model, with voices, effects and music. When the user brings a story, a joke or a fairy tale instead of a textbook, follow [stories.md](references/stories.md) (with [puppets.md](references/puppets.md), [painting.md](references/painting.md) and [sound.md](references/sound.md)) in place of the PDF steps; the engine, previews, review, site and team below apply unchanged.
+
Follow the pipeline forward, entering at the requested stage for existing work. User requests override defaults. Re-create explanations, examples and drawings; keep source PDFs, page images and extracted text outside the static output folder and out of version control (`.gitignore`: `*.pdf`, `books/*/pages/`). Deliver a self-contained book folder with a cover, contents, chapters and local preview instructions.
## Project layout
@@ -33,6 +35,8 @@ site/<book>/ the static book (only this is delivered)
chNN/index.html, audio/<lang>/ a lesson, its beat MP3s + timings.js
```
+A picture book adds `books/<book>/story.md` (the user's telling, verbatim), `storyboard.md`, `sets.js` (set sketches) and `art/` (generated pictures, `painted.json`, `costs.tsv`); its `site/<book>/lib/` holds the paper kit (`paper.js`, `cast.js`, `shared.js` from `assets/templates/picture-book/`) and `img/` the baked sets, props and puppet pieces; each episode `chNN/` has one script per scene and `audio/<lang>/`, `audio/sfx/`, `audio/bgm/`.
+
`SKILL` means this skill's absolute folder; `<book>` is the book slug, `<lang>` its primary language code. Existing books keep their paths. Needs: `uv`, `ffmpeg`/`ffprobe`, Edge TTS network access (or Kokoro, local: `uv run --python 3.12 --with kokoro`) and Playwright browsers (`uv run --with playwright playwright install chromium firefox`). Preview: `python3 SKILL/scripts/serve.py 8765 site` (no browser caching).
## Pipeline
diff --git a/.claude/skills/papermorph/assets/templates/picture-book/chapter.html b/.claude/skills/papermorph/assets/templates/picture-book/chapter.html
new file mode 100644
index 0000000..18afe1c
--- /dev/null
+++ b/.claude/skills/papermorph/assets/templates/picture-book/chapter.html
@@ -0,0 +1,69 @@
+<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<title>PICTURE BOOK TITLE</title>
+<link rel="stylesheet" href="../lib/engine.css">
+<link rel="expect" href="#bar" blocking="render">
+</head>
+<body>
+<!-- A picture-book episode: one beat per scene. Copy lib/*.js into site/<book>/lib/ next to the engine, this file to
+ site/<book>/chNN/index.html and scene1.js beside it. Order matters: engine, sets and baked pieces, kit, cast, the
+ audio data (tts.py: timings.js; mouths.py: mouths.js; join.py: shots.js), shared helpers, then the scenes. -->
+<script src="../lib/engine.js"></script>
+<script src="../img/sets/sets.js"></script>
+<script src="../img/puppets/baked.js" onerror="0"></script>
+<script src="../lib/paper.js"></script>
+<script src="../lib/cast.js"></script>
+<script src="audio/en/timings.js"></script>
+<script src="audio/en/mouths.js"></script>
+<script src="audio/en/shots.js"></script>
+<script src="../lib/shared.js"></script>
+<script src="scene1.js"></script>
+<script>
+'use strict';
+const CHAPTER = { number: 1, title: 'PICTURE BOOK TITLE', minutes: 2, language: 'en' }; // next: '../ch02/' once it exists
+try { if (localStorage.getItem('captions') === null) setCaptions(true); } catch {} // captions on at the first visit; the reader's own choice is kept
+
+/* ---------- beats: one per scene ----------
+ [id, title, run, { lead: false, pre }]: id names audio/en/<id>.mp3 (the joined scene clip) and its TIMINGS entry;
+ `pre` is the seconds of picture before the speech starts (the scene's PRE constant). */
+const BEATS = [
+ ['scene1', 'The visit', (m, D) => scene1(panel(0), D), { lead: false, pre: PRE1 }],
+].map(([id, title, run, extra]) => ({ id, title, run, ...extra }));
+
+/* ---------- background music ----------
+ One track per listed scene group: [file in audio/bgm/ without .mp3, [scene ids], gain]. A track's position is the
+ time since its first scene began, so pausing and seeking keep it in step; 0.8 s crossfades between tracks; the music
+ ducks to 30 % while anyone speaks and sits at 70 % otherwise. Leave BGM empty for a silent film; a scene can mute its
+ music for a moment with window.MUSIC_OFF = { sceneId: t => boolean }. */
+const BGM = [/* ['theme', ['scene1', 'scene2'], .3] */]
+ .map(([n, beats, gain]) => ({ n, beats, gain, a: Object.assign(new Audio(`audio/bgm/${n}.mp3`), { preload: 'auto', loop: true, volume: 0 }), v: 0 }));
+const beatLen = id => { const b = BEATS.find(x => x.id === id); return (b.pre || 0) + TIMINGS[id].dur + .6; };
+let lastTick = performance.now();
+function bgmTick(now) {
+ const dt = Math.min(.1, (now - lastTick) / 1000); lastTick = now;
+ const id = BEATS[P.i]?.id, on = P.started && P.playing && !P.waiting && !P.done;
+ const speaking = P.audio && !P.audio.paused && !P.audio.ended;
+ const vol = +(document.getElementById('volume')?.value ?? 1) * (speaking ? .3 : .7); // the music ducks well under the voices
+ for (const m of BGM) {
+ const k = m.beats.indexOf(id), current = on && k >= 0 && !(window.MUSIC_OFF?.[id]?.(P.t));
+ m.v = Math.max(0, Math.min(1, m.v + (current ? 1 : -1) * dt / .8));
+ m.a.volume = m.v * m.gain * vol;
+ if (current) {
+ const want = (m.beats.slice(0, k).reduce((s, b) => s + beatLen(b), 0) + P.t) % (m.a.duration || 1e9);
+ if (Math.abs(m.a.currentTime - want) > .5) m.a.currentTime = want;
+ if (m.a.paused) m.a.play().catch(() => {});
+ } else if (m.v === 0 && !m.a.paused) m.a.pause();
+ }
+ if (!on && !P.done) for (const m of BGM) m.a.pause();
+ requestAnimationFrame(bgmTick);
+}
+requestAnimationFrame(bgmTick);
+// Build every puppet and prop once at load, off screen, so their bitmaps are ready before the first beat needs them.
+paperWarm(g => { kidPuppet(g); });
+boot();
+</script>
+</body>
+</html>
diff --git a/.claude/skills/papermorph/assets/templates/picture-book/lib/cast.js b/.claude/skills/papermorph/assets/templates/picture-book/lib/cast.js
new file mode 100644
index 0000000..12b4592
--- /dev/null
+++ b/.claude/skills/papermorph/assets/templates/picture-book/lib/cast.js
@@ -0,0 +1,120 @@
+/* cast.js — the puppets, in the flat cut-paper style of South Park: a big round head straight on the body, two
+ touching eyes, a mouth low on the face, mitten hands. Built at the feet (0, 0) facing us. They turn by sliding the
+ face to one side (look -1 … 1), as that show does; the paper pieces never deform.
+ pose(o, f): x, y, s; look (face slide), eyeX/eyeY (pupils, -1 … 1), lids (0 open … 1 shut; .55 is deadpan), shut
+ (blink), mouth (a Rhubarb shape or an expression below), brow (0 none, >0 angry, <0 worried), headR, bob, squash,
+ armL/armR (degrees, + raises outward; 0 hangs at the side), legL/legR (degrees), sit (hide legs), hold (prop key).
+
+ To add a character: write another entry in SHAPES (copy `kid` and change the numbers: sx/sy the shoulder, hipX the
+ hip, body and head outlines, eyes [x, y, rx, ry], mouth [x, y], slide how far the face moves, hair [colour, path],
+ optional glasses/hat/extra/legH/cheeks/chin), then a one-line builder like kidPuppet below. A grown-up is a taller
+ body (legH 96, sy and the head moved up). Colours (coat, stripe, pants, skin) are options of the builder, so one shape
+ serves many characters. An animal or anything not built like a kid gets its own builder with the same contract
+ (build in g, bakeAll(g), return { g, pose(o, f) }) — see spKid for the pattern. */
+'use strict';
+const SP_INK = '#1d1a1a';
+// How far a shut eye's lid comes down: 1 covers it; a book may set window.SP_SHUT = .9 to leave the lid line showing.
+const SP_SHUT = window.SP_SHUT ?? 1;
+// Mouths, centred on the mouth point: Rhubarb shapes A–H and X (mouths.py writes them), plus expressions. They open downward, like the show's.
+const SP_MOUTHS = {
+ X: `<path d="M-13,0 Q0,4 13,0" fill="none" stroke="${SP_INK}" stroke-width="3" stroke-linecap="round"/>`,
+ A: `<path d="M-11,1 L11,1" stroke="${SP_INK}" stroke-width="3" stroke-linecap="round"/>`,
+ B: `<path d="M-13,-1 L13,-1 Q11,8 0,9 Q-11,8 -13,-1 Z" fill="#5a1414"/><path d="M-10,0 h20" stroke="#fff" stroke-width="2.4"/>`,
+ C: `<path d="M-14,-2 L14,-2 Q12,12 0,13 Q-12,12 -14,-2 Z" fill="#5a1414"/><ellipse cy="9" rx="7" ry="3" fill="#d9606a"/>`,
+ D: `<path d="M-18,-3 L18,-3 Q16,18 0,19 Q-16,18 -18,-3 Z" fill="#5a1414"/><ellipse cy="13" rx="10" ry="4.5" fill="#d9606a"/>`,
+ E: `<ellipse cy="3" rx="8" ry="10" fill="#5a1414"/>`,
+ F: `<ellipse cy="1" rx="5" ry="5.5" fill="#5a1414"/>`,
+ G: `<path d="M-12,-1 L12,-1 Q10,6 0,7 Q-10,6 -12,-1 Z" fill="#5a1414"/><path d="M-9,1 h18" stroke="#fff" stroke-width="3"/>`,
+ H: `<path d="M-13,-2 L13,-2 Q11,10 0,11 Q-11,10 -13,-2 Z" fill="#5a1414"/><ellipse cy="2" rx="5" ry="3" fill="#d9606a"/>`,
+ flat: `<path d="M-12,1 L12,1" stroke="${SP_INK}" stroke-width="3.2" stroke-linecap="round"/>`,
+ frown: `<path d="M-13,4 Q0,-3 13,4" fill="none" stroke="${SP_INK}" stroke-width="3" stroke-linecap="round"/>`,
+ smile: `<path d="M-15,-2 Q0,9 15,-2" fill="none" stroke="${SP_INK}" stroke-width="3" stroke-linecap="round"/>`,
+ grin: `<path d="M-18,-3 L18,-3 Q15,15 0,16 Q-15,15 -18,-3 Z" fill="#5a1414"/><path d="M-16,-1 h32 v4 q-16,3 -32,0 z" fill="#fff"/>`,
+ O: `<ellipse cy="5" rx="11" ry="14" fill="#5a1414"/>`,
+ wobble: `<path d="M-14,2 q3.5,-4 7,0 t7,0 t7,0 t7,0" fill="none" stroke="${SP_INK}" stroke-width="3" stroke-linecap="round"/>`,
+ chew: `<path d="M-12,0 Q0,-5 12,0" fill="none" stroke="${SP_INK}" stroke-width="3" stroke-linecap="round"/>`,
+};
+document.body.insertAdjacentHTML('afterbegin', `<svg width="0" height="0" style="position:absolute" aria-hidden="true"><defs>${
+ Object.entries(SP_MOUTHS).map(([k, s]) => `<g id="sp${k}">${s}</g>`).join('')}
+ <radialGradient id="spShadow"><stop offset="0" stop-color="#2a1c10" stop-opacity=".42"/><stop offset=".6" stop-color="#2a1c10" stop-opacity=".22"/><stop offset="1" stop-color="#2a1c10" stop-opacity="0"/></radialGradient></defs></svg>`);
+
+
+const UNIFORM = { coat: '#3563c0', stripe: '#f4f1ea', pants: '#25356a' };
+const SHAPES = {
+ // a kid: big round head, bowl of dark hair, thin body. Copy this entry for the next character.
+ kid: { sx: 54, sy: -146, hipX: 18, legW: 26, shoe: 20, body: 'M-44,-166 C-64,-150 -68,-78 -62,-50 Q-30,-36 0,-36 Q30,-36 62,-50 C68,-78 64,-150 44,-166 Z',
+ head: [0, -246, 92, 86], neck: -158, eyes: [24, -254, 20, 25], mouth: [0, -196], cheeks: null, slide: 28, glasses: 0,
+ hair: ['#2a1f1a', 'M-90,-258 C-94,-320 -56,-336 0,-336 C56,-336 94,-320 90,-258 L72,-280 Q0,-296 -72,-280 Z'] },
+};
+
+let spClip = 0;
+const REST_SP = { x: 0, y: 0, s: 1, look: 0, eyeX: 0, eyeY: 0, lids: 0, shut: false, mouth: 'X', brow: 0, headR: 0, bob: 0, squash: 0,
+ armL: 0, armR: 0, legL: 0, legR: 0, sit: false, hold: null, holdL: null };
+// holds: { key: svg } drawn in the hand of the screen-right arm (hold) or screen-left arm (holdL), at the mitten centre
+function spKid(parent, shape, { skin = '#f7d9bb', coat = UNIFORM.coat, stripe = UNIFORM.stripe, pants = UNIFORM.pants, holds = {} } = {}) {
+ const S = typeof shape === 'string' ? SHAPES[shape] : shape, g = mk('g', {}, parent), id = 'spc' + (++spClip);
+ const legH = S.legH || 46, [hx, hy, hrx, hry] = S.head, [ex, ey, erx, ery] = S.eyes, [mx, my] = S.mouth;
+ const arm = side => `<g data-p="arm${side}"><g filter="url(#paper)"><rect x="-14" y="-6" width="28" height="64" rx="13" fill="${coat}"/>
+ <path d="M${side === 'R' ? 7 : -7},-2 v56" stroke="${stripe}" stroke-width="5"/>
+ <circle cy="72" r="18" fill="#f2efe6"/><ellipse cx="${side === 'R' ? -14 : 14}" cy="62" rx="7" ry="10" fill="#f2efe6"/></g>
+ ${Object.entries(holds).map(([k, s]) => `<g data-p="hold${side}_${k}" transform="translate(0,72)">${s}</g>`).join('')}</g>`;
+ const leg = side => `<g data-p="leg${side}"><g filter="url(#paper)"><rect x="${-S.legW / 2}" y="0" width="${S.legW}" height="${legH}" rx="6" fill="${pants}"/>
+ <ellipse cx="${side === 'R' ? 6 : -6}" cy="${legH - 2}" rx="${S.shoe}" ry="11" fill="#1f1d1d"/></g></g>`;
+ const eye = sx => `<ellipse cx="${sx * ex}" cy="${ey}" rx="${erx}" ry="${ery}"`;
+ // a soft shadow on the ground, a little to the right: the painted sets are lit from the left
+ g.innerHTML = `<ellipse data-p="shadow" cx="${S.sx * .18}" cy="-2" rx="${S.sx + 34}" ry="16" fill="url(#spShadow)"/><g data-p="all"><g data-p="legs">${leg('L')}${leg('R')}</g>
+ <g data-p="body"><g filter="url(#paper)"><path d="${S.body}" fill="${coat}"/>
+ <path d="M-24,${S.sy - 22} L0,${S.sy + 8} L24,${S.sy - 22}" fill="none" stroke="${stripe}" stroke-width="7" stroke-linejoin="round"/>
+ ${S.extra || `<path d="M0,${S.sy + 8} V-40" stroke="#26478f" stroke-width="3"/>`}</g></g>
+ ${arm('L')}${arm('R')}
+ <g data-p="head"><g filter="url(#paper)"><ellipse cx="${hx}" cy="${hy}" rx="${hrx}" ry="${hry}" fill="${skin}"/>
+ ${S.chin ? `<path d="${S.chin}" fill="none" stroke="#d9a888" stroke-width="3" stroke-linecap="round"/>` : ''}</g>
+ <clipPath id="${id}"><ellipse cx="${hx}" cy="${hy}" rx="${hrx}" ry="${hry}"/></clipPath>
+ <g clip-path="url(#${id})"><g data-p="feat">
+ ${S.cheeks ? `<circle cx="${-S.cheeks[0]}" cy="${S.cheeks[1]}" r="13" fill="#ef9f98" opacity=".55"/><circle cx="${S.cheeks[0]}" cy="${S.cheeks[1]}" r="13" fill="#ef9f98" opacity=".55"/>` : ''}
+ <g data-p="whites" filter="url(#paper)">${eye(-1)} fill="#fff"/>${eye(1)} fill="#fff"/></g>
+ <g data-p="pupils"><circle cx="${-ex}" cy="${ey}" r="${erx * .22}" fill="${SP_INK}"/><circle cx="${ex}" cy="${ey}" r="${erx * .22}" fill="${SP_INK}"/></g>
+ <clipPath id="${id}e">${eye(-1)}/>${eye(1)}/></clipPath>
+ <g clip-path="url(#${id}e)"><g data-p="lids">
+ <rect x="${-ex - erx - 2}" y="${ey - ery * 3}" width="${2 * (ex + erx) + 4}" height="${ery * 2}" fill="${skin}"/>
+ <path d="M${-ex - erx - 2},${ey - ery} H${ex + erx + 2}" stroke="${SP_INK}" stroke-width="3"/></g></g>
+ ${eye(-1)} fill="none" stroke="${SP_INK}" stroke-width="2"/>${eye(1)} fill="none" stroke="${SP_INK}" stroke-width="2"/>
+ ${S.glasses ? `<g fill="none" stroke="${SP_INK}" stroke-width="4.5"><circle cx="${-ex}" cy="${ey}" r="${S.glasses}"/><circle cx="${ex}" cy="${ey}" r="${S.glasses}"/>
+ <path d="M${-ex + S.glasses},${ey - 4} Q0,${ey - 10} ${ex - S.glasses},${ey - 4}"/></g>` : ''}
+ <path data-p="browL" d="M${-ex - 16},${ey - ery - 12} L${-ex + 14},${ey - ery - 6}" stroke="${SP_INK}" stroke-width="4" stroke-linecap="round"/>
+ <path data-p="browR" d="M${ex + 16},${ey - ery - 12} L${ex - 14},${ey - ery - 6}" stroke="${SP_INK}" stroke-width="4" stroke-linecap="round"/>
+ <use class="mouth" href="#spX" transform="translate(${mx},${my})"/></g></g>
+ <g data-p="hair"><g filter="url(#paper)"><path d="${S.hair[1]}" fill="${S.hair[0]}"/>${S.hat || ''}</g></g></g></g>`;
+ bakeAll(g);
+ const P = pieces(g), holdKeys = Object.keys(holds);
+ const legY = -(legH + 6), ery2 = ery * 2;
+ return { g, S, pose(o, f) {
+ o = { ...REST_SP, ...o };
+ const j = k => .35 * jit(f >> 1, k); // the animator's hand: small, and held for two frames
+ tf(g, `translate(${(o.x + j(1) * .8).toFixed(1)},${(o.y + j(2) * .6).toFixed(1)}) scale(${o.s})`);
+ // squash > 0 flattens the figure on its feet (a landing, a sigh)
+ tf(P.all, `translate(0,${o.bob.toFixed(1)}) scale(${(1 + .5 * o.squash).toFixed(3)},${(1 - o.squash).toFixed(3)}) rotate(${(j(3) * .4).toFixed(2)})`);
+ vis(P.legs, !o.sit); vis(P.shadow, !o.sit);
+ tf(P.legL, `translate(${-S.hipX},${legY}) rotate(${(o.legL + j(4) * .5).toFixed(2)})`);
+ tf(P.legR, `translate(${S.hipX},${legY}) rotate(${(-o.legR + j(5) * .5).toFixed(2)})`);
+ tf(P.armL, `translate(${-S.sx},${S.sy}) rotate(${(24 + o.armL + j(6) * .6).toFixed(2)})`);
+ tf(P.armR, `translate(${S.sx},${S.sy}) rotate(${(-24 - o.armR + j(7) * .6).toFixed(2)})`);
+ for (const k of holdKeys) { vis(P[`holdR_${k}`], o.hold === k); vis(P[`holdL_${k}`], o.holdL === k);
+ // a held thing stays upright whatever the arm does
+ tf(P[`holdR_${k}`], `translate(0,72) rotate(${(24 + o.armR).toFixed(2)})`); tf(P[`holdL_${k}`], `translate(0,72) rotate(${(-24 - o.armL).toFixed(2)})`); }
+ tf(P.head, `rotate(${(o.headR + j(8) * .6).toFixed(2)},0,${S.neck})`);
+ const lx = o.look * S.slide;
+ tf(P.feat, `translate(${lx.toFixed(1)},0)`); tf(P.hair, `translate(${(lx * .25).toFixed(1)},0)`);
+ tf(P.pupils, `translate(${(o.eyeX * erx * .5).toFixed(1)},${(o.eyeY * ery * .45).toFixed(1)})`);
+ tf(P.lids, `translate(0,${((o.shut ? SP_SHUT : o.lids) * ery2).toFixed(1)})`);
+ const b = o.brow;
+ vis(P.browL, b !== 0); vis(P.browR, b !== 0);
+ tf(P.browL, `rotate(${(-14 * b).toFixed(1)},${-ex},${ey - ery - 9})`); tf(P.browR, `rotate(${(14 * b).toFixed(1)},${ex},${ey - ery - 9})`);
+ const m = g.querySelector('.mouth'), href = '#sp' + (o.mouth || 'X'); if (m._m !== href) m.setAttribute('href', m._m = href);
+ } };
+}
+const kidPuppet = (p, o) => spKid(p, 'kid', o); // kidPuppet(parent, { coat, stripe, pants, skin, holds: { key: svg } })
+
+// A walk in the show's manner: the figure bobs on twos and the stubby legs scissor. (For feet that never slide on the
+// ground, use walk() in paper.js, which also tells how far the hip has travelled.)
+function spWalk(q) { const k = Math.floor(q * FPS / 2) % 2 ? 1 : -1; return { legL: 16 * k, legR: -16 * k, bob: k > 0 ? -6 : 0, armL: 8 * k, armR: -8 * k, k }; }
diff --git a/.claude/skills/papermorph/assets/templates/picture-book/lib/paper.js b/.claude/skills/papermorph/assets/templates/picture-book/lib/paper.js
new file mode 100644
index 0000000..74a0d48
--- /dev/null
+++ b/.claude/skills/papermorph/assets/templates/picture-book/lib/paper.js
@@ -0,0 +1,227 @@
+/* paper.js — a paper-cutout stop-motion kit on top of the engine.
+ Sets are baked bitmaps (img/sets/, from SKILL/scripts/bake_sets.py or painted.py); puppets are live SVG pieces with the
+ same paper filter. Everything moves on a 12 fps clock (on twos), each frame with its own small hand jitter, so
+ pause, seek and ?beat=N&t=S show exactly the frame a viewer would see. */
+'use strict';
+const FPS = 12;
+
+// Filters, mouths and patterns live in their own hidden SVG: the engine clears the scene at every beat.
+const PAPER_DEFS = `<defs>
+ <filter id="paper" x="-15%" y="-15%" width="130%" height="135%" color-interpolation-filters="sRGB">
+ <feTurbulence type="fractalNoise" baseFrequency="0.035" numOctaves="2" seed="3" result="warp"/>
+ <feDisplacementMap in="SourceGraphic" in2="warp" scale="3.5" xChannelSelector="R" yChannelSelector="G" result="cut"/>
+ <feTurbulence type="fractalNoise" baseFrequency="0.75" numOctaves="3" seed="7" result="fib"/>
+ <feColorMatrix in="fib" type="matrix" values="0 0 0 0 .25 0 0 0 0 .17 0 0 0 0 .08 .5 0 0 0 -.14" result="tint"/>
+ <feComposite in="tint" in2="cut" operator="in" result="grain"/>
+ <feMerge result="tex"><feMergeNode in="cut"/><feMergeNode in="grain"/></feMerge>
+ <feDropShadow in="tex" dx="2.5" dy="3.5" stdDeviation="2.2" flood-color="#2a1608" flood-opacity=".38"/>
+ </filter>
+ <pattern id="check" width="10" height="10" patternUnits="userSpaceOnUse">
+ <rect width="10" height="10" fill="#f6efe0"/><rect width="5" height="5" fill="#c8322f"/><rect x="5" y="5" width="5" height="5" fill="#c8322f"/>
+ </pattern>
+ <g id="mX"><path d="M-8,-1 Q0,6 8,-1" fill="none" stroke="#5a2a1e" stroke-width="2.6" stroke-linecap="round"/></g>
+ <g id="mA"><path d="M-7,1 L7,1" fill="none" stroke="#5a2a1e" stroke-width="2.6" stroke-linecap="round"/></g>
+ <g id="mB"><ellipse rx="6.5" ry="2.6" fill="#6b1f1f"/></g>
+ <g id="mC"><ellipse rx="7" ry="4.6" fill="#6b1f1f"/><ellipse cy="2.6" rx="4" ry="1.8" fill="#e07a78"/></g>
+ <g id="mD"><path d="M-9,-3 Q0,-5 9,-3 Q8,9 0,10 Q-8,9 -9,-3Z" fill="#6b1f1f"/><ellipse cy="6.5" rx="5" ry="2.6" fill="#e07a78"/></g>
+ <g id="mE"><ellipse rx="5" ry="6" fill="#6b1f1f"/></g>
+ <g id="mF"><circle r="3.6" fill="#6b1f1f"/></g>
+ <g id="mG"><ellipse rx="6.5" ry="2.6" fill="#6b1f1f"/><path d="M-5,-1.5 h10" stroke="#f6efe0" stroke-width="2"/></g>
+ <g id="mH"><ellipse rx="6" ry="3.8" fill="#6b1f1f"/><ellipse cy="-1" rx="2.6" ry="1.6" fill="#e07a78"/></g>
+ <radialGradient id="vignette" cx="50%" cy="45%" r="75%"><stop offset="60%" stop-color="#1e0f05" stop-opacity="0"/><stop offset="100%" stop-color="#1e0f05" stop-opacity=".45"/></radialGradient>
+</defs>`;
+document.body.insertAdjacentHTML('afterbegin', `<svg width="0" height="0" style="position:absolute" aria-hidden="true">${PAPER_DEFS}</svg>`);
+// The exposure flicker is an HTML layer over the stage: changing it every frame inside the SVG would repaint the whole picture.
+const FLICKER = document.getElementById('stage').insertAdjacentElement('afterend', Object.assign(document.createElement('div'),
+ { style: 'position:absolute;left:0;top:0;width:1600px;height:900px;background:#000;opacity:0;pointer-events:none;will-change:opacity' }));
+
+// Seeded noise in [-1, 1]: the same frame always gets the same jitter.
+function jit(f, k) { let h = Math.imul(f * 374761393 + k * 668265263, 1274126177); h ^= h >>> 13; h = Math.imul(h, 1103515245); return ((h ^ (h >>> 16)) >>> 0) / 2147483648 - 1; }
+const ease = x => x <= 0 ? 0 : x >= 1 ? 1 : x * x * (3 - 2 * x);
+const span = (t, a, b) => ease((t - a) / (b - a));
+
+// draw(q, f) runs once per 12 fps frame with q the frame's time; a pure function of time, like every beat clock.
+function stopClock(D, draw) { let last = null; clockRun(t => { const f = Math.floor(t * FPS + 1e-6); if (f === last) return; last = f; draw(f / FPS, f); }, D); }
+
+/* ---------- camera over a baked set ----------
+ A view {x, y, z} is the world point at the frame's centre and the zoom. Moves: to(view, t0, dur) eases each given
+ key from where the camera is at t0 (zooms keep one world point still, as the engine's camera does); cut(view, t0).
+ Layers slide by their parallax factor k against the base view. soft(t0, on) swaps the far layers (k < 1) for their
+ blurred copies: shallow focus on close shots (on = 'all' blurs the puppets' plane too, for a set seen behind a close-up). Puppets go in cam.stage, on the k = 1 plane in front of `after`. */
+function paperCam(p, setName, v0 = {}, { after = null, stages = [] } = {}) {
+ const root = mk('g', {}, p), view = mk('g', {}, root), world = mk('g', {}, view), layers = [], ops = [], softs = [], shakes = [];
+ let stage = null; const stageAt = {};
+ for (const L of SETS[setName]) {
+ const g = mk('g', {}, world), [x, y, width, height] = L.box, img = { x, y, width, height, preserveAspectRatio: 'none' };
+ const sharp = mk('image', { href: `../img/sets/${setName}/${L.name}.webp`, ...img }, g);
+ const blur = L.soft ? mk('image', { href: `../img/sets/${setName}/${L.name}-soft.webp`, ...img, visibility: 'hidden' }, g) : null;
+ layers.push({ g, k: L.k, sharp, blur, name: L.name });
+ if (stages.includes(L.name)) layers.push({ g: stageAt[L.name] = mk('g', {}, world), k: L.k });
+ if (L.name === (after || 'house') || (!after && L.k === 1 && !stage)) layers.push({ g: stage = mk('g', {}, world), k: 1 });
+ }
+ mk('rect', { width: 1600, height: 900, fill: 'url(#vignette)' }, root);
+ // Parallax is measured from the set's own framing (base), wherever the beat's first view is.
+ const base = { x: 800, y: 450, z: 1 }, start = { ...base, ...v0 };
+ function at(t, n = ops.length) {
+ const s = { ...start };
+ for (let i = 0; i < n && ops[i].t0 <= t; i++) {
+ const o = ops[i], a = o.from || (o.from = at(o.t0, i)), q = o.dur ? ease(Math.min(1, (t - o.t0) / o.dur)) : 1;
+ const v = {}; for (const k in o.v) v[k] = typeof o.v[k] === 'function' ? o.v[k](t) : o.v[k]; // a key may follow
+ if ('z' in v) s.z = a.z * (v.z / a.z) ** q;
+ const u = 'z' in v && Math.abs(v.z - a.z) > 1e-6 ? (1 / s.z - 1 / a.z) / (1 / v.z - 1 / a.z) : q;
+ for (const k of ['x', 'y']) if (k in v) s[k] = a[k] + (v[k] - a[k]) * u;
+ }
+ return s;
+ }
+ const cam = { root, world, stage, stageAt, at,
+ to(v, t0, dur = 1) { ops.push({ v, t0, dur }); ops.sort((a, b) => a.t0 - b.t0); ops.forEach(o => delete o.from); return cam; },
+ cut: (v, t0) => cam.to(v, t0, 0),
+ show(name, on) { for (const L of layers) if (L.name === name) vis(L.g, on); return cam; }, // swap a set layer (weather)
+ soft(t0, on) { softs.push([t0, on]); softs.sort((a, b) => a[0] - b[0]); return cam; },
+ shake(t0, dur, amp = 10) { shakes.push([t0, dur, amp]); return cam; },
+ apply(q, f) {
+ const s = at(q);
+ let sx = 0, sy = 0;
+ for (const [t0, d, amp] of shakes) if (q >= t0 && q < t0 + d) { sx += jit(f, 91) * amp; sy += jit(f, 92) * amp; }
+ view.setAttribute('transform', `translate(${800 + sx} ${450 + sy}) scale(${s.z}) translate(${-s.x} ${-s.y})`);
+ const dx = s.x - base.x, dy = s.y - base.y;
+ let soft = false; for (const [t0, on] of softs) if (q >= t0) soft = on;
+ for (const L of layers) {
+ L.g.setAttribute('transform', `translate(${((1 - L.k) * dx).toFixed(1)} ${((1 - L.k) * dy).toFixed(1)})`);
+ if (L.blur) { const b = soft === 'all' || (soft && L.k < 1); vis(L.blur, b); vis(L.sharp, !b); } // never 'visible': it would show through a hidden camera
+ }
+ FLICKER.style.opacity = (.02 + .02 * jit(f, 30)).toFixed(3); // the exposure flicker of real frames
+ },
+ };
+ return cam;
+}
+
+/* ---------- small live pieces ---------- */
+// Chimney smoke: paper puffs that rise, drift and fade, one cycle every `every` seconds.
+function smoke(parent, x, y, n = 4, every = 3.2) {
+ const puffs = Array.from({ length: n }, () => { const g = mk('g', {}, parent); g.innerHTML = '<g filter="url(#paper)"><circle r="20" fill="#f4ecdc"/></g>'; return g; });
+ bakeAll(parent);
+ return q => puffs.forEach((g, i) => {
+ const u = ((q / every + i / n) % 1 + 1) % 1;
+ tf(g, `translate(${(x + 60 * u + 12 * Math.sin(u * 6)).toFixed(1)},${(y - 190 * u).toFixed(1)}) scale(${((14 + 30 * u) / 20).toFixed(3)})`);
+ g.setAttribute('opacity', (Math.min(1, u * 5) * (1 - u) * .95).toFixed(2));
+ });
+}
+
+// The mouth shape a clip's cues give `t` seconds into it ('X' rest before and after).
+const mouthAt = (clip, t) => { let m = 'X'; if (t < 0) return m; for (const [at, k] of MOUTHS[clip] || []) { if (at > t) break; m = k; } return m; };
+
+/* ---------- puppets ----------
+ A puppet is paper pieces on brass pins, built at its hip (0, 0) facing right, feet near y 166. pose(o, f) sets the
+ whole state for frame f; any key left out keeps its rest value. turn (1 … -1) squashes the flat figure to turn it
+ round: through the thin middle (|turn| < .55) the front head shows, past it the figure is the mirrored profile. */
+const pinAt = (x, y) => `<circle cx="${x}" cy="${y}" r="3.4" fill="#caa24c" stroke="#7d5f22" stroke-width="1.2"/>`;
+const tf = (el, s) => { if (el._t !== s) el.setAttribute('transform', el._t = s); };
+const vis = (el, on) => { const v = on ? 'inherit' : 'hidden'; if (el._v !== v) el.setAttribute('visibility', el._v = v); };
+
+function pieces(g) { const o = {}; g.querySelectorAll('[data-p]').forEach(e => o[e.dataset.p] = e); return o; }
+function face(h, o) { // eyes and mouth of one head
+ h.querySelectorAll('.eyeO').forEach(e => vis(e, !o.shut)); h.querySelectorAll('.eyeC').forEach(e => vis(e, !!o.shut));
+ h.querySelectorAll('.mouth').forEach(e => { const m = '#m' + (o.mouth || 'X'); if (e._m !== m) e.setAttribute('href', e._m = m); });
+}
+// Blinks: closed for two frames at each listed time.
+const blinking = (q, times) => times.some(b => q >= b && q < b + 2 / FPS);
+
+/* ---------- baking puppet pieces ----------
+ Running the paper filter live on every piece costs too much once a close-up enlarges them, so every filtered
+ piece is drawn once to a bitmap (at RES px per unit) and replaced by that image. Parts that change (eyes, mouths,
+ brows, pieces with data-p) stay live; a filtered live part is baked on its own. Identical pieces share one bitmap. */
+const RES = 4, bakedReady = new Map(), bakedJobs = new Map(), PAPER_EXTRA = []; // extra defs (patterns) other files add
+// Pieces baked ahead of time (SKILL/scripts/bake_puppets.py): img/puppets/<hash>.webp, listed in
+// window.BAKED. A piece missing from it (just edited) is baked here in the browser; ?bake ignores the list.
+const BAKED = new URLSearchParams(location.search).has('bake') ? {} : (window.BAKED || {});
+const keyHash = k => { let h = 2166136261; for (let i = 0; i < k.length; i++) h = Math.imul(h ^ k.charCodeAt(i), 16777619); return (h >>> 0).toString(16).padStart(8, '0'); };
+const isLive = e => e.hasAttribute('data-p') || ['eyeO', 'eyeC', 'mouth'].some(c => e.classList.contains(c));
+function rasterize(svg, w, h) {
+ return new Promise((ok, no) => {
+ const img = new Image();
+ img.onload = () => { const c = document.createElement('canvas'); c.width = w; c.height = h; c.getContext('2d').drawImage(img, 0, 0, w, h); URL.revokeObjectURL(img.src); c.toBlob(b => ok(URL.createObjectURL(b))); };
+ img.onerror = no;
+ img.src = URL.createObjectURL(new Blob([svg], { type: 'image/svg+xml' }));
+ });
+}
+function bakeAll(root) {
+ // Measure everything first, then change the DOM: a getBBox after each change would lay the page out again every time.
+ const covered = el => { for (let c = el, a = el.parentNode; a && a !== root; c = a, a = a.parentNode) if (isLive(c)) return false; else if (a.hasAttribute?.('filter')) return true; return false; };
+ const items = [];
+ for (const el of root.querySelectorAll('[filter]')) {
+ if (covered(el)) continue; // drawn into a filtered ancestor's bitmap
+ const bb = el.getBBox(), x = Math.floor(bb.x - 10), y = Math.floor(bb.y - 10), w = Math.ceil(bb.width + 22), h = Math.ceil(bb.height + 24);
+ const clone = el.cloneNode(true);
+ ['transform', 'visibility', 'data-p', 'opacity'].forEach(a => clone.removeAttribute(a));
+ [...clone.children].forEach((c, i) => { if (isLive(el.children[i])) c.remove(); });
+ items.push({ el, x, y, w, h, html: clone.outerHTML });
+ }
+ const jobs = [];
+ for (const { el, x, y, w, h, html } of items) {
+ const key = `${x} ${y} ${w} ${h}|${html}`;
+ const apply = url => {
+ if (!el.hasAttribute('filter')) return;
+ el.removeAttribute('filter');
+ [...el.children].forEach(c => { if (!isLive(c)) c.remove(); });
+ el.insertBefore(mk('image', { href: url, x, y, width: w, height: h }), el.firstChild);
+ };
+ const file = BAKED[keyHash(key)];
+ if (file) { apply(`../img/puppets/${file}`); continue; }
+ if (bakedReady.has(key)) { apply(bakedReady.get(key)); continue; }
+ if (!bakedJobs.has(key)) bakedJobs.set(key, rasterize(`<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="${w * RES}" height="${h * RES}" viewBox="${x} ${y} ${w} ${h}">${PAPER_DEFS}<defs>${PAPER_EXTRA.join('')}</defs>${html}</svg>`, w * RES, h * RES)
+ .then(url => (bakedReady.set(key, url), url)));
+ jobs.push(bakedJobs.get(key).then(apply));
+ }
+ return Promise.all(jobs);
+}
+// Build the book's pieces once at load, off screen, so their bitmaps are ready before the first beat needs them.
+function paperWarm(build) {
+ const svg = mk('svg', { width: 1, height: 1, style: 'position:absolute;left:-10px;top:-10px' });
+ document.body.appendChild(svg);
+ build(mk('g', {}, svg));
+ return bakeAll(svg).then(() => svg.remove());
+}
+
+/* ---------- walking ----------
+ A compass walk: the stance foot stays planted while the hip rides over it, so feet never slide. tau seconds into
+ the walk, `period` s per two steps; returns leg angles and knee bends (degrees), how far the hip has travelled (d)
+ and how far it has dropped from standing (drop), both in the puppet's own units. */
+function walk(tau, { L = 166, A = 22, period = 1, knee = 38 } = {}) {
+ tau = Math.max(0, tau);
+ const a = A * Math.PI / 180, ph = 2 * Math.PI * tau / period, j = Math.floor((ph + Math.PI / 2) / Math.PI);
+ const ts = (j % 2 ? 1 : -1) * a * Math.sin(ph), near = a * Math.sin(ph) * 180 / Math.PI;
+ const swing = knee * Math.max(0, Math.cos(ph - j * Math.PI)), nearStance = j % 2 === 1;
+ return { ph, d: j * 2 * L * Math.sin(a) - L * Math.sin(ts), drop: L * (1 - Math.cos(ts)),
+ near, far: -near, kNear: nearStance ? 0 : swing, kFar: nearStance ? swing : 0 };
+}
+
+// A piece of the set that sits in front of puppets (a trunk, a bush, a blanket): drawn like a puppet piece, baked.
+function prop(parent, svg, attrs = {}) { const g = mk('g', attrs, parent); g.innerHTML = svg; bakeAll(g); return g; }
+
+// The iris closing on (cx, cy) between t0 and t0 + dur, as in old films; then black.
+function iris(p, t0, dur, cx, cy) {
+ const e = mk('path', { fill: '#120a05', 'fill-rule': 'evenodd' }, p);
+ return q => {
+ const u = (q - t0) / dur; vis(e, u > 0);
+ if (u <= 0) return;
+ const r = Math.max(0, 1900 * (1 - ease(Math.min(1, u))));
+ e.setAttribute('d', `M-50,-50 H1650 V950 H-50 Z M${cx - r},${cy} a${r},${r} 0 1 0 ${2 * r},0 a${r},${r} 0 1 0 ${-2 * r},0 Z`);
+ };
+}
+// A scene change: a tree trunk (or any dark foreground, redraw it) passing close in front of the camera, right to left: 'in' ends with the frame covered (a scene
+// ends), 'out' starts covered and uncovers it (the next scene begins).
+function trunkWipe(p, t0, dur, mode = 'in') {
+ const g = mk('g', {}, p);
+ g.innerHTML = `<g filter="url(#paper)"><path d="M0,-40 C40,200 -30,600 20,940 L2100,940 L2100,-40 Z" fill="#5a3b24"/>
+ ${[160, 420, 700, 980, 1300, 1600].map((x, i) => `<path d="M${x},-40 C${x + 30},${200 + i * 40} ${x - 40},${560 - i * 30} ${x + 10},940" stroke="#46301d" stroke-width="${10 + (i % 3) * 5}" fill="none"/>`).join('')}</g>`;
+ bakeAll(g);
+ const [a, b] = mode === 'in' ? [1650, -200] : [-200, -2150];
+ return q => { const u = Math.min(1, Math.max(0, (q - t0) / dur)); vis(g, mode === 'in' ? u > 0 : u < 1); tf(g, `translate(${(a + (b - a) * ease(u)).toFixed(0)},0)`); };
+}
+// The title card at the end: a paper label that drops in on its pin.
+function endCard(p, t0) {
+ const g = prop(p, `<g filter="url(#paper)"><rect x="560" y="330" width="480" height="240" rx="14" fill="#f3e9d2"/><rect x="580" y="350" width="440" height="200" rx="8" fill="none" stroke="#c8322f" stroke-width="5"/></g>
+ <text x="800" y="478" text-anchor="middle" font-family="Georgia, serif" font-size="78" font-style="italic" fill="#5a2a1e">The End</text>${pinAt(800, 342)}`);
+ return q => { const u = (q - t0) * FPS; vis(g, u >= 0); const d = [-60, -20, 8, -3, 0][Math.min(4, Math.max(0, Math.floor(u / 2)))]; tf(g, `translate(0,${d})`); };
+}
diff --git a/.claude/skills/papermorph/assets/templates/picture-book/lib/shared.js b/.claude/skills/papermorph/assets/templates/picture-book/lib/shared.js
new file mode 100644
index 0000000..a783eb9
--- /dev/null
+++ b/.claude/skills/papermorph/assets/templates/picture-book/lib/shared.js
@@ -0,0 +1,40 @@
+/* shared.js — what every scene of the book uses: timing helpers, painted props, and the sound effects. Put the book's
+ recurring places and props here too (a classroom or a street built the same way whenever it appears, so the staging
+ matches across cuts): a function like `function room(p) { const cam = paperCam(p, 'room'); … return { cam, … }; }`. */
+'use strict';
+// Beat-clock time of `t` seconds into clip `clip` of a joined scene whose speech starts `pre` s in (join.py's `parts`).
+const clipAt = (scene, pre, clip, t = 0) => pre + TIMINGS[scene].parts[clip] + t;
+// Beat-clock time of the n-th caption cue (one per sentence) of a joined scene: for cutting on sentences.
+const cueAt = (scene, pre, n) => pre + TIMINGS[scene].cues[n][0];
+const onTwos = q => Math.floor(q * FPS / 2) % 2 ? 1 : -1;
+const between = (q, a, b) => q >= a && q < b;
+const tween = (q, t0, d, a, b) => a + (b - a) * span(q, t0, t0 + d);
+// Who is speaking: the mouth for this frame from the listed clips of a joined scene, or 'X' (rest).
+const lips = (q, scene, pre, ...clips) => { for (const c of clips) { const m = mouthAt(c, q - clipAt(scene, pre, c)); if (m !== 'X') return m; } return 'X'; };
+// Chewing on twos: the mouth alternates between two shapes.
+const chew = q => onTwos(q) > 0 ? 'chew' : 'A';
+
+/* ---------- painted props (img/props/<name>.webp, from painted.py) ---------- */
+// A picture at (x, y), w by h, to hold in a puppet's hand (holds: { key: svg }) or drop into prop().
+const artSVG = (name, x, y, w, h) => `<image href="../img/props/${name}.webp" x="${x}" y="${y}" width="${w}" height="${h}"/>`;
+
+/* ---------- sound effects ----------
+ sfx(beat, at, name, vol): play audio/sfx/<name>.mp3 (SKILL/scripts/sfx.py) when the clock of beat `beat` passes `at`
+ in normal playback (seeking past it does not fire it). Pausing stops them. They play at half volume under the voices. */
+const SFX = [], sfxOn = [];
+const sfx = (beat, at, name, vol = 1) => SFX.push({ beat, at, name, vol });
+let sfxLast = { i: -1, t: 0 };
+function sfxTick() {
+ const id = BEATS[P.i]?.id, on = P.started && P.playing && !P.waiting && !P.done;
+ if (on && sfxLast.i === P.i && P.t > sfxLast.t && P.t - sfxLast.t < .5)
+ for (const e of SFX) if (e.beat === id && e.at > sfxLast.t && e.at <= P.t) {
+ const a = new Audio(`audio/sfx/${e.name}.mp3`);
+ a.volume = .5 * e.vol * +(document.getElementById('volume')?.value ?? 1); // effects sit under the voices
+ a.playbackRate = P.rate || 1;
+ a.play().catch(() => {}); sfxOn.push(a); a.onended = () => sfxOn.splice(sfxOn.indexOf(a), 1);
+ }
+ if (!on) while (sfxOn.length) sfxOn.pop().pause();
+ sfxLast = { i: P.i, t: P.t };
+ requestAnimationFrame(sfxTick);
+}
+requestAnimationFrame(sfxTick);
diff --git a/.claude/skills/papermorph/assets/templates/picture-book/narration.en.json b/.claude/skills/papermorph/assets/templates/picture-book/narration.en.json
new file mode 100644
index 0000000..6a071fb
--- /dev/null
+++ b/.claude/skills/papermorph/assets/templates/picture-book/narration.en.json
@@ -0,0 +1,15 @@
+{
+ "engine": "edge",
+ "voice": "en-GB-RyanNeural",
+ "rate": "+0%",
+ "voices": {
+ "kid": { "voice": "en-US-AnaNeural", "rate": "+0%", "pitch": "+0Hz" },
+ "dad": { "voice": "en-US-GuyNeural", "rate": "-5%", "pitch": "-10Hz" }
+ },
+ "beats": {
+ "s01": "Once upon a time, a kid knocked on the door.",
+ "s02": { "speaker": "kid", "text": "Dad? Are you home?" },
+ "s02b": { "speaker": "dad", "text": "[[open]]Of course I am. Come in." },
+ "s03": { "speaker": "kid", "text": "Good. I brought you a cat." }
+ }
+}
diff --git a/.claude/skills/papermorph/assets/templates/picture-book/painted.json b/.claude/skills/papermorph/assets/templates/picture-book/painted.json
new file mode 100644
index 0000000..62eb5dd
--- /dev/null
+++ b/.claude/skills/papermorph/assets/templates/picture-book/painted.json
@@ -0,0 +1,13 @@
+{
+ "frame": [1600, 900],
+ "pad": [60, 34],
+ "fonts": { "sign": "/System/Library/Fonts/STHeiti Medium.ttc" },
+ "sets": {
+ "room": [
+ { "name": "wall", "file": "bg-room.png",
+ "words": [{ "x": 800, "y": 200, "size": 60, "text": "WELCOME", "colour": "#f6d68a", "font": "sign" }] },
+ { "name": "table", "file": "table.png", "cut": { "x": 1000, "bottom": 860, "width": 520 } }
+ ]
+ },
+ "props": { "cat": "p-cat.png" }
+}
diff --git a/.claude/skills/papermorph/assets/templates/picture-book/scene1.js b/.claude/skills/papermorph/assets/templates/picture-book/scene1.js
new file mode 100644
index 0000000..985d0e0
--- /dev/null
+++ b/.claude/skills/papermorph/assets/templates/picture-book/scene1.js
@@ -0,0 +1,26 @@
+/* scene1.js — one scene of the film = one beat: a set, two puppets, a joined voice track, a sound effect. Copy it for
+ scene2.js … and list them in chapter.html. A scene is a pure function of time: stopClock calls the drawing once per
+ 12 fps frame with q, the beat's clock, so pause, seek and ?beat=N&t=S show exactly the frame a viewer would see.
+ Cut shots with cam.cut(view, t0), move with cam.to(view, t0, dur); a close-up on whoever speaks is a cut, not a zoom.
+ Build the scene's pictures first (outside stopClock), then pose every puppet every frame. */
+'use strict';
+const PRE1 = 1.0; // seconds of picture before the first word (the beat's `pre`)
+
+function scene1(p, D) {
+ const cam = paperCam(p, 'room'); // the set 'room' from img/sets/sets.js; puppets go in cam.stage
+ cam.cut({ x: 800, y: 450, z: 1 }, 0).to({ x: 860, y: 470, z: 1.12 }, 1, 9); // a slow push-in
+ const kid = kidPuppet(cam.stage, { coat: '#c94a3c', stripe: '#c94a3c' });
+ const dad = kidPuppet(cam.stage, { coat: '#3e7fc4', stripe: '#f4f1ea' });
+ sfx('scene1', .3, 'knock'); // audio/sfx/knock.mp3 (SKILL/scripts/sfx.py)
+ const enter = clipAt('scene1', PRE1, 's02'); // when the kid's first line starts
+
+ stopClock(D, (q, f) => {
+ cam.apply(q, f);
+ const walkIn = span(q, .1, enter - .2); // the kid walks in from the left, then stands
+ const w = spWalk(q), moving = walkIn > 0 && walkIn < 1;
+ kid.pose({ x: -200 + 780 * walkIn, y: 800, s: .95, look: .6, mouth: lips(q, 'scene1', PRE1, 's02', 's03'),
+ ...(moving ? { legL: w.legL, legR: w.legR, bob: w.bob } : {}), shut: blinking(q, [2.4, 6.1]) }, f);
+ dad.pose({ x: 1250, y: 800, s: 1, look: -.6, mouth: lips(q, 'scene1', PRE1, 's02b'), brow: q > enter ? -.3 : 0,
+ shut: blinking(q, [3.3]) }, f);
+ });
+}
diff --git a/.claude/skills/papermorph/assets/templates/picture-book/sets.js b/.claude/skills/papermorph/assets/templates/picture-book/sets.js
new file mode 100644
index 0000000..0d068f1
--- /dev/null
+++ b/.claude/skills/papermorph/assets/templates/picture-book/sets.js
@@ -0,0 +1,53 @@
+// Paper sets, drawn once and baked to bitmaps: uv run --with playwright --with pillow python SKILL/scripts/bake_sets.py
+// books/<book>/art/sets.js site/<book>
+// The paper filters are too heavy to run on large layers every frame. Each set is a function returning a list of
+// layers back to front: {name, k, box: [x, y, w, h] in world px, scale, svg, soft?}.
+// k parallax: 1 moves with the puppets' plane, below 1 is farther (slides less when the camera pans).
+// scale bitmap pixels per world px (1.2 is plenty for a 1600 x 900 frame; raise it for layers a close-up fills).
+// soft false skips the blurred -soft copy (use it for small foreground pieces); the camera swaps the copy in for
+// shallow focus on close shots.
+// The puppets stand on the first k = 1 layer ('floor' below) and in front of it; layers after it hide them (the table).
+// Give a layer more room than the 1600 x 900 frame (here -100 … 1700) so a pan or shake never shows its edge.
+// These sketches are a finished look on their own (free) and the composition reference an image model repaints:
+// bake one, give the picture to paint.py as a reference, and put the result in with painted.py.
+const DEFS = `<defs>
+ <filter id="paper" x="-15%" y="-15%" width="130%" height="135%" color-interpolation-filters="sRGB">
+ <feTurbulence type="fractalNoise" baseFrequency="0.035" numOctaves="2" seed="3" result="warp"/>
+ <feDisplacementMap in="SourceGraphic" in2="warp" scale="3.5" xChannelSelector="R" yChannelSelector="G" result="cut"/>
+ <feTurbulence type="fractalNoise" baseFrequency="0.75" numOctaves="3" seed="7" result="fib"/>
+ <feColorMatrix in="fib" type="matrix" values="0 0 0 0 .25 0 0 0 0 .17 0 0 0 0 .08 .5 0 0 0 -.14" result="tint"/>
+ <feComposite in="tint" in2="cut" operator="in" result="grain"/>
+ <feMerge result="tex"><feMergeNode in="cut"/><feMergeNode in="grain"/></feMerge>
+ <feDropShadow in="tex" dx="2.5" dy="3.5" stdDeviation="2.2" flood-color="#2a1608" flood-opacity=".38"/>
+ </filter>
+ <filter id="paperBig" x="-5%" y="-10%" width="110%" height="125%" color-interpolation-filters="sRGB">
+ <feTurbulence type="fractalNoise" baseFrequency="0.02" numOctaves="2" seed="5" result="warp"/>
+ <feDisplacementMap in="SourceGraphic" in2="warp" scale="5" xChannelSelector="R" yChannelSelector="G" result="cut"/>
+ <feTurbulence type="fractalNoise" baseFrequency="0.7" numOctaves="3" seed="11" result="fib"/>
+ <feColorMatrix in="fib" type="matrix" values="0 0 0 0 .25 0 0 0 0 .17 0 0 0 0 .08 .5 0 0 0 -.15" result="tint"/>
+ <feComposite in="tint" in2="cut" operator="in" result="grain"/>
+ <feMerge result="tex"><feMergeNode in="cut"/><feMergeNode in="grain"/></feMerge>
+ <feDropShadow in="tex" dx="4" dy="6" stdDeviation="5" flood-color="#2a1608" flood-opacity=".32"/>
+ </filter>
+</defs>`;
+// Wrap shapes in the paper filter: 'paper' for pieces, 'paperBig' for large flat areas.
+const P = (body, f = 'paper') => `<g filter="url(#${f})">${body}</g>`;
+const win = (x, y, w, h, glass = '#9cc6de', frame = '#f4f1ea') => `<rect x="${x}" y="${y}" width="${w}" height="${h}" fill="${glass}"/><path d="M${x},${y} h${w} v${h} h${-w} Z M${x + w / 2},${y} v${h}" fill="none" stroke="${frame}" stroke-width="6"/>`;
+
+// A room: back wall with a window and a picture, a floor, and a table in front of the puppets.
+function room() {
+ const wall = P(`<rect x="-100" y="-60" width="1800" height="800" fill="#f3ecd9"/>`, 'paperBig')
+ + P(`${win(1100, 140, 260, 300)}<path d="M1090,130 h280 v320 h-280 Z" fill="none" stroke="#c9bfa6" stroke-width="10"/>`)
+ + P(`<rect x="300" y="170" width="260" height="170" fill="#7ec0e0"/><path d="M300,340 l70,-90 l60,60 l50,-70 l80,100 Z" fill="#6f9a6a"/><circle cx="480" cy="230" r="22" fill="#ffe08a"/>`);
+ const floor = P(`<rect x="-100" y="700" width="1800" height="320" fill="#c69a64"/>${Array.from({ length: 8 }, (_, i) => `<path d="M-100,${730 + i * 36} h1800" stroke="#b78a55" stroke-width="3"/>`).join('')}`, 'paperBig');
+ const table = P(`<rect x="1040" y="660" width="440" height="30" rx="6" fill="#8a5a36"/><rect x="1070" y="690" width="24" height="170" fill="#8a5a36"/><rect x="1430" y="690" width="24" height="170" fill="#8a5a36"/>
+ <circle cx="1420" cy="636" r="26" fill="#e9dcc4"/><rect x="1400" y="610" width="40" height="8" fill="#c8322f"/>`);
+ return [
+ { name: 'wall', k: .85, box: [-100, -60, 1800, 800], scale: 1.2, svg: wall },
+ { name: 'floor', k: 1, box: [-100, 690, 1800, 330], scale: 1.2, svg: floor },
+ { name: 'table', k: 1, box: [1000, 590, 520, 290], scale: 1.5, soft: false, svg: table },
+ ];
+}
+
+const SETS = { room };
+if (typeof window !== 'undefined') window.SETS = SETS, window.SET_DEFS = DEFS;
diff --git a/.claude/skills/papermorph/references/intake.md b/.claude/skills/papermorph/references/intake.md
index a75c3f0..4a38f6c 100644
--- a/.claude/skills/papermorph/references/intake.md
+++ b/.claude/skills/papermorph/references/intake.md
@@ -25,11 +25,11 @@ Offer the animation tiers as reference points. The published books at https://pa
1. **Diagrams that change**: symbols, number lines, graphs and shapes built in code, rearranged as the narration explains (the maths books). Lightest: about 100k tokens a chapter, works on a smaller model.
2. **Illustrated scenes**: characters act out the idea, the camera moves, external images and a storyboard before motion (the science book). About 400k tokens a chapter on a large model.
-3. **Picture book**: coming, not available yet.
+3. **Picture book**: a short film of paper puppets acting out a story, the sets drawn in code or painted by an image model ([stories.md](stories.md)). For stories, jokes and fairy tales, including a story book's PDF.
4. **Documentary**: coming, not available yet.
5. **Custom**: the user describes what they want; you judge which abilities it needs and say so.
-Recommend one from the chapter's content: abstract and procedural ideas fit tier 1 ([diagrams.md](diagrams.md)); physical and narrative ones fit tier 2 ([scenes.md](scenes.md)). Mixing per beat is allowed under any tier.
+When the user brings a story rather than a textbook, go straight to [stories.md](stories.md), which has its own short intake. Otherwise recommend one from the chapter's content: abstract and procedural ideas fit tier 1 ([diagrams.md](diagrams.md)); physical and narrative ones fit tier 2 ([scenes.md](scenes.md)). Mixing per beat is allowed under any tier.
## 4. The look, by tier
diff --git a/.claude/skills/papermorph/references/painting.md b/.claude/skills/papermorph/references/painting.md
new file mode 100644
index 0000000..4d43776
--- /dev/null
+++ b/.claude/skills/papermorph/references/painting.md
@@ -0,0 +1,30 @@
+# Painted sets: an image model for everything that stays still
+
+In the painted look, one question splits the work: **does it move?** Streets, rooms, walls, shelves, furniture, signs, and props that only move as a whole (a bun, a bottle, an umbrella, a cart, a desk) are painted by an image model. Anything with joints, a face or a change of shape (people, animals, rain and snow, thought bubbles, clock hands) stays a paper puppet in code ([puppets.md](puppets.md)). A painting never has to act and a puppet never has to look like a painting, so neither does the other's job badly. *Joke Collection* paints its episodes this way for well under a dollar each.
+
+## Choosing the look
+
+Paint one set two or three ways at the cheapest quality, stand the puppets in each (composite a frame), and let the user choose. In *Joke Collection* the candidates were flat paper like the puppets, warm gouache, and a richer torn-paper collage with light; the user chose the collage: "no need to copy South Park 100%; use the image model as far as it goes while what can move, moves". Keep the chosen picture as the style reference for every later set and prop, and record the style words in `style.json`.
+
+## Getting the composition you need
+
+Puppets stand at fixed places, counters must hide the right legs, and cuts must match. The reliable way is to draw the set first as a rough SVG sketch (`bake_sets.py` renders it), then ask the model to repaint *that picture* in the style of the reference: the layout survives, the look changes. Then:
+
+- **Cut-outs for whatever people stand behind.** A counter, a cart, rows of desks, a lectern: paint each as its own picture on a transparent background and place it as a layer (`painted.py`, `cut`).
+- **Variants by editing, not redrawing.** Rain and snow versions of a street, a door open and shut, a bun with a bite: edit the one picture, so a cut between versions changes only that.
+- **Leave signs blank.** Image models garble text, Chinese and Japanese worst. Paint the banner, the shop sign, the blackboard empty and let `painted.py` write the words on in a real font.
+- **Paint wider than the frame.** Camera shakes and zooms see past the edge; `painted.py` pads full frames.
+
+Everything that comes out goes through `painted.py` (manifest `books/<book>/art/painted.json`): sets resized to the 1600×900 frame, blurred copies for close-ups, cut-outs placed, words written, props written to `img/props/`. Stand the puppets in a frame and look before going on.
+
+## Cost
+
+Money is the user's, so the user sets a ceiling and sees every cent:
+
+- `paint.py` takes quality `low` or `medium` only. Try low first: in these books low was often good enough for the final set (about $0.02 a picture; medium about $0.02–0.03; high cost five times as much and, once used in a film, looked the same).
+- Every picture is logged with its cost (`--ledger books/<book>/art/costs.tsv`); before a batch, say how many pictures and what they will cost; after it, report the real balance from the provider, not an estimate. OpenRouter refuses any image request when the balance is under one dollar.
+- After every batch, put the pictures on one contact sheet and open it for the user (Finder, the browser), even when working on your own: they like to see each stage.
+
+## Credits and licences
+
+Pictures you generate belong in the book; say which model painted them in the series page's footer. Stock or web images are a different matter: a public site redistributes the files, so only licences that allow redistribution (CC0 and the like) will do, and the look rarely matches the puppets. Painting your own is usually simpler.
diff --git a/.claude/skills/papermorph/references/puppets.md b/.claude/skills/papermorph/references/puppets.md
new file mode 100644
index 0000000..7ff9acf
--- /dev/null
+++ b/.claude/skills/papermorph/references/puppets.md
@@ -0,0 +1,32 @@
+# Paper puppets and the stop-motion look
+
+The actors of a picture book are paper puppets drawn in code: pieces of coloured paper pinned at the joints, moved a little each frame, like a cut-out film shot by hand. Because a pose is only a set of numbers, any action the story needs (ducking, swinging an axe, diving through a window, shoving a thought bubble) costs a few lines, never a new drawing, and a puppet looks the same in every shot. The kit is in `assets/templates/picture-book/` (`paper.js`, `cast.js`, `shared.js`, `chapter.html`); copy it into `site/<book>/lib/` and the episode folder.
+
+Two cast styles are on the shelf, both from the same kit: jointed storybook figures seen mostly in profile (*Little Red Riding Hood*: the wolf, Grandma, the woodcutter) and round-headed figures that face us, in the spirit of South Park (*Joke Collection*). Pick with the user; the second is quicker to build and to act with.
+
+## What makes it read as stop motion
+
+- **Twelve frames a second, on twos.** `stopClock` samples every movement into steps; the slight jerk is the style, not a defect. Big moves still ease in and out across those steps.
+- **The animator's hand.** Each frame nudges every puppet by a tiny random amount (`jit(frame, k)`, the same nudge for the same frame, so pause, seek and `?beat=N&t=S` show exactly what playback shows), and the picture flickers faintly. Keep it small: at full strength it read as shaking ("抖动有点太剧烈", the user said); a third of a pixel-ish wobble, held for two frames, felt hand-made.
+- **Paper you can feel.** Grain, torn edges and a soft drop shadow on every piece (the `#paper` filter), brass pins at the joints, and a soft contact shadow under the feet so a puppet stands on the ground, leaning the way the set's light falls.
+- **Replacement, not morphing.** Mouths are swapped shapes timed to the words; a blink is two closed frames; a door opens through a few boards of different widths; a bun bitten is a different picture.
+
+## Acting
+
+- **Nobody freezes.** Whoever speaks lip-syncs; everyone blinks at their own moments, never in unison; listeners' eyes follow the speaker; reactions get a small head turn or a lid drop. A crowd glances about on its own and turns as one only when something happens (a staggered snap, a frame or two apart).
+- **Turning round is a whole-body swap.** A puppet has a complete side set and a complete front set. A turn squashes the side view, swaps to the whole front figure for the narrowest frames and comes out mirrored. A front head on a side body looked wrong every time.
+- **Feet don't slide.** Walks use a compass step (`walk()`): the planted foot stays put while the hip swings over it; distance is scale. Runs are on twos with a bigger bob.
+- **Hands touch what they hold.** A held prop belongs to the hand's piece; when something is handed over, both hands meet it.
+- **Things behind things.** A counter, a cart, a desk row or a lectern sits on its own layer between puppets, so the person behind shows from the chest up (`paperCam(…, { after, stages })` puts puppet layers between set layers).
+
+## Cameras
+
+`paperCam(parent, set, view)` is one camera on one set: layers slide with parallax, `to`/`cut` move it on the scene's clock, `soft` swaps in the blurred copy of the set for close-ups, `shake` jolts it, `show(layer, on)` swaps a layer (rain and snow versions of the same street). Several cameras can live in one scene; cut between places by showing one `cam.root` and hiding the others. Close-ups zoom the same set and blur it, so the speaker stays sharp.
+
+## Performance
+
+Paper filters are expensive live. Every finished piece is baked to a bitmap: sets with `bake_sets.py` (SVG sketches) or `painted.py` (painted pictures), puppet and prop pieces with `bake_puppets.py`, which seeks every episode to its end so each piece is asked for once and writes `img/puppets/<hash>.webp` with `baked.js`. The parts that change every frame (eyes, mouths, brows, fingers) stay live. Rebake after changing any piece; a piece missing from `baked.js` is baked in the browser and costs a stall. Full-frame effects that change every frame (the flicker) live outside the SVG so the picture isn't redrawn each frame.
+
+## Seeing your own work
+
+The preview server must not cache (`serve.py`). Look at contact sheets that advance the clock the way playback does (`strip.py chNN OUT scene1/0.5`), at full-size frames at the key moments, at the last frame of each scene beside the first of the next, and play the whole episode through once at speed. Some faults appear only in continuous playback (a camera layer shown once and never hidden again), so don't rely on jumps with `?t=` alone.
diff --git a/.claude/skills/papermorph/references/sound.md b/.claude/skills/papermorph/references/sound.md
new file mode 100644
index 0000000..ffa81c1
--- /dev/null
+++ b/.claude/skills/papermorph/references/sound.md
@@ -0,0 +1,22 @@
+# Sound for picture books
+
+Voices carry the story; everything else sits under them. In early cuts the music and effects were loud enough that the lines got lost ("说话的声音听不见"), and that was the first thing the user noticed.
+
+## Voices
+
+- **One voice per character.** List them under `voices` in `narration.<lang>.json` and write each line as `{"speaker": name, "text": …}`; `tts.py` synthesizes every line (Edge voices, with rate and pitch: children were adult voices sped up and pitched up). The narrator is a voice too.
+- **Lines in other languages** are spoken in their own language by a native voice (Edge has Japanese, Chinese, Korean and more) and subtitled in the book's language. The caption shows both: the original and the translation in brackets.
+- **Mouths** follow the words: `mouths.py` turns each line's word timings into mouth shapes, and `lips(q, scene, pre, line…)` picks the shape for the frame.
+- **One clip per scene.** `join.py` joins a scene's lines into one audio clip with short pauses, and inserts silence where the action needs room (`line@T+S`: S seconds of silence T seconds into the line). Gaps for a held stare, a fly landing, a class turning round belong here, not in rushed animation. Changing a line means `tts.py`, `mouths.py` and `join.py` again.
+
+## Sound effects
+
+`sfx.py` synthesizes effects (knock, door, bell, chop, bang, bonk, thud, crash, coin, beep, rain, crickets and more) as small MP3s, free and consistent. Keep them soft and natural: the first rain was a high hiss and read as scary; pink noise with patter and taps on umbrellas read as rain. An effect is placed on the scene clock with `sfx(scene, t, name, volume)` and plays at half volume under the voices; it stops when playback pauses. Cut an effect to its shot: a six-second rain under a one-second shot spills into the next.
+
+## Music
+
+Music is optional and goes under everything: about 70 % of its own level, ducking to 30 % while anyone speaks, fading in and out over most of a second. Give a scene silence when silence is the joke. Don't let music stop dead in the middle of a scene; carry it to the end or fade it, and bring an earlier theme back when the story returns to an earlier place. Use tracks the book may redistribute (generated for the book, or openly licensed) and credit them.
+
+## Captions
+
+Picture books turn captions on at a reader's first visit (`chapter.html` does this); the reader's own choice is remembered after that.
diff --git a/.claude/skills/papermorph/references/stories.md b/.claude/skills/papermorph/references/stories.md
new file mode 100644
index 0000000..4b4fca7
--- /dev/null
+++ b/.claude/skills/papermorph/references/stories.md
@@ -0,0 +1,45 @@
+# Picture books: from a story to an episode
+
+A picture book is a short animated film, two to four minutes, told by paper puppets in front of sets. It starts from a story rather than a textbook: a fairy tale, a joke, something that happened to the user, or a story book's PDF. The published examples are on the shelf at https://papermorph.diamonddoge.org/: *Little Red Riding Hood* (everything drawn in code) and *Joke Collection* (painted sets, puppets in code; two episodes, one of them made overnight by a fresh session from the user's bedtime telling).
+
+The craft is in four references: this one (the story and the shots), [puppets.md](puppets.md) (the paper puppets and the stop-motion look), [painting.md](painting.md) (sets and props painted by an image model) and [sound.md](sound.md) (voices, sound effects, music). The engine, the player, previews, checks and the team are the same as for every other book.
+
+## Intake for a story
+
+The same spirit as [intake.md](intake.md): a light conversation, choices to click, the user's words kept verbatim. What to settle, skipping whatever the telling already settles:
+
+1. **The story itself.** Let the user tell it in their own words and keep that telling in `books/<book>/story.md` untouched. Ask what is true and must stay (a real joke has one real punchline), who the people are, where it happens, what language each person speaks.
+2. **The look.** Two ways, both with paper puppets ([puppets.md](puppets.md)):
+ - *Paper, all in code*: sets and props drawn as SVG paper too. No image cost, plainer, very consistent (Little Red Riding Hood).
+ - *Painted world, paper actors* (recommended when an image budget is fine): an image model paints the sets and everything that stays still; the puppets and anything that moves stay in code (Joke Collection, under a dollar of pictures per episode). Ask for a budget ceiling and keep to it ([painting.md](painting.md)).
+3. **Language and voices**: the narration language, one voice per character ([sound.md](sound.md)).
+4. **A series or one film.** A series shares cast, sets and the series page; each episode is a chapter (`chNN`).
+
+Record the answers in `style.json` (an `illustration` block: the look, the budget, the cast with a line each, the sets) and go on to the script.
+
+## The script comes first
+
+Write the script and a storyboard table (`books/<book>/storyboard.md`: scene, shot, what we see, who says what) and show them to the user before building anything. Changing a story on paper is cheap; once every shot is animated it is expensive, and almost every real failure in these books was a story failure that no amount of animation fixed.
+
+What made the difference, from the books:
+
+- **Set up everything the punchline needs.** The first cut of *Breakfast in the Bathroom* had Bo ask "Wanna go eat breakfast… in the bathroom?" out of nowhere; viewers took it literally. It became a joke once the film first showed his two everyday questions, "Breakfast?" every morning at the stall and "Bathroom?" after every class, and then the morning he overslept and came in starving.
+- **Show the motive before the line.** Bo's stomach growls; a bun appears in a thought bubble; he glances at the door and a toilet appears beside it; the two bubbles shove each other and merge. Only then does he speak. The audience is ahead of him, which is where comedy happens.
+- **Every event needs a cause the audience has seen.** In *Little Red Riding Hood* the first rescue had a woodcutter from nowhere, Grandma suddenly out of the wardrobe and the wolf flying out of the window "as if Grandma had superpowers" (the user's words). The fix was a chain: the woodcutter chopping wood near the cottage earlier, a cut to Grandma's eye in the wardrobe crack during the questions, the cry for help, Grandma's umbrella on the wolf's head, the woodcutter blocking the door, the window the only way out, and outside, the window still broken.
+- **The audience understands what the characters don't.** In *Do You Need a Bag?* the clerk speaks only Japanese and the customer only English: each line is spoken in its own language with subtitles, and a thought bubble shows the mishearing ("…REJI…?" turning into "VEGGIE?"), so the joke works for viewers who speak neither.
+- **Keep the user's story.** Tighten the wording, add the small connecting moments a film needs, and list every addition for the user; don't swap their joke for a different one.
+
+## Scenes, shots, cuts
+
+One scene is one beat, with one joined audio clip ([sound.md](sound.md)); cuts inside a scene are timed to its clock. Plan shots the way a film does, because a fixed wide frame for a whole scene plays like a slideshow:
+
+- a wide shot to say where we are, two-shots for conversations, a close-up for whoever speaks, closer and closer as tension rises (the three questions to "Grandma");
+- reverse angles: whoever is in close-up has behind them what the other person sees (a separate camera on a matching set, not a zoom of the same one);
+- an insert to make a detail readable (a coin on the counter, the clock, a face in a door crack);
+- held silences: the beat where nobody speaks is often the joke. Blinks, eyes and a tiny head turn carry it.
+
+Everybody in the shot stays alive and stays there: extras blink and glance about in close-ups too (in an early cut the whole class vanished whenever someone spoke). Between places, cut or use a paper-theatre wipe; at the end, a title card.
+
+## Delivering
+
+Deliver the episode URL with what was made, the final script, the decisions the user should review (every line or moment you added), known problems, and the real cost of pictures. For a series, add the episode to the series page with a still and a line, and set the previous episode's `CHAPTER.next`.
diff --git a/.claude/skills/papermorph/references/team.md b/.claude/skills/papermorph/references/team.md
index c035cfd..3514832 100644
--- a/.claude/skills/papermorph/references/team.md
+++ b/.claude/skills/papermorph/references/team.md
@@ -26,3 +26,7 @@ Start each worker in the background with a short brief: the chapter and its page
## Before delivering
Check the reports against each other (an odd claim is worth one look at the file), confirm lint and e2e pass, and deliver the chapter URL with `?review`. If the user wants the cost, it is in the subagent transcripts (`subagents/agent-<id>.jsonl` under the session's folder in `~/.claude/projects/`: usage per assistant message, each message id counted once) plus your own session's usage.
+
+## Picture books
+
+The same shape, split by scene instead of by step: the strong coordinator writes the script with the user, builds what every scene shares (cast, sets and their painting, the episode's helpers, the voices and joined audio), and writes a short brief for scene workers (the kit, the style, how to check, how to reply). Then one **middle** worker per scene, in parallel, each writing only its own `sceneN.js` and checking it with contact sheets; a **small** worker synthesizes the sound effects from recipes; a **middle** worker looks at every scene's contact sheet and reports problems with scene and time, so the coordinator reads a list instead of the pictures; the coordinator reworks or sends back. A fresh session as coordinator matters even more here: contact sheets are large, and a long conversation rereads them at every step. An episode made this way from a bedtime telling, in one night: about 22 million tokens, most of them the coordinator rereading its own context.
diff --git a/.claude/skills/papermorph/scripts/bake_puppets.py b/.claude/skills/papermorph/scripts/bake_puppets.py
new file mode 100644
index 0000000..14a94ca
--- /dev/null
+++ b/.claude/skills/papermorph/scripts/bake_puppets.py
@@ -0,0 +1,56 @@
+#!/usr/bin/env python3
+"""Bake every paper piece a picture book uses (puppets and props, every scene of every chapter) to bitmaps.
+
+ uv run --with playwright --with pillow python bake_puppets.py site/<book> [--url http://localhost:8790/site/<book>/] [--clean]
+
+The page would otherwise run the paper filter on each piece at startup. This opens every chNN of the book with ?bake
+(which ignores existing bitmaps), seeks it to its last beat (which builds every scene before it, so every piece is asked
+for once), and saves each piece to SITE/img/puppets/<hash>.webp, listed in baked.js (window.BAKED) that paper.js reads.
+Run it with a preview server up (python3 SKILL/scripts/serve.py 8790 site) after changing a puppet or prop drawing.
+--url is the book's address as the server shows it (default http://localhost:8790/); files this run did not produce are
+kept (a piece another chapter or an earlier run made) unless --clean removes them first. Needs Playwright's Chromium.
+"""
+import argparse, base64, io, json, pathlib
+from PIL import Image
+from playwright.sync_api import sync_playwright
+
+READY = """async () => {
+ let n = -1; while (bakedJobs.size !== n) { n = bakedJobs.size; await Promise.all([...bakedJobs.values()]); await new Promise(r => setTimeout(r, 300)); }
+ const out = [];
+ for (const [key, url] of bakedReady) { const blob = await (await fetch(url)).blob();
+ out.push([keyHash(key), await new Promise(r => { const f = new FileReader(); f.onload = () => r(f.result); f.readAsDataURL(blob); })]); }
+ return out; }"""
+
+
+def main():
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ ap.add_argument('site'); ap.add_argument('--url', default='http://localhost:8790/'); ap.add_argument('--clean', action='store_true')
+ a = ap.parse_args()
+ site = pathlib.Path(a.site); out = site / 'img/puppets'; url = a.url.rstrip('/') + '/'
+ got = []
+ with sync_playwright() as p:
+ b = p.chromium.launch(); pg = b.new_page(viewport={'width': 1600, 'height': 900})
+ for ch in sorted(d.name for d in site.glob('ch[0-9][0-9]')):
+ pg.goto(f'{url}{ch}/?bake', timeout=600000)
+ last = pg.evaluate('BEATS.length - 1')
+ pg.goto(f'{url}{ch}/?bake&beat={last}&t=0.1', timeout=600000)
+ got += pg.evaluate(READY)
+ print(ch, 'beat', last, len(got), 'pieces so far')
+ b.close()
+ out.mkdir(parents=True, exist_ok=True)
+ if a.clean:
+ for f in out.glob('*.webp'): f.unlink()
+ man_path = out / 'baked.js'
+ man = {}
+ if man_path.exists() and not a.clean:
+ man = {h: f for h, f in json.loads(man_path.read_text().split('=', 1)[1].rstrip().rstrip(';')).items() if (out / f).exists()}
+ for h, data in got:
+ f = out / f'{h}.webp'
+ Image.open(io.BytesIO(base64.b64decode(data.split(',')[1]))).save(f, quality=88, method=6)
+ man[h] = f.name
+ man_path.write_text('window.BAKED = ' + json.dumps(man) + ';\n')
+ print(len(got), 'pieces baked,', len(man), 'listed,', sum((out / f).stat().st_size for f in man.values()) // 1024, 'KB')
+
+
+if __name__ == '__main__':
+ main()
diff --git a/.claude/skills/papermorph/scripts/bake_sets.py b/.claude/skills/papermorph/scripts/bake_sets.py
new file mode 100644
index 0000000..2cd32e9
--- /dev/null
+++ b/.claude/skills/papermorph/scripts/bake_sets.py
@@ -0,0 +1,57 @@
+#!/usr/bin/env python3
+"""Bake a picture book's SVG set sketches to WebP layers (plus a blurred -soft copy for shallow focus).
+
+ uv run --with playwright --with pillow python bake_sets.py books/<book>/art/sets.js site/<book> [SET ...]
+
+SETS.JS (template: assets/templates/picture-book/sets.js) defines window.SETS = {setName: () => [layer, ...]} and
+window.SET_DEFS (an SVG <defs> string with the paper filters). A layer is {name, k, box: [x, y, w, h] in world px,
+scale, svg, soft?}: k is the parallax factor (1 = the puppets' plane), scale the bitmap's pixels per world px, soft:
+false skips the blurred copy. Writes SITE/img/sets/<set>/<layer>.webp, <layer>-soft.webp and the placement manifest
+SITE/img/sets/sets.js that paper.js reads. With SET names only those sets are baked and the manifest keeps the others.
+
+The sketches are a finished look on their own (free) and the composition reference an image model repaints (give the
+baked picture to paint.py, then put the result in with painted.py). Needs Playwright's Chromium.
+"""
+import asyncio, base64, io, json, pathlib, sys
+from PIL import Image
+from playwright.async_api import async_playwright
+
+JS = """async ([name, i, soft]) => {
+ const L = SETS[name]()[i], [x, y, w, h] = L.box, s = L.scale || 1;
+ const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${w * s}" height="${h * s}" viewBox="${x} ${y} ${w} ${h}">${window.SET_DEFS || ''}${L.svg}</svg>`;
+ const img = new Image(); img.src = URL.createObjectURL(new Blob([svg], { type: 'image/svg+xml' }));
+ await img.decode();
+ const c = document.createElement('canvas'); c.width = w * s; c.height = h * s;
+ const g = c.getContext('2d'); if (soft) g.filter = `blur(${5 * s}px)`; g.drawImage(img, 0, 0);
+ return c.toDataURL('image/png');
+}"""
+
+
+async def main(sets_js, site, only):
+ out = pathlib.Path(site) / 'img/sets'
+ async with async_playwright() as p:
+ b = await p.chromium.launch(); pg = await b.new_page()
+ await pg.add_script_tag(path=str(pathlib.Path(sets_js).resolve()))
+ names = only or await pg.evaluate('Object.keys(SETS)')
+ man = {}
+ for n in names:
+ layers = await pg.evaluate(f'SETS[{json.dumps(n)}]().map(l => ({{name: l.name, k: l.k, box: l.box, soft: l.soft !== false}}))')
+ (out / n).mkdir(parents=True, exist_ok=True)
+ for i, L in enumerate(layers):
+ for soft in ([False, True] if L['soft'] else [False]):
+ png = await pg.evaluate(JS, [n, i, soft])
+ f = out / n / (L['name'] + ('-soft' if soft else '') + '.webp')
+ Image.open(io.BytesIO(base64.b64decode(png.split(',')[1]))).save(f, quality=86, method=6)
+ print(f.relative_to(out), f.stat().st_size // 1024, 'KB')
+ man[n] = layers
+ old = out / 'sets.js'
+ if old.exists() and only:
+ man = {**json.loads(old.read_text().split('=', 1)[1].rstrip().rstrip(';')), **man}
+ old.write_text('window.SETS = ' + json.dumps(man) + ';\n')
+ await b.close()
+
+
+if __name__ == '__main__':
+ if len(sys.argv) < 3:
+ print(__doc__); sys.exit(0 if sys.argv[1:] in (['-h'], ['--help']) else 2)
+ asyncio.run(main(sys.argv[1], sys.argv[2], sys.argv[3:]))
diff --git a/.claude/skills/papermorph/scripts/join.py b/.claude/skills/papermorph/scripts/join.py
new file mode 100644
index 0000000..383f020
--- /dev/null
+++ b/.claude/skills/papermorph/scripts/join.py
@@ -0,0 +1,57 @@
+#!/usr/bin/env python3
+"""Join several narration clips into one clip per scene, so a whole scene plays as one beat.
+
+ python3 join.py site/<book>/chNN/audio/en scene1=s01,s02,s02b scene2=s03,[email protected]+1.5,s05
+
+Each argument is SCENE=CLIP,CLIP,...; a clip may be CLIP@T+S@T+S: S seconds of silence inserted T seconds into it
+(room for an action in the middle of a line). A short pause (0.35 s) goes between clips. Writes AUDIO_DIR/SCENE.mp3 and
+AUDIO_DIR/shots.js: TIMINGS.SCENE = {dur, marks, cues, parts} with each clip's start in `parts` (marks become
+"clip.mark") and the caption cues moved along; the mouth cues of clips with holes are moved too (MOUTHS.clip). Load
+shots.js after timings.js and mouths.js. Run after tts.py and mouths.py; needs ffmpeg.
+"""
+import json, subprocess, sys, pathlib, tempfile
+if len(sys.argv) < 3 or sys.argv[1] in ('-h', '--help'):
+ print(__doc__); sys.exit(0 if sys.argv[1:2] in (['-h'], ['--help']) else 2)
+GAP = .35
+d = pathlib.Path(sys.argv[1]); T = json.loads((d / 'timings.js').read_text().split('=', 1)[1].rstrip().rstrip(';'))
+out, H = {}, {} # H: every shot's holes, for the mouths
+for arg in sys.argv[2:]:
+ shot, beats = arg.split('='); beats = beats.split(',')
+ holes = {} # beat -> [(at, seconds)]: silences inserted inside a clip, room for action
+ for i, b in enumerate(beats):
+ name, *ins = b.split('@'); beats[i] = name
+ holes[name] = [tuple(map(float, x.split('+'))) for x in ins]
+ with tempfile.TemporaryDirectory() as tmp:
+ def piece(b): # the clip's file, cut at its holes with silence between
+ if not holes[b]: return [str((d / f'{b}.mp3').resolve())]
+ out, start = [], 0
+ for k, (at, sec) in enumerate(holes[b] + [(None, 0)]):
+ seg = pathlib.Path(tmp) / f'{b}-{k}.mp3'
+ cmd = ['ffmpeg', '-v', 'error', '-y', '-i', str(d / f'{b}.mp3'), '-ss', str(start)] + (['-to', str(at)] if at is not None else []) + ['-c:a', 'libmp3lame', '-b:a', '64k', str(seg)]
+ subprocess.run(cmd, check=True); out.append(str(seg))
+ if at is not None:
+ sil = pathlib.Path(tmp) / f'{b}-s{k}.mp3'
+ subprocess.run(['ffmpeg', '-v', 'error', '-y', '-f', 'lavfi', '-i', 'anullsrc=r=24000:cl=mono', '-t', str(sec), '-b:a', '64k', str(sil)], check=True); out.append(str(sil)); start = at
+ return out
+ shift = lambda b, t: t + sum(sec for at, sec in holes[b] if t >= at)
+ gap = pathlib.Path(tmp) / 'gap.mp3'
+ subprocess.run(['ffmpeg', '-v', 'error', '-y', '-f', 'lavfi', '-i', 'anullsrc=r=24000:cl=mono', '-t', str(GAP), '-b:a', '64k', str(gap)], check=True)
+ lst = pathlib.Path(tmp) / 'list.txt'
+ lst.write_text(''.join(''.join(f"file '{f}'\n" for f in piece(b)) + (f"file '{gap}'\n" if i < len(beats) - 1 else '') for i, b in enumerate(beats)))
+ subprocess.run(['ffmpeg', '-v', 'error', '-y', '-f', 'concat', '-safe', '0', '-i', str(lst), '-c:a', 'libmp3lame', '-b:a', '64k', str(d / f'{shot}.mp3')], check=True)
+ parts, cues, marks, at = {}, [], {}, 0
+ for b in beats:
+ parts[b] = round(at, 3)
+ cues += [[round(shift(b, t) + at, 3), c] for t, c in T[b]['cues']]
+ marks.update({f'{b}.{k}': round(shift(b, v) + at, 3) for k, v in T[b]['marks'].items()})
+ at += T[b]['dur'] + sum(sec for _, sec in holes[b]) + GAP
+ dur = float(subprocess.run(['ffprobe', '-v', 'error', '-show_entries', 'format=duration', '-of', 'csv=p=0', str(d / f'{shot}.mp3')], capture_output=True, text=True).stdout)
+ H.update(holes)
+ out[shot] = {'dur': round(dur, 3), 'marks': marks, 'cues': cues, 'parts': parts}
+# a clip with holes gets its mouth cues moved the same way (and shut at each hole), after mouths.js in the page
+mp = d / 'mouths.js'; M = json.loads(mp.read_text().split('=', 1)[1].rstrip().rstrip(';')) if mp.exists() else {}
+sh = lambda b, t: t + sum(sec for at, sec in H[b] if t >= at)
+moved = {b: sorted([[round(sh(b, t), 3), k] for t, k in M[b]] + [[round(sh(b, at - 1e-3), 3), 'X'] for at, _ in H[b]])
+ for b in H if H[b] and b in M}
+(d / 'shots.js').write_text(''.join(f'TIMINGS.{k} = {json.dumps(v)};\n' for k, v in out.items()) + ''.join(f'MOUTHS.{b} = {json.dumps(v)};\n' for b, v in moved.items()))
+print({k: (v['dur'], v['parts']) for k, v in out.items()})
diff --git a/.claude/skills/papermorph/scripts/lint.py b/.claude/skills/papermorph/scripts/lint.py
index 1e95df2..27d3eee 100644
--- a/.claude/skills/papermorph/scripts/lint.py
+++ b/.claude/skills/papermorph/scripts/lint.py
@@ -93,7 +93,12 @@ def decls(text):
def timings(path):
t = path.read_text(encoding='utf-8')
- return json.loads(t[t.index('{'):t.rindex('}') + 1])
+ T = json.loads(t[t.index('{'):t.rindex('}') + 1])
+ shots = path.with_name('shots.js') # join.py's joined scenes: TIMINGS.scene = {...};
+ if shots.exists():
+ for m in re.finditer(r'^TIMINGS\.(\w+) = (\{.*\});$', shots.read_text(encoding='utf-8'), re.M):
+ T[m.group(1)] = json.loads(m.group(2))
+ return T
def words(s):
@@ -150,6 +155,8 @@ def lint_chapter(ch, content, out):
if nar.exists():
N = json.loads(nar.read_text(encoding='utf-8-sig')).get('beats', {})
for b, text in N.items():
+ if isinstance(text, dict): # a beat with a speaker
+ text = text['text']
if b not in T:
err('stale', f'narration beat {b} has no timings')
continue
diff --git a/.claude/skills/papermorph/scripts/mouths.py b/.claude/skills/papermorph/scripts/mouths.py
new file mode 100644
index 0000000..80cb0b3
--- /dev/null
+++ b/.claude/skills/papermorph/scripts/mouths.py
@@ -0,0 +1,40 @@
+#!/usr/bin/env python3
+"""Mouth shapes for every beat of a narration, from the TTS word times, for puppets that talk.
+
+ python3 mouths.py content/<book>/chNN/narration.en.json site/<book>/chNN/audio/en
+
+Reads the .timings.json cache that tts.py wrote next to the narration file and writes AUDIO_DIR/mouths.js
+(window.MOUTHS = {beat: [[seconds, shape], ...]}). Shapes follow the cartoon set Rhubarb uses: A closed (m b p),
+B teeth/most consonants, C open (e i), D wide (a), E round (o), F pucker (oo w u), G f/v, H l, X rest. Each word's
+letters become shapes spread over the word's time; a pause between words closes the mouth. Letters are read as
+English spelling; for another language the rules below are a rough guide only. Run it after tts.py (and before
+join.py, which moves the cues of clips it joins).
+"""
+import json, re, sys, pathlib
+if len(sys.argv) < 3 or sys.argv[1] in ('-h', '--help'):
+ print(__doc__); sys.exit(0 if sys.argv[1:2] in (['-h'], ['--help']) else 2)
+src, out = pathlib.Path(sys.argv[1]), pathlib.Path(sys.argv[2])
+cache = json.loads(src.with_suffix('.timings.json').read_text())
+RULES = [('oo', 'F'), ('ou', 'F'), ('ow', 'F'), ('th', 'B'), ('ee', 'C'), ('ea', 'C'), ('ai', 'C'), ('ay', 'C'),
+ ('m', 'A'), ('b', 'A'), ('p', 'A'), ('f', 'G'), ('v', 'G'), ('w', 'F'), ('u', 'F'), ('o', 'E'), ('a', 'D'),
+ ('e', 'C'), ('i', 'C'), ('y', 'C'), ('l', 'H')]
+def shapes(word):
+ w, i, s = re.sub(r'[^a-z]', '', word.lower()), 0, []
+ while i < len(w):
+ for k, v in RULES:
+ if w.startswith(k, i): s.append(v); i += len(k); break
+ else: s.append('B'); i += 1
+ out = [x for j, x in enumerate(s) if j == 0 or x != s[j - 1]]
+ return out or ['B']
+res = {}
+for beat, e in cache.items():
+ words, dur, cues = e['words'], e['dur'], []
+ for j, (t, w) in enumerate(words):
+ end = min(words[j + 1][0] if j + 1 < len(words) else dur - .1, t + .55)
+ sh = shapes(w); step = (end - t) / len(sh)
+ cues += [[round(t + k * step, 3), x] for k, x in enumerate(sh)]
+ if j + 1 < len(words) and words[j + 1][0] - end > .12: cues.append([round(end, 3), 'X']) # a pause closes the mouth
+ cues.append([round(min(dur, (words[-1][0] + .55) if words else 0), 3), 'X'])
+ res[beat] = cues
+(out / 'mouths.js').write_text('window.MOUTHS = ' + json.dumps(res, separators=(',', ':')) + ';\n')
+print(len(res), 'beats;', next(iter(res.items()), None))
diff --git a/.claude/skills/papermorph/scripts/paint.py b/.claude/skills/papermorph/scripts/paint.py
new file mode 100644
index 0000000..02a5af0
--- /dev/null
+++ b/.claude/skills/papermorph/scripts/paint.py
@@ -0,0 +1,75 @@
+#!/usr/bin/env python3
+"""One picture from an image model (OpenRouter /images), from a prompt and optional reference pictures.
+
+ python3 paint.py OUT.png "prompt" [ref.png ...] [--ar 16:9] [--q low|medium] [--bg transparent]
+ [--model openai/gpt-image-2.5-flare] --ledger books/<book>/art/costs.tsv
+ python3 paint.py --total books/<book>/art/costs.tsv # sum a ledger, per model and overall
+
+Reference pictures steer composition and characters (a baked set sketch makes a good composition reference, see
+bake_sets.py). Quality is low or medium only: high costs several times as much and has never been needed; the
+script refuses it. --bg transparent asks for a cut-out (props, characters); otherwise the model chooses.
+The key is read from ~/.config/openrouter/key or $OPENROUTER_API_KEY. OpenRouter refuses image requests while the
+account balance is below $1.00, so top up before a batch.
+
+Each call prints the cost OpenRouter reports and appends one line to the ledger (date, file, model, quality, cost, tab
+separated; the ledger and its folder are created). Test the cheapest quality first and total the ledger before and
+after a batch, so the spend is known.
+"""
+import argparse, base64, datetime, json, os, pathlib, sys, urllib.request, urllib.error
+
+
+def total(path):
+ rows = [l.rstrip("\n").split("\t") for l in pathlib.Path(path).read_text(encoding="utf-8").splitlines() if l.strip()]
+ by = {}
+ for r in rows:
+ by[r[2]] = by.get(r[2], 0) + float(r[4])
+ for m, c in sorted(by.items()):
+ print(f"{m:40s} {c:8.4f} USD")
+ print(f"{'total':40s} {sum(by.values()):8.4f} USD ({len(rows)} pictures)")
+
+
+def key():
+ f = pathlib.Path("~/.config/openrouter/key").expanduser()
+ k = os.environ.get("OPENROUTER_API_KEY") or (f.read_text().strip() if f.exists() else "")
+ if not k:
+ raise SystemExit("no key: put it in ~/.config/openrouter/key or set OPENROUTER_API_KEY")
+ return k
+
+
+def main():
+ if len(sys.argv) == 3 and sys.argv[1] == "--total":
+ return total(sys.argv[2])
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ ap.add_argument("out"); ap.add_argument("prompt"); ap.add_argument("refs", nargs="*")
+ ap.add_argument("--ar", default="16:9"); ap.add_argument("--q", default="medium", choices=["low", "medium", "high"])
+ ap.add_argument("--bg", default="auto", choices=["auto", "transparent", "opaque"])
+ ap.add_argument("--model", default="openai/gpt-image-2.5-flare")
+ ap.add_argument("--ledger", required=True, help="tab-separated cost log, e.g. books/<book>/art/costs.tsv")
+ a = ap.parse_args()
+ if a.q == "high":
+ raise SystemExit("quality high is refused: use low or medium")
+ body = {"model": a.model, "prompt": a.prompt, "aspect_ratio": a.ar, "output_format": "png"}
+ if a.model.startswith("openai/"):
+ body.update(quality=a.q, background=a.bg)
+ else:
+ body["resolution"] = "2K"
+ if a.refs:
+ body["input_references"] = [{"type": "image_url", "image_url": {"url": "data:image/png;base64," + base64.b64encode(pathlib.Path(r).read_bytes()).decode()}} for r in a.refs]
+ req = urllib.request.Request("https://openrouter.ai/api/v1/images", json.dumps(body).encode(),
+ {"Authorization": f"Bearer {key()}", "Content-Type": "application/json"})
+ try:
+ r = json.load(urllib.request.urlopen(req, timeout=600))
+ except urllib.error.HTTPError as e:
+ raise SystemExit(f"{e.code} {e.read().decode()[:500]}")
+ out = pathlib.Path(a.out); out.parent.mkdir(parents=True, exist_ok=True)
+ out.write_bytes(base64.b64decode(r["data"][0]["b64_json"]))
+ usage = r.get("usage") or {}
+ cost = usage.get("cost", 0) or 0
+ print(a.out, f"cost {cost} USD", json.dumps(usage))
+ led = pathlib.Path(a.ledger); led.parent.mkdir(parents=True, exist_ok=True)
+ with led.open("a", encoding="utf-8") as f:
+ f.write(f"{datetime.date.today()}\t{a.out}\t{a.model}\t{a.q}\t{cost}\n")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/.claude/skills/papermorph/scripts/painted.py b/.claude/skills/papermorph/scripts/painted.py
new file mode 100644
index 0000000..93589f8
--- /dev/null
+++ b/.claude/skills/papermorph/scripts/painted.py
@@ -0,0 +1,111 @@
+#!/usr/bin/env python3
+"""Put image-model pictures into a picture book: painted sets and cut-out props, from a JSON manifest.
+
+ uv run --with pillow python painted.py books/<book>/art/painted.json site/<book>
+
+Replaces the SVG sketch of a set (bake_sets.py) by its painted layers. For every set in the manifest the layers are
+written to SITE/img/sets/<set>/<layer>.webp with a blurred <layer>-soft.webp for close-ups, and the set's entry in
+SITE/img/sets/sets.js is replaced. Full-frame pictures are resized to the 1600x900 frame and grown by mirrored, blurred
+edges (`pad`) so a shaking or zooming camera never sees past them; a `cut` layer is a transparent picture cropped to its
+opaque part and placed by its left x, bottom y and width, so characters can stand behind it. Words for signs and boards
+(the model leaves them blank) are written onto the picture. Props go to SITE/img/props/<name>.webp. Run bake_sets.py
+first (it rewrites sets.js); run this again after any change. Paths in the manifest are relative to the manifest.
+
+ {
+ "frame": [1600, 900], "pad": [60, 34], (optional, these are the defaults)
+ "fonts": {"sign": "/System/Library/Fonts/STHeiti Medium.ttc"}, (a path, or {"path": ..., "index": 0}; optional)
+ "sets": {
+ "street": [
+ {"name": "bg", "file": "bg-street.png",
+ "words": [{"x": 584, "y": 449, "size": 60, "text": "OPEN", "colour": "#f6d68a", "font": "sign"}]},
+ {"name": "cart", "file": "cart.png", "cut": {"x": 1010, "bottom": 800, "width": 470}},
+ {"name": "wall", "file": "wall.png", "box": [0, 0, 1600, 900]} (a box in world px: x, y, w, h)
+ ]},
+ "props": {"bun": "p-bun.png"} (largest side 800 px)
+ }
+
+A layer with neither `cut` nor `box` is a full frame. `font` names an entry of `fonts` or is a path; without one the
+first CJK-capable system font found is used (macOS Hiragino/PingFang/STHeiti, Windows YaHei, Noto/WenQuanYi on Linux).
+"""
+import json, pathlib, sys
+from PIL import Image, ImageDraw, ImageFilter, ImageFont
+
+SYSTEM_FONTS = [('/System/Library/Fonts/STHeiti Medium.ttc', 0), ('/System/Library/Fonts/PingFang.ttc', 0),
+ ('/System/Library/Fonts/Hiragino Sans GB.ttc', 0), ('C:/Windows/Fonts/msyh.ttc', 0),
+ ('/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc', 0), ('/usr/share/fonts/truetype/wqy/wqy-microhei.ttc', 0),
+ ('/System/Library/Fonts/Helvetica.ttc', 0), ('/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf', 0)]
+
+
+def load_font(spec, size, base):
+ path, idx = (spec['path'], spec.get('index', 0)) if isinstance(spec, dict) else (spec, 0)
+ p = pathlib.Path(path).expanduser()
+ p = p if p.is_absolute() else base / p
+ return ImageFont.truetype(str(p), size, index=idx)
+
+
+def default_font(size):
+ for path, idx in SYSTEM_FONTS:
+ if pathlib.Path(path).exists():
+ return ImageFont.truetype(path, size, index=idx)
+ return ImageFont.load_default()
+
+
+def words(im, items, ox, oy, fonts, base):
+ d = ImageDraw.Draw(im)
+ for w in items:
+ f = w.get('font')
+ spec = fonts.get(f, f) if f else None
+ font = load_font(spec, w['size'], base) if spec else default_font(w['size'])
+ d.text((w['x'] - ox, w['y'] - oy), w['text'], fill=w.get('colour', '#ffffff'), font=font, anchor='mm')
+
+
+def padded(im, pad):
+ px, py = pad; W, H = im.size; out = Image.new('RGBA', (W + 2 * px, H + 2 * py))
+ out.paste(im.transpose(Image.FLIP_LEFT_RIGHT).transpose(Image.FLIP_TOP_BOTTOM).resize((W + 2 * px, H + 2 * py)).filter(ImageFilter.GaussianBlur(12)))
+ for dx, dy, flip, box in [(-px, 0, Image.FLIP_LEFT_RIGHT, (0, 0, px, H)), (W, 0, Image.FLIP_LEFT_RIGHT, (W - px, 0, W, H)),
+ (0, -py, Image.FLIP_TOP_BOTTOM, (0, 0, W, py)), (0, H, Image.FLIP_TOP_BOTTOM, (0, H - py, W, H))]:
+ out.paste(im.crop(box).transpose(flip).filter(ImageFilter.GaussianBlur(3)), (dx + px, dy + py))
+ out.paste(im, (px, py)); return out
+
+
+def tight(im): # crop a cut-out to its opaque part
+ return im.crop(im.getchannel('A').point(lambda v: 255 if v > 20 else 0).getbbox())
+
+
+def main(manifest, site):
+ mp = pathlib.Path(manifest).resolve(); base = mp.parent
+ m = json.loads(mp.read_text(encoding='utf-8'))
+ W, H = m.get('frame', [1600, 900]); pad = m.get('pad', [60, 34]); fonts = m.get('fonts', {})
+ sets_js = pathlib.Path(site) / 'img/sets/sets.js'
+ sets = json.loads(sets_js.read_text().split('=', 1)[1].strip().rstrip(';')) if sets_js.exists() else {}
+ for name, layers in m.get('sets', {}).items():
+ out = sets_js.parent / name; out.mkdir(parents=True, exist_ok=True)
+ for f in out.glob('*.webp'): f.unlink()
+ entry = []
+ for L in layers:
+ im = Image.open(base / L['file']).convert('RGBA')
+ if 'cut' in L:
+ c = L['cut']; im = tight(im); im = im.resize((c['width'], round(im.height * c['width'] / im.width)), Image.LANCZOS)
+ b = [c['x'], c['bottom'] - im.height, c['width'], im.height]; words(im, L.get('words', []), b[0], b[1], fonts, base)
+ elif 'box' in L:
+ b = L['box']; im = im.resize((b[2], b[3]), Image.LANCZOS); words(im, L.get('words', []), b[0], b[1], fonts, base)
+ else:
+ im = im.resize((W, H), Image.LANCZOS); words(im, L.get('words', []), 0, 0, fonts, base)
+ im = padded(im, pad); b = [-pad[0], -pad[1], W + 2 * pad[0], H + 2 * pad[1]]
+ im.save(out / f"{L['name']}.webp", quality=88, method=6)
+ im.filter(ImageFilter.GaussianBlur(6)).save(out / f"{L['name']}-soft.webp", quality=80, method=6)
+ entry.append({'name': L['name'], 'k': L.get('k', 1), 'box': b, 'soft': True})
+ print(name, L['name'], b)
+ sets[name] = entry
+ sets_js.parent.mkdir(parents=True, exist_ok=True)
+ sets_js.write_text('window.SETS = ' + json.dumps(sets) + ';\n')
+ props = pathlib.Path(site) / 'img/props'; props.mkdir(parents=True, exist_ok=True)
+ for name, src in m.get('props', {}).items():
+ im = tight(Image.open(base / src).convert('RGBA')); im.thumbnail((800, 800), Image.LANCZOS)
+ im.save(props / f'{name}.webp', quality=88, method=6); print('prop', name, im.size)
+
+
+if __name__ == '__main__':
+ if len(sys.argv) != 3:
+ print(__doc__); sys.exit(0 if sys.argv[1:] in (['-h'], ['--help']) else 2)
+ main(*sys.argv[1:3])
diff --git a/.claude/skills/papermorph/scripts/sfx.py b/.claude/skills/papermorph/scripts/sfx.py
new file mode 100644
index 0000000..5ad7475
--- /dev/null
+++ b/.claude/skills/papermorph/scripts/sfx.py
@@ -0,0 +1,488 @@
+#!/usr/bin/env python3
+"""Sound effects for a picture book, synthesized with numpy (no samples): named recipes written as mono 44.1 kHz MP3s.
+
+ uv run --with numpy python sfx.py site/<book>/ch01/audio/sfx knock door rain # these effects, OUT_DIR/<name>.mp3
+ uv run --with numpy python sfx.py site/<book>/ch01/audio/sfx all # every recipe
+ python3 sfx.py --list # names with a one-line description
+
+Needs ffmpeg. Every file is faded (5 ms) and peak-normalised to -3 dBFS; each recipe is seeded by its name, so a name
+always renders the same sound. Play them from a chapter with sfx(beat, seconds, 'name', volume) (paper-cutout kit,
+shared.js), which plays them at half volume under the voices.
+
+Add a recipe: write a function that returns a float array at SR, built from the small toolkit below (t_of, unit, place,
+lp1/hp1/bpf filters, pluck, pink, drops), and list it in RECIPES. Keep them soft and natural: a hard high hiss reads
+as "scary rain" and a bare sine as a phone, so layer a low thump under a click, shape every sound with a decay, and
+listen before using one. Recipes: sting growl gulp door tick bell whoosh fly violin crickets chair (character and
+house sounds), knock chop bang bonk thud crash (wood, axe, glass, a wardrobe door), plop sniff chomp burp lick bark
+(eating and a dog), chime beep card coin (a convenience store), rain and rain-short (gentle rain).
+"""
+import math
+import os
+import subprocess
+import sys
+import tempfile
+import wave
+import zlib
+
+import numpy as np
+
+SR = 44100
+rng = np.random.default_rng(1019) # replaced per recipe in main(), seeded by the recipe's name
+
+
+def t_of(dur):
+ return np.arange(int(round(dur * SR))) / SR
+
+
+def unit(x):
+ return x / np.max(np.abs(x))
+
+
+def place(y, x, t0):
+ i = int(t0 * SR)
+ n = min(len(x), len(y) - i)
+ y[i:i + n] += x[:n]
+
+
+def lp1(x, fc):
+ """One-pole low-pass."""
+ a = math.exp(-2 * math.pi * fc / SR)
+ out, s = [], 0.0
+ for v in x.tolist():
+ s = a * s + (1 - a) * v
+ out.append(s)
+ return np.array(out)
+
+
+def hp1(x, fc):
+ return x - lp1(x, fc)
+
+
+def bpf(x, fc, q=5.0):
+ """RBJ constant-peak band-pass; fc may be a per-sample array."""
+ fcs = np.broadcast_to(np.asarray(fc, float), x.shape).tolist()
+ out, x1, x2, y1, y2 = [], 0.0, 0.0, 0.0, 0.0
+ for v, f in zip(x.tolist(), fcs):
+ w = 2 * math.pi * f / SR
+ al, c = math.sin(w) / (2 * q), math.cos(w)
+ y = (al * (v - x2) + 2 * c * y1 - (1 - al) * y2) / (1 + al)
+ out.append(y)
+ x2, x1, y2, y1 = x1, v, y1, y
+ return np.array(out)
+
+
+def pluck(f, dur, decay=0.996):
+ """Karplus-Strong string with a two-point average (lowpass) in the loop."""
+ n = int(round(SR / f - 0.5))
+ buf = rng.uniform(-1, 1, n).tolist()
+ out = []
+ for i in range(int(dur * SR)):
+ j = i % n
+ s = buf[j]
+ out.append(s)
+ buf[j] = decay * 0.5 * (s + buf[(j + 1) % n])
+ return np.array(out)
+
+
+def pink(n):
+ """1/f noise: white noise shaped in the frequency domain."""
+ f = np.fft.rfftfreq(n, 1 / SR)
+ f[0] = 1
+ return np.fft.irfft(np.fft.rfft(rng.standard_normal(n)) / np.sqrt(f), n)
+
+
+def drops(n, rate, fc, q, decay, lo, hi):
+ """Random short band-passed ticks (rain on stone or fabric): `rate` per second, pitch near fc."""
+ y = np.zeros(n)
+ for _ in range(rng.poisson(rate * n / SR)):
+ m = int(decay * 6 * SR)
+ s = np.arange(m) / SR
+ d = bpf(rng.standard_normal(m), fc * rng.uniform(.8, 1.25), q) * np.exp(-s / decay)
+ place(y, d * rng.uniform(lo, hi), rng.uniform(0, n / SR - decay * 6))
+ return y
+
+
+noise = lambda n: rng.standard_normal(n)
+
+
+def sting():
+ """A four-note plucked flourish that settles into a chord (a title or a joke landing)."""
+ dur, y = 2.5, np.zeros(int(2.5 * SR))
+ for f, t0 in [(146.83, 0.00), (196.00, 0.18), (246.94, 0.36), (293.66, 0.54)]:
+ place(y, pluck(f, 0.9), t0)
+ for k, f in enumerate([98.00, 123.47, 146.83, 196.00, 246.94, 392.00]):
+ place(y, pluck(f, dur - 0.80), 0.80 + k * 0.015)
+ return y
+
+
+def growl():
+ """A low, wavering growl."""
+ t = t_of(1.4)
+ brown = hp1(np.cumsum(rng.standard_normal(len(t))), 20)
+ y = bpf(brown, 110 + 30 * np.sin(2 * np.pi * 1.1 * t), q=6)
+ rate = 6 + 0.8 * np.sin(2 * np.pi * 0.4 * t) # tremolo 5-7 Hz
+ trem = 0.35 + 0.65 * (0.5 + 0.5 * np.sin(2 * np.pi * np.cumsum(rate) / SR))
+ swells = np.interp(t, np.arange(0, 1.6, 0.3), rng.uniform(0.5, 1, 6))
+ return unit(y) * trem * swells
+
+
+def gulp():
+ """Three quick glugs."""
+ y = np.zeros(int(1.0 * SR))
+ for t0 in (0.0, 0.3, 0.6):
+ t = t_of(0.2)
+ tt = np.minimum(t, 0.12)
+ phase = 2 * np.pi * (320 * tt - 100 * tt ** 2 / 0.12 + 120 * np.maximum(t - 0.12, 0))
+ glug = np.sin(phase) * np.exp(-t / 0.045)
+ click = rng.standard_normal(len(t)) * np.exp(-t / 0.002) * 0.15
+ place(y, glug + click, t0)
+ return y
+
+
+def door():
+ """A door shut hard: a low thump and a dull bang."""
+ t = t_of(0.6)
+ bang = lp1(lp1(rng.standard_normal(len(t)), 400), 400) * np.exp(-t / 0.05)
+ thump = np.sin(2 * np.pi * 70 * t) * np.exp(-t / 0.08)
+ return unit(bang) * 0.7 + unit(thump) * 0.9
+
+
+def tick():
+ """A small dry click."""
+ t = t_of(0.1)
+ click = np.zeros(len(t))
+ n = int(0.002 * SR)
+ click[:n] = hp1(rng.standard_normal(n), 2000) * np.exp(-t[:n] / 0.0008)
+ m = int(0.010 * SR)
+ sine = np.zeros(len(t))
+ sine[:m] = np.sin(2 * np.pi * 3000 * t[:m]) * np.exp(-t[:m] / 0.003)
+ return unit(click) * 0.6 + unit(sine) * 0.8
+
+
+def bell():
+ """A school bell: a ringing hammer, three seconds."""
+ dur, t = 3.0, t_of(3.0)
+ y = np.zeros(len(t))
+ partials = [(1000, 1.0, 0.12), (2410, 0.5, 0.08), (3920, 0.25, 0.05)]
+ for ts in np.arange(0, dur, 1 / 22): # hammer strikes at ~22 Hz
+ i0 = int(ts * SR)
+ seg = np.arange(min(int(0.5 * SR), len(t) - i0)) / SR
+ for f, a, tau in partials:
+ y[i0:i0 + len(seg)] += a * np.exp(-seg / tau) * np.sin(2 * np.pi * f * seg)
+ env = np.clip((dur - t) / 0.3, 0, 1) # full 2.7 s, then 0.3 s release
+ return unit(y) * env
+
+
+def whoosh():
+ """A swift pass: filtered noise sweeping up."""
+ dur = 0.45
+ t = t_of(dur)
+ y = bpf(rng.standard_normal(len(t)), 400 * (2500 / 400) ** (t / dur), q=2.5)
+ return unit(y) * np.sin(np.pi * t / dur) ** 2
+
+
+def fly():
+ """A fly circling: a buzzing 220 Hz saw with vibrato."""
+ dur = 3.0
+ t = t_of(dur)
+ f = 220 + 12 * np.sin(2 * np.pi * 8 * t) # 8 Hz vibrato, +-12 Hz
+ phase = 2 * np.pi * np.cumsum(f) / SR
+ saw = np.zeros(len(t))
+ for k in range(1, 69): # band-limited sawtooth, harmonics below ~15 kHz
+ saw += np.sin(k * phase) / k
+ wander = lp1(rng.standard_normal(len(t)), 0.7) # circling amplitude
+ y = unit(saw) * (0.65 + 0.35 * unit(wander))
+ y = hp1(hp1(y, 150), 150)
+ return y * np.minimum(t / 0.3, 1) * np.minimum((dur - t) / 0.3, 1)
+
+
+def violin():
+ """A sad four-note violin phrase with a little echo."""
+ dur, out = 3.5, np.zeros(int(3.5 * SR) + int(0.2 * SR))
+ t0 = 0.0
+ for f, d in [(440.0, 0.7), (392.0, 0.7), (349.23, 0.7), (329.63, 1.4)]:
+ t = t_of(d)
+ vib = np.where(t > 0.15, 0.006 * np.sin(2 * np.pi * 5.5 * t) * np.minimum((t - 0.15) / 0.2, 1), 0)
+ phase = 2 * np.pi * np.cumsum(f * (1 + vib)) / SR
+ wave_ = sum(np.sin(k * phase) / k for k in range(1, 13))
+ env = np.minimum(t / 0.08, 1) * np.minimum((d - t) / 0.05, 1)
+ place(out, wave_ * env * 0.5, t0)
+ t0 += d
+ for _ in range(2): # ~3 kHz low-pass, two one-poles
+ out = lp1(out, 3000)
+ echo = out.copy()
+ for delay, gain in [(0.060, 10 ** (-10 / 20)), (0.110, 10 ** (-16 / 20))]:
+ d = int(delay * SR)
+ echo[d:] += gain * out[:-d]
+ return echo[:int(dur * SR)]
+
+
+def crickets():
+ """Crickets in the evening."""
+ dur, y = 3.0, np.zeros(int(3.0 * SR))
+ pulse_len = int(0.012 * SR)
+ s = np.arange(pulse_len) / SR
+ pulse_env = np.sin(np.pi * s / 0.012) ** 2
+ for f, off, gain in [(4500, 0.0, 1.0), (4800, 0.27, 0.6)]:
+ for b0 in np.arange(off, dur, 0.6):
+ amp = gain * rng.uniform(0.8, 1.0)
+ for p in range(3): # three pulses at 30 Hz
+ place(y, amp * np.sin(2 * np.pi * f * s) * pulse_env, b0 + p / 30)
+ return y
+
+
+def chair():
+ """A chair scraping the floor."""
+ t = t_of(0.5)
+ y = bpf(rng.standard_normal(len(t)), 700, q=6)
+ jitter = np.repeat(rng.uniform(0.3, 1, int(np.ceil(0.5 / 0.01))), int(0.01 * SR))[:len(t)]
+ return unit(y) * jitter
+
+
+def knock():
+ """Knuckles on a wooden door."""
+ t = t_of(.18)
+ return unit(bpf(noise(len(t)), 190, q=3) * np.exp(-t / .02)) * .8 + unit(np.sin(2 * np.pi * 95 * t) * np.exp(-t / .03)) * .7
+
+
+def chop():
+ """An axe into a log: a crack, the wood's ring, a low thump."""
+ t = t_of(.32)
+ crack = hp1(noise(len(t)), 2500) * np.exp(-t / .004)
+ wood = bpf(noise(len(t)), 620, q=2.5) * np.exp(-t / .045)
+ thump = np.sin(2 * np.pi * 120 * t) * np.exp(-t / .06)
+ return unit(crack) * .5 + unit(wood) * .8 + unit(thump) * .7
+
+
+def bang():
+ """A door flung against the wall, then a rattle."""
+ t = t_of(.6)
+ y = unit(lp1(noise(len(t)), 500) * np.exp(-t / .07)) * .7 + unit(np.sin(2 * np.pi * 68 * t) * np.exp(-t / .1)) * .9
+ for k, at in enumerate((.11, .17, .21)):
+ place(y, unit(bpf(noise(int(.03 * SR)), 900, q=4)) * np.exp(-t_of(.03) / .006) * (.35 - .1 * k), at)
+ return y
+
+
+def bonk():
+ """An umbrella on a head: a hollow pitch that drops."""
+ t = t_of(.4)
+ f = 560 * np.exp(-t / .25)
+ tone = np.sin(2 * np.pi * np.cumsum(f) / SR) * np.exp(-t / .12)
+ return unit(tone) + unit(hp1(noise(len(t)), 1500) * np.exp(-t / .003)) * .4
+
+
+def thud():
+ """A soft fall onto a floor."""
+ t = t_of(.4)
+ return unit(lp1(lp1(noise(len(t)), 180), 180) * np.exp(-t / .08)) * .8 + unit(np.sin(2 * np.pi * 58 * t) * np.exp(-t / .12)) * .8
+
+
+def crash():
+ """A window pane: the hit, a hiss of glass, then shards tinkling down."""
+ t = t_of(1.6)
+ y = unit(hp1(noise(len(t)), 1800) * np.exp(-t / .07)) * .9
+ y += unit(bpf(noise(len(t)), 4200, q=1.5) * np.exp(-t / .3)) * .35
+ y += unit(lp1(noise(len(t)), 300) * np.exp(-t / .05)) * .5
+ for _ in range(46):
+ at = rng.uniform(0, 1.1) ** 1.6
+ d = t_of(rng.uniform(.03, .12))
+ ping = np.sin(2 * np.pi * rng.uniform(2600, 7500) * d) * np.exp(-d / (d[-1] / 3))
+ place(y, ping * rng.uniform(.15, .45) * (1 - at / 1.3), at)
+ return y
+
+
+def plop():
+ """A single bloop, like a drop in a bowl."""
+ dur = 0.35
+ t = t_of(dur)
+ f = 400 + 500 * np.minimum(t / 0.04, 1) # pitch rises 400 -> 900 Hz in 40 ms
+ bloop = np.sin(2 * np.pi * np.cumsum(f) / SR) * np.exp(-t / 0.06)
+ n = int(0.002 * SR)
+ tick = np.zeros(len(t))
+ tick[:n] = hp1(rng.standard_normal(n), 2000) * np.exp(-t[:n] / 0.0008)
+ return unit(bloop) + 0.12 * unit(tick)
+
+
+def sniff():
+ """Three short sniffs."""
+ dur = 0.9
+ y = np.zeros(int(dur * SR))
+ n = int(0.10 * SR)
+ s = np.arange(n) / SR
+ env = np.minimum(s / 0.03, 1) * np.clip(1 - (s - 0.03) / 0.07, 0, 1) # 30 ms rise, 70 ms fall
+ for t0, fc, level in [(0.0, 2500, 1.0), (0.25, 2750, 0.8), (0.5, 2300, 0.9)]:
+ noise = bpf(rng.standard_normal(n), fc, q=2)
+ place(y, unit(noise) * env * level, t0)
+ return y
+
+
+def chomp():
+ """A bite of something crunchy."""
+ dur = 0.4
+ t = t_of(dur)
+ thump = np.sin(2 * np.pi * 90 * t) * np.exp(-t / 0.06)
+ crackle = hp1(rng.standard_normal(len(t)), 1500)
+ gate = np.zeros(len(t))
+ for _ in range(rng.integers(6, 11)): # 6-10 tiny bursts in the first 200 ms
+ i0 = int(rng.uniform(0, 0.2) * SR)
+ n = int(rng.uniform(0.005, 0.015) * SR)
+ n = min(n, len(t) - i0)
+ gate[i0:i0 + n] = np.sin(np.pi * np.arange(n) / n)
+ return unit(thump) + 0.6 * unit(crackle * gate)
+
+
+def burp():
+ """A low, short burp."""
+ dur = 0.8
+ t = t_of(dur)
+ f = 110 - 30 * t / dur # 110 -> 80 Hz
+ phase = 2 * np.pi * np.cumsum(f) / SR
+ saw = sum(np.sin(k * phase) / k for k in range(1, 9))
+ am = 0.6 + 0.4 * np.sin(2 * np.pi * 30 * t + 0.8 * np.sin(2 * np.pi * 3.7 * t)) # irregular 30 Hz
+ y = saw * am
+ y = lp1(lp1(y, 900), 900)
+ env = np.minimum(t / 0.04, 1) * np.clip((dur - t) / 0.6, 0, 1) # 40 ms rise, slow 0.6 s fade
+ return unit(y) * env
+
+
+def lick():
+ """A wet lick."""
+ dur = 0.5
+ t = t_of(dur)
+ n = len(t)
+ fc = 800 + 2200 * np.minimum(t / 0.3, 1) # centre sweeps 800 -> 3000 Hz
+ wet = bpf(rng.standard_normal(n), fc, q=2)
+ wobble = 0.7 + 0.3 * np.sin(2 * np.pi * 60 * t)
+ env = np.minimum(t / 0.05, 1) * np.clip((dur - t) / 0.2, 0, 1)
+ y = unit(wet) * wobble * env
+ m = int(0.002 * SR)
+ s = np.arange(m) / SR
+ click = hp1(rng.standard_normal(m), 2000) * np.exp(-s / 0.0008)
+ place(y, unit(click) * 0.4, 0.46)
+ return y
+
+
+def bark():
+ """A small dog barks once."""
+ dur = 0.35
+ t = t_of(dur)
+ f = 420 - 120 * np.minimum(t / 0.15, 1) # 420 -> 300 Hz
+ phase = 2 * np.pi * np.cumsum(f) / SR
+ tone = sum(np.sin(k * phase) / k for k in range(1, 7))
+ breath = bpf(rng.standard_normal(len(t)), 1200, q=2)
+ env = np.minimum(t / 0.01, 1) * np.exp(-t / 0.12) # 10 ms attack, ~120 ms decay
+ return (0.7 * unit(tone) + 0.3 * unit(breath)) * env
+
+
+def chime():
+ """Two soft notes, E6 then C6, second starting at 0.35 s."""
+ y = np.zeros(int(1.6 * SR))
+ for f, t0 in [(1318.51, 0.0), (1046.50, 0.35)]:
+ t = t_of(1.25)
+ env = np.minimum(t / 0.005, 1) * np.exp(-t / 0.2)
+ tone = np.sin(2 * np.pi * f * t) + 0.2 * np.sin(2 * np.pi * 2 * f * t)
+ place(y, tone * env, t0)
+ return y
+
+
+def beep():
+ """Barcode scanner: one clean 2.7 kHz sine, 0.12 s, then quiet tail."""
+ y = np.zeros(int(0.25 * SR))
+ t = t_of(0.12)
+ place(y, np.sin(2 * np.pi * 2700 * t) * 0.8, 0.0)
+ return y
+
+
+def card():
+ """Terminal accepting: two short 1.8 kHz beeps, then a softer rising tone."""
+ y = np.zeros(int(0.62 * SR))
+ t = t_of(0.08)
+ beep_tone = np.sin(2 * np.pi * 1800 * t) * np.sin(np.pi * t / 0.08) ** 2
+ place(y, beep_tone, 0.0)
+ place(y, beep_tone, 0.20)
+ t = t_of(0.24)
+ f = np.linspace(2000, 2600, len(t))
+ rise = np.sin(2 * np.pi * np.cumsum(f) / SR) * np.sin(np.pi * t / 0.24) ** 2 * 0.5
+ place(y, rise, 0.36)
+ return y
+
+
+def coin():
+ """100-yen coin on a counter: inharmonic metallic tap, tiny wood knock, small bounce."""
+ y = np.zeros(int(0.9 * SR))
+ partials = [(3200, 1.0, 0.12), (5100, 0.6, 0.10), (7400, 0.4, 0.08), (9800, 0.25, 0.06)]
+
+ def metal(gain):
+ t = t_of(0.4)
+ tap = sum(a * np.exp(-t / tau) * np.sin(2 * np.pi * f * t) for f, a, tau in partials)
+ click = rng.standard_normal(len(t)) * np.exp(-t / 0.001)
+ return (tap + click * 0.3) * gain
+
+ place(y, metal(1.0), 0.0)
+ place(y, metal(0.3), 0.06) # small second bounce, quieter
+ t = t_of(0.05)
+ knock = np.sin(2 * np.pi * 450 * t) * np.exp(-t / 0.015)
+ place(y, lp1(knock + rng.standard_normal(len(t)) * np.exp(-t / 0.003) * 0.2, 2500) * 0.4, 0.0)
+ return y
+
+
+def rain(dur=5.0, fade=.35):
+ """Gentle rain: a soft pink-noise wash, fine patter on the pavement and drops tapping on umbrellas."""
+ t = t_of(dur)
+ n = len(t)
+ wash = hp1(lp1(lp1(pink(n), 3500), 3500), 120)
+ patter = drops(n, 90, 2200, 2.0, .004, .2, .6)
+ taps = drops(n, 22, 700, 3.0, .012, .4, 1.0)
+ y = unit(wash) * .75 + unit(patter) * .25 + unit(taps) * .3
+ return y * np.minimum(t / fade, 1) * np.minimum((dur - t) / fade, 1)
+
+
+RECIPES = {name: globals()[name] for name in (
+ "sting growl gulp door tick bell whoosh fly violin crickets chair knock chop bang bonk thud crash plop sniff "
+ "chomp burp lick bark chime beep card coin rain").split()}
+RECIPES["rain-short"] = lambda: rain(1.15, .12)
+RECIPES["rain-short"].__doc__ = "About one second of the same rain, for a quick cut."
+
+
+def write_mp3(path, y):
+ fade = int(0.005 * SR)
+ ramp = np.linspace(0, 1, fade)
+ y = y.copy()
+ y[:fade] *= ramp
+ y[-fade:] *= ramp[::-1]
+ y *= 10 ** (-3 / 20) / np.max(np.abs(y))
+ pcm = (np.clip(y, -1, 1) * 32767).astype("<i2")
+ with tempfile.TemporaryDirectory() as d:
+ wav = os.path.join(d, "x.wav")
+ with wave.open(wav, "wb") as w:
+ w.setnchannels(1)
+ w.setsampwidth(2)
+ w.setframerate(SR)
+ w.writeframes(pcm.tobytes())
+ subprocess.run(["ffmpeg", "-y", "-loglevel", "error", "-i", wav, "-ac", "1", "-ar", str(SR),
+ "-b:a", "128k", str(path)], check=True)
+
+
+def main(argv):
+ global rng
+ if argv == ["--list"]:
+ for name, fn in RECIPES.items():
+ doc = (fn.__doc__ or "").strip().splitlines()
+ print(f"{name:12s}{doc[0] if doc else ''}")
+ return
+ if len(argv) < 2 or argv[0] in ("-h", "--help"):
+ print(__doc__)
+ sys.exit(0 if argv[:1] in (["-h"], ["--help"]) else 2)
+ out, names = argv[0], (list(RECIPES) if argv[1:] == ["all"] else argv[1:])
+ unknown = [n for n in names if n not in RECIPES]
+ if unknown:
+ sys.exit(f"unknown: {', '.join(unknown)} (sfx.py --list)")
+ os.makedirs(out, exist_ok=True)
+ for name in names:
+ rng = np.random.default_rng(zlib.crc32(name.encode()))
+ write_mp3(os.path.join(out, name + ".mp3"), RECIPES[name]())
+ print("wrote", name)
+
+
+if __name__ == "__main__":
+ main(sys.argv[1:])
diff --git a/.claude/skills/papermorph/scripts/tts.py b/.claude/skills/papermorph/scripts/tts.py
index 57fa3b1..b11eba7 100644
--- a/.claude/skills/papermorph/scripts/tts.py
+++ b/.claude/skills/papermorph/scripts/tts.py
@@ -9,6 +9,9 @@ access. Kokoro (Apache 2.0) runs locally: its first run downloads the model (abo
voices start with the accent's letter (am_michael, af_heart: American; bm_george, bf_emma: British) and its word
timings cover English. Both need ffmpeg/ffprobe.
+A book with several speakers lists them under "voices" ({name: {"voice", "rate", "pitch"}}) and writes a
+beat as {"speaker": name, "text": ...}; plain string beats use the file's own voice. Pitch is Edge only ("+20Hz").
+
Narration text may contain [[mark]] tags placed before a word. The output
timings.js records each clip's duration and the time (seconds) at which the
word after every mark starts, so page animations can wait for that word,
@@ -42,10 +45,10 @@ FIRST_RETRY_DELAY = 2 # seconds before the second request; doubles after eac
PROBE_TEXT = "1, 2, 3." # checks the voice after a beat fails; any voice reads digits in its own language
-async def synth(text, voice, rate, mp3_path):
+async def synth(text, voice, rate, mp3_path, pitch="+0Hz"):
import edge_tts
words = [] # (seconds, word)
- comm = edge_tts.Communicate(text, voice, rate=rate, boundary="WordBoundary")
+ comm = edge_tts.Communicate(text, voice, rate=rate, pitch=pitch, boundary="WordBoundary")
with open(mp3_path, "wb") as f:
async for chunk in comm.stream():
if chunk["type"] == "audio":
@@ -55,12 +58,12 @@ async def synth(text, voice, rate, mp3_path):
return words
-async def synth_with_retries(beat, text, voice, rate, mp3_path):
+async def synth_with_retries(beat, text, voice, rate, mp3_path, pitch):
"""synth(), requested again after NoAudioReceived; each attempt rewrites mp3_path from the start."""
from edge_tts.exceptions import NoAudioReceived
for attempt in range(1, MAX_ATTEMPTS + 1):
try:
- return await synth(text, voice, rate, mp3_path)
+ return await synth(text, voice, rate, mp3_path, pitch)
except NoAudioReceived:
if attempt == MAX_ATTEMPTS:
raise
@@ -76,7 +79,7 @@ async def explain_no_audio(beat, voice, rate, out_dir):
with tempfile.NamedTemporaryFile(dir=out_dir, prefix=".probe-", suffix=".mp3", delete=False) as f:
probe_path = Path(f.name)
try:
- await synth(PROBE_TEXT, voice, rate, probe_path)
+ await synth(PROBE_TEXT, voice, rate, probe_path) # default pitch
voice_works = True
except NoAudioReceived:
voice_works = False
@@ -90,10 +93,10 @@ async def explain_no_audio(beat, voice, rate, out_dir):
"Rerun later, or choose another voice for the whole book (uv run --with edge-tts edge-tts --list-voices).")
-async def edge_beat(beat, text, voice, rate, mp3_path, out_dir):
+async def edge_beat(beat, text, voice, rate, mp3_path, out_dir, pitch):
from edge_tts.exceptions import NoAudioReceived
try:
- return await synth_with_retries(beat, text, voice, rate, mp3_path)
+ return await synth_with_retries(beat, text, voice, rate, mp3_path, pitch)
except NoAudioReceived:
raise SystemExit(await explain_no_audio(beat, voice, rate, out_dir)) from None
@@ -195,7 +198,7 @@ async def main(src, out_dir):
out_dir.mkdir(parents=True, exist_ok=True)
cache_path = Path(src).with_suffix(".timings.json") # build cache, kept out of the site
cache = json.loads(cache_path.read_text(encoding="utf-8-sig")) if cache_path.exists() else {}
- voice, rate, engine = spec["voice"], spec["rate"], spec.get("engine", "edge")
+ engine, voices = spec.get("engine", "edge"), spec.get("voices", {})
if engine not in ("edge", "kokoro"):
raise SystemExit(f"unknown engine {engine!r}: use edge or kokoro")
result = {}
@@ -204,11 +207,16 @@ async def main(src, out_dir):
if {"dur", "marks", "cues"} <= v.keys() and (out_dir / f"{b}.mp3").exists()}
timings_path = out_dir / "timings.js"
for beat, raw in spec["beats"].items():
+ who = voices[raw["speaker"]] if isinstance(raw, dict) else spec
+ raw = raw["text"] if isinstance(raw, dict) else raw
+ voice, rate, pitch = who["voice"], who.get("rate", "+0%"), who.get("pitch", "+0Hz")
+ if pitch != "+0Hz" and engine == "kokoro":
+ raise SystemExit(f"{beat}: pitch is Edge only")
mp3 = out_dir / f"{beat}.mp3"
old = cache.get(beat)
clean, marks = split_marks(raw)
tag = "" if engine == "edge" else f"{engine}|" # Edge keys stay as they were, so its audio is kept
- key = hashlib.sha1(f"{tag}{voice}|{rate}|{clean}".encode()).hexdigest()
+ key = hashlib.sha1(f"{tag}{voice}|{rate}|{'' if pitch == '+0Hz' else pitch + '|'}{clean}".encode()).hexdigest()
# Existing caches included [[marks]] in the key; reuse an unchanged old beat once,
# then save its spoken-text key so future mark edits do not regenerate audio.
legacy_key = hashlib.sha1(f"{voice}|{rate}|{raw}".encode()).hexdigest()
@@ -224,7 +232,7 @@ async def main(src, out_dir):
try:
if not reusable:
words = (kokoro_beat(clean, voice, rate, clip) if engine == "kokoro"
- else await edge_beat(beat, clean, voice, rate, clip, out_dir))
+ else await edge_beat(beat, clean, voice, rate, clip, out_dir, pitch))
entry = {"key": key, "dur": duration(clip), "words": words,
"marks": mark_times(clean, marks, words), "cues": caption_cues(clean, words)}
if tmp:
diff --git a/README.md b/README.md
index 18ab610..cdd49f0 100644
--- a/README.md
+++ b/README.md
@@ -39,7 +39,7 @@ The Skill starts by asking: it finds your PDF, says what the book is, suggests a
- [x] **Math books:** formulas and diagrams that change step by step, with quizzes. Two books on the shelf.
- [ ] **Physics books:** illustrated scenes, acting characters and camera work. Chapters 9–12 are on the shelf; chapter 12 was made by the new Skill.
-- [ ] **Picture books:** image models and storyboards for interactive picture books. In local testing.
+- [x] **Picture books:** short films of paper puppets from a story, a joke or a fairy tale; sets drawn in code or painted by an image model. *Little Red Riding Hood* and *Joke Collection* are on the shelf.
- [ ] **Humanities documentaries:** history and social science titles.
Along the way, the bookshelf grows and new Skills are released.
@@ -58,7 +58,7 @@ In Claude Code with Opus 5.5, run:
/papermorph
```
-It looks for the PDF in your project, then asks the rest. Diagrams that change (tier 1) suit maths and other abstract topics; illustrated scenes (tier 2) suit physics and stories. Picture books and documentaries are coming.
+It looks for the PDF in your project, then asks the rest. Diagrams that change (tier 1) suit maths and other abstract topics; illustrated scenes (tier 2) suit physics and stories. For a picture book, bring a story instead of a PDF. Documentaries are coming.
Before you review a chapter, `scripts/lint.py` catches broken names, missing audio and stale narration in under a second.