An AI skill that turns books into animated, narrated, interactive web experiences
JavaScript ai-agentsai-educationanimationclaudeclaude-codeclaude-skillsedtecheducationinteractive-textbookscormtext-to-video
fix(scripts): one ledger layout with a chapter column; paint.py explains a credit refusal
yzr56e188ad9947
diff --git a/.claude/skills/papermorph/scripts/eleven.py b/.claude/skills/papermorph/scripts/eleven.pyindex 8e7e9e2..6943a0f 100644--- a/.claude/skills/papermorph/scripts/eleven.py+++ b/.claude/skills/papermorph/scripts/eleven.py@@ -46,8 +46,9 @@ should stay long (a turn of the film) needs its beat run without it.alignment, so the marks, cues and loudness come from the clip as heard. takes.json records the tempo with the take, so arerun keeps a sped clip, and a changed tempo makes it again from the cached take (no new take is paid for)."""-import argparse, atexit, datetime, hashlib, json, pathlib, re, subprocess, sys, urllib.error, urllib.request+import argparse, atexit, hashlib, json, pathlib, re, subprocess, sys, urllib.error, urllib.requestfrom paint import key+from ledger import appendfrom tts import ABBREV, split_marks, mark_times, duration, write_atomicimport level as lv@@ -151,8 +152,7 @@ timings, spent = {}, 0def charge():"""Log what was paid for, once the takes are made: a run stopped partway logs only its finished takes."""if a.ledger and spent:- 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{model}\ttts{spent}c\t{spent * PRICE:.4f}\n")+ append(a.ledger, a.out, model, f"tts{spent}c", f"{spent * PRICE:.4f}")atexit.register(charge) # at the end, or when a later step (a failed take, Whisper) stops the rundiff --git a/.claude/skills/papermorph/scripts/ledger.py b/.claude/skills/papermorph/scripts/ledger.pyindex 624cc72..0b41b84 100644--- a/.claude/skills/papermorph/scripts/ledger.py+++ b/.claude/skills/papermorph/scripts/ledger.py@@ -1,9 +1,24 @@-"""Sums for the paint scripts' 5-column TSV ledgers (date, file, model, quality, cost)."""-import pathlib+"""One cost ledger for every paid script: tab-separated rows (date, chapter, file, model, what, cost in USD).++ from ledger import append, print_total+ append("books/<book>/art/costs.tsv", "books/<book>/art/ch04/vials.png", "openai/gpt-image-2.5-flare", "low", 0.004)++The chapter is read from the file's path (its first chNN, e.g. art/ch04/ or ch01-desk.png; "-" when there is none),+so episodes made in parallel are told apart in one ledger. Older rows have no chapter column (date, file, model, what,+cost); print_total sums both.+"""+import datetime, pathlib, re+++def append(path, file, model, what, cost):+ ch = re.search(r"(?<![A-Za-z])ch\d+", str(file))+ led = pathlib.Path(path); led.parent.mkdir(parents=True, exist_ok=True)+ with led.open("a", encoding="utf-8") as f:+ f.write(f"{datetime.date.today()}\t{ch[0] if ch else '-'}\t{file}\t{model}\t{what}\t{cost}\n")def rows(path):- """Parsed non-empty ledger rows: [date, file, model, quality, cost]."""+ """Parsed non-empty ledger rows; the model is r[-3] and the cost r[-1] in both layouts."""text = pathlib.Path(path).read_text(encoding="utf-8")return [l.rstrip("\n").split("\t") for l in text.splitlines() if l.strip()]@@ -13,7 +28,7 @@ def print_total(path, note=""):rs = rows(path)by = {}for r in rs:- by[r[2]] = by.get(r[2], 0) + float(r[4])+ by[r[-3]] = by.get(r[-3], 0) + float(r[-1])tail = f" ({len(rs)} rows{', ' + note if note else ''})"for m, c in sorted(by.items()):print(f"{m:40s} {c:8.4f} USD")diff --git a/.claude/skills/papermorph/scripts/paint.py b/.claude/skills/papermorph/scripts/paint.pyindex 53d2f9e..71ebdb8 100644--- a/.claude/skills/papermorph/scripts/paint.py+++ b/.claude/skills/papermorph/scripts/paint.py@@ -9,16 +9,17 @@ Reference pictures steer composition and characters (a baked set sketch makes abake_sets.py). Quality is low or medium only: high costs several times as much and has never been needed; thescript 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.+account balance is below $1.00, so top up before a batch; a refusal for credit prints the balance left. Voice+(eleven.py) spends from the same balance: when several runs share it, make the pictures first.-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+Each call prints the cost OpenRouter reports and appends one line to the ledger (date, chapter, file, model, quality,+cost, tab separated, see ledger.py; the ledger and its folder are created). Test the cheapest quality first and total the ledger before andafter a batch, so the spend is known. An existing OUT is never replaced (it may be an approved, paid picture) unless--force is given."""-import argparse, base64, datetime, json, mimetypes, os, pathlib, sys, urllib.request, urllib.error+import argparse, base64, json, mimetypes, os, pathlib, sys, urllib.request, urllib.error-from ledger import print_total+from ledger import append, print_totaltotal = print_total@@ -30,6 +31,16 @@ def key():return k+def balance(k):+ """The account's credit left in USD, or None when OpenRouter does not say."""+ try:+ d = json.load(urllib.request.urlopen(urllib.request.Request("https://openrouter.ai/api/v1/credits",+ headers={"Authorization": f"Bearer {k}"}), timeout=30))["data"]+ return d["total_credits"] - d["total_usage"]+ except Exception:+ return None++def main():if len(sys.argv) == 3 and sys.argv[1] == "--total":return total(sys.argv[2])@@ -59,13 +70,16 @@ def main():r = json.load(urllib.request.urlopen(req, timeout=600))except urllib.error.HTTPError as e:err = e.read().decode(errors="replace").replace(k, "***")[:500] # redact the whole body, then trim+ if e.code == 402 or "credit" in err.lower() or "balance" in err.lower():+ left = balance(k)+ err += (f"\nOpenRouter refuses image requests while the balance is under $1.00 (left: "+ f"{'unknown' if left is None else f'${left:.2f}'}). Top up at https://openrouter.ai/settings/credits; "+ "when several runs share the balance, make the pictures before the voice (eleven.py spends from it too).")raise SystemExit(f"{e.code} {err}")usage = r.get("usage") or {}cost = usage.get("cost", 0) or 0print(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: # logged first: the call is paid for even if no picture came back- f.write(f"{datetime.date.today()}\t{a.out}\t{a.model}\t{a.q}\t{cost}\n")+ append(a.ledger, a.out, a.model, a.q, cost) # logged first: the call is paid for even if no picture came backtry:png = base64.b64decode(r["data"][0]["b64_json"])except (KeyError, IndexError, TypeError):diff --git a/.claude/skills/papermorph/scripts/paint_openai.py b/.claude/skills/papermorph/scripts/paint_openai.pyindex 79c35ba..6f4004f 100644--- a/.claude/skills/papermorph/scripts/paint_openai.py+++ b/.claude/skills/papermorph/scripts/paint_openai.py@@ -12,16 +12,16 @@ The key is read from $OPENAI_API_KEY, else from --env FILE, else ~/.config/paperOpenAI's response reports usage tokens but not a USD cost, so the ledger records an estimate(about 0.02 USD per low picture, 0.05 per medium at 1536x1024) — check the invoice for exact numbers.-Each call prints the usage and appends one line to the ledger (date, file, model, quality, cost).+Each call prints the usage and appends one line to the ledger (date, chapter, file, model, quality, cost; see ledger.py)."""-import argparse, base64, datetime, json, os, pathlib, sys, urllib.request, urllib.error+import argparse, base64, json, os, pathlib, sys, urllib.request, urllib.errorAPI = "https://api.openai.com/v1"SIZES = {"16:9": "1536x1024", "9:16": "1024x1536", "1:1": "1024x1024"}EST = {"low": 0.02, "medium": 0.05, "high": 0.20}-from ledger import print_total+from ledger import append, print_totaldef total(path):print_total(path, 'estimated')@@ -99,9 +99,7 @@ def main():usage = r.get("usage") or {}cost = (usage.get("cost") if isinstance(usage, dict) else None) or EST[a.q]print(a.out, f"cost {cost} USD (est)", 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:.4f}\n")+ append(a.ledger, a.out, a.model, a.q, f"{cost:.4f}")if __name__ == "__main__":diff --git a/.claude/skills/papermorph/scripts/video.py b/.claude/skills/papermorph/scripts/video.pyindex 99bb24d..74eb997 100644--- a/.claude/skills/papermorph/scripts/video.py+++ b/.claude/skills/papermorph/scripts/video.py@@ -11,11 +11,12 @@ Kling 3.0 std, 5 s, cost about $0.42 and kept an engraving's style; Veo 3.1 litethe script polls every 20 s for up to 15 minutes. A job that ends other than completed stops the script; a timeout or alost connection prints the job id to --resume. The key is read from ~/.config/openrouter/key or $OPENROUTER_API_KEY.-Prints the cost OpenRouter reports and appends a row to the ledger (date, file, model, "video<N>s", cost), the same+Prints the cost OpenRouter reports and appends a row to the ledger (date, chapter, file, model, "video<N>s", cost), the sameledger paint.py writes, so `python3 paint.py --total LEDGER` sums both."""-import argparse, base64, datetime, json, mimetypes, pathlib, sys, time, urllib.error, urllib.request+import argparse, base64, json, mimetypes, pathlib, sys, time, urllib.error, urllib.requestfrom paint import key+from ledger import appendap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)ap.add_argument("out"); ap.add_argument("frame"); ap.add_argument("prompt")@@ -56,6 +57,5 @@ if s["status"] != "completed": raise SystemExit(f"{s['status']}: {s.get('error')out = pathlib.Path(a.out); out.parent.mkdir(parents=True, exist_ok=True)out.write_bytes(call(f"https://openrouter.ai/api/v1/videos/{jid}/content?index=0").read())cost = (s.get("usage") or {}).get("cost", 0) or 0-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}\tvideo{a.duration}s\t{cost}\n")+append(a.ledger, a.out, a.model, f"video{a.duration}s", cost)print(a.out, f"cost {cost} USD")