An AI skill that turns books into animated, narrated, interactive web experiences
JavaScript ai-agentsai-educationanimationclaudeclaude-codeclaude-skillsedtecheducationinteractive-textbookscormtext-to-video
fix: review batch A for the engine and Skill scripts
yzr90f39b8f71e7
diff --git a/.claude/skills/papermorph/scripts/engine.py b/.claude/skills/papermorph/scripts/engine.pyindex 7a8da4f..9723074 100644--- a/.claude/skills/papermorph/scripts/engine.py+++ b/.claude/skills/papermorph/scripts/engine.py@@ -9,7 +9,8 @@python3 engine.py site/stats --latex # also MathJax, for a book whose chapters use TX()The engine is not part of this skill: it is the engine/ folder of a repository, versioned by tags, and anyone may-fork it. Without --from, ./engine is used when it exists (a checkout of that repository), otherwise DEFAULT.+fork it. Without --from, the engine/ folder here or above the target is used (a checkout of that repository),+otherwise DEFAULT; the source used is printed.Each book keeps a full copy in lib/, so it runs on its own; fix the engine at its source and sync, never edit thecopies. lib/book.css holds the book's own settings and overrides; it is created from the default and neveroverwritten. MathJax (engine/vendor/mathjax) goes only into books that ask for it with --latex; after that, a book@@ -43,9 +44,11 @@ def fetch(spec: str) -> Path:return out-def source(spec):- if spec is None:- spec = 'engine' if Path('engine/engine.js').exists() else DEFAULT+def source(spec, target):+ if spec is None: # the repository's engine/: here, or above the books+ local = [d / 'engine' for d in (Path.cwd(), *target.resolve().parents) if (d / 'engine' / 'engine.js').exists()]+ spec = str(local[0]) if local else DEFAULT+ print(f'engine source: {spec}', file=sys.stderr)path = Path(spec)if path.is_dir():if not (path / 'engine.js').exists():@@ -70,7 +73,7 @@ def main():ap.add_argument('--check', action='store_true', help='only report differing copies')ap.add_argument('--latex', action='store_true', help='also copy MathJax, for TX() formulas')a = ap.parse_args()- engine = source(a.src)+ engine = source(a.src, a.target)shared = sorted(p for p in engine.iterdir() if p.suffix in ('.js', '.css') and p.name != OWN)stale = []for book in books(a.target):diff --git a/.claude/skills/papermorph/scripts/join.py b/.claude/skills/papermorph/scripts/join.pyindex 0681c42..0417365 100644--- a/.claude/skills/papermorph/scripts/join.py+++ b/.claude/skills/papermorph/scripts/join.py@@ -68,7 +68,8 @@ for arg in args:shift = lambda b, t: t + sum(sec for at, sec in holes[b] if t >= at)gap = pathlib.Path(tmp) / 'gap.mp3'; silence(gap, GAP)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)))+ q = lambda f: "file '" + str(f).replace("'", "'\\''") + "'\n" # the concat list's quoting: ' becomes '\''+ lst.write_text(''.join(''.join(q(f) for f in piece(b)) + (q(gap) 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 = {}, [], {}, 0for b in beats:diff --git a/.claude/skills/papermorph/scripts/lint.py b/.claude/skills/papermorph/scripts/lint.pyindex 27d3eee..437e1d9 100644--- a/.claude/skills/papermorph/scripts/lint.py+++ b/.claude/skills/papermorph/scripts/lint.py@@ -13,7 +13,7 @@ Errors (exit status 1):stale the narration's text or [[marks]] differ from timings.js: run tts.py againstyle style.json is not valid JSON or lacks schema, tier, book, words, look or voiceWarnings: a beat's m('name') not among that beat's own marks (beats built by shared helpers can mislead this);- no beats recognised in a chapter.+ no beats recognised in a chapter; no narration file to check against.--content defaults to content/<book> (content/ for the first book's legacy layout), --brief to books/<book>."""import argparse, json, re, sys@@ -155,8 +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 isinstance(text, dict): # a beat with a speaker; its caption is the subtitle when it has one+ text = text.get('sub') or text['text']if b not in T:err('stale', f'narration beat {b} has no timings')continue@@ -165,6 +165,8 @@ def lint_chapter(ch, content, out):cues = ' '.join(c[1] for c in T[b].get('cues', []))if cues and words(text) != words(cues):err('stale', f'beat {b}: narration text differs from the generated audio')+ else:+ warn('stale', f'no narration at {nar}: narration not checked (pass --content)')def lint_style(brief, out):diff --git a/.claude/skills/papermorph/scripts/serve.py b/.claude/skills/papermorph/scripts/serve.pyindex 43c46bb..d856cd2 100644--- a/.claude/skills/papermorph/scripts/serve.py+++ b/.claude/skills/papermorph/scripts/serve.py@@ -3,16 +3,44 @@python3 serve.py 8765 site # then open http://localhost:8765/<book>/-python3 -m http.server sends no Cache-Control and has a backlog of 5, which drops connections when a page opens-many files at once; this server sends no-store and queues up to 128.+python3 -m http.server sends no Cache-Control, has a backlog of 5 (it drops connections when a page opens many+files at once) and ignores Range requests (Chrome then restarts audio from 0 on every seek, so a seek looks out of+sync). This server sends no-store, queues up to 128, serves byte ranges, and listens on this computer only."""-import functools, http.server, sys+import functools, http.server, os, re, sysclass NoStore(http.server.SimpleHTTPRequestHandler):def end_headers(self):self.send_header("Cache-Control", "no-store")+ self.send_header("Accept-Ranges", "bytes")super().end_headers()+ def send_head(self): # a byte range of a file: 206 with just those bytes+ m = re.fullmatch(r"bytes=(\d*)-(\d*)", self.headers.get("Range", ""))+ path = self.translate_path(self.path)+ if not m or m.groups() == ("", "") or not os.path.isfile(path):+ return super().send_head()+ size = os.path.getsize(path)+ a, b = m.groups()+ start, end = (max(size - int(b), 0), size - 1) if not a else (int(a), min(int(b) if b else size - 1, size - 1))+ if start >= size or start > end:+ self.send_response(416); self.send_header("Content-Range", f"bytes */{size}"); self.end_headers(); return None+ f = open(path, "rb"); f.seek(start)+ self.send_response(206)+ self.send_header("Content-Type", self.guess_type(path))+ self.send_header("Content-Range", f"bytes {start}-{end}/{size}")+ self.send_header("Content-Length", str(end - start + 1))+ self.end_headers()+ self._left = end - start + 1+ return f++ def copyfile(self, source, outputfile):+ left, self._left = getattr(self, "_left", None), None+ if left is None:+ return super().copyfile(source, outputfile)+ while left > 0 and (chunk := source.read(min(65536, left))):+ outputfile.write(chunk); left -= len(chunk)+class Server(http.server.ThreadingHTTPServer):request_queue_size = 128daemon_threads = True@@ -22,5 +50,5 @@ if __name__ == "__main__":print(__doc__)sys.exit(0 if sys.argv[1:] in (["-h"], ["--help"]) else 2)port, root = int(sys.argv[1]), sys.argv[2]- print(f"serving {root} at http://localhost:{port}/ (no-store)", flush=True)- Server(("", port), functools.partial(NoStore, directory=root)).serve_forever()+ print(f"serving {root} at http://localhost:{port}/ (no-store, byte ranges)", flush=True)+ Server(("127.0.0.1", port), functools.partial(NoStore, directory=root)).serve_forever()diff --git a/engine/check_latex.py b/engine/check_latex.pyindex d5f2998..edf18b3 100644--- a/engine/check_latex.py+++ b/engine/check_latex.py@@ -303,8 +303,9 @@ async def check_tex_chapter(browser):assert not errors, errorsallowed = {"ch01/", "lib/engine.js", "lib/engine.css", "lib/volume.js", "lib/volume.css", "lib/book.css","lib/mathjax.js", "ch01/audio/en/timings.js"}+ rest = lambda u: urlparse(u).path.split("/__latex__/tex/")[1] # audio URLs carry ?v=<duration>stray = [u for u in requests if not u.startswith(f"{ORIGIN}/__latex__/tex/")- or (u.split("/__latex__/tex/")[1] not in allowed and not u.endswith(".mp3"))]+ or (rest(u) not in allowed and not rest(u).endswith(".mp3"))]assert not stray, f"unexpected requests: {stray}"print("PASS network: only the page's own files")await page.close()diff --git a/engine/engine.js b/engine/engine.jsindex a33c7db..e3000d6 100644--- a/engine/engine.js+++ b/engine/engine.js@@ -18,7 +18,7 @@ const TRANSLATIONS = {helpShowAnswer: 'Show the answer', helpLeaveBox: 'Leave an answer box', helpClose: 'Press {key} to close.',paused: 'Paused. Press space or click to continue.',soundFailed: 'Sound could not play. The lesson continues with the on-screen text.',- startLesson: 'Start lesson', coverKeys: 'Press {space} to start, {help} for shortcuts.', spaceKey: 'Space',+ startLesson: 'Start lesson', startFilm: 'Play', aboutMinutesFilm: 'About {n} minutes, with sound.', coverKeys: 'Press {space} to start, {help} for shortcuts.', spaceKey: 'Space',chapterNumber: 'Chapter {n}', aboutMinutes: 'About {n} minutes, with sound and quick checks.',allChapters: 'All chapters', playLabel: 'Play or pause (space)', backLabel: 'Previous step (left arrow)', restartLabel: 'Restart lesson',volumeLabel: 'Adjust volume', volumeTitle: 'Volume (0 = muted)', volumeSlider: 'Volume',@@ -52,7 +52,7 @@ const TRANSLATIONS = {helpShowAnswer: 'Показать ответ', helpLeaveBox: 'Выйти из поля ответа', helpClose: 'Нажмите {key}, чтобы закрыть.',paused: 'Пауза. Нажмите пробел или щёлкните, чтобы продолжить.',soundFailed: 'Звук не воспроизводится. Урок продолжится с текстом на экране.',- startLesson: 'Начать урок', coverKeys: '{space} — начать, {help} — горячие клавиши.', spaceKey: 'Пробел',+ startLesson: 'Начать урок', startFilm: 'Смотреть', aboutMinutesFilm: { one: 'Около {n} минуты, со звуком.', few: 'Около {n} минут, со звуком.', many: 'Около {n} минут, со звуком.', other: 'Около {n} минуты, со звуком.' }, coverKeys: '{space} — начать, {help} — горячие клавиши.', spaceKey: 'Пробел',chapterNumber: 'Глава {n}',aboutMinutes: { one: 'Около {n} минуты, со звуком и проверками.', few: 'Около {n} минут, со звуком и проверками.',many: 'Около {n} минут, со звуком и проверками.', other: 'Около {n} минуты, со звуком и проверками.' },@@ -88,7 +88,7 @@ const TRANSLATIONS = {helpShowAnswer: '显示答案', helpLeaveBox: '离开答题框', helpClose: '按 {key} 关闭。',paused: '已暂停。按空格键或点击继续。',soundFailed: '声音无法播放。课程将借助屏幕上的文字继续。',- startLesson: '开始上课', coverKeys: '按 {space} 开始,按 {help} 查看快捷键。', spaceKey: '空格',+ startLesson: '开始上课', startFilm: '播放', aboutMinutesFilm: '约 {n} 分钟,有配音。', coverKeys: '按 {space} 开始,按 {help} 查看快捷键。', spaceKey: '空格',chapterNumber: '第 {n} 章', aboutMinutes: '约 {n} 分钟,含配音和随堂小测。',allChapters: '全部章节', playLabel: '播放或暂停(空格)', backLabel: '上一步(左方向键)', restartLabel: '重新开始本课',volumeLabel: '调节音量', volumeTitle: '音量(0 为静音)', volumeSlider: '音量',@@ -122,7 +122,7 @@ const TRANSLATIONS = {helpShowAnswer: '答えを表示', helpLeaveBox: '解答欄から出る', helpClose: '{key} で閉じる。',paused: '一時停止中。スペースキーかクリックで再開します。',soundFailed: '音声を再生できません。画面の文字で授業を続けます。',- startLesson: '授業を始める', coverKeys: '{space} で開始、{help} でショートカット一覧。', spaceKey: 'スペース',+ startLesson: '授業を始める', startFilm: '再生', aboutMinutesFilm: '約{n}分、音声つき。', coverKeys: '{space} で開始、{help} でショートカット一覧。', spaceKey: 'スペース',chapterNumber: '第{n}章', aboutMinutes: '約{n}分、音声と確認問題つき。',allChapters: 'すべての章', playLabel: '再生/一時停止(スペース)', backLabel: '前のステップ(左矢印)', restartLabel: '授業を最初から',volumeLabel: '音量を調整', volumeTitle: '音量(0 でミュート)', volumeSlider: '音量',@@ -205,7 +205,7 @@ document.body.insertAdjacentHTML('afterbegin', `<div id="frame"><button class="cover" id="cover"><div><p class="cover-k" id="coverK"></p><h1 class="cover-t" id="coverT"></h1>- <span class="go"><svg width="24" height="24" viewBox="0 0 18 18"><path d="M3 1.5v15l13-7.5z" fill="currentColor"/></svg>${translate('startLesson')}</span>+ <span class="go"><svg width="24" height="24" viewBox="0 0 18 18"><path d="M3 1.5v15l13-7.5z" fill="currentColor"/></svg><span id="coverGo">${translate('startLesson')}</span></span><small><span id="coverMeta"></span> ${translate('coverKeys', { space: `<kbd>${translate('spaceKey')}</kbd>`, help: '<kbd>?</kbd>' })}</small></div></button><div id="bar">@@ -1408,6 +1408,7 @@ function quiz(pos, qs, done, label = translate('quickCheck')) {const q = qs[k];let first = true, resolved = false;const fb = h('div', 'fb'), body = h('div', 'body'), acts = h('div', 'acts');+ fb.setAttribute('role', 'status'); // screen readers announce right or wrongconst bCheck = h('button', 'btn', [translate('check'), kbd('Enter')]), bShow = h('button', 'btn quiet', [translate('showAnswer'), kbd('S')]);const bNext = h('button', 'btn go', [k < qs.length - 1 ? translate('nextQuestion') : translate('continue'), kbd('Enter')]);bShow.hidden = bNext.hidden = true;@@ -1966,12 +1967,12 @@ function beatDone() {function filmDone() {progress(p => { p.done = [...new Set([...(p.done || []), CHAPTER.number])]; });if (!CHAPTER.next) return;- const next = h('button', 'btn go', translate('nextChapter'));+ const next = h('button', 'btn go', [translate('nextChapter'), kbd('Enter')]);next.onclick = () => { location.href = CHAPTER.next; };+ P.keys = e => e.key === 'Enter' ? (next.onclick(), true) : false; // not focused, so Space still replaysconst c = card({ x: 0, y: 770, w: 0, cls: 'side' }, 'next');Object.assign(c.style, { left: 'auto', right: '40px', width: 'auto' });c.append(h('div', 'acts', [next]));- next.focus({ preventScroll: true });}let last = performance.now();function frame(now) {@@ -2145,7 +2146,9 @@ function boot() {$('bHome').href = `../#ch${String(CHAPTER.number).padStart(2, '0')}`;progress(p => { p.last = CHAPTER.number; });document.getElementById('stage').setAttribute('aria-label', translate('stageLabelTitled', { title: CHAPTER.title }));- $('coverMeta').textContent = translate('aboutMinutes', { n: num(CHAPTER.minutes) });+ const film = !BEATS.some(b => b.ask); // a picture book: no questions, so no "lesson" or "quick checks" on its cover+ if (film) $('coverGo').textContent = translate('startFilm');+ $('coverMeta').textContent = translate(film ? 'aboutMinutesFilm' : 'aboutMinutes', { n: num(CHAPTER.minutes) });buildSegs();const qs = new URLSearchParams(location.search);if (qs.has('beat')) {diff --git a/site/joke-collection/ch02/audio/bgm/m2-wolf.mp3 b/site/joke-collection/ch02/audio/bgm/m2-wolf.mp3deleted file mode 100644index eca9045..0000000Binary files a/site/joke-collection/ch02/audio/bgm/m2-wolf.mp3 and /dev/null differdiff --git a/site/joke-collection/ch07/ch07.srt b/site/joke-collection/ch07/ch07.srtdeleted file mode 100644index d5efeca..0000000--- a/site/joke-collection/ch07/ch07.srt+++ /dev/null@@ -1,103 +0,0 @@-1-00:00:01,104 --> 00:00:08,211-Last summer, my cousin Yui flew in from Osaka, to spend a week at Uncle Pedro's farm in the south of Spain.--2-00:00:08,726 --> 00:00:11,421-Yui had four years of English in school.--3-00:00:11,122 --> 00:00:12,749-Spain was going to test all of it.--4-00:00:14,628 --> 00:00:16,718-The cow is the queen of the house!--5-00:00:17,838 --> 00:00:21,497-Uncle Pedro had one rule about his cow, Luna.--6-00:00:21,198 --> 00:00:22,473-You may look.--7-00:00:22,174 --> 00:00:23,632-You may pet.--8-00:00:23,333 --> 00:00:25,223-But you never joke about the cow.--9-00:00:27,028 --> 00:00:29,163-And she's the cleverest cow in town!--10-00:00:32,106 --> 00:00:34,610-In Japanese, baka means stupid.--11-00:00:34,311 --> 00:00:36,479-In Spanish, vaca means cow.--12-00:00:36,996 --> 00:00:42,035-Say them fast, and Uncle Pedro had just called the queen an idiot.--13-00:00:41,736 --> 00:00:42,924-Three times.--14-00:00:44,756 --> 00:00:45,930-Hang in there.--15-00:00:47,702 --> 00:00:50,240-That's it! Vaca!--16-00:00:51,364 --> 00:00:52,658-I'm so sorry.--17-00:00:56,472 --> 00:00:57,683-Vaca.--18-00:00:57,384 --> 00:00:58,425-Cow.--19-00:00:58,126 --> 00:00:59,131-Not baka.--20-00:01:01,502 --> 00:01:04,269-See? She agrees.--21-00:01:06,700 --> 00:01:08,383-Come on! To my house!--22-00:01:09,898 --> 00:01:11,104-My… cow?--23-00:01:12,972 --> 00:01:17,672-That evening, Uncle Pedro painted MIKASA over her stable.--24-00:01:17,373 --> 00:01:20,018-He thinks it's Japanese for 'the queen's house.'--25-00:01:20,590 --> 00:01:22,404-Nobody corrected him.--26-00:01:22,105 --> 00:01:23,779-The cow answers to it now.diff --git a/site/joke-collection/img/props/hw-blank.webp b/site/joke-collection/img/props/hw-blank.webpdeleted file mode 100644index 06c6b99..0000000Binary files a/site/joke-collection/img/props/hw-blank.webp and /dev/null differdiff --git a/site/three-little-pigs/img/bg_far.webp b/site/three-little-pigs/img/bg_far.webpdeleted file mode 100644index 98fbc08..0000000Binary files a/site/three-little-pigs/img/bg_far.webp and /dev/null differdiff --git a/site/three-little-pigs/img/bg_front.webp b/site/three-little-pigs/img/bg_front.webpdeleted file mode 100644index a984ab2..0000000Binary files a/site/three-little-pigs/img/bg_front.webp and /dev/null differdiff --git a/site/three-little-pigs/img/bg_mid.webp b/site/three-little-pigs/img/bg_mid.webpdeleted file mode 100644index d472c87..0000000Binary files a/site/three-little-pigs/img/bg_mid.webp and /dev/null differdiff --git a/site/three-little-pigs/img/house_brick.webp b/site/three-little-pigs/img/house_brick.webpdeleted file mode 100644index 3cd5cbf..0000000Binary files a/site/three-little-pigs/img/house_brick.webp and /dev/null differdiff --git a/site/three-little-pigs/img/house_sticks.webp b/site/three-little-pigs/img/house_sticks.webpdeleted file mode 100644index 33f44fc..0000000Binary files a/site/three-little-pigs/img/house_sticks.webp and /dev/null differdiff --git a/site/three-little-pigs/img/house_straw.webp b/site/three-little-pigs/img/house_straw.webpdeleted file mode 100644index 3d28df0..0000000Binary files a/site/three-little-pigs/img/house_straw.webp and /dev/null differdiff --git a/site/three-little-pigs/making/bug-wolf-mouth.webp b/site/three-little-pigs/making/bug-wolf-mouth.webpdeleted file mode 100644index c85edab..0000000Binary files a/site/three-little-pigs/making/bug-wolf-mouth.webp and /dev/null differdiff --git a/site/three-little-pigs/making/layers-composite.webp b/site/three-little-pigs/making/layers-composite.webpdeleted file mode 100644index 4d7f0f2..0000000Binary files a/site/three-little-pigs/making/layers-composite.webp and /dev/null differdiff --git a/site/three-little-pigs/making/still-10.webp b/site/three-little-pigs/making/still-10.webpdeleted file mode 100644index d819f49..0000000Binary files a/site/three-little-pigs/making/still-10.webp and /dev/null differdiff --git a/site/three-little-pigs/making/still-4.webp b/site/three-little-pigs/making/still-4.webpdeleted file mode 100644index d0cb6ef..0000000Binary files a/site/three-little-pigs/making/still-4.webp and /dev/null differdiff --git a/site/three-little-pigs/making/still-7.webp b/site/three-little-pigs/making/still-7.webpdeleted file mode 100644index b3b6099..0000000Binary files a/site/three-little-pigs/making/still-7.webp and /dev/null differdiff --git a/site/three-little-pigs/making/try2-slideshow.webp b/site/three-little-pigs/making/try2-slideshow.webpdeleted file mode 100644index 1e863c3..0000000Binary files a/site/three-little-pigs/making/try2-slideshow.webp and /dev/null differ