Let people add plays from photos; library, editor, compose; full-page PDF
- Replace the static nginx site with a small Node server: serves public/, stores plays on a /data volume and exposes a JSON API. Writes need a shared UPLOAD_PASSWORD; unpublished plays are hidden without it. - Page photos (shrunk to <=1.15 MP JPEG in the browser) are transcribed one request per page by a Claude vision model (claude-haiku-5-5 by default, CLAUDE_MODEL to change) into the play markup, then stitched together: speaker spellings unified, gaps in page numbers marked as missing pages, failed pages flagged. DAILY_PAGE_LIMIT caps spend. - New pages: library (play menu), add (upload + progress), editor (text next to the photos, checks for [?] readings and one-off names, publish, delete). The reader loads plays from the API and remembers the chosen role per play; old /?postava= links still work. - PDF export: text now flows across original pages and prints at the on-screen size, so A4 sheets are full instead of half empty; page numbers in the footer. - docker-compose.yml + .env.example for one-click deploys; the 1931 play moves to seed/ and is copied into an empty volume on first start. - Tests: parser leniency, transcription assembly, API end to end with a stubbed Claude client. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01HA82gVRDXpoukzgMFumoJt
This commit is contained in:
parent
2608d10dd2
commit
46aa1236ed
32 changed files with 1761 additions and 160 deletions
287
server/main.mjs
Normal file
287
server/main.mjs
Normal file
|
|
@ -0,0 +1,287 @@
|
|||
// 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.
|
||||
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";
|
||||
|
||||
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"),
|
||||
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),
|
||||
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) {
|
||||
try { return JSON.parse((await readBody(req, 64 * 1024)).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, client) {
|
||||
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 {
|
||||
const { text } = await transcribePage(client, config.model, await store.getImage(id, i + 1));
|
||||
result = splitPage(text);
|
||||
} catch (err) {
|
||||
console.error(`[${id}] page ${i + 1}: ${describeError(err)}`);
|
||||
result = { num: "?", error: describeError(err) };
|
||||
}
|
||||
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;
|
||||
await store.setText(id, assemble(results));
|
||||
await store.updateMeta(id, () => ({ status: "draft", progress: null, failed, model: config.model }));
|
||||
} catch (err) {
|
||||
console.error(`[${id}] job failed:`, err);
|
||||
await store.updateMeta(id, () => ({ status: "draft", progress: null, jobError: describeError(err) })).catch(() => {});
|
||||
} finally {
|
||||
running.delete(id);
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 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) {
|
||||
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 });
|
||||
|
||||
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);
|
||||
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;
|
||||
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 }))));
|
||||
}
|
||||
}
|
||||
|
||||
if (sub === "images" && n) {
|
||||
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 (!config.apiKey) throw new HttpError(503, "Přepis není nastavený: na serveru chybí 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, client);
|
||||
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, client) {
|
||||
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("/"));
|
||||
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 client = config.apiKey ? makeClient(config.apiKey) : null;
|
||||
|
||||
// Resume transcriptions interrupted by a restart.
|
||||
for (const meta of await store.list())
|
||||
if (meta.status === "processing") {
|
||||
if (client) runJob(store, meta.id, client);
|
||||
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"})`);
|
||||
});
|
||||
}
|
||||
|
||||
if (process.argv[1] === fileURLToPath(import.meta.url)) main();
|
||||
37
server/prompt.mjs
Normal file
37
server/prompt.mjs
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
// Instructions for transcribing one photographed page of a play into the
|
||||
// reader's markup (documented in AGENTS.md). Kept byte-stable so the prompt
|
||||
// prefix can be cached across the pages of an upload.
|
||||
|
||||
export const SYSTEM_PROMPT = `You transcribe photographed pages of theatre play scripts (often old typescripts, often in Czech) into a plain-text markup used by a script-reading app.
|
||||
|
||||
Transcribe exactly what is on the page: keep the original spelling, punctuation, missing spaces ("dobře.Ale"), and line breaks. Do not translate, modernise, correct or summarise. Do not invent text you cannot read; if a word is illegible, write your best reading followed by [?].
|
||||
|
||||
Output only the markup, nothing else: no commentary, no code fences.
|
||||
|
||||
First line of output: "=" followed by the page number exactly as printed on the page (e.g. "-5-" gives "=5"). If no page number is visible, write "=?".
|
||||
|
||||
Markup, one directive per line:
|
||||
- "@Name" starts a new speech by Name. Write the character name the way the script writes it, in normal capitalisation (LÍDA -> Lída), without a trailing colon or period. Always spell the same character the same way.
|
||||
- A line with no prefix is dialogue belonging to the current speech. If the page starts in the middle of a speech continued from the previous page, start directly with the dialogue lines, without any "@" line.
|
||||
- ">(text" starts a stage direction (usually written in parentheses and indented); each further line of the same direction starts with "> " (greater-than, one space).
|
||||
- "> text" (greater-than, two spaces) is a verse or song line.
|
||||
- "#text" is a scene description written at the left margin (e.g. at the start of an act: where the scene takes place).
|
||||
- "~text" is a centred line: act or scene titles, "Opona" / "O p o n a", character lists centred on the page.
|
||||
- "." on its own line is a blank line. Put it before and after a stage direction that stands on its own between speeches (not inside one character's speech).
|
||||
- A hyphen that splits a word at the end of a line stays as "-" ("nepří-" then "jemné" on the next line). A dash that is punctuation at the end of a line must be written as an en dash "–".
|
||||
|
||||
Example:
|
||||
=12
|
||||
dobře.Ale proč právě já ?
|
||||
@Továrník
|
||||
Nu,vidíte, už to začíná ve vás fungovat.Ano,
|
||||
roky.Nyní je rok 1931.
|
||||
.
|
||||
>(Rozhovor je přerušen příchodem strážníka
|
||||
> a mladé dámy)
|
||||
.
|
||||
@Lída
|
||||
Jsem jen tak –
|
||||
~O p o n a`;
|
||||
|
||||
export const USER_PROMPT = "Transcribe this page into the markup.";
|
||||
120
server/store.mjs
Normal file
120
server/store.mjs
Normal file
|
|
@ -0,0 +1,120 @@
|
|||
// Plays on disk, one directory each under DATA_DIR/plays/<id>/:
|
||||
// meta.json { id, title, note, published, status, created, updated, images, pages, progress, model }
|
||||
// play.txt the markup
|
||||
// img/NNN.jpg the uploaded page photos, in upload order
|
||||
// Writes go to a temp file and are renamed into place so a crash never leaves half a file.
|
||||
import { mkdir, readFile, writeFile, rename, readdir, rm, cp, stat } from "node:fs/promises";
|
||||
import { randomBytes } from "node:crypto";
|
||||
import path from "node:path";
|
||||
|
||||
const ID_RE = /^[a-z0-9][a-z0-9-]{0,79}$/;
|
||||
|
||||
export class NotFound extends Error {}
|
||||
|
||||
export function slugify(title) {
|
||||
const base = title.normalize("NFD").replace(/\p{M}/gu, "").toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 50) || "hra";
|
||||
return `${base}-${randomBytes(3).toString("hex")}`;
|
||||
}
|
||||
|
||||
export function createStore(dataDir) {
|
||||
const root = path.join(dataDir, "plays");
|
||||
const dir = (id) => {
|
||||
if (!ID_RE.test(id)) throw new NotFound(id);
|
||||
return path.join(root, id);
|
||||
};
|
||||
|
||||
async function atomicWrite(file, data) {
|
||||
const tmp = `${file}.${randomBytes(4).toString("hex")}.tmp`;
|
||||
await writeFile(tmp, data);
|
||||
await rename(tmp, file);
|
||||
}
|
||||
|
||||
async function getMeta(id) {
|
||||
try {
|
||||
return JSON.parse(await readFile(path.join(dir(id), "meta.json"), "utf8"));
|
||||
} catch (err) {
|
||||
if (err.code === "ENOENT") throw new NotFound(id);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
// Serialise read-modify-write of one play's meta (the transcription job and
|
||||
// HTTP requests both update it).
|
||||
const locks = new Map();
|
||||
function updateMeta(id, fn) {
|
||||
const run = (locks.get(id) || Promise.resolve()).then(async () => {
|
||||
const meta = await getMeta(id);
|
||||
const next = { ...meta, ...(await fn(meta)), updated: new Date().toISOString() };
|
||||
await atomicWrite(path.join(dir(id), "meta.json"), JSON.stringify(next, null, 2));
|
||||
return next;
|
||||
});
|
||||
locks.set(id, run.catch(() => {}));
|
||||
return run;
|
||||
}
|
||||
|
||||
return {
|
||||
root,
|
||||
async init() { await mkdir(root, { recursive: true }); },
|
||||
|
||||
async list() {
|
||||
const ids = (await readdir(root, { withFileTypes: true })).filter((d) => d.isDirectory() && ID_RE.test(d.name));
|
||||
const metas = await Promise.all(ids.map((d) => getMeta(d.name).catch(() => null)));
|
||||
return metas.filter(Boolean).sort((a, b) => a.title.localeCompare(b.title, "cs"));
|
||||
},
|
||||
|
||||
getMeta,
|
||||
updateMeta,
|
||||
|
||||
async create({ title, note = "", id = slugify(title), text = "", published = false, status = "draft" }) {
|
||||
const d = dir(id);
|
||||
await mkdir(path.join(d, "img"), { recursive: true });
|
||||
const now = new Date().toISOString();
|
||||
const meta = { id, title, note, published, status, created: now, updated: now, images: 0, pages: [], progress: null };
|
||||
await atomicWrite(path.join(d, "play.txt"), text);
|
||||
await atomicWrite(path.join(d, "meta.json"), JSON.stringify(meta, null, 2));
|
||||
return meta;
|
||||
},
|
||||
|
||||
async getText(id) {
|
||||
try { return await readFile(path.join(dir(id), "play.txt"), "utf8"); }
|
||||
catch (err) { if (err.code === "ENOENT") throw new NotFound(id); throw err; }
|
||||
},
|
||||
async setText(id, text) {
|
||||
await getMeta(id);
|
||||
await atomicWrite(path.join(dir(id), "play.txt"), text);
|
||||
},
|
||||
|
||||
imagePath(id, n) {
|
||||
if (!Number.isInteger(n) || n < 1 || n > 999) throw new NotFound(`${id}/${n}`);
|
||||
return path.join(dir(id), "img", `${String(n).padStart(3, "0")}.jpg`);
|
||||
},
|
||||
async putImage(id, n, buf) { await atomicWrite(this.imagePath(id, n), buf); },
|
||||
async getImage(id, n) {
|
||||
try { return await readFile(this.imagePath(id, n)); }
|
||||
catch (err) { if (err.code === "ENOENT") throw new NotFound(`${id}/${n}`); throw err; }
|
||||
},
|
||||
async clearImages(id) {
|
||||
const d = path.join(dir(id), "img");
|
||||
await rm(d, { recursive: true, force: true });
|
||||
await mkdir(d);
|
||||
},
|
||||
|
||||
async remove(id) {
|
||||
await getMeta(id);
|
||||
await rm(dir(id), { recursive: true, force: true });
|
||||
},
|
||||
|
||||
// First start with an empty volume: copy in the plays bundled with the image.
|
||||
async seed(seedDir) {
|
||||
if ((await readdir(root)).length) return 0;
|
||||
let n = 0;
|
||||
for (const d of await readdir(seedDir).catch(() => [])) {
|
||||
if (!ID_RE.test(d) || !(await stat(path.join(seedDir, d))).isDirectory()) continue;
|
||||
await cp(path.join(seedDir, d), path.join(root, d), { recursive: true });
|
||||
n++;
|
||||
}
|
||||
return n;
|
||||
},
|
||||
};
|
||||
}
|
||||
125
server/transcribe.mjs
Normal file
125
server/transcribe.mjs
Normal file
|
|
@ -0,0 +1,125 @@
|
|||
// 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);
|
||||
}
|
||||
|
||||
// Split model output into { num, body }: the first "=N" line is the page number.
|
||||
export function splitPage(text) {
|
||||
const lines = text.replace(/\r/g, "").replace(/^```\w*\n|\n```$/g, "").split("\n");
|
||||
let num = "?";
|
||||
const first = lines.findIndex((l) => l.trim() !== "");
|
||||
if (first >= 0 && /^=/.test(lines[first].trim())) {
|
||||
num = lines[first].trim().slice(1).replace(/^[-–\s]+|[-–.\s]+$/g, "") || "?";
|
||||
lines.splice(0, first + 1);
|
||||
}
|
||||
// The page structure is ours to set; drop any further page markers the model wrote.
|
||||
const body = lines.filter((l) => !/^[=!]/.test(l)).join("\n").trim();
|
||||
return { num, body };
|
||||
}
|
||||
|
||||
const nameKey = (n) => n.normalize("NFD").replace(/\p{M}/gu, "").toLowerCase().replace(/[^\p{L}\p{N}]+/gu, " ").trim();
|
||||
|
||||
// Different pages may spell a name differently (LÍDA / Lída / Lida:). Map every
|
||||
// variant to one spelling: an ALL-CAPS name counts as its Title-case form, and a
|
||||
// spelling with diacritics wins over one without (OCR drops accents far more
|
||||
// often than it invents them), then the most frequent one.
|
||||
const titleCase = (s) => s.toLocaleLowerCase("cs").replace(/(^|[\s-])(\p{L})/gu, (m, a, b) => a + b.toLocaleUpperCase("cs"));
|
||||
const accents = (s) => s.normalize("NFD").match(/\p{M}/gu)?.length || 0;
|
||||
|
||||
export function normalizeSpeakers(bodies) {
|
||||
const variants = new Map(); // key -> Map(spelling -> count)
|
||||
const fromCaps = new Set(); // spellings we made up by Title-casing
|
||||
const clean = (raw) => {
|
||||
const n = raw.trim().replace(/[:.]+$/, "").trim();
|
||||
if (n.length > 1 && n === n.toLocaleUpperCase("cs") && n !== n.toLocaleLowerCase("cs")) {
|
||||
fromCaps.add(titleCase(n));
|
||||
return titleCase(n);
|
||||
}
|
||||
return n;
|
||||
};
|
||||
for (const body of bodies)
|
||||
for (const line of body.split("\n"))
|
||||
if (line.startsWith("@")) {
|
||||
const name = clean(line.slice(1));
|
||||
const key = nameKey(name);
|
||||
if (!key) continue;
|
||||
if (!variants.has(key)) variants.set(key, new Map());
|
||||
const m = variants.get(key);
|
||||
m.set(name, (m.get(name) || 0) + 1);
|
||||
}
|
||||
const best = new Map();
|
||||
for (const [key, m] of variants) {
|
||||
const asWritten = (s) => (fromCaps.has(s) ? 0 : 1);
|
||||
const rank = [...m.keys()].sort((a, b) => accents(b) - accents(a) || m.get(b) - m.get(a) || asWritten(b) - asWritten(a));
|
||||
best.set(key, rank[0]);
|
||||
}
|
||||
return bodies.map((body) => body.split("\n").map((line) => {
|
||||
if (!line.startsWith("@")) return line;
|
||||
const key = nameKey(clean(line.slice(1)));
|
||||
return best.has(key) ? `@${best.get(key)}` : line;
|
||||
}).join("\n"));
|
||||
}
|
||||
|
||||
// Build the play file from per-page results [{ num, body } | { error }], in upload order.
|
||||
// Pages without a readable number get the next number in sequence; numeric gaps
|
||||
// between pages become "missing page" markers.
|
||||
export function assemble(pages) {
|
||||
const bodies = normalizeSpeakers(pages.map((p) => p.body || ""));
|
||||
const out = [];
|
||||
let prev = null;
|
||||
pages.forEach((p, i) => {
|
||||
let num = p.num && p.num !== "?" ? p.num : null;
|
||||
if (!num && prev !== null) num = String(prev + 1);
|
||||
if (!num) num = String(i + 1);
|
||||
const n = /^\d+$/.test(num) ? Number(num) : null;
|
||||
if (n !== null && prev !== null && n > prev + 1) out.push(n === prev + 2 ? `!${prev + 1}` : `!${prev + 1}-${n - 1}`);
|
||||
if (n !== null) prev = n;
|
||||
out.push(`=${num}`);
|
||||
if (p.error) out.push(`>(Stranu se nepodařilo přepsat: ${p.error})`);
|
||||
else out.push(bodies[i]);
|
||||
});
|
||||
return out.join("\n") + "\n";
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue