An AI skill that turns books into animated, narrated, interactive web experiences
JavaScript ai-agentsai-educationanimationclaudeclaude-codeclaude-skillsedtecheducationinteractive-textbookscormtext-to-video
fix: audit book runtime and production skill
yzr6d9ac655075b
diff --git a/.claude/skills/papermorph/SKILL.md b/.claude/skills/papermorph/SKILL.mdindex 2b7bc6c..2e4f163 100644--- a/.claude/skills/papermorph/SKILL.md+++ b/.claude/skills/papermorph/SKILL.md@@ -1,13 +1,13 @@---name: papermorph-description: Make or edit animated, narrated, interactive web books from reference PDFs. Use for book planning, chapter animation and exercises, narration, cover and contents pages, and requested publishing, including "make the next chapter" or "fix this animation".+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.---# PapermorphMake the picture explain the idea through change: rearrange, split, balance, count, compare. Each chapter is one 1600×900 SVG stage plus controls; **beats** pair narration clips with timed actions. Quick checks and final practice happen inside the picture. Templates supply mechanics; choose the visual argument for the content.-Follow the pipeline forward, entering at the requested stage for existing work. User requests override defaults. Default to code/SVG artwork; record any other asset choices in the book's conventions. Re-create explanations, examples and drawings; keep source PDFs, page images and extracted text outside the published folder and out of version control (`.gitignore`: `*.pdf`, `books/*/pages/`). Publishing and pushing require the user's instruction.+Follow the pipeline forward, entering at the requested stage for existing work. User requests override defaults. Default to code/SVG artwork; record any other asset choices in the book's conventions. 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@@ -20,8 +20,7 @@ books/<book>/chapters/chNN.md brief storyboard, relevant errata and feedbackcontent/<book>/chNN/ narration.<lang>.json and TTS cachetools/<book>/ targeted tests when needed-site/ the only published folder- index.html, lib/bookshelf.* bookshelf (once there are books)+site/ static output; private sources stay outside<book>/index.html cover + contents (assets/templates/book.html)<book>/unit-art.js unit sketches (assets/templates/unit-art.js)<book>/lib/engine.js, .css this book's engine copy (assets/engine/)@@ -35,12 +34,12 @@ site/ the only published folderResolve intake, book map and pilot decisions with the user; reuse answers and approvals already given.-1. **Intake.** Choose a slug; create `books/<book>/BOOK.md` from the template. Record readers, tone, primary language, scope, assets/guide and publishing destination. Ask for missing decisions together, with defaults.+1. **Intake.** Choose a slug; create `books/<book>/BOOK.md` from the template. Record readers, tone, primary language, scope and assets/guide. Ask for missing decisions together, with defaults.2. **Split.** Run `uv run --with pymupdf SKILL/scripts/outline.py books/<book>/book.pdf`; use `--level N -o books/<book>/sections.json` at chapter depth. For a PDF without bookmarks, inspect `split_pages.py … --pages 1-12 --out books/<book>/pages`, then write the map from its contents (schema: `outline.py --help`). Match the map to the contents; extract chapter text with `split_pages.py … --sections books/<book>/sections.json --out books/<book>/pages --text-only`.3. **Book map.** Read contents and chapter openings; inspect more text where the scope is unclear. Create `chapters.md` with columns `# | Title | Unit | Minutes | Status` (planned, ready, user-approved); put colours and candidate recurring visual models in BOOK.md. Confirm the list and visual approach with the user.4. **Initialize.** Follow [site.md](references/site.md#start-a-book-folder) to copy the book engine, cover/contents and chapter skeleton before making the pilot.5. **Pilot.** Make chapter 1 through the chapter loop. Deliver it for the user's review and record approved conventions in BOOK.md. Implement helpers as needed; share one when another chapter uses it.-6. **Remaining chapters and finish.** Produce chapters sequentially (see *Context*). Complete cover text, unit sketches and bookshelf navigation using [site.md](references/site.md). Deliver the book and any unresolved issues for human review; reuse each chapter's delivery results. Commit or deploy within the user's authorization.+6. **Remaining chapters and finish.** Produce chapters sequentially (see *Context*). Complete cover text, contents and unit sketches using [site.md](references/site.md). Deliver the static book folder, its entry URL for local preview and any unresolved issues for human review; reuse each chapter's delivery results.## Chapter loopdiff --git a/.claude/skills/papermorph/assets/engine/engine.js b/.claude/skills/papermorph/assets/engine/engine.jsindex 6ec278a..aa84be8 100644--- a/.claude/skills/papermorph/assets/engine/engine.js+++ b/.claude/skills/papermorph/assets/engine/engine.js@@ -989,7 +989,7 @@ function quiz(pos, qs, done, label = 'Quick check') {const api = {grade(ok, msg, score) {if (resolved) return;- if (first) { SCORE[q.id] = score || { right: +ok, total: 1 }; first = false; }+ if (first) { if (!Object.hasOwn(SCORE, q.id)) SCORE[q.id] = score || { right: +ok, total: 1 }; first = false; }say(ok ? 'ok' : 'no', [ok ? 'Correct. ' : 'Not quite. ', ...[].concat(msg || [])]);if (guide) {mood(guide, ok ? 'happy' : 'oops');@@ -1220,9 +1220,9 @@ const grid = (items, cols, { multi = true, text = false } = {}) => (body, api) =function rat(str) {const t = String(str).trim().replace(/^[−–]/, '-').replace(/\s+/g, ' ');let m = t.match(/^(-?)(\d+)(?:\.(\d+))?$/);- if (m) { const d = 10 ** (m[3] || '').length; return [(m[1] ? -1 : 1) * (Number(m[2]) * d + Number(m[3] || 0)), d]; }+ if (m) { const d = 10 ** (m[3] || '').length, n = (m[1] ? -1 : 1) * (Number(m[2]) * d + Number(m[3] || 0)); return Number.isSafeInteger(n) && Number.isSafeInteger(d) ? [n, d] : null; }m = t.match(/^(-?)(?:(\d+) )?(\d+) ?\/ ?(\d+)$/);- if (m && Number(m[4]) > 0) { const d = Number(m[4]); return [(m[1] ? -1 : 1) * (Number(m[2] || 0) * d + Number(m[3])), d]; }+ if (m && Number(m[4]) > 0) { const d = Number(m[4]), n = (m[1] ? -1 : 1) * (Number(m[2] || 0) * d + Number(m[3])); return Number.isSafeInteger(n) && Number.isSafeInteger(d) ? [n, d] : null; }return null;}const gcd = (a, b) => { a = Math.abs(a); b = Math.abs(b); while (b) [a, b] = [b, a % b]; return a; };@@ -1267,7 +1267,7 @@ const blanks = rowsIn => (body, api) => {r.boxes.forEach(b => { b.classList.toggle('good', ok); b.classList.toggle('bad', !ok); });} else for (const b of r.boxes) {const want = rat(b.dataset.ans), got = rat(b.value);- const good = !!got && got[0] * want[1] === want[0] * got[1] && (!b.dataset.lowest || lowest(got));+ const good = !!got && !!want && BigInt(got[0]) * BigInt(want[1]) === BigInt(want[0]) * BigInt(got[1]) && (!b.dataset.lowest || lowest(got));b.classList.toggle('good', good);b.classList.toggle('bad', !good);ok = ok && good;@@ -1611,7 +1611,12 @@ fit();// Per-book progress shared with the cover/contents at the parent URL folder.const BOOK_PROGRESS_KEY = 'animebook:progress:' + new URL('../', location.href).pathname;function progress(f) {- try { const p = JSON.parse(localStorage.getItem(BOOK_PROGRESS_KEY) || '{}'); f(p); localStorage.setItem(BOOK_PROGRESS_KEY, JSON.stringify(p)); } catch {}+ try {+ const saved = JSON.parse(localStorage.getItem(BOOK_PROGRESS_KEY) || '{}');+ const p = saved && typeof saved === 'object' && !Array.isArray(saved) ? saved : {};+ p.done = Array.isArray(p.done) ? p.done.filter(n => Number.isInteger(n) && n > 0) : [];+ f(p); localStorage.setItem(BOOK_PROGRESS_KEY, JSON.stringify(p));+ } catch {}}function boot() {$('coverK').textContent = `Chapter ${CHAPTER.number}`;diff --git a/.claude/skills/papermorph/assets/templates/BOOK.md b/.claude/skills/papermorph/assets/templates/BOOK.mdindex b07cf5a..0e9c551 100644--- a/.claude/skills/papermorph/assets/templates/BOOK.md+++ b/.claude/skills/papermorph/assets/templates/BOOK.md@@ -3,7 +3,7 @@Read this compact current state for chapter work. The chapter map/status lives in `chapters.md`; storyboards, errata and feedback live in `chapters/chNN.md`.## Intake-- Readers: … · Tone: … · Narration language: … · Guide character: … · Publish to: …+- Readers: … · Tone: … · Narration language: … · Guide character: …- Slug: … · Primary language code: … · Asset approach: code/SVG by default, or agreed assets.- Source: `book.pdf` · Page map: `sections.json` · N pages, N chapters in N units.diff --git a/.claude/skills/papermorph/assets/templates/book.html b/.claude/skills/papermorph/assets/templates/book.htmlindex 9804927..b4af5e0 100644--- a/.claude/skills/papermorph/assets/templates/book.html+++ b/.claude/skills/papermorph/assets/templates/book.html@@ -158,11 +158,6 @@ main#contents { padding-bottom: 80px; }.stagger .top { animation: rise .6s var(--ease) backwards; }.stagger .unit h2, .stagger .ch { animation: rise .6s var(--ease) backwards; animation-delay: calc(min(var(--i), 14) * 32ms + 80ms); }-.back-shelf { color: var(--dim); font: 13px var(--ui); text-decoration: none; white-space: nowrap; }-.back-shelf:hover { color: var(--chalk); }-.cover-back { position: absolute; top: 24px; left: 24px; }-.contents-back { margin-left: 16px; }-/* ---------- page-to-page motion ---------- */@view-transition { navigation: auto; }::view-transition-group(*) { animation-duration: .5s; animation-timing-function: var(--ease); }@@ -170,7 +165,6 @@ main#contents { padding-bottom: 80px; }::view-transition-old(lesson) { animation-duration: .18s; }@media (max-width: 560px) {.home strong { font-size: 18px; }- .contents-back { margin-left: 0; font-size: 11px; }#contents .top { flex-wrap: wrap; gap: 8px 12px; }.unit-art { width: calc(100% - 32px); right: 16px; opacity: .32; }.unit h2 { min-height: 0; padding-top: 104px; }@@ -205,14 +199,12 @@ main#contents { padding-bottom: 80px; }<a class="btn quiet" id="resume" hidden></a></div><p class="meta" id="meta"></p>- <a class="back-shelf cover-back" href="../">← Back to the bookshelf</a></section><main id="contents"><header class="top"><a class="home" href="#book" aria-label="Back to the cover"><svg class="mascot" id="guideSmall" width="52" height="36"></svg><strong>BOOK <i>&</i> TITLE</strong></a><span class="prog" id="prog"></span>- <a class="back-shelf contents-back" href="../">← Bookshelf</a></header><div id="units"></div></main>@@ -227,8 +219,11 @@ const HUES = ['#f4a48c', '#86c9e8', '#f3c95c', '#e8a0c8', '#8fd6b0', '#bba8ee',const id = n => 'ch' + String(n).padStart(2, '0');let P = {};const BOOK_PROGRESS_KEY = 'animebook:progress:' + new URL('.', location.href).pathname;-try { P = JSON.parse(localStorage.getItem(BOOK_PROGRESS_KEY) || '{}'); } catch {}-const done = new Set(P.done || []);+try {+ const saved = JSON.parse(localStorage.getItem(BOOK_PROGRESS_KEY) || '{}');+ if (saved && typeof saved === 'object' && !Array.isArray(saved)) P = saved;+} catch {}+const done = new Set(Array.isArray(P.done) ? P.done.filter(n => Number.isInteger(n) && n > 0) : []);// Contents.let n = 0, total = 0, i = 0; // i staggers the entrance, in reading order@@ -247,7 +242,7 @@ document.querySelectorAll('.unit').forEach(u => seen.observe(u));const finished = [...done].filter(k => k <= total).length;document.getElementById('prog').innerHTML = finished ? `<b>${finished}</b> of ${total} finished` : `${total} chapter${total === 1 ? '' : 's'}`;document.getElementById('meta').textContent = `${total} chapters · ${UNITS.length} units · with sound`;-const last = P.last && document.getElementById(id(P.last));+const last = Number.isInteger(P.last) && document.getElementById(id(P.last));if (last) {const r = document.getElementById('resume');r.hidden = false;diff --git a/.claude/skills/papermorph/references/authoring.md b/.claude/skills/papermorph/references/authoring.mdindex 85ad664..680e071 100644--- a/.claude/skills/papermorph/references/authoring.md+++ b/.claude/skills/papermorph/references/authoring.md@@ -47,7 +47,8 @@ Principles that held up over a whole book:- Write for the ear: short sentences, one idea each. Say math in words ("negative seven halves", "x squared"); the picture shows the symbols.- Match the audience: plain, warm, never childish. Explain why, not only how.- Question beats get one short line ("Quick check. Find the mean."); the card holds the question.-- `tts.py` caches word timings beside the script; the output folder receives `<beat>.mp3` and `timings.js` (duration, marks, sentence captions).+- `tts.py` caches word timings beside the narration JSON; the output folder receives `<beat>.mp3` and `timings.js` (duration, marks, sentence captions). Moving or adding `[[marks]]` reuses the spoken-text cache and recalculates timings. Existing caches made with raw-text keys are reused for an unchanged beat and then upgraded; changing its marks before that upgrade may require one new synthesis.+- Audio is replaced only after synthesis and timing validation succeed, and each completed beat is cached immediately. After a later failure, rerun the same command to reuse completed beats rather than regenerating the chapter.## Questions@@ -68,6 +69,7 @@ New types are welcome when the content calls for one; each needs keyboard play (- The prompt is HTML text; put math in it with `$m(...)`.- Feedback: right → `why` (and an animation via `fx`/`onRight`); wrong → a hint aimed at that mistake; after a wrong try, Show answer.- Grade meaning: equal values match (6/8 = 3/4) unless the lowest form is asked for; sets and pairs in any order; no denominators of zero; never judge irrationality from finitely many digits.+- The built-in numeric parser uses safe integer numerators and denominators and exact integer products for equality. For answers outside that range, use a subject-specific input and grader rather than allowing rounded values to pass.- Place cards so they don't cover the object being asked about (`BAND` under a number line, `TOPR` top right, a custom `{x, y, w, cls: 'side'}` beside a figure, `SCREEN` for practice).## Content rulesdiff --git a/.claude/skills/papermorph/references/engine.md b/.claude/skills/papermorph/references/engine.mdindex ebf0557..71a4950 100644--- a/.claude/skills/papermorph/references/engine.md+++ b/.claude/skills/papermorph/references/engine.md@@ -61,7 +61,7 @@ quiz(position, [{ id: 'c-mean', prompt: ['Find the mean of ', $m('7, 3, 9'), '.'- `tap(values, right, why, v => wrongWhy, onRight?)` points on the number line; `tapEls(row, idx, right, …)` tokens of a `tokens` row; `pickEls([{el, box: [x,y,w,h], label}], right, …)` any drawn objects; `pickPoint(P, [x,y], why, (x,y) => wrongWhy, onRight?, test?)` grid points (arrows + Enter or click); `sorter(items, trayXY)` drag into the set diagram (keys 1–6).- Answer animations run on their own clock: `fx`, `fxp`, `pulseFx`, `shakeFx`, `floatText`, `qlayer()` (a layer cleared with the question). They are finished automatically when the beat is left.- A new type: `build(body, api)` returns `{ reveal, check?, lock?, key?(e), hint? }` and calls `api.grade(ok, message, {right, total})`. `key` handles its shortcuts (return true when used); `hint` lists the keys under the prompt. Every action needs a key; the help overlay (`?`) lists the global ones.-- Scores: `SCORE[id]` keeps the first try; a multi-row question scores one per row.+- Scores: `SCORE[id]` keeps the first try across revisits and step jumps; restarting the chapter clears it. A multi-row question scores one per row. A correct retry changes the feedback, not the first-attempt score.## Player@@ -69,6 +69,8 @@ Space play/pause, ←/→ previous/next beat (Shift+←/→ during a question),Progress uses the stable legacy key `animebook:progress:<book-path>` (keep it when renaming the project so existing readers retain their progress); the cover template reads the same key. Books served in different folders have separate saved places and completion lists.+Treat saved progress as optional: malformed JSON, `null` or a non-object value starts with empty progress; only an array of positive integer chapter numbers is used for completion. Preserve each existing book's key when applying engine fixes.+Keep `<link rel="expect" href="#bar" blocking="render">` in every chapter's head; without it Chromium may paint before the player exists and cancel the page transition from the contents page.## Trapsdiff --git a/.claude/skills/papermorph/references/review.md b/.claude/skills/papermorph/references/review.mdindex 5e01d3b..1287a0e 100644--- a/.claude/skills/papermorph/references/review.md+++ b/.claude/skills/papermorph/references/review.md@@ -29,4 +29,6 @@ Report the delivery result and any unresolved defects in a few lines. A new visuFor changes to playback, question types or grading, run existing tests that exercise the changed behavior. If needed, adapt `assets/templates/e2e.py` into `tools/<book>/e2e_chNN.py`; set `URL` to the actual chapter URL. Check the relevant wrong/right feedback, Show answer and continuation, or pause/replay/seek behavior. Shared timing/replay changes warrant the whole book's blank check and existing affected tests; ordinary new chapters use the delivery pass above.+For scoring changes, verify a wrong first attempt stays recorded after leaving and revisiting the question, and that restarting clears it. For progress changes, check book isolation and loading with missing or malformed stored data. Apply common fixes to the affected book engines and the Skill engine/template, preserving book-specific helpers and legacy keys.+Test details: keyboard first, plus mouse for changed drag handling; Enter checks and Esc leaves answer boxes; press Esc before S. Multi-row questions score per row. Use R on the finish card (Enter opens the next chapter). Python's server lacks Range requests, so let audio play naturally instead of setting `audio.currentTime`.diff --git a/.claude/skills/papermorph/references/site.md b/.claude/skills/papermorph/references/site.mdindex 5223e7b..3dbd529 100644--- a/.claude/skills/papermorph/references/site.md+++ b/.claude/skills/papermorph/references/site.md@@ -1,6 +1,6 @@-# The site: book folder, contents, bookshelf, publishing+# The book: static folder, cover and contents-The site is static: HTML, JS, CSS, MP3. No build step, backend, database or accounts; reading progress lives in the browser (`localStorage`). Only `site/` is published.+The book is static: HTML, JS, CSS, MP3. No build step, backend, database or accounts; reading progress lives in the browser (`localStorage`). The runnable output is `site/<book>/`; source material and production notes stay outside it.## Start a book folder@@ -22,7 +22,7 @@ Use the agreed primary language: rename the narration source, load `audio/<lang>Each book has its own engine, source materials, narration and optional tests. The engine and cover derive the same progress key from the book's URL folder. Keep existing books on their current paths; their legacy progress remains intact.-A chapter returns to its book's index; the cover/contents returns to the bookshelf. With no bookshelf yet, create a minimal `site/index.html` linking to the book's cover. When adding a bookshelf, use underlined text and a small arrow for the entry; preserve cover → contents → chapter navigation.+A chapter returns to its book's index. Preserve cover → contents → chapter navigation and the return from contents to cover. The book opens directly at `/<book>/`; it needs no parent index page. Keep existing books' navigation when editing them.## Cover and contents (`index.html`)@@ -40,27 +40,15 @@ Give each unit a small sketch of its own ideas, drawn in the unit colour, with oKeep the existing infinity guide by default. For an agreed custom guide, adapt `mascotEl` and the cover drawing together, retaining blink, happy hop and wrong-answer tilt states.-## Bookshelf+## Local preview and delivery-`site/index.html` with `lib/bookshelf.js` and `.css` lists the books. Add an entry to `books` in `bookshelf.js`:--```js-{ id: 'history', title: '…', subject: 'History', href: 'history/', coverTitle: ['Line one', 'line two'],- series: 'An animated book', description: '…', chapters: 24, units: 6,- artwork: '<svg viewBox="0 0 260 175" class="book-art">…</svg>', features: ['…', '…', '…'] }-```--List ready books. Folder-based entries use their own counts and artwork; their saved place is available on the book cover.--## Publishing--Use the user's publishing authorization. Any static host works; for Cloudflare Pages:+Serve the static output over HTTP for audio playback:```sh-npx wrangler pages deploy site --project-name <project> --branch main --commit-hash $(git rev-parse --short HEAD)+python3 -m http.server 8765 -d site```-Commit first, deploy the committed state, then confirm the live URL serves a changed file with a cache-busting query. Record commit, URL and deployment id in `books/<book>/releases.md`. Publish only `site/`.+Open `http://localhost:8765/<book>/`. Confirm the cover opens the contents, ready chapter links load their lessons, and lessons return to the book's contents. Deliver `site/<book>/` with its HTML, scripts, styles and audio, the preview command and entry URL, available chapter count and unresolved issues. Source PDFs, extracted pages, narration drafts and development environments are not part of the static book.## Languagesdiff --git a/.claude/skills/papermorph/scripts/check_blank.py b/.claude/skills/papermorph/scripts/check_blank.pyindex 720c56b..50f9627 100644--- a/.claude/skills/papermorph/scripts/check_blank.py+++ b/.claude/skills/papermorph/scripts/check_blank.py@@ -68,5 +68,12 @@ if __name__ == "__main__":ap.add_argument("chapters", nargs="*")ap.add_argument("--url", default="http://localhost:8765/")a = ap.parse_args()+ if not a.book_dir.is_dir():+ ap.error(f"book directory does not exist: {a.book_dir}")chs = a.chapters or sorted(d.name for d in a.book_dir.glob("ch[0-9][0-9]") if d.is_dir())+ if not chs:+ ap.error(f"no chapter folders in {a.book_dir}")+ missing = [ch for ch in chs if not (a.book_dir / ch / "index.html").is_file()]+ if missing:+ ap.error(f"chapter pages not found: {', '.join(missing)}")sys.exit(asyncio.run(main(a.book_dir, chs, a.url if a.url.endswith("/") else a.url + "/")))diff --git a/.claude/skills/papermorph/scripts/split_pages.py b/.claude/skills/papermorph/scripts/split_pages.pyindex 1ebb799..d52d7b5 100644--- a/.claude/skills/papermorph/scripts/split_pages.py+++ b/.claude/skills/papermorph/scripts/split_pages.py@@ -31,7 +31,7 @@ def main():ap.add_argument("--out", type=Path, default=Path("book_pages"))ap.add_argument("--dpi", type=int, default=150)ap.add_argument("--list", action="store_true", help="print the map and stop")- ap.add_argument("--only", nargs="*", help="render only these section folders")+ ap.add_argument("--only", nargs="+", help="render only these section folders")ap.add_argument("--overwrite", action="store_true")ap.add_argument("--text-only", action="store_true", help="write text.md files, skip the images")ap.add_argument("--pages", help="preview a page or inclusive range (e.g. 3 or 1-12), independently of the map")@@ -60,6 +60,10 @@ def main():nxt = en + 1if nxt != len(doc) + 1:ap.error(f"the map ends at page {nxt - 1}; the PDF has {len(doc)} pages")+ if a.only:+ unknown = set(a.only) - seen+ if unknown:+ ap.error(f"unknown section folders: {', '.join(sorted(unknown))}")print(f"{len(doc)} pages, {len(sections)} sections, {a.dpi} dpi")if a.list:for s in sections:diff --git a/.claude/skills/papermorph/scripts/tts.py b/.claude/skills/papermorph/scripts/tts.pyindex 9720f19..43f7456 100644--- a/.claude/skills/papermorph/scripts/tts.py+++ b/.claude/skills/papermorph/scripts/tts.py@@ -19,6 +19,7 @@ import jsonimport reimport subprocessimport sys+import tempfilefrom pathlib import Pathimport edge_tts@@ -44,6 +45,8 @@ def split_marks(raw):# MARK.split alternates text, name, text, name, ...for i, part in enumerate(MARK.split(raw)):if i % 2:+ if part in marks:+ raise ValueError(f"duplicate mark {part!r} in one beat")marks[part] = poselse:clean.append(part)@@ -91,6 +94,17 @@ def duration(mp3):return round(float(r.stdout), 3)+def write_atomic(path, text):+ """Replace output only after its complete contents have been written."""+ with tempfile.NamedTemporaryFile(dir=path.parent, prefix=f".{path.name}-", delete=False) as f:+ tmp = Path(f.name)+ try:+ tmp.write_text(text, encoding="utf-8")+ tmp.replace(path)+ finally:+ tmp.unlink(missing_ok=True)++async def main(src, out_dir):spec = json.loads(Path(src).read_text())out_dir = Path(out_dir)@@ -99,21 +113,48 @@ async def main(src, out_dir):cache = json.loads(cache_path.read_text()) if cache_path.exists() else {}voice, rate = spec["voice"], spec["rate"]result = {}+ public = lambda v: {k: v[k] for k in ("dur", "marks", "cues")}+ live = {b: public(v) for b, v in cache.items()+ 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():- key = hashlib.sha1(f"{voice}|{rate}|{raw}".encode()).hexdigest()mp3 = out_dir / f"{beat}.mp3"old = cache.get(beat)clean, marks = split_marks(raw)- if old and old.get("key") == key and "words" in old and mp3.exists():+ key = hashlib.sha1(f"{voice}|{rate}|{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()+ reusable = old and old.get("key") in (key, legacy_key) and "words" in old and mp3.exists() and mp3.stat().st_size > 0+ tmp = None+ if reusable:words = old["words"]+ clip = mp3else:- words = await synth(clean, voice, rate, mp3)- print(f"{beat}: synthesized")- result[beat] = {"key": key, "dur": duration(mp3), "words": words,- "marks": mark_times(clean, marks, words), "cues": caption_cues(clean, words)}- cache_path.write_text(json.dumps(result, indent=1))- js = {b: {"dur": v["dur"], "marks": v["marks"], "cues": v["cues"]} for b, v in result.items()}- (out_dir / "timings.js").write_text("window.TIMINGS = " + json.dumps(js, indent=1) + ";\n")+ with tempfile.NamedTemporaryFile(dir=out_dir, prefix=f".{beat}-", suffix=".mp3", delete=False) as f:+ tmp = Path(f.name)+ clip = tmp+ try:+ if not reusable:+ words = await synth(clean, voice, rate, clip)+ entry = {"key": key, "dur": duration(clip), "words": words,+ "marks": mark_times(clean, marks, words), "cues": caption_cues(clean, words)}+ if tmp:+ tmp.replace(mp3)+ print(f"{beat}: synthesized")+ result[beat] = entry+ cache[beat] = entry+ # A later failed beat must not discard the successful beats' cache.+ write_atomic(cache_path, json.dumps(cache, indent=1))+ # Keep the successful MP3's timings consistent even if a later beat fails.+ live[beat] = public(entry)+ write_atomic(timings_path, "window.TIMINGS = " + json.dumps(live, indent=1) + ";\n")+ finally:+ if tmp:+ tmp.unlink(missing_ok=True)+ write_atomic(cache_path, json.dumps(result, indent=1))+ js = {b: public(v) for b, v in result.items()}+ write_atomic(timings_path, "window.TIMINGS = " + json.dumps(js, indent=1) + ";\n")if __name__ == "__main__":diff --git a/site/index.html b/site/index.htmlindex 498054d..ade2974 100644--- a/site/index.html+++ b/site/index.html@@ -288,8 +288,11 @@ const UNITS = [const HUES = ['#f4a48c', '#86c9e8', '#f3c95c', '#e8a0c8', '#8fd6b0', '#bba8ee', '#f0b45a'];const id = n => 'ch' + String(n).padStart(2, '0');let P = {};-try { P = JSON.parse(localStorage.getItem('progress') || '{}') || {}; } catch {}-const done = new Set(P.done || []);+try {+ const saved = JSON.parse(localStorage.getItem('progress') || '{}');+ if (saved && typeof saved === 'object' && !Array.isArray(saved)) P = saved;+} catch {}+const done = new Set(Array.isArray(P.done) ? P.done.filter(n => Number.isInteger(n) && n > 0) : []);// Contents.let n = 0, total = 0, i = 0; // i staggers the entrance, in reading order@@ -308,7 +311,7 @@ document.querySelectorAll('.unit').forEach(u => seen.observe(u));const finished = [...done].filter(k => k <= total).length;document.getElementById('prog').innerHTML = finished ? `<b>${finished}</b> of ${total} finished` : `${total} chapters`;document.getElementById('meta').textContent = `${total} chapters · ${UNITS.length} units · with sound`;-const last = P.last && document.getElementById(id(P.last));+const last = Number.isInteger(P.last) && document.getElementById(id(P.last));if (last) {const r = document.getElementById('resume');r.hidden = false;diff --git a/site/lib/engine.js b/site/lib/engine.jsindex 1fc1e17..64fe4ba 100644--- a/site/lib/engine.js+++ b/site/lib/engine.js@@ -989,7 +989,7 @@ function quiz(pos, qs, done, label = 'Quick check') {const api = {grade(ok, msg, score) {if (resolved) return;- if (first) { SCORE[q.id] = score || { right: +ok, total: 1 }; first = false; }+ if (first) { if (!Object.hasOwn(SCORE, q.id)) SCORE[q.id] = score || { right: +ok, total: 1 }; first = false; }say(ok ? 'ok' : 'no', [ok ? 'Correct. ' : 'Not quite. ', ...[].concat(msg || [])]);if (guide) {mood(guide, ok ? 'happy' : 'oops');@@ -1220,9 +1220,9 @@ const grid = (items, cols, { multi = true, text = false } = {}) => (body, api) =function rat(str) {const t = String(str).trim().replace(/^[−–]/, '-').replace(/\s+/g, ' ');let m = t.match(/^(-?)(\d+)(?:\.(\d+))?$/);- if (m) { const d = 10 ** (m[3] || '').length; return [(m[1] ? -1 : 1) * (Number(m[2]) * d + Number(m[3] || 0)), d]; }+ if (m) { const d = 10 ** (m[3] || '').length, n = (m[1] ? -1 : 1) * (Number(m[2]) * d + Number(m[3] || 0)); return Number.isSafeInteger(n) && Number.isSafeInteger(d) ? [n, d] : null; }m = t.match(/^(-?)(?:(\d+) )?(\d+) ?\/ ?(\d+)$/);- if (m && Number(m[4]) > 0) { const d = Number(m[4]); return [(m[1] ? -1 : 1) * (Number(m[2] || 0) * d + Number(m[3])), d]; }+ if (m && Number(m[4]) > 0) { const d = Number(m[4]), n = (m[1] ? -1 : 1) * (Number(m[2] || 0) * d + Number(m[3])); return Number.isSafeInteger(n) && Number.isSafeInteger(d) ? [n, d] : null; }return null;}const gcd = (a, b) => { a = Math.abs(a); b = Math.abs(b); while (b) [a, b] = [b, a % b]; return a; };@@ -1267,7 +1267,7 @@ const blanks = rowsIn => (body, api) => {r.boxes.forEach(b => { b.classList.toggle('good', ok); b.classList.toggle('bad', !ok); });} else for (const b of r.boxes) {const want = rat(b.dataset.ans), got = rat(b.value);- const good = !!got && got[0] * want[1] === want[0] * got[1] && (!b.dataset.lowest || lowest(got));+ const good = !!got && !!want && BigInt(got[0]) * BigInt(want[1]) === BigInt(want[0]) * BigInt(got[1]) && (!b.dataset.lowest || lowest(got));b.classList.toggle('good', good);b.classList.toggle('bad', !good);ok = ok && good;@@ -1610,7 +1610,12 @@ fit();// ?beat=N&t=S opens a paused frame, for reviewing a single moment.// Per-browser progress shared with the contents page: last chapter opened, chapters finished.function progress(f) {- try { const p = JSON.parse(localStorage.getItem('progress') || '{}'); f(p); localStorage.setItem('progress', JSON.stringify(p)); } catch {}+ try {+ const saved = JSON.parse(localStorage.getItem('progress') || '{}');+ const p = saved && typeof saved === 'object' && !Array.isArray(saved) ? saved : {};+ p.done = Array.isArray(p.done) ? p.done.filter(n => Number.isInteger(n) && n > 0) : [];+ f(p); localStorage.setItem('progress', JSON.stringify(p));+ } catch {}}function boot() {$('coverK').textContent = `Chapter ${CHAPTER.number}`;diff --git a/site/math-notebook/index.html b/site/math-notebook/index.htmlindex be0bd17..4ad0aa4 100644--- a/site/math-notebook/index.html+++ b/site/math-notebook/index.html@@ -231,8 +231,11 @@ const HUES = ['#f4a48c', '#86c9e8', '#f3c95c', '#e8a0c8', '#8fd6b0', '#bba8ee',const id = n => 'ch' + String(n).padStart(2, '0');let P = {};const BOOK_PROGRESS_KEY = 'animebook:progress:' + new URL('.', location.href).pathname;-try { P = JSON.parse(localStorage.getItem(BOOK_PROGRESS_KEY) || '{}'); } catch {}-const done = new Set(P.done || []);+try {+ const saved = JSON.parse(localStorage.getItem(BOOK_PROGRESS_KEY) || '{}');+ if (saved && typeof saved === 'object' && !Array.isArray(saved)) P = saved;+} catch {}+const done = new Set(Array.isArray(P.done) ? P.done.filter(n => Number.isInteger(n) && n > 0) : []);// Contents.let n = 0, total = 0, i = 0; // i staggers the entrance, in reading order@@ -252,7 +255,7 @@ const finished = [...done].filter(k => k <= total).length;document.getElementById('prog').innerHTML = finished ? `<b>${finished}</b> of ${total} finished` : `${total} chapter${total === 1 ? '' : 's'}`;const plural = (n, w) => `${n} ${w}${n === 1 ? '' : 's'}`;document.getElementById('meta').textContent = `${plural(total, 'chapter')} · ${plural(UNITS.length, 'unit')} · with sound`;-const last = P.last && document.getElementById(id(P.last));+const last = Number.isInteger(P.last) && document.getElementById(id(P.last));if (last) {const r = document.getElementById('resume');r.hidden = false;diff --git a/site/math-notebook/lib/engine.js b/site/math-notebook/lib/engine.jsindex a7cf863..40c1c91 100644--- a/site/math-notebook/lib/engine.js+++ b/site/math-notebook/lib/engine.js@@ -994,7 +994,7 @@ function quiz(pos, qs, done, label = 'Quick check') {const api = {grade(ok, msg, score) {if (resolved) return;- if (first) { SCORE[q.id] = score || { right: +ok, total: 1 }; first = false; }+ if (first) { if (!Object.hasOwn(SCORE, q.id)) SCORE[q.id] = score || { right: +ok, total: 1 }; first = false; }say(ok ? 'ok' : 'no', [ok ? 'Correct. ' : 'Not quite. ', ...[].concat(msg || [])]);if (guide) {mood(guide, ok ? 'happy' : 'oops');@@ -1225,9 +1225,9 @@ const grid = (items, cols, { multi = true, text = false } = {}) => (body, api) =function rat(str) {const t = String(str).trim().replace(/^[−–]/, '-').replace(/\s+/g, ' ');let m = t.match(/^(-?)(\d+)(?:\.(\d+))?$/);- if (m) { const d = 10 ** (m[3] || '').length; return [(m[1] ? -1 : 1) * (Number(m[2]) * d + Number(m[3] || 0)), d]; }+ if (m) { const d = 10 ** (m[3] || '').length, n = (m[1] ? -1 : 1) * (Number(m[2]) * d + Number(m[3] || 0)); return Number.isSafeInteger(n) && Number.isSafeInteger(d) ? [n, d] : null; }m = t.match(/^(-?)(?:(\d+) )?(\d+) ?\/ ?(\d+)$/);- if (m && Number(m[4]) > 0) { const d = Number(m[4]); return [(m[1] ? -1 : 1) * (Number(m[2] || 0) * d + Number(m[3])), d]; }+ if (m && Number(m[4]) > 0) { const d = Number(m[4]), n = (m[1] ? -1 : 1) * (Number(m[2] || 0) * d + Number(m[3])); return Number.isSafeInteger(n) && Number.isSafeInteger(d) ? [n, d] : null; }return null;}const gcd = (a, b) => { a = Math.abs(a); b = Math.abs(b); while (b) [a, b] = [b, a % b]; return a; };@@ -1272,7 +1272,7 @@ const blanks = rowsIn => (body, api) => {r.boxes.forEach(b => { b.classList.toggle('good', ok); b.classList.toggle('bad', !ok); });} else for (const b of r.boxes) {const want = rat(b.dataset.ans), got = rat(b.value);- const good = !!got && got[0] * want[1] === want[0] * got[1] && (!b.dataset.lowest || lowest(got));+ const good = !!got && !!want && BigInt(got[0]) * BigInt(want[1]) === BigInt(want[0]) * BigInt(got[1]) && (!b.dataset.lowest || lowest(got));b.classList.toggle('good', good);b.classList.toggle('bad', !good);ok = ok && good;@@ -1616,7 +1616,12 @@ fit();// Per-book progress shared with the cover/contents at the parent URL folder.const BOOK_PROGRESS_KEY = 'animebook:progress:' + new URL('../', location.href).pathname;function progress(f) {- try { const p = JSON.parse(localStorage.getItem(BOOK_PROGRESS_KEY) || '{}'); f(p); localStorage.setItem(BOOK_PROGRESS_KEY, JSON.stringify(p)); } catch {}+ try {+ const saved = JSON.parse(localStorage.getItem(BOOK_PROGRESS_KEY) || '{}');+ const p = saved && typeof saved === 'object' && !Array.isArray(saved) ? saved : {};+ p.done = Array.isArray(p.done) ? p.done.filter(n => Number.isInteger(n) && n > 0) : [];+ f(p); localStorage.setItem(BOOK_PROGRESS_KEY, JSON.stringify(p));+ } catch {}}function boot() {$('coverK').textContent = `Chapter ${CHAPTER.number}`;