theater-reader/public/parse.js
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

133 lines
5.4 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// Parser for the play markup (format documented in AGENTS.md).
//
// Result: [{ num, missing, blocks }] where a block is one of
// { type: "speech", speaker, cont, parts } cont = continues from the previous page
// { type: "direction", parts } stage direction standing on its own
// { type: "scene", lines } scene description at the left margin
// { type: "center", text } centred line (titles, "O p o n a")
// { type: "gap" } explicit blank line
// and a part is { kind: "text" | "stage" | "verse", lines: [string] }.
// Uncertain readings: "{word}" or "{word|other reading}" (the first one is used).
export const UNCERTAIN = /\{([^{}\n]*)\}/g;
export const plainText = (s) => s.replace(/\{([^{}|\n]*)(?:\|[^{}\n]*)?\}/g, "$1").replace(/ ?\[\?\]/g, "");
// plain: drop the uncertainty marks (for reading); the editor keeps them.
export function parsePlay(source, { plain = false } = {}) {
const pages = [];
let page = null;
let block = null; // block currently receiving lines
let lastSpeaker = null;
const close = () => { block = null; };
const addPart = (kind, line, continues) => {
const parts = block.parts;
const last = parts[parts.length - 1];
if (last && last.kind === kind && (kind !== "stage" || continues)) last.lines.push(line);
else parts.push({ kind, lines: [line] });
};
for (let raw of source.replace(/\r/g, "").split("\n")) {
if (plain) raw = plainText(raw);
if (raw.trim() === "") continue;
if (raw.startsWith("=") || raw.startsWith("!")) {
const missing = raw.startsWith("!");
page = { num: raw.slice(1).trim(), missing, blocks: [] };
pages.push(page);
close();
continue;
}
if (!page) { page = { num: "?", missing: false, blocks: [] }; pages.push(page); }
if (raw.startsWith("@")) {
lastSpeaker = raw.slice(1).trim();
block = { type: "speech", speaker: lastSpeaker, cont: false, parts: [] };
page.blocks.push(block);
} else if (raw === ".") {
page.blocks.push({ type: "gap" });
close();
} else if (raw.startsWith("~")) {
page.blocks.push({ type: "center", text: raw.slice(1) });
close();
} else if (raw.startsWith("#")) {
if (!block || block.type !== "scene") {
block = { type: "scene", lines: [] };
page.blocks.push(block);
}
block.lines.push(raw.slice(1));
} else if (raw.startsWith(">")) {
const body = raw.slice(1);
const kind = /^ {2,}/.test(body) ? "verse" : "stage";
if (!block || block.type === "scene") {
block = { type: "direction", parts: [] };
page.blocks.push(block);
}
// a single leading space continues the previous stage direction
addPart(kind, kind === "verse" ? body.trimStart() : body.trim(), /^ \S/.test(body));
} else {
// dialogue; after a page break or a standalone direction it belongs to the last speaker
if (!block || block.type !== "speech") {
// speaker "" = we don't know who says it (e.g. the first page is missing)
block = { type: "speech", speaker: lastSpeaker || "", cont: true, parts: [] };
page.blocks.push(block);
}
addPart("text", raw, false);
}
}
return pages;
}
// Characters ordered by how many speeches they have.
export function speakers(pages) {
const counts = new Map();
for (const p of pages)
for (const b of p.blocks)
if (b.type === "speech" && !b.cont && b.speaker) counts.set(b.speaker, (counts.get(b.speaker) || 0) + 1);
return [...counts].sort((a, b) => b[1] - a[1]).map(([name, count]) => ({ name, count }));
}
// Join typescript lines into running text: re-unite words hyphenated across a
// line break ("nepří-" + "jemné", also the typist's "ne -" + "spokojenců").
// A dash meant as punctuation at a line end is written "–" in the source.
export function joinLines(lines) {
let out = "";
for (const line of lines) {
const t = line.trim().replace(/\s{2,}/g, " ");
if (!out) { out = t; continue; }
if (/\p{L} ?-$/u.test(out) && /^\p{Ll}/u.test(t)) out = out.slice(0, out.length - (out.endsWith(" -") ? 2 : 1)) + t;
else out += " " + t;
}
return out;
}
// Add the space after sentence punctuation that the typist usually skipped
// ("dobře.Ale" -> "dobře. Ale") and drop the space it put before punctuation
// ("ano ?" -> "ano?"); leaves numbers like "1931." alone.
export function tidySpacing(text) {
return text
.replace(/([.,!?;:])(?=\p{L})/gu, "$1 ")
.replace(/ +([,.!?;:)])/g, "$1")
.replace(/\( +/g, "(")
.replace(/\s{2,}/g, " ");
}
// Problems worth showing in the editor: [{ page, message }].
export function lint(pages) {
const out = [];
const seen = new Set();
for (const p of pages) {
if (p.num === "?" || p.num === "") out.push({ page: p.num, message: "Strana nemá číslo." });
if (seen.has(p.num)) out.push({ page: p.num, message: `Strana ${p.num} je v textu dvakrát.` });
seen.add(p.num);
for (const b of p.blocks) {
if (b.type === "speech" && !b.speaker) out.push({ page: p.num, message: "Replika bez postavy (chybí řádek @Jméno)." });
if (!b.parts) continue;
for (const part of b.parts)
for (const line of part.lines)
if (/[{}]/.test(line.replace(UNCERTAIN, ""))) out.push({ page: p.num, message: `Neuzavřená složená závorka: „${line.trim()}“` });
}
}
return out;
}