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
This commit is contained in:
parent
3f2cf95f1d
commit
ab842a1d73
8 changed files with 187 additions and 43 deletions
|
|
@ -7,7 +7,7 @@ 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 } from "./transcribe.mjs";
|
||||
import { splitPage, assemble, normalizeSpeakers } from "./transcribe.mjs";
|
||||
import { makeProvider } from "./providers.mjs";
|
||||
|
||||
const here = path.dirname(fileURLToPath(import.meta.url));
|
||||
|
|
@ -56,8 +56,8 @@ async function readBody(req, limit) {
|
|||
}
|
||||
return Buffer.concat(chunks);
|
||||
}
|
||||
async function readJson(req) {
|
||||
try { return JSON.parse((await readBody(req, 64 * 1024)).toString("utf8") || "{}"); }
|
||||
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."); }
|
||||
}
|
||||
|
||||
|
|
@ -122,8 +122,9 @@ export async function runJob(store, id, provider) {
|
|||
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: `${provider.name}:${provider.model}` }));
|
||||
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(() => {});
|
||||
|
|
@ -133,11 +134,16 @@ export async function runJob(store, id, provider) {
|
|||
}
|
||||
|
||||
// ---- API
|
||||
const publicMeta = ({ pages, ...m }) => ({ ...m, failedPages: (pages || []).flatMap((p, i) => (p?.error ? [{ image: i + 1, error: p.error }] : [])) });
|
||||
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]
|
||||
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 });
|
||||
|
|
@ -170,11 +176,24 @@ async function api(req, res, store, provider, parts) {
|
|||
if (method === "GET") return send(res, 200, publicMeta(meta));
|
||||
if (method === "PATCH") {
|
||||
await requireAuth(req);
|
||||
const body = await readJson(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") {
|
||||
|
|
@ -196,7 +215,25 @@ async function api(req, res, store, provider, parts) {
|
|||
}
|
||||
}
|
||||
|
||||
if (sub === "images" && n) {
|
||||
// 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") {
|
||||
|
|
|
|||
|
|
@ -4,7 +4,9 @@
|
|||
|
||||
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 [?].
|
||||
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.
|
||||
|
||||
Mark every word you are not sure of by wrapping it in curly braces: {slovo}. If another reading is also likely, add it after a vertical bar: {slovo|slova}. Mark a word when its letters are faded, smudged, overtyped, handwritten, cut off at the edge of the photo, or when you cannot see its diacritics clearly. A reader checks each marked word against the photo, so mark honestly: too few marks hide mistakes, but marking words you read clearly wastes their time. Curly braces mean only this; never use them for anything else.
|
||||
|
||||
Output only the markup, nothing else: no commentary, no code fences.
|
||||
|
||||
|
|
@ -24,8 +26,8 @@ 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.
|
||||
Nu,vidíte, už to {začíná|začalo} ve vás fungovat.Ano,
|
||||
roky.Nyní je rok {1931}.
|
||||
.
|
||||
>(Rozhovor je přerušen příchodem strážníka
|
||||
> a mladé dámy)
|
||||
|
|
|
|||
|
|
@ -89,7 +89,11 @@ export function createStore(dataDir) {
|
|||
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 putImage(id, n, buf) {
|
||||
const file = this.imagePath(id, n);
|
||||
await mkdir(path.dirname(file), { recursive: true }); // seeded plays come without img/
|
||||
await atomicWrite(file, 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; }
|
||||
|
|
|
|||
|
|
@ -1,5 +1,11 @@
|
|||
// Stitch per-page transcriptions (see providers.mjs) into one play file.
|
||||
|
||||
// Uncertain readings are marked "{word}" or "{word|other reading}". Older
|
||||
// transcriptions used "word[?]"; convert those so the editor finds them too.
|
||||
export function migrateUncertain(text) {
|
||||
return text.replace(/([\p{L}\p{N}'’-]+)([.,;:!?…]*) ?\[\?\]/gu, "{$1}$2").replace(/ ?\[\?\]/g, "");
|
||||
}
|
||||
|
||||
// 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");
|
||||
|
|
@ -11,7 +17,7 @@ export function splitPage(text) {
|
|||
}
|
||||
// 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 };
|
||||
return { num, body: migrateUncertain(body) };
|
||||
}
|
||||
|
||||
const nameKey = (n) => n.normalize("NFD").replace(/\p{M}/gu, "").toLowerCase().replace(/[^\p{L}\p{N}]+/gu, " ").trim();
|
||||
|
|
@ -27,7 +33,8 @@ 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();
|
||||
// an uncertain name "{Lída}" counts as "Lída"
|
||||
const n = raw.replace(/\{([^{}|]*)(\|[^{}]*)?\}/g, "$1").trim().replace(/[:.]+$/, "").trim();
|
||||
if (n.length > 1 && n === n.toLocaleUpperCase("cs") && n !== n.toLocaleLowerCase("cs")) {
|
||||
fromCaps.add(titleCase(n));
|
||||
return titleCase(n);
|
||||
|
|
@ -57,23 +64,66 @@ export function normalizeSpeakers(bodies) {
|
|||
}).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 || ""));
|
||||
export const countUncertain = (body) => (body.match(/\{[^{}\n]*\}/g) || []).length;
|
||||
const pageInt = (num) => (/^\d+/.test(num || "") ? parseInt(num, 10) : null);
|
||||
|
||||
// Build the play from per-photo results [{ num, body } | { error } | null], in upload order.
|
||||
//
|
||||
// Pages are sorted by the number the model read off each photo, so upload order
|
||||
// doesn't matter. A photo without a readable number stays right after the photo
|
||||
// uploaded before it. Two photos of the same page (an accidental re-upload or a
|
||||
// retake) keep only the better transcription: fewer uncertain words, then more text.
|
||||
// Numeric gaps become "missing page" markers.
|
||||
//
|
||||
// Returns { text, photos, duplicates }:
|
||||
// photos[i] the photo (1-based) shown with the i-th page marker of text, or null
|
||||
// duplicates [{ image, page, kept, body }] photos left out as repeats of a page
|
||||
export function assemble(results) {
|
||||
const bodies = normalizeSpeakers(results.map((r) => r?.body || ""));
|
||||
let entries = results.map((r, i) => ({ image: i + 1, num: r?.error ? null : r?.num, n: r?.error ? null : pageInt(r?.num), body: bodies[i], error: r?.error }));
|
||||
|
||||
// sort key: the page number; unnumbered photos follow their upload predecessor
|
||||
let anchor = 0;
|
||||
for (const e of entries) {
|
||||
if (e.n !== null) anchor = e.n;
|
||||
e.key = e.n !== null ? e.n : anchor + 0.5;
|
||||
}
|
||||
entries.sort((a, b) => a.key - b.key || (a.n === null) - (b.n === null) || a.image - b.image);
|
||||
|
||||
// drop repeats of the same page
|
||||
const duplicates = [];
|
||||
const byNum = new Map();
|
||||
for (const e of entries) {
|
||||
if (e.n === null) continue;
|
||||
const kept = byNum.get(e.num);
|
||||
if (!kept) { byNum.set(e.num, e); continue; }
|
||||
const better = countUncertain(e.body) - countUncertain(kept.body) || kept.body.length - e.body.length;
|
||||
const [keep, drop] = better < 0 ? [e, kept] : [kept, e];
|
||||
byNum.set(e.num, keep);
|
||||
drop.dropped = true;
|
||||
duplicates.push({ image: drop.image, page: e.num, kept: keep.image, body: drop.body });
|
||||
}
|
||||
for (const d of duplicates) d.kept = byNum.get(d.page).image; // a later, better copy may have won
|
||||
entries = entries.filter((e) => !e.dropped);
|
||||
|
||||
const taken = new Set(entries.filter((e) => e.n !== null).map((e) => e.n));
|
||||
const out = [];
|
||||
const photos = [];
|
||||
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}`);
|
||||
for (const e of entries) {
|
||||
let num = e.num;
|
||||
let n = e.n;
|
||||
// guess the number of an unnumbered page if the next number is free
|
||||
if (n === null && prev !== null && !taken.has(prev + 1)) { n = prev + 1; num = String(n); taken.add(n); }
|
||||
if (n === null) num = "?";
|
||||
if (n !== null && prev !== null && n > prev + 1) {
|
||||
out.push(n === prev + 2 ? `!${prev + 1}` : `!${prev + 1}-${n - 1}`);
|
||||
photos.push(null);
|
||||
}
|
||||
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";
|
||||
photos.push(e.image);
|
||||
out.push(e.error ? `>(Stranu se nepodařilo přepsat: ${e.error})` : e.body);
|
||||
}
|
||||
return { text: out.filter((l) => l !== "").join("\n") + "\n", photos, duplicates };
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue