theater-reader/tests/transcribe.test.mjs
agent ab842a1d73 Sort pages by their number, drop repeated photos, mark uncertain words
The model now wraps words it isn't sure of in {word} or {word|other}; the
reader shows the first reading. Pages are ordered by the number on each
photo and a page photographed twice is kept once (fewer uncertain words,
then more text). meta.photos records which photo goes with which page.
New POST /images/:n/transcribe re-reads a single photo for the editor.
Seeded plays get an img/ folder on their first photo.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HA82gVRDXpoukzgMFumoJt
2026-11-04 16:15:27 +00:00

130 lines
7 KiB
JavaScript

import test from "node:test";
import assert from "node:assert/strict";
import { splitPage, normalizeSpeakers, assemble } from "../server/transcribe.mjs";
import { anthropicProvider, openRouterProvider, makeProvider, PageError } from "../server/providers.mjs";
import { parsePlay, lint } from "../public/parse.js";
test("splitPage takes the page number from the first line", () => {
assert.deepEqual(splitPage("=-12-\n@Lída\nAno."), { num: "12", body: "@Lída\nAno." });
assert.deepEqual(splitPage("=?\ntext"), { num: "?", body: "text" });
assert.deepEqual(splitPage("```\n=3\n@A\nx\n=4\n```"), { num: "3", body: "@A\nx" });
assert.equal(splitPage("@A\nx").num, "?");
});
test("speaker spellings are unified across pages", () => {
const out = normalizeSpeakers(["@LÍDA\nx\n@Lida\ny", "@Lida:\nz\n@PANÍ BÁBA\nw\n@Paní bába\nv"]);
assert.deepEqual(out, ["@Lída\nx\n@Lída\ny", "@Lída\nz\n@Paní bába\nw\n@Paní bába\nv"]);
});
test("assemble numbers pages, marks gaps and failed pages", () => {
const { text, photos } = assemble([
{ num: "5", body: "@Mise\nAno." },
{ num: "?", body: "dál" },
{ num: "9", body: "@Lída\nNe." },
{ error: "model declined" },
]);
assert.equal(text, "=5\n@Mise\nAno.\n=6\ndál\n!7-8\n=9\n@Lída\nNe.\n=10\n>(Stranu se nepodařilo přepsat: model declined)\n");
assert.deepEqual(photos, [1, 2, null, 3, 4]);
const pages = parsePlay(text);
assert.deepEqual(pages.map((p) => p.num), ["5", "6", "7-8", "9", "10"]);
assert.equal(pages[1].blocks[0].speaker, "Mise"); // continues across the page break
assert.deepEqual(lint(pages), []);
});
test("assemble sorts by page number and drops repeated photos of a page", () => {
const { text, photos, duplicates } = assemble([
{ num: "1", body: "{jedna}" },
{ num: "3", body: "tři" },
{ num: "?", body: "po trojce" }, // no number: stays after the photo uploaded before it
{ num: "2", body: "dva" },
{ num: "1", body: "jedna" }, // retake of page 1 with no uncertain words: wins
{ num: "3", body: "tři" }, // the same photo again
]);
assert.equal(text, "=1\njedna\n=2\ndva\n=3\ntři\n=4\npo trojce\n");
assert.deepEqual(photos, [5, 4, 2, 3]);
assert.deepEqual(duplicates.map((d) => [d.image, d.page, d.kept]), [[1, "1", 5], [6, "3", 2]]);
});
test("an unnumbered page whose guess is taken keeps no number", () => {
const { text } = assemble([{ num: "1", body: "a" }, { num: "?", body: "b" }, { num: "2", body: "c" }]);
assert.equal(text, "=1\na\n=?\nb\n=2\nc\n");
});
test("uncertain words: old [?] marks are converted, the reader drops the braces", () => {
assert.equal(splitPage("=1\nTo je divné[?] slovo, ne[?]?").body, "To je {divné} slovo, {ne}?");
const [page] = parsePlay("=1\n@{Lída}\nTo je {divné|dívčí} slovo.", { plain: true });
assert.equal(page.blocks[0].speaker, "Lída");
assert.deepEqual(page.blocks[0].parts[0].lines, ["To je divné slovo."]);
assert.equal(normalizeSpeakers(["@{LÍDA}\nx"])[0], "@Lída\nx");
assert.deepEqual(lint(parsePlay("=1\n@A\nnějaké {slovo")).map((x) => x.message), ["Neuzavřená složená závorka: „nějaké {slovo“"]);
});
const stub = (response) => ({ messages: { create: async (params) => { stub.last = params; return response; } } });
const JPEG = Buffer.from([0xff, 0xd8, 1]);
test("anthropic: sends the image and reads text blocks", async () => {
const client = stub({ stop_reason: "end_turn", content: [{ type: "thinking", thinking: "" }, { type: "text", text: "=1\n@A\nx" }], usage: {} });
const text = await anthropicProvider({ client, model: "claude-haiku-5-5" }).transcribe(JPEG);
assert.equal(text, "=1\n@A\nx");
assert.equal(stub.last.messages[0].content[0].source.media_type, "image/jpeg");
assert.equal(stub.last.model, "claude-haiku-5-5");
});
test("anthropic: refusals and truncation become page errors", async () => {
const p = (r) => anthropicProvider({ client: stub(r), model: "m" }).transcribe(JPEG);
await assert.rejects(p({ stop_reason: "refusal", content: [] }), PageError);
await assert.rejects(p({ stop_reason: "max_tokens", content: [{ type: "text", text: "x" }] }), PageError);
});
// fake fetch: returns the queued responses in order and records the requests
function fakeFetch(...responses) {
const calls = [];
const f = async (url, init) => {
calls.push({ url, init, body: JSON.parse(init.body) });
const r = responses.shift();
if (r instanceof Error) throw r;
return new Response(JSON.stringify(r.body), { status: r.status || 200, headers: { "content-type": "application/json" } });
};
f.calls = calls;
return f;
}
const ok = (text, finish = "stop") => ({ body: { choices: [{ finish_reason: finish, message: { role: "assistant", content: text } }] } });
test("openrouter: sends a data-URL image with the key and reads the answer", async () => {
const f = fakeFetch(ok("=2\n@Lída\nAno."));
const p = openRouterProvider({ apiKey: "sk-or-test", model: "google/gemini-3.1-flash-lite", fetchImpl: f });
assert.equal(await p.transcribe(JPEG), "=2\n@Lída\nAno.");
const [{ url, init, body }] = f.calls;
assert.equal(url, "https://openrouter.ai/api/v1/chat/completions");
assert.equal(init.headers.Authorization, "Bearer sk-or-test");
assert.equal(body.model, "google/gemini-3.1-flash-lite");
assert.equal(body.messages[0].role, "system");
assert.match(body.messages[1].content[0].image_url.url, /^data:image\/jpeg;base64,/);
});
test("openrouter: retries rate limits and network errors, then gives up with a readable message", async () => {
const f = fakeFetch({ status: 429, body: { error: { code: 429, message: "slow down" } } }, new Error("ECONNRESET"), ok("=1\nx"));
assert.equal(await openRouterProvider({ apiKey: "k", model: "m", fetchImpl: f, retryDelayMs: 1 }).transcribe(JPEG), "=1\nx");
assert.equal(f.calls.length, 3);
const g = fakeFetch({ status: 402, body: { error: { code: 402, message: "Insufficient credits" } } });
await assert.rejects(openRouterProvider({ apiKey: "k", model: "m", fetchImpl: g, retryDelayMs: 1 }).transcribe(JPEG), /out of credit/);
assert.equal(g.calls.length, 1); // not retried
// an error inside a 200 body counts too
const h = fakeFetch({ body: { error: { code: 401, message: "No auth" } } });
await assert.rejects(openRouterProvider({ apiKey: "k", model: "m", fetchImpl: h }).transcribe(JPEG), /key rejected/);
});
test("openrouter: truncated, filtered or empty answers are page errors", async () => {
for (const r of [ok("x", "length"), ok("x", "content_filter"), ok(""), { body: { choices: [] } }])
await assert.rejects(openRouterProvider({ apiKey: "k", model: "m", fetchImpl: fakeFetch(r) }).transcribe(JPEG), PageError);
});
test("provider choice: OpenRouter first, then Anthropic, else off", () => {
assert.equal(makeProvider({}), null);
assert.equal(makeProvider({ ANTHROPIC_API_KEY: "a" }).name, "anthropic");
const p = makeProvider({ ANTHROPIC_API_KEY: "a", OPENROUTER_API_KEY: "o" });
assert.deepEqual([p.name, p.model], ["openrouter", "google/gemini-3.1-flash-lite"]);
assert.equal(makeProvider({ OPENROUTER_API_KEY: "o", OPENROUTER_MODEL: "qwen/x" }).model, "qwen/x");
});