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
129 lines
5.9 KiB
JavaScript
129 lines
5.9 KiB
JavaScript
// 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");
|
||
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: migrateUncertain(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) => {
|
||
// 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);
|
||
}
|
||
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"));
|
||
}
|
||
|
||
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;
|
||
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}`);
|
||
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 };
|
||
}
|