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:
agent 2026-11-03 09:43:32 +00:00
parent 2608d10dd2
commit 46aa1236ed
32 changed files with 1761 additions and 160 deletions

125
server/transcribe.mjs Normal file
View 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";
}