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:
parent
46aa1236ed
commit
f353c14619
11 changed files with 258 additions and 91 deletions
|
|
@ -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"})`);
|
||||
});
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue