theater-reader/server/main.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

323 lines
15 KiB
JavaScript

// 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 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 { splitPage, assemble, normalizeSpeakers } from "./transcribe.mjs";
import { makeProvider } from "./providers.mjs";
const here = path.dirname(fileURLToPath(import.meta.url));
const env = process.env;
export const config = {
port: Number(env.PORT || 8080),
dataDir: env.DATA_DIR || "/data",
publicDir: path.resolve(here, "../public"),
seedDir: path.resolve(here, "../seed"),
password: env.UPLOAD_PASSWORD || "",
dailyPageLimit: Number(env.DAILY_PAGE_LIMIT || 300),
maxPages: Number(env.MAX_PAGES || 80),
maxImageBytes: 8 * 1024 * 1024,
maxTextBytes: 2 * 1024 * 1024,
concurrency: 3,
};
const MIME = {
".html": "text/html; charset=utf-8", ".js": "text/javascript; charset=utf-8", ".css": "text/css; charset=utf-8",
".json": "application/json; charset=utf-8", ".txt": "text/plain; charset=utf-8", ".woff2": "font/woff2",
".svg": "image/svg+xml", ".png": "image/png", ".ico": "image/x-icon",
};
const SECURITY_HEADERS = {
"X-Content-Type-Options": "nosniff",
"Referrer-Policy": "no-referrer",
"Content-Security-Policy": "default-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' blob: data:; frame-ancestors 'none'",
};
class HttpError extends Error {
constructor(status, message) { super(message); this.status = status; }
}
function send(res, status, body, type = "application/json; charset=utf-8", extra = {}) {
const data = typeof body === "string" || Buffer.isBuffer(body) ? body : JSON.stringify(body);
res.writeHead(status, { "Content-Type": type, "Cache-Control": "no-cache", ...SECURITY_HEADERS, ...extra });
res.end(data);
}
async function readBody(req, limit) {
const chunks = [];
let size = 0;
for await (const chunk of req) {
size += chunk.length;
if (size > limit) throw new HttpError(413, "Soubor je příliš velký.");
chunks.push(chunk);
}
return Buffer.concat(chunks);
}
async function readJson(req, limit = 64 * 1024) {
try { return JSON.parse((await readBody(req, limit)).toString("utf8") || "{}"); }
catch (err) { if (err instanceof HttpError) throw err; throw new HttpError(400, "Neplatný JSON."); }
}
const digest = (s) => createHash("sha256").update(String(s)).digest();
function isAuthed(req) {
const given = req.headers["x-upload-password"];
return Boolean(config.password && given && timingSafeEqual(digest(given), digest(config.password)));
}
async function requireAuth(req) {
if (!config.password) throw new HttpError(403, "Nahrávání je vypnuté: na serveru není nastavené UPLOAD_PASSWORD.");
if (!isAuthed(req)) {
await new Promise((r) => setTimeout(r, 1000)); // slow down password guessing
throw new HttpError(401, "Špatné heslo.");
}
}
// ---- usage cap: pages transcribed per UTC day, so a leaked password can't run up a big bill
async function takePages(n) {
const file = path.join(config.dataDir, "usage.json");
const day = new Date().toISOString().slice(0, 10);
let usage = {};
try { usage = JSON.parse(await readFile(file, "utf8")); } catch { /* first use */ }
const used = usage.day === day ? usage.pages : 0;
if (used + n > config.dailyPageLimit)
throw new HttpError(429, `Denní limit ${config.dailyPageLimit} stran je vyčerpán (dnes už ${used}). Zkuste to zítra.`);
await writeFile(file, JSON.stringify({ day, pages: used + n }));
}
// ---- transcription job (runs in the background; progress lives in meta.json)
const running = new Set();
export async function runJob(store, id, provider) {
if (running.has(id)) return;
running.add(id);
try {
const meta = await store.getMeta(id);
const results = meta.pages.slice(0, meta.images);
const todo = [];
for (let i = 0; i < meta.images; i++) if (!results[i] || results[i].error) todo.push(i);
let done = meta.images - todo.length;
await store.updateMeta(id, () => ({ status: "processing", progress: { done, total: meta.images } }));
const worker = async () => {
while (todo.length) {
const i = todo.shift();
let result;
try {
result = splitPage(await provider.transcribe(await store.getImage(id, i + 1)));
} catch (err) {
const reason = String(err?.message || err);
console.error(`[${id}] page ${i + 1}: ${reason}`);
result = { num: "?", error: reason };
}
results[i] = result;
done++;
await store.updateMeta(id, (m) => {
const pages = m.pages.slice();
pages[i] = result;
return { pages, progress: { done, total: meta.images } };
});
}
};
await Promise.all(Array.from({ length: config.concurrency }, worker));
const failed = results.filter((r) => r.error).length;
const { text, photos, duplicates } = assemble(results);
await store.setText(id, text);
await store.updateMeta(id, () => ({ status: "draft", progress: null, failed, photos, duplicates, model: `${provider.name}:${provider.model}` }));
} catch (err) {
console.error(`[${id}] job failed:`, err);
await store.updateMeta(id, () => ({ status: "draft", progress: null, jobError: String(err?.message || err) })).catch(() => {});
} finally {
running.delete(id);
}
}
// ---- API
const publicMeta = ({ pages, ...m }) => ({
...m,
photos: m.photos || null,
duplicates: m.duplicates || [],
failedPages: (pages || []).flatMap((p, i) => (p?.error ? [{ image: i + 1, error: p.error }] : [])),
});
async function api(req, res, store, provider, parts) {
const method = req.method;
const [, , id, sub, n] = parts; // ["", "plays", id, sub, n, action]
if (parts[1] === "config" && method === "GET")
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 }); }
if (parts[1] !== "plays") throw new HttpError(404, "Nenalezeno.");
if (!id) {
if (method === "GET") {
const authed = isAuthed(req);
const plays = (await store.list()).filter((p) => p.published || authed).map(publicMeta);
return send(res, 200, plays);
}
if (method === "POST") {
await requireAuth(req);
const { title, note } = await readJson(req);
if (typeof title !== "string" || !title.trim()) throw new HttpError(400, "Chybí název hry.");
const meta = await store.create({ title: title.trim().slice(0, 200), note: String(note || "").trim().slice(0, 500) });
return send(res, 201, publicMeta(meta));
}
throw new HttpError(405, "Metoda není povolena.");
}
const meta = await store.getMeta(id);
// Unpublished plays are visible only with the password.
if (!meta.published && !isAuthed(req)) throw new NotFound(id);
if (!sub) {
if (method === "GET") return send(res, 200, publicMeta(meta));
if (method === "PATCH") {
await requireAuth(req);
const body = await readJson(req, config.maxTextBytes);
const patch = {};
if (typeof body.title === "string" && body.title.trim()) patch.title = body.title.trim().slice(0, 200);
if (typeof body.note === "string") patch.note = body.note.trim().slice(0, 500);
if (typeof body.published === "boolean") patch.published = body.published;
// which photo belongs to which page marker of the text (the editor keeps this in step)
if (Array.isArray(body.photos)) {
if (body.photos.length > 2000 || !body.photos.every((p) => p === null || (Number.isInteger(p) && p >= 1 && p <= meta.images)))
throw new HttpError(400, "Neplatné přiřazení fotek.");
patch.photos = body.photos;
}
// left-out repeat photos; the editor swaps them with the page's chosen photo
if (Array.isArray(body.duplicates)) {
const ok = (d) => d && Number.isInteger(d.image) && d.image >= 1 && d.image <= meta.images && Number.isInteger(d.kept)
&& typeof d.page === "string" && d.page.length <= 20 && typeof d.body === "string" && d.body.length <= 50_000;
if (body.duplicates.length > config.maxPages || !body.duplicates.every(ok)) throw new HttpError(400, "Neplatný seznam opakovaných fotek.");
patch.duplicates = body.duplicates.map(({ image, page, kept, body: text }) => ({ image, page, kept, body: text }));
}
return send(res, 200, publicMeta(await store.updateMeta(id, () => patch)));
}
if (method === "DELETE") {
await requireAuth(req);
if (running.has(id)) throw new HttpError(409, "Hra se právě přepisuje, chvíli počkejte.");
await store.remove(id);
return send(res, 200, { ok: true });
}
}
if (sub === "text") {
if (method === "GET") return send(res, 200, await store.getText(id), MIME[".txt"]);
if (method === "PUT") {
await requireAuth(req);
if (running.has(id)) throw new HttpError(409, "Hra se právě přepisuje, chvíli počkejte.");
const text = (await readBody(req, config.maxTextBytes)).toString("utf8");
await store.setText(id, text);
return send(res, 200, publicMeta(await store.updateMeta(id, () => ({ edited: true }))));
}
}
// Transcribe one photo and hand back { num, body } without touching the text:
// the editor puts it into the page (re-reading a failed page, adding a page later).
if (sub === "images" && n && parts[5] === "transcribe" && method === "POST") {
await requireAuth(req);
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, "Hra se právě přepisuje.");
const num = Number(n);
const jpeg = await store.getImage(id, num);
await takePages(1);
let result;
try { result = splitPage(await provider.transcribe(jpeg)); }
catch (err) { throw new HttpError(502, `Přepis se nepovedl: ${err?.message || err}`); }
// spell the speakers the way the rest of the play does
const [, body] = normalizeSpeakers([await store.getText(id), result.body]);
await store.updateMeta(id, (m) => { const pages = m.pages.slice(); pages[num - 1] = result; return { pages }; });
return send(res, 200, { num: result.num, body });
}
if (sub === "images" && n && !parts[5]) {
const num = Number(n);
if (method === "GET") return send(res, 200, await store.getImage(id, num), "image/jpeg", { "Cache-Control": "private, max-age=3600" });
if (method === "PUT") {
await requireAuth(req);
if (running.has(id)) throw new HttpError(409, "Hra se právě přepisuje.");
if (!Number.isInteger(num) || num < 1 || num > config.maxPages) throw new HttpError(400, `Nejvýše ${config.maxPages} stran.`);
if (!/^image\/jpeg\b/.test(req.headers["content-type"] || "")) throw new HttpError(415, "Očekávám JPEG.");
const buf = await readBody(req, config.maxImageBytes);
if (buf[0] !== 0xff || buf[1] !== 0xd8) throw new HttpError(415, "Soubor není JPEG.");
await store.putImage(id, num, buf);
return send(res, 200, publicMeta(await store.updateMeta(id, (m) => {
const pages = m.pages.slice();
pages[num - 1] = null; // a replaced photo gets transcribed again
return { images: Math.max(m.images, num), pages };
})));
}
}
if (sub === "transcribe" && method === "POST") {
await requireAuth(req);
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.");
const pending = Array.from({ length: meta.images }, (_, i) => meta.pages[i]).filter((p) => !p || p.error).length;
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, provider);
return send(res, 202, publicMeta(next));
}
throw new HttpError(405, "Metoda není povolena.");
}
// ---- static files
async function serveStatic(req, res, pathname) {
if (req.method !== "GET" && req.method !== "HEAD") throw new HttpError(405, "Metoda není povolena.");
const rel = pathname === "/" ? "index.html" : decodeURIComponent(pathname).replace(/^\/+/, "");
const file = path.resolve(config.publicDir, rel);
if (!file.startsWith(config.publicDir + path.sep)) throw new HttpError(404, "Nenalezeno.");
let info;
try { info = await stat(file); } catch { throw new HttpError(404, "Nenalezeno."); }
if (!info.isFile()) throw new HttpError(404, "Nenalezeno.");
const ext = path.extname(file);
const cache = rel.startsWith("fonts/") ? "public, max-age=2592000" : "no-cache";
res.writeHead(200, { "Content-Type": MIME[ext] || "application/octet-stream", "Content-Length": info.size, "Cache-Control": cache, ...SECURITY_HEADERS });
if (req.method === "HEAD") return res.end();
res.end(await readFile(file));
}
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, provider, pathname.slice(4).split("/"));
return await serveStatic(req, res, pathname);
} catch (err) {
if (err instanceof NotFound) return send(res, 404, { error: "Nenalezeno." });
if (err instanceof HttpError) return send(res, err.status, { error: err.message });
console.error(`${req.method} ${pathname}:`, err);
if (!res.headersSent) send(res, 500, { error: "Chyba serveru." });
}
});
}
async function main() {
const store = createStore(config.dataDir);
await store.init();
const seeded = await store.seed(config.seedDir);
if (seeded) console.log(`seeded ${seeded} play(s) into ${store.root}`);
const provider = makeProvider(env);
// Resume transcriptions interrupted by a restart.
for (const meta of await store.list())
if (meta.status === "processing") {
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, 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"})`);
});
}
if (process.argv[1] === fileURLToPath(import.meta.url)) main();