Login button, sorted and de-duplicated pages, page-by-page editor with uncertain-word review #3
8 changed files with 187 additions and 43 deletions
|
|
@ -1,4 +1,4 @@
|
||||||
// Parser for the play markup in public/plays/*.txt (format documented in AGENTS.md).
|
// Parser for the play markup (format documented in AGENTS.md).
|
||||||
//
|
//
|
||||||
// Result: [{ num, missing, blocks }] where a block is one of
|
// Result: [{ num, missing, blocks }] where a block is one of
|
||||||
// { type: "speech", speaker, cont, parts } cont = continues from the previous page
|
// { type: "speech", speaker, cont, parts } cont = continues from the previous page
|
||||||
|
|
@ -8,7 +8,12 @@
|
||||||
// { type: "gap" } explicit blank line
|
// { type: "gap" } explicit blank line
|
||||||
// and a part is { kind: "text" | "stage" | "verse", lines: [string] }.
|
// and a part is { kind: "text" | "stage" | "verse", lines: [string] }.
|
||||||
|
|
||||||
export function parsePlay(source) {
|
// 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 = [];
|
const pages = [];
|
||||||
let page = null;
|
let page = null;
|
||||||
let block = null; // block currently receiving lines
|
let block = null; // block currently receiving lines
|
||||||
|
|
@ -23,7 +28,8 @@ export function parsePlay(source) {
|
||||||
else parts.push({ kind, lines: [line] });
|
else parts.push({ kind, lines: [line] });
|
||||||
};
|
};
|
||||||
|
|
||||||
for (const raw of source.replace(/\r/g, "").split("\n")) {
|
for (let raw of source.replace(/\r/g, "").split("\n")) {
|
||||||
|
if (plain) raw = plainText(raw);
|
||||||
if (raw.trim() === "") continue;
|
if (raw.trim() === "") continue;
|
||||||
|
|
||||||
if (raw.startsWith("=") || raw.startsWith("!")) {
|
if (raw.startsWith("=") || raw.startsWith("!")) {
|
||||||
|
|
@ -112,7 +118,7 @@ export function lint(pages) {
|
||||||
const out = [];
|
const out = [];
|
||||||
const seen = new Set();
|
const seen = new Set();
|
||||||
for (const p of pages) {
|
for (const p of pages) {
|
||||||
if (p.num === "?") out.push({ page: p.num, message: "Text před první značkou strany (=číslo)." });
|
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.` });
|
if (seen.has(p.num)) out.push({ page: p.num, message: `Strana ${p.num} je v textu dvakrát.` });
|
||||||
seen.add(p.num);
|
seen.add(p.num);
|
||||||
for (const b of p.blocks) {
|
for (const b of p.blocks) {
|
||||||
|
|
@ -120,7 +126,7 @@ export function lint(pages) {
|
||||||
if (!b.parts) continue;
|
if (!b.parts) continue;
|
||||||
for (const part of b.parts)
|
for (const part of b.parts)
|
||||||
for (const line of part.lines)
|
for (const line of part.lines)
|
||||||
if (line.includes("[?]")) out.push({ page: p.num, message: `Nejisté čtení: „${line.trim()}“` });
|
if (/[{}]/.test(line.replace(UNCERTAIN, ""))) out.push({ page: p.num, message: `Neuzavřená složená závorka: „${line.trim()}“` });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return out;
|
return out;
|
||||||
|
|
|
||||||
|
|
@ -149,7 +149,7 @@ async function loadPlay(id) {
|
||||||
$("edit-link").href = `edit.html?id=${encodeURIComponent(play.id)}`;
|
$("edit-link").href = `edit.html?id=${encodeURIComponent(play.id)}`;
|
||||||
$("edit-link").hidden = false;
|
$("edit-link").hidden = false;
|
||||||
}
|
}
|
||||||
pages = parsePlay(await api(`plays/${encodeURIComponent(id)}/text`));
|
pages = parsePlay(await api(`plays/${encodeURIComponent(id)}/text`), { plain: true });
|
||||||
fillRoles();
|
fillRoles();
|
||||||
renderScript();
|
renderScript();
|
||||||
save();
|
save();
|
||||||
|
|
|
||||||
|
|
@ -7,7 +7,7 @@ import { createHash, timingSafeEqual } from "node:crypto";
|
||||||
import path from "node:path";
|
import path from "node:path";
|
||||||
import { fileURLToPath } from "node:url";
|
import { fileURLToPath } from "node:url";
|
||||||
import { createStore, NotFound } from "./store.mjs";
|
import { createStore, NotFound } from "./store.mjs";
|
||||||
import { splitPage, assemble } from "./transcribe.mjs";
|
import { splitPage, assemble, normalizeSpeakers } from "./transcribe.mjs";
|
||||||
import { makeProvider } from "./providers.mjs";
|
import { makeProvider } from "./providers.mjs";
|
||||||
|
|
||||||
const here = path.dirname(fileURLToPath(import.meta.url));
|
const here = path.dirname(fileURLToPath(import.meta.url));
|
||||||
|
|
@ -56,8 +56,8 @@ async function readBody(req, limit) {
|
||||||
}
|
}
|
||||||
return Buffer.concat(chunks);
|
return Buffer.concat(chunks);
|
||||||
}
|
}
|
||||||
async function readJson(req) {
|
async function readJson(req, limit = 64 * 1024) {
|
||||||
try { return JSON.parse((await readBody(req, 64 * 1024)).toString("utf8") || "{}"); }
|
try { return JSON.parse((await readBody(req, limit)).toString("utf8") || "{}"); }
|
||||||
catch (err) { if (err instanceof HttpError) throw err; throw new HttpError(400, "Neplatný JSON."); }
|
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));
|
await Promise.all(Array.from({ length: config.concurrency }, worker));
|
||||||
|
|
||||||
const failed = results.filter((r) => r.error).length;
|
const failed = results.filter((r) => r.error).length;
|
||||||
await store.setText(id, assemble(results));
|
const { text, photos, duplicates } = assemble(results);
|
||||||
await store.updateMeta(id, () => ({ status: "draft", progress: null, failed, model: `${provider.name}:${provider.model}` }));
|
await store.setText(id, text);
|
||||||
|
await store.updateMeta(id, () => ({ status: "draft", progress: null, failed, photos, duplicates, model: `${provider.name}:${provider.model}` }));
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error(`[${id}] job failed:`, err);
|
console.error(`[${id}] job failed:`, err);
|
||||||
await store.updateMeta(id, () => ({ status: "draft", progress: null, jobError: String(err?.message || err) })).catch(() => {});
|
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
|
// ---- 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) {
|
async function api(req, res, store, provider, parts) {
|
||||||
const method = req.method;
|
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")
|
if (parts[1] === "config" && method === "GET")
|
||||||
return send(res, 200, { uploads: Boolean(config.password), transcription: Boolean(provider), model: provider?.model || null, maxPages: config.maxPages });
|
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 === "GET") return send(res, 200, publicMeta(meta));
|
||||||
if (method === "PATCH") {
|
if (method === "PATCH") {
|
||||||
await requireAuth(req);
|
await requireAuth(req);
|
||||||
const body = await readJson(req);
|
const body = await readJson(req, config.maxTextBytes);
|
||||||
const patch = {};
|
const patch = {};
|
||||||
if (typeof body.title === "string" && body.title.trim()) patch.title = body.title.trim().slice(0, 200);
|
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.note === "string") patch.note = body.note.trim().slice(0, 500);
|
||||||
if (typeof body.published === "boolean") patch.published = body.published;
|
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)));
|
return send(res, 200, publicMeta(await store.updateMeta(id, () => patch)));
|
||||||
}
|
}
|
||||||
if (method === "DELETE") {
|
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);
|
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 === "GET") return send(res, 200, await store.getImage(id, num), "image/jpeg", { "Cache-Control": "private, max-age=3600" });
|
||||||
if (method === "PUT") {
|
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.
|
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.
|
Output only the markup, nothing else: no commentary, no code fences.
|
||||||
|
|
||||||
|
|
@ -24,8 +26,8 @@ Example:
|
||||||
=12
|
=12
|
||||||
dobře.Ale proč právě já ?
|
dobře.Ale proč právě já ?
|
||||||
@Továrník
|
@Továrník
|
||||||
Nu,vidíte, už to začíná ve vás fungovat.Ano,
|
Nu,vidíte, už to {začíná|začalo} ve vás fungovat.Ano,
|
||||||
roky.Nyní je rok 1931.
|
roky.Nyní je rok {1931}.
|
||||||
.
|
.
|
||||||
>(Rozhovor je přerušen příchodem strážníka
|
>(Rozhovor je přerušen příchodem strážníka
|
||||||
> a mladé dámy)
|
> 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}`);
|
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`);
|
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) {
|
async getImage(id, n) {
|
||||||
try { return await readFile(this.imagePath(id, n)); }
|
try { return await readFile(this.imagePath(id, n)); }
|
||||||
catch (err) { if (err.code === "ENOENT") throw new NotFound(`${id}/${n}`); throw err; }
|
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.
|
// 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.
|
// Split model output into { num, body }: the first "=N" line is the page number.
|
||||||
export function splitPage(text) {
|
export function splitPage(text) {
|
||||||
const lines = text.replace(/\r/g, "").replace(/^```\w*\n|\n```$/g, "").split("\n");
|
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.
|
// 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();
|
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();
|
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 variants = new Map(); // key -> Map(spelling -> count)
|
||||||
const fromCaps = new Set(); // spellings we made up by Title-casing
|
const fromCaps = new Set(); // spellings we made up by Title-casing
|
||||||
const clean = (raw) => {
|
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")) {
|
if (n.length > 1 && n === n.toLocaleUpperCase("cs") && n !== n.toLocaleLowerCase("cs")) {
|
||||||
fromCaps.add(titleCase(n));
|
fromCaps.add(titleCase(n));
|
||||||
return titleCase(n);
|
return titleCase(n);
|
||||||
|
|
@ -57,23 +64,66 @@ export function normalizeSpeakers(bodies) {
|
||||||
}).join("\n"));
|
}).join("\n"));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Build the play file from per-page results [{ num, body } | { error }], in upload order.
|
export const countUncertain = (body) => (body.match(/\{[^{}\n]*\}/g) || []).length;
|
||||||
// Pages without a readable number get the next number in sequence; numeric gaps
|
const pageInt = (num) => (/^\d+/.test(num || "") ? parseInt(num, 10) : null);
|
||||||
// between pages become "missing page" markers.
|
|
||||||
export function assemble(pages) {
|
// Build the play from per-photo results [{ num, body } | { error } | null], in upload order.
|
||||||
const bodies = normalizeSpeakers(pages.map((p) => p.body || ""));
|
//
|
||||||
|
// 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 out = [];
|
||||||
|
const photos = [];
|
||||||
let prev = null;
|
let prev = null;
|
||||||
pages.forEach((p, i) => {
|
for (const e of entries) {
|
||||||
let num = p.num && p.num !== "?" ? p.num : null;
|
let num = e.num;
|
||||||
if (!num && prev !== null) num = String(prev + 1);
|
let n = e.n;
|
||||||
if (!num) num = String(i + 1);
|
// guess the number of an unnumbered page if the next number is free
|
||||||
const n = /^\d+$/.test(num) ? Number(num) : null;
|
if (n === null && prev !== null && !taken.has(prev + 1)) { n = prev + 1; num = String(n); taken.add(n); }
|
||||||
if (n !== null && prev !== null && n > prev + 1) out.push(n === prev + 2 ? `!${prev + 1}` : `!${prev + 1}-${n - 1}`);
|
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;
|
if (n !== null) prev = n;
|
||||||
out.push(`=${num}`);
|
out.push(`=${num}`);
|
||||||
if (p.error) out.push(`>(Stranu se nepodařilo přepsat: ${p.error})`);
|
photos.push(e.image);
|
||||||
else out.push(bodies[i]);
|
out.push(e.error ? `>(Stranu se nepodařilo přepsat: ${e.error})` : e.body);
|
||||||
});
|
}
|
||||||
return out.join("\n") + "\n";
|
return { text: out.filter((l) => l !== "").join("\n") + "\n", photos, duplicates };
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -8,14 +8,16 @@ import { config, createServer } from "../server/main.mjs";
|
||||||
import { createStore } from "../server/store.mjs";
|
import { createStore } from "../server/store.mjs";
|
||||||
|
|
||||||
const PASS = "tajne-heslo";
|
const PASS = "tajne-heslo";
|
||||||
const JPEG = Buffer.from([0xff, 0xd8, 0xff, 0xe0, 1, 2, 3]);
|
// photo n is a tiny "JPEG" ending in byte n; the stub answers by that byte
|
||||||
const replies = ["=-1-\n~JEDNÁNÍ PRVNÍ\n@LÍDA\nDobrý den.", "=2\nještě já.\n@Mise\nAno."];
|
const jpeg = (n) => Buffer.from([0xff, 0xd8, 0xff, 0xe0, n]);
|
||||||
const provider = { name: "stub", model: "stub-model", transcribe: async () => replies.shift() };
|
const JPEG = jpeg(1);
|
||||||
|
const replies = { 1: "=-1-\n~JEDNÁNÍ PRVNÍ\n@LÍDA\nDobrý den.", 2: "=2\nještě já.\n@Mise\nAno." };
|
||||||
|
const provider = { name: "stub", model: "stub-model", transcribe: async (img) => replies[img.at(-1)] };
|
||||||
|
|
||||||
let dir, server, base;
|
let dir, server, base;
|
||||||
test.before(async () => {
|
test.before(async () => {
|
||||||
dir = await mkdtemp(path.join(tmpdir(), "tr-"));
|
dir = await mkdtemp(path.join(tmpdir(), "tr-"));
|
||||||
Object.assign(config, { dataDir: dir, password: PASS, dailyPageLimit: 3 });
|
Object.assign(config, { dataDir: dir, password: PASS, dailyPageLimit: 4 });
|
||||||
const store = createStore(dir);
|
const store = createStore(dir);
|
||||||
await store.init();
|
await store.init();
|
||||||
await store.seed(config.seedDir);
|
await store.seed(config.seedDir);
|
||||||
|
|
@ -34,6 +36,12 @@ test("seeded play is listed and readable", async () => {
|
||||||
assert.match(text, /^!1-4\n=5\n@Mise/);
|
assert.match(text, /^!1-4\n=5\n@Mise/);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("a photo can be added to a seeded play (which has no img/ folder)", async () => {
|
||||||
|
const res = await call("/api/plays/hra-1931/images/1", authed({ method: "PUT", headers: { "content-type": "image/jpeg" }, body: JPEG }));
|
||||||
|
assert.equal(res.status, 200);
|
||||||
|
assert.equal((await res.json()).images, 1);
|
||||||
|
});
|
||||||
|
|
||||||
test("static files are served with security headers, traversal is refused", async () => {
|
test("static files are served with security headers, traversal is refused", async () => {
|
||||||
const res = await call("/");
|
const res = await call("/");
|
||||||
assert.equal(res.status, 200);
|
assert.equal(res.status, 200);
|
||||||
|
|
@ -62,7 +70,7 @@ test("upload → transcribe → draft → publish", async () => {
|
||||||
|
|
||||||
assert.equal((await call(`/api/plays/${id}/images/1`, authed({ method: "PUT", headers: { "content-type": "image/png" }, body: JPEG }))).status, 415);
|
assert.equal((await call(`/api/plays/${id}/images/1`, authed({ method: "PUT", headers: { "content-type": "image/png" }, body: JPEG }))).status, 415);
|
||||||
for (const n of [1, 2]) {
|
for (const n of [1, 2]) {
|
||||||
res = await call(`/api/plays/${id}/images/${n}`, authed({ method: "PUT", headers: { "content-type": "image/jpeg" }, body: JPEG }));
|
res = await call(`/api/plays/${id}/images/${n}`, authed({ method: "PUT", headers: { "content-type": "image/jpeg" }, body: jpeg(n) }));
|
||||||
assert.equal(res.status, 200);
|
assert.equal(res.status, 200);
|
||||||
}
|
}
|
||||||
res = await call(`/api/plays/${id}/transcribe`, authed({ method: "POST" }));
|
res = await call(`/api/plays/${id}/transcribe`, authed({ method: "POST" }));
|
||||||
|
|
@ -78,13 +86,21 @@ test("upload → transcribe → draft → publish", async () => {
|
||||||
assert.equal(meta.failed, 0);
|
assert.equal(meta.failed, 0);
|
||||||
const text = await (await call(`/api/plays/${id}/text`, authed())).text();
|
const text = await (await call(`/api/plays/${id}/text`, authed())).text();
|
||||||
assert.equal(text, "=1\n~JEDNÁNÍ PRVNÍ\n@Lída\nDobrý den.\n=2\nještě já.\n@Mise\nAno.\n");
|
assert.equal(text, "=1\n~JEDNÁNÍ PRVNÍ\n@Lída\nDobrý den.\n=2\nještě já.\n@Mise\nAno.\n");
|
||||||
|
assert.deepEqual(meta.photos, [1, 2]);
|
||||||
|
|
||||||
|
// the editor can re-read one photo; speaker spellings follow the play
|
||||||
|
replies[2] = "=2\n@LÍDA\nZnovu {přečteno}.";
|
||||||
|
res = await call(`/api/plays/${id}/images/2/transcribe`, authed({ method: "POST" }));
|
||||||
|
assert.deepEqual(await res.json(), { num: "2", body: "@Lída\nZnovu {přečteno}." });
|
||||||
|
res = await call(`/api/plays/${id}`, authed({ method: "PATCH", body: JSON.stringify({ photos: [2, 9] }) }));
|
||||||
|
assert.equal(res.status, 400); // there is no photo 9
|
||||||
|
|
||||||
res = await call(`/api/plays/${id}`, authed({ method: "PATCH", body: JSON.stringify({ published: true }) }));
|
res = await call(`/api/plays/${id}`, authed({ method: "PATCH", body: JSON.stringify({ published: true }) }));
|
||||||
assert.equal((await res.json()).published, true);
|
assert.equal((await res.json()).published, true);
|
||||||
assert.equal((await (await call("/api/plays")).json()).length, 2);
|
assert.equal((await (await call("/api/plays")).json()).length, 2);
|
||||||
assert.equal((await call(`/api/plays/${id}/images/2`)).status, 200);
|
assert.equal((await call(`/api/plays/${id}/images/2`)).status, 200);
|
||||||
|
|
||||||
// the daily cap (3 pages) is now nearly used up
|
// the daily cap (4 pages) is now nearly used up
|
||||||
const id2 = (await (await call("/api/plays", authed({ method: "POST", body: JSON.stringify({ title: "Další" }) }))).json()).id;
|
const id2 = (await (await call("/api/plays", authed({ method: "POST", body: JSON.stringify({ title: "Další" }) }))).json()).id;
|
||||||
for (const n of [1, 2]) await call(`/api/plays/${id2}/images/${n}`, authed({ method: "PUT", headers: { "content-type": "image/jpeg" }, body: JPEG }));
|
for (const n of [1, 2]) await call(`/api/plays/${id2}/images/${n}`, authed({ method: "PUT", headers: { "content-type": "image/jpeg" }, body: JPEG }));
|
||||||
res = await call(`/api/plays/${id2}/transcribe`, authed({ method: "POST" }));
|
res = await call(`/api/plays/${id2}/transcribe`, authed({ method: "POST" }));
|
||||||
|
|
|
||||||
|
|
@ -17,19 +17,48 @@ test("speaker spellings are unified across pages", () => {
|
||||||
});
|
});
|
||||||
|
|
||||||
test("assemble numbers pages, marks gaps and failed pages", () => {
|
test("assemble numbers pages, marks gaps and failed pages", () => {
|
||||||
const text = assemble([
|
const { text, photos } = assemble([
|
||||||
{ num: "5", body: "@Mise\nAno." },
|
{ num: "5", body: "@Mise\nAno." },
|
||||||
{ num: "?", body: "dál" },
|
{ num: "?", body: "dál" },
|
||||||
{ num: "9", body: "@Lída\nNe." },
|
{ num: "9", body: "@Lída\nNe." },
|
||||||
{ error: "model declined" },
|
{ error: "model declined" },
|
||||||
]);
|
]);
|
||||||
assert.equal(text, "=5\n@Mise\nAno.\n=6\ndál\n!7-8\n=9\n@Lída\nNe.\n=10\n>(Stranu se nepodařilo přepsat: model declined)\n");
|
assert.equal(text, "=5\n@Mise\nAno.\n=6\ndál\n!7-8\n=9\n@Lída\nNe.\n=10\n>(Stranu se nepodařilo přepsat: model declined)\n");
|
||||||
|
assert.deepEqual(photos, [1, 2, null, 3, 4]);
|
||||||
const pages = parsePlay(text);
|
const pages = parsePlay(text);
|
||||||
assert.deepEqual(pages.map((p) => p.num), ["5", "6", "7-8", "9", "10"]);
|
assert.deepEqual(pages.map((p) => p.num), ["5", "6", "7-8", "9", "10"]);
|
||||||
assert.equal(pages[1].blocks[0].speaker, "Mise"); // continues across the page break
|
assert.equal(pages[1].blocks[0].speaker, "Mise"); // continues across the page break
|
||||||
assert.deepEqual(lint(pages), []);
|
assert.deepEqual(lint(pages), []);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("assemble sorts by page number and drops repeated photos of a page", () => {
|
||||||
|
const { text, photos, duplicates } = assemble([
|
||||||
|
{ num: "1", body: "{jedna}" },
|
||||||
|
{ num: "3", body: "tři" },
|
||||||
|
{ num: "?", body: "po trojce" }, // no number: stays after the photo uploaded before it
|
||||||
|
{ num: "2", body: "dva" },
|
||||||
|
{ num: "1", body: "jedna" }, // retake of page 1 with no uncertain words: wins
|
||||||
|
{ num: "3", body: "tři" }, // the same photo again
|
||||||
|
]);
|
||||||
|
assert.equal(text, "=1\njedna\n=2\ndva\n=3\ntři\n=4\npo trojce\n");
|
||||||
|
assert.deepEqual(photos, [5, 4, 2, 3]);
|
||||||
|
assert.deepEqual(duplicates.map((d) => [d.image, d.page, d.kept]), [[1, "1", 5], [6, "3", 2]]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("an unnumbered page whose guess is taken keeps no number", () => {
|
||||||
|
const { text } = assemble([{ num: "1", body: "a" }, { num: "?", body: "b" }, { num: "2", body: "c" }]);
|
||||||
|
assert.equal(text, "=1\na\n=?\nb\n=2\nc\n");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("uncertain words: old [?] marks are converted, the reader drops the braces", () => {
|
||||||
|
assert.equal(splitPage("=1\nTo je divné[?] slovo, ne[?]?").body, "To je {divné} slovo, {ne}?");
|
||||||
|
const [page] = parsePlay("=1\n@{Lída}\nTo je {divné|dívčí} slovo.", { plain: true });
|
||||||
|
assert.equal(page.blocks[0].speaker, "Lída");
|
||||||
|
assert.deepEqual(page.blocks[0].parts[0].lines, ["To je divné slovo."]);
|
||||||
|
assert.equal(normalizeSpeakers(["@{LÍDA}\nx"])[0], "@Lída\nx");
|
||||||
|
assert.deepEqual(lint(parsePlay("=1\n@A\nnějaké {slovo")).map((x) => x.message), ["Neuzavřená složená závorka: „nějaké {slovo“"]);
|
||||||
|
});
|
||||||
|
|
||||||
const stub = (response) => ({ messages: { create: async (params) => { stub.last = params; return response; } } });
|
const stub = (response) => ({ messages: { create: async (params) => { stub.last = params; return response; } } });
|
||||||
const JPEG = Buffer.from([0xff, 0xd8, 1]);
|
const JPEG = Buffer.from([0xff, 0xd8, 1]);
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue