Transcribe through OpenRouter when OPENROUTER_API_KEY is set

A Claude subscription can't be used by the app, so let it use any cheap
vision model on OpenRouter instead (default google/gemini-3.1-flash-lite,
OPENROUTER_MODEL to change). The Anthropic API stays available as the
second choice. Both providers share the prompt and live behind one
{ name, model, transcribe } interface in server/providers.mjs; OpenRouter
retries 408/429/5xx and network errors and turns 401/402/404 into
messages the editor can show.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HA82gVRDXpoukzgMFumoJt
This commit is contained in:
agent 2026-11-04 15:38:24 +00:00
parent 46aa1236ed
commit f353c14619
11 changed files with 258 additions and 91 deletions

View file

@ -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
View 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));

View file

@ -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) {