Add plays from photos (OpenRouter or Claude), library, editor, compose; full-page PDF #2
11 changed files with 258 additions and 91 deletions
14
.env.example
14
.env.example
|
|
@ -1,13 +1,21 @@
|
|||
# Copy to .env (chmod 600) and fill in. Never commit .env.
|
||||
|
||||
# API key from https://platform.claude.com (Anthropic API, billed separately from a Claude subscription).
|
||||
# Without it the app still works; uploaded photos just have to be typed up by hand.
|
||||
# Transcription of page photos. Set ONE of the two keys; OpenRouter wins if both are set.
|
||||
# Without either the app still works; uploaded photos just have to be typed up by hand.
|
||||
|
||||
# OpenRouter key from https://openrouter.ai/settings/keys (prepaid credit).
|
||||
OPENROUTER_API_KEY=
|
||||
# Any OpenRouter model that accepts images. Default ~$0.0015 a page; google/gemini-2.5-flash-lite
|
||||
# is cheaper (~$0.0005), anthropic/claude-haiku-5.5 or google/gemini-3.5-flash read hard pages better.
|
||||
OPENROUTER_MODEL=google/gemini-3.1-flash-lite
|
||||
|
||||
# Or: Anthropic API key from https://platform.claude.com (billed separately from a Claude subscription).
|
||||
ANTHROPIC_API_KEY=
|
||||
|
||||
# Password people need to add and edit plays. Without it uploading is switched off.
|
||||
UPLOAD_PASSWORD=
|
||||
|
||||
# Vision model used for transcription. claude-sonnet-5-5 reads hard pages better at ~20x the price.
|
||||
# Claude model when using ANTHROPIC_API_KEY. claude-sonnet-5-5 reads hard pages better at ~20x the price.
|
||||
CLAUDE_MODEL=claude-haiku-5-5
|
||||
|
||||
# Safety cap on pages transcribed per day (all users together), and pages per play.
|
||||
|
|
|
|||
10
AGENTS.md
10
AGENTS.md
|
|
@ -1,14 +1,16 @@
|
|||
# AGENTS.md — theater-reader
|
||||
|
||||
A Node 22 server (`server/`) serving a no-build front end (`public/`, plain HTML/CSS/ES modules) and a JSON API for plays
|
||||
kept on a volume. Transcription of page photos goes through the Anthropic SDK (`@anthropic-ai/sdk`, the only dependency).
|
||||
kept on a volume. Page photos are transcribed by a vision model through OpenRouter (plain `fetch`, chosen when `OPENROUTER_API_KEY` is set) or the
|
||||
Anthropic SDK (`@anthropic-ai/sdk`, the only dependency, used with `ANTHROPIC_API_KEY`).
|
||||
UI language is Czech.
|
||||
|
||||
## Layout
|
||||
|
||||
- `server/main.mjs`: HTTP server, routing, static files, auth (`x-upload-password` header vs `UPLOAD_PASSWORD`), daily page cap, background transcription job.
|
||||
- `server/store.mjs`: plays on disk, `DATA_DIR/plays/<id>/{meta.json,play.txt,img/NNN.jpg}`. Atomic writes; per-play lock for meta updates.
|
||||
- `server/transcribe.mjs`: one Claude request per photo (`transcribePage`), then `splitPage` → `normalizeSpeakers` → `assemble` into one play file. `server/prompt.mjs` holds the prompt, which teaches the markup below.
|
||||
- `server/providers.mjs`: `makeProvider(env)` returns `{ name, model, transcribe(jpeg) }` for OpenRouter or Anthropic. Errors become `PageError`s whose message is shown in the editor. OpenRouter retries 408/429/5xx and network errors itself.
|
||||
- `server/transcribe.mjs`: `splitPage` → `normalizeSpeakers` → `assemble` turn the per-photo answers into one play file. `server/prompt.mjs` holds the prompt (shared by both providers), which teaches the markup below.
|
||||
- `public/`: four pages: `index.html` library (`library.js`), `read.html` reader (`reader.js`), `add.html` upload (`add.js`: shrinks photos to ≤1.15 MP JPEG in the browser), `edit.html` editor (`edit.js`). `api.js` holds the fetch and password helpers. `parse.js` is the markup parser, shared with the server tests.
|
||||
- `seed/`: plays copied into an empty data volume on first start.
|
||||
- `public/fonts/`: self-hosted woff2 + OFL licences, made by `tools/fetch_fonts.py` (keep its `FAMILIES` and `FONTS` in `reader.js` in step).
|
||||
|
|
@ -23,10 +25,10 @@ edited by hand, so it can't overwrite corrections.
|
|||
## Run / test
|
||||
|
||||
- Dev port **3010** on loopback. Preview with `ssh -p 14922 -L 3010:localhost:3010 <host>`.
|
||||
`podman-compose --env-file <file> up -d --build` (env file with `UPLOAD_PASSWORD`, and optionally `ANTHROPIC_API_KEY`, chmod 600, outside the repo).
|
||||
`podman-compose --env-file <file> up -d --build` (env file with `UPLOAD_PASSWORD`, and optionally `OPENROUTER_API_KEY` or `ANTHROPIC_API_KEY`, chmod 600, outside the repo).
|
||||
- Tests (parser, transcription assembly, API end to end with Claude stubbed):
|
||||
`podman run --rm -v "$PWD":/app:ro,Z -w /app docker.io/library/node:22-alpine npm test` (run `npm ci` in the same image first if `node_modules` is missing).
|
||||
- To exercise the full UI without spending API credit, point `ANTHROPIC_BASE_URL` at a stub server that returns a Messages response.
|
||||
- To exercise the full UI without spending API credit, use `ANTHROPIC_API_KEY=dummy` and point `ANTHROPIC_BASE_URL` at a stub server that returns a Messages response.
|
||||
|
||||
## Play markup
|
||||
|
||||
|
|
|
|||
|
|
@ -15,7 +15,7 @@ A link like `read.html?hra=hra-1931&postava=Lída` opens a play with the charact
|
|||
**Adding plays** (anyone with the upload password):
|
||||
|
||||
1. *Přidat hru*: give the title and pick a photo of each page.
|
||||
2. Each photo is read by a Claude vision model (Claude Haiku 5.5 by default) and turned into the script markup: speakers, stage directions, page numbers. Missing pages are noticed from gaps in the page numbers.
|
||||
2. Each photo is read by a vision model, through OpenRouter (default `google/gemini-3.1-flash-lite`) or the Anthropic API (`claude-haiku-5-5`), and turned into the script markup: speakers, stage directions, page numbers. Missing pages are noticed from gaps in the page numbers.
|
||||
3. The editor shows the text next to the photos and lists things to check (uncertain words marked `[?]`, characters who speak only once, pages that failed). Fix, tick *Zveřejněno*, save.
|
||||
|
||||
## Deploying
|
||||
|
|
@ -29,9 +29,12 @@ The app listens on port 3010 on loopback (`PORT` and `BIND_ADDRESS` change that)
|
|||
|
||||
| Variable | |
|
||||
|---|---|
|
||||
| `ANTHROPIC_API_KEY` | API key from [platform.claude.com](https://platform.claude.com). **A Claude Pro/Max subscription can't be used for this.** The API is billed separately, pay as you go. Without a key the app still works, but uploaded pages have to be typed up by hand. |
|
||||
| `OPENROUTER_API_KEY` | Key from [openrouter.ai](https://openrouter.ai/settings/keys) (prepaid credit). Used for transcription when set. |
|
||||
| `OPENROUTER_MODEL` | Any OpenRouter model that accepts images. Default `google/gemini-3.1-flash-lite` (about $0.0015 a page). `google/gemini-2.5-flash-lite` is cheaper. `anthropic/claude-haiku-5.5` and `google/gemini-3.5-flash` are alternatives if pages come out badly. |
|
||||
| `ANTHROPIC_API_KEY` | Instead of OpenRouter: an API key from [platform.claude.com](https://platform.claude.com). **A Claude Pro/Max subscription can't be used for this.** The API is billed separately. |
|
||||
| | Without either key the app still works, but uploaded pages have to be typed up by hand. |
|
||||
| `UPLOAD_PASSWORD` | Shared password for adding, editing and deleting plays. Unset = uploading switched off. |
|
||||
| `CLAUDE_MODEL` | `claude-haiku-5-5` (default, around $0.001 a page) or `claude-sonnet-5-5` (reads hard pages better, roughly 20× the price). |
|
||||
| `CLAUDE_MODEL` | With the Anthropic key: `claude-haiku-5-5` (default, around $0.001 a page) or `claude-sonnet-5-5` (reads hard pages better, roughly 20× the price). |
|
||||
| `DAILY_PAGE_LIMIT` | Cap on pages transcribed per day, for all users together (default 300), so a leaked password can't run up a bill. |
|
||||
| `MAX_PAGES` | Maximum photos per play (default 80). |
|
||||
|
||||
|
|
|
|||
|
|
@ -6,6 +6,8 @@ services:
|
|||
image: theater-reader:latest
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
OPENROUTER_API_KEY: ${OPENROUTER_API_KEY:-}
|
||||
OPENROUTER_MODEL: ${OPENROUTER_MODEL:-google/gemini-3.1-flash-lite}
|
||||
ANTHROPIC_API_KEY: ${ANTHROPIC_API_KEY:-}
|
||||
UPLOAD_PASSWORD: ${UPLOAD_PASSWORD:-}
|
||||
CLAUDE_MODEL: ${CLAUDE_MODEL:-claude-haiku-5-5}
|
||||
|
|
|
|||
|
|
@ -20,7 +20,7 @@
|
|||
|
||||
<fieldset class="field">
|
||||
<legend>Fotky stran</legend>
|
||||
<p class="muted" id="ai-note">Každou stranu přečte umělá inteligence (Claude) a přepíše ji do textu. Text pak zkontrolujete a opravíte v editoru, než hru zveřejníte.</p>
|
||||
<p class="muted" id="ai-note">Každou stranu přečte umělá inteligence a přepíše ji do textu. Text pak zkontrolujete a opravíte v editoru, než hru zveřejníte.</p>
|
||||
<label class="dropzone" id="drop">
|
||||
<input type="file" id="files" accept="image/*" multiple>
|
||||
<span><b>Vyberte fotky</b> nebo je sem přetáhněte. Jedna fotka = jedna strana.</span>
|
||||
|
|
|
|||
|
|
@ -105,7 +105,7 @@ async function main() {
|
|||
return;
|
||||
}
|
||||
if (!cfg.transcription) {
|
||||
$("ai-note").textContent = "Automatický přepis není na serveru zapnutý (chybí klíč k API). Fotky se nahrají a text pak napíšete v editoru ručně.";
|
||||
$("ai-note").textContent = "Automatický přepis není na serveru zapnutý (chybí klíč OPENROUTER_API_KEY nebo ANTHROPIC_API_KEY). Fotky se nahrají a text pak napíšete v editoru ručně.";
|
||||
$("go").textContent = "Nahrát";
|
||||
}
|
||||
if (!getPassword()) askPassword("Přidávat hry může jen ten, kdo zná heslo.");
|
||||
|
|
|
|||
|
|
@ -1,13 +1,14 @@
|
|||
// Theater reader server: serves the app from public/ and a small JSON API for
|
||||
// plays stored on a volume. Uploading and editing need UPLOAD_PASSWORD;
|
||||
// transcription additionally needs ANTHROPIC_API_KEY.
|
||||
// transcription additionally needs OPENROUTER_API_KEY or ANTHROPIC_API_KEY.
|
||||
import http from "node:http";
|
||||
import { readFile, writeFile, stat } from "node:fs/promises";
|
||||
import { createHash, timingSafeEqual } from "node:crypto";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { createStore, NotFound } from "./store.mjs";
|
||||
import { DEFAULT_MODEL, makeClient, transcribePage, describeError, splitPage, assemble } from "./transcribe.mjs";
|
||||
import { splitPage, assemble } from "./transcribe.mjs";
|
||||
import { makeProvider } from "./providers.mjs";
|
||||
|
||||
const here = path.dirname(fileURLToPath(import.meta.url));
|
||||
const env = process.env;
|
||||
|
|
@ -16,8 +17,6 @@ export const config = {
|
|||
dataDir: env.DATA_DIR || "/data",
|
||||
publicDir: path.resolve(here, "../public"),
|
||||
seedDir: path.resolve(here, "../seed"),
|
||||
apiKey: env.ANTHROPIC_API_KEY || "",
|
||||
model: env.CLAUDE_MODEL || DEFAULT_MODEL,
|
||||
password: env.UPLOAD_PASSWORD || "",
|
||||
dailyPageLimit: Number(env.DAILY_PAGE_LIMIT || 300),
|
||||
maxPages: Number(env.MAX_PAGES || 80),
|
||||
|
|
@ -89,7 +88,7 @@ async function takePages(n) {
|
|||
|
||||
// ---- transcription job (runs in the background; progress lives in meta.json)
|
||||
const running = new Set();
|
||||
export async function runJob(store, id, client) {
|
||||
export async function runJob(store, id, provider) {
|
||||
if (running.has(id)) return;
|
||||
running.add(id);
|
||||
try {
|
||||
|
|
@ -105,11 +104,11 @@ export async function runJob(store, id, client) {
|
|||
const i = todo.shift();
|
||||
let result;
|
||||
try {
|
||||
const { text } = await transcribePage(client, config.model, await store.getImage(id, i + 1));
|
||||
result = splitPage(text);
|
||||
result = splitPage(await provider.transcribe(await store.getImage(id, i + 1)));
|
||||
} catch (err) {
|
||||
console.error(`[${id}] page ${i + 1}: ${describeError(err)}`);
|
||||
result = { num: "?", error: describeError(err) };
|
||||
const reason = String(err?.message || err);
|
||||
console.error(`[${id}] page ${i + 1}: ${reason}`);
|
||||
result = { num: "?", error: reason };
|
||||
}
|
||||
results[i] = result;
|
||||
done++;
|
||||
|
|
@ -124,10 +123,10 @@ export async function runJob(store, id, client) {
|
|||
|
||||
const failed = results.filter((r) => r.error).length;
|
||||
await store.setText(id, assemble(results));
|
||||
await store.updateMeta(id, () => ({ status: "draft", progress: null, failed, model: config.model }));
|
||||
await store.updateMeta(id, () => ({ status: "draft", progress: null, failed, model: `${provider.name}:${provider.model}` }));
|
||||
} catch (err) {
|
||||
console.error(`[${id}] job failed:`, err);
|
||||
await store.updateMeta(id, () => ({ status: "draft", progress: null, jobError: describeError(err) })).catch(() => {});
|
||||
await store.updateMeta(id, () => ({ status: "draft", progress: null, jobError: String(err?.message || err) })).catch(() => {});
|
||||
} finally {
|
||||
running.delete(id);
|
||||
}
|
||||
|
|
@ -136,12 +135,12 @@ export async function runJob(store, id, client) {
|
|||
// ---- API
|
||||
const publicMeta = ({ pages, ...m }) => ({ ...m, failedPages: (pages || []).flatMap((p, i) => (p?.error ? [{ image: i + 1, error: p.error }] : [])) });
|
||||
|
||||
async function api(req, res, store, client, parts) {
|
||||
async function api(req, res, store, provider, parts) {
|
||||
const method = req.method;
|
||||
const [, , id, sub, n] = parts; // ["", "plays", id, sub, n]
|
||||
|
||||
if (parts[1] === "config" && method === "GET")
|
||||
return send(res, 200, { uploads: Boolean(config.password), transcription: Boolean(config.apiKey), model: config.model, maxPages: config.maxPages });
|
||||
return send(res, 200, { uploads: Boolean(config.password), transcription: Boolean(provider), model: provider?.model || null, maxPages: config.maxPages });
|
||||
|
||||
if (parts[1] === "login" && method === "POST") { await requireAuth(req); return send(res, 200, { ok: true }); }
|
||||
|
||||
|
|
@ -218,7 +217,7 @@ async function api(req, res, store, client, parts) {
|
|||
|
||||
if (sub === "transcribe" && method === "POST") {
|
||||
await requireAuth(req);
|
||||
if (!config.apiKey) throw new HttpError(503, "Přepis není nastavený: na serveru chybí ANTHROPIC_API_KEY.");
|
||||
if (!provider) throw new HttpError(503, "Přepis není nastavený: na serveru chybí OPENROUTER_API_KEY nebo ANTHROPIC_API_KEY.");
|
||||
if (running.has(id)) throw new HttpError(409, "Přepis už běží.");
|
||||
if (!meta.images) throw new HttpError(400, "Nejdřív nahrajte fotky stran.");
|
||||
if (meta.edited) throw new HttpError(409, "Text už byl ručně upraven; nový přepis by úpravy přepsal.");
|
||||
|
|
@ -226,7 +225,7 @@ async function api(req, res, store, client, parts) {
|
|||
if (!pending) throw new HttpError(400, "Všechny strany už jsou přepsané.");
|
||||
await takePages(pending);
|
||||
const next = await store.updateMeta(id, () => ({ status: "processing", progress: { done: meta.images - pending, total: meta.images }, jobError: null }));
|
||||
runJob(store, id, client);
|
||||
runJob(store, id, provider);
|
||||
return send(res, 202, publicMeta(next));
|
||||
}
|
||||
|
||||
|
|
@ -249,12 +248,12 @@ async function serveStatic(req, res, pathname) {
|
|||
res.end(await readFile(file));
|
||||
}
|
||||
|
||||
export function createServer(store, client) {
|
||||
export function createServer(store, provider) {
|
||||
return http.createServer(async (req, res) => {
|
||||
const { pathname } = new URL(req.url, "http://localhost");
|
||||
try {
|
||||
if (pathname === "/healthz") return send(res, 200, "ok", MIME[".txt"]);
|
||||
if (pathname.startsWith("/api/")) return await api(req, res, store, client, pathname.slice(4).split("/"));
|
||||
if (pathname.startsWith("/api/")) return await api(req, res, store, provider, pathname.slice(4).split("/"));
|
||||
return await serveStatic(req, res, pathname);
|
||||
} catch (err) {
|
||||
if (err instanceof NotFound) return send(res, 404, { error: "Nenalezeno." });
|
||||
|
|
@ -270,17 +269,17 @@ async function main() {
|
|||
await store.init();
|
||||
const seeded = await store.seed(config.seedDir);
|
||||
if (seeded) console.log(`seeded ${seeded} play(s) into ${store.root}`);
|
||||
const client = config.apiKey ? makeClient(config.apiKey) : null;
|
||||
const provider = makeProvider(env);
|
||||
|
||||
// Resume transcriptions interrupted by a restart.
|
||||
for (const meta of await store.list())
|
||||
if (meta.status === "processing") {
|
||||
if (client) runJob(store, meta.id, client);
|
||||
if (provider) runJob(store, meta.id, provider);
|
||||
else await store.updateMeta(meta.id, () => ({ status: "draft", progress: null, jobError: "přepis přerušen" }));
|
||||
}
|
||||
|
||||
createServer(store, client).listen(config.port, () => {
|
||||
console.log(`theater-reader on :${config.port} (data ${config.dataDir}; uploads ${config.password ? "on" : "off"}; transcription ${client ? config.model : "off"})`);
|
||||
createServer(store, provider).listen(config.port, () => {
|
||||
console.log(`theater-reader on :${config.port} (data ${config.dataDir}; uploads ${config.password ? "on" : "off"}; transcription ${provider ? `${provider.name} ${provider.model}` : "off"})`);
|
||||
});
|
||||
}
|
||||
|
||||
|
|
|
|||
144
server/providers.mjs
Normal file
144
server/providers.mjs
Normal file
|
|
@ -0,0 +1,144 @@
|
|||
// Vision model backends. Each provider is { name, model, transcribe(jpeg) -> markup text }.
|
||||
// OpenRouter is used when OPENROUTER_API_KEY is set, otherwise the Anthropic API
|
||||
// when ANTHROPIC_API_KEY is set, otherwise transcription is off.
|
||||
import Anthropic from "@anthropic-ai/sdk";
|
||||
import { SYSTEM_PROMPT, USER_PROMPT } from "./prompt.mjs";
|
||||
|
||||
export const DEFAULT_CLAUDE_MODEL = "claude-haiku-5-5";
|
||||
export const DEFAULT_OPENROUTER_MODEL = "google/gemini-3.1-flash-lite";
|
||||
const OPENROUTER_URL = "https://openrouter.ai/api/v1/chat/completions";
|
||||
|
||||
// A failure with a message fit to show in the editor.
|
||||
export class PageError extends Error {}
|
||||
|
||||
export function makeProvider(env) {
|
||||
if (env.OPENROUTER_API_KEY)
|
||||
return openRouterProvider({ apiKey: env.OPENROUTER_API_KEY, model: env.OPENROUTER_MODEL || DEFAULT_OPENROUTER_MODEL });
|
||||
if (env.ANTHROPIC_API_KEY)
|
||||
return anthropicProvider({ client: new Anthropic({ apiKey: env.ANTHROPIC_API_KEY, maxRetries: 4 }), model: env.CLAUDE_MODEL || DEFAULT_CLAUDE_MODEL });
|
||||
return null;
|
||||
}
|
||||
|
||||
// ---- Anthropic Messages API (via the official SDK)
|
||||
export function anthropicProvider({ client, model }) {
|
||||
return {
|
||||
name: "anthropic",
|
||||
model,
|
||||
async transcribe(jpeg) {
|
||||
let response;
|
||||
try {
|
||||
response = await client.messages.create({
|
||||
model,
|
||||
max_tokens: 16000,
|
||||
// Copying text off a page needs little reasoning; low effort keeps it cheap.
|
||||
output_config: { effort: "low" },
|
||||
system: [{ type: "text", text: SYSTEM_PROMPT, cache_control: { type: "ephemeral" } }],
|
||||
messages: [{
|
||||
role: "user",
|
||||
content: [
|
||||
{ type: "image", source: { type: "base64", media_type: "image/jpeg", data: jpeg.toString("base64") } },
|
||||
{ type: "text", text: USER_PROMPT },
|
||||
],
|
||||
}],
|
||||
});
|
||||
} catch (err) {
|
||||
throw new PageError(describeAnthropicError(err));
|
||||
}
|
||||
if (response.stop_reason === "refusal") throw new PageError("model declined to transcribe this page");
|
||||
if (response.stop_reason === "max_tokens") throw new PageError("transcription was cut off (page too long)");
|
||||
const text = response.content.filter((b) => b.type === "text").map((b) => b.text).join("").trim();
|
||||
if (!text) throw new PageError("model returned no text");
|
||||
return text;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function describeAnthropicError(err) {
|
||||
if (err instanceof Anthropic.AuthenticationError) return "API key rejected (check ANTHROPIC_API_KEY)";
|
||||
if (err instanceof Anthropic.PermissionDeniedError) return "API key not allowed to use this model";
|
||||
if (err instanceof Anthropic.NotFoundError) return "model not found (check CLAUDE_MODEL)";
|
||||
if (err instanceof Anthropic.RateLimitError) return "rate limited by the API, try again later";
|
||||
if (err instanceof Anthropic.BadRequestError) return `API rejected the request: ${err.message}`;
|
||||
if (err instanceof Anthropic.APIError) return `API error ${err.status ?? ""}: ${err.message}`.trim();
|
||||
return String(err?.message || err);
|
||||
}
|
||||
|
||||
// ---- OpenRouter (OpenAI-style chat completions over plain fetch)
|
||||
const RETRYABLE = new Set([408, 429, 500, 502, 503, 504]);
|
||||
|
||||
export function openRouterProvider({ apiKey, model, fetchImpl = fetch, retries = 3, retryDelayMs = 2000 }) {
|
||||
async function post(body) {
|
||||
for (let attempt = 0; ; attempt++) {
|
||||
let res;
|
||||
try {
|
||||
res = await fetchImpl(OPENROUTER_URL, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${apiKey}`,
|
||||
"Content-Type": "application/json",
|
||||
"X-Title": "Divadelni ctecka", // shown in the OpenRouter activity log
|
||||
},
|
||||
body: JSON.stringify(body),
|
||||
signal: AbortSignal.timeout(180_000),
|
||||
});
|
||||
} catch (err) {
|
||||
if (attempt < retries) { await sleep(retryDelayMs * 2 ** attempt); continue; }
|
||||
throw new PageError(`could not reach OpenRouter: ${err.message}`);
|
||||
}
|
||||
let data = null;
|
||||
try { data = await res.json(); } catch { /* not JSON */ }
|
||||
if (res.ok && !data?.error) return data;
|
||||
const status = data?.error?.code && Number.isInteger(data.error.code) ? data.error.code : res.status;
|
||||
if (RETRYABLE.has(status) && attempt < retries) {
|
||||
const wait = Number(res.headers.get("retry-after")) * 1000 || retryDelayMs * 2 ** attempt;
|
||||
await sleep(wait);
|
||||
continue;
|
||||
}
|
||||
throw new PageError(describeOpenRouterError(status, data?.error?.message));
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
name: "openrouter",
|
||||
model,
|
||||
async transcribe(jpeg) {
|
||||
const data = await post({
|
||||
model,
|
||||
max_tokens: 16000,
|
||||
messages: [
|
||||
{ role: "system", content: SYSTEM_PROMPT },
|
||||
{
|
||||
role: "user",
|
||||
content: [
|
||||
{ type: "image_url", image_url: { url: `data:image/jpeg;base64,${jpeg.toString("base64")}` } },
|
||||
{ type: "text", text: USER_PROMPT },
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
const choice = data?.choices?.[0];
|
||||
if (!choice) throw new PageError("OpenRouter returned no answer");
|
||||
if (choice.error) throw new PageError(`model error: ${choice.error.message || "unknown"}`);
|
||||
if (choice.finish_reason === "content_filter") throw new PageError("model declined to transcribe this page");
|
||||
if (choice.finish_reason === "length") throw new PageError("transcription was cut off (page too long)");
|
||||
const content = choice.message?.content;
|
||||
const text = (Array.isArray(content) ? content.map((c) => c.text || "").join("") : content || "").trim();
|
||||
if (!text) throw new PageError("model returned no text");
|
||||
return text;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function describeOpenRouterError(status, message = "") {
|
||||
const detail = message ? `: ${message}` : "";
|
||||
switch (status) {
|
||||
case 401: return "OpenRouter key rejected (check OPENROUTER_API_KEY)";
|
||||
case 402: return "OpenRouter account is out of credit";
|
||||
case 403: return `OpenRouter refused the request${detail}`;
|
||||
case 404: return `model not found or can't read images (check OPENROUTER_MODEL)${detail}`;
|
||||
case 429: return "rate limited by OpenRouter, try again later";
|
||||
default: return `OpenRouter error ${status}${detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||
|
|
@ -1,50 +1,4 @@
|
|||
// Turn page photos into play markup with a Claude vision model, one request
|
||||
// per page, then stitch the pages together.
|
||||
import Anthropic from "@anthropic-ai/sdk";
|
||||
import { SYSTEM_PROMPT, USER_PROMPT } from "./prompt.mjs";
|
||||
|
||||
export const DEFAULT_MODEL = "claude-haiku-5-5";
|
||||
|
||||
export class PageError extends Error {}
|
||||
|
||||
// Transcribe one JPEG. `client` is an Anthropic client (injected so tests can stub it).
|
||||
export async function transcribePage(client, model, jpeg) {
|
||||
const response = await client.messages.create({
|
||||
model,
|
||||
max_tokens: 16000,
|
||||
// Copying text off a page needs little reasoning; low effort keeps it cheap.
|
||||
output_config: { effort: "low" },
|
||||
system: [{ type: "text", text: SYSTEM_PROMPT, cache_control: { type: "ephemeral" } }],
|
||||
messages: [{
|
||||
role: "user",
|
||||
content: [
|
||||
{ type: "image", source: { type: "base64", media_type: "image/jpeg", data: jpeg.toString("base64") } },
|
||||
{ type: "text", text: USER_PROMPT },
|
||||
],
|
||||
}],
|
||||
});
|
||||
if (response.stop_reason === "refusal") throw new PageError("model declined to transcribe this page");
|
||||
if (response.stop_reason === "max_tokens") throw new PageError("transcription was cut off (page too long)");
|
||||
const text = response.content.filter((b) => b.type === "text").map((b) => b.text).join("").trim();
|
||||
if (!text) throw new PageError("model returned no text");
|
||||
return { text, usage: response.usage };
|
||||
}
|
||||
|
||||
export function makeClient(apiKey) {
|
||||
return new Anthropic({ apiKey, maxRetries: 4 });
|
||||
}
|
||||
|
||||
// A short, human-readable reason for a failed page (shown in the editor).
|
||||
export function describeError(err) {
|
||||
if (err instanceof PageError) return err.message;
|
||||
if (err instanceof Anthropic.AuthenticationError) return "API key rejected (check ANTHROPIC_API_KEY)";
|
||||
if (err instanceof Anthropic.PermissionDeniedError) return "API key not allowed to use this model";
|
||||
if (err instanceof Anthropic.NotFoundError) return "model not found (check CLAUDE_MODEL)";
|
||||
if (err instanceof Anthropic.RateLimitError) return "rate limited by the API, try again later";
|
||||
if (err instanceof Anthropic.BadRequestError) return `API rejected the request: ${err.message}`;
|
||||
if (err instanceof Anthropic.APIError) return `API error ${err.status ?? ""}: ${err.message}`.trim();
|
||||
return String(err?.message || err);
|
||||
}
|
||||
// Stitch per-page transcriptions (see providers.mjs) into one play file.
|
||||
|
||||
// Split model output into { num, body }: the first "=N" line is the page number.
|
||||
export function splitPage(text) {
|
||||
|
|
|
|||
|
|
@ -10,16 +10,16 @@ import { createStore } from "../server/store.mjs";
|
|||
const PASS = "tajne-heslo";
|
||||
const JPEG = Buffer.from([0xff, 0xd8, 0xff, 0xe0, 1, 2, 3]);
|
||||
const replies = ["=-1-\n~JEDNÁNÍ PRVNÍ\n@LÍDA\nDobrý den.", "=2\nještě já.\n@Mise\nAno."];
|
||||
const client = { messages: { create: async (p) => ({ stop_reason: "end_turn", content: [{ type: "text", text: replies.shift() }], usage: {} }) } };
|
||||
const provider = { name: "stub", model: "stub-model", transcribe: async () => replies.shift() };
|
||||
|
||||
let dir, server, base;
|
||||
test.before(async () => {
|
||||
dir = await mkdtemp(path.join(tmpdir(), "tr-"));
|
||||
Object.assign(config, { dataDir: dir, password: PASS, apiKey: "test", dailyPageLimit: 3 });
|
||||
Object.assign(config, { dataDir: dir, password: PASS, dailyPageLimit: 3 });
|
||||
const store = createStore(dir);
|
||||
await store.init();
|
||||
await store.seed(config.seedDir);
|
||||
server = createServer(store, client).listen(0);
|
||||
server = createServer(store, provider).listen(0);
|
||||
base = `http://127.0.0.1:${server.address().port}`;
|
||||
});
|
||||
test.after(async () => { server.close(); await rm(dir, { recursive: true, force: true }); });
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { splitPage, normalizeSpeakers, assemble, transcribePage, PageError } from "../server/transcribe.mjs";
|
||||
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", () => {
|
||||
|
|
@ -30,17 +31,71 @@ test("assemble numbers pages, marks gaps and failed pages", () => {
|
|||
});
|
||||
|
||||
const stub = (response) => ({ messages: { create: async (params) => { stub.last = params; return response; } } });
|
||||
const JPEG = Buffer.from([0xff, 0xd8, 1]);
|
||||
|
||||
test("transcribePage sends the image and reads text blocks", async () => {
|
||||
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 transcribePage(client, "claude-haiku-5-5", Buffer.from([0xff, 0xd8, 1]));
|
||||
const text = await anthropicProvider({ client, model: "claude-haiku-5-5" }).transcribe(JPEG);
|
||||
assert.equal(text, "=1\n@A\nx");
|
||||
const img = stub.last.messages[0].content[0];
|
||||
assert.equal(img.source.media_type, "image/jpeg");
|
||||
assert.equal(stub.last.messages[0].content[0].source.media_type, "image/jpeg");
|
||||
assert.equal(stub.last.model, "claude-haiku-5-5");
|
||||
});
|
||||
|
||||
test("transcribePage reports refusals and truncation", async () => {
|
||||
await assert.rejects(transcribePage(stub({ stop_reason: "refusal", content: [] }), "m", Buffer.alloc(2)), PageError);
|
||||
await assert.rejects(transcribePage(stub({ stop_reason: "max_tokens", content: [{ type: "text", text: "x" }] }), "m", Buffer.alloc(2)), PageError);
|
||||
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");
|
||||
});
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue