From ab842a1d73b218e4dbdf9b5f89d983371c2d2de0 Mon Sep 17 00:00:00 2001 From: agent Date: Wed, 4 Nov 2026 16:15:27 +0000 Subject: [PATCH 1/3] 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 Claude-Session: https://claude.ai/code/session_01HA82gVRDXpoukzgMFumoJt --- public/parse.js | 16 +++++--- public/reader.js | 2 +- server/main.mjs | 55 ++++++++++++++++++++----- server/prompt.mjs | 8 ++-- server/store.mjs | 6 ++- server/transcribe.mjs | 84 +++++++++++++++++++++++++++++++-------- tests/server.test.mjs | 28 ++++++++++--- tests/transcribe.test.mjs | 31 ++++++++++++++- 8 files changed, 187 insertions(+), 43 deletions(-) diff --git a/public/parse.js b/public/parse.js index b060b2e..0bfc3ee 100644 --- a/public/parse.js +++ b/public/parse.js @@ -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 // { type: "speech", speaker, cont, parts } cont = continues from the previous page @@ -8,7 +8,12 @@ // { type: "gap" } explicit blank line // 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 = []; let page = null; let block = null; // block currently receiving lines @@ -23,7 +28,8 @@ export function parsePlay(source) { 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.startsWith("=") || raw.startsWith("!")) { @@ -112,7 +118,7 @@ export function lint(pages) { const out = []; const seen = new Set(); 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.` }); seen.add(p.num); for (const b of p.blocks) { @@ -120,7 +126,7 @@ export function lint(pages) { if (!b.parts) continue; for (const part of b.parts) 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; diff --git a/public/reader.js b/public/reader.js index 61e75dd..21aff97 100644 --- a/public/reader.js +++ b/public/reader.js @@ -149,7 +149,7 @@ async function loadPlay(id) { $("edit-link").href = `edit.html?id=${encodeURIComponent(play.id)}`; $("edit-link").hidden = false; } - pages = parsePlay(await api(`plays/${encodeURIComponent(id)}/text`)); + pages = parsePlay(await api(`plays/${encodeURIComponent(id)}/text`), { plain: true }); fillRoles(); renderScript(); save(); diff --git a/server/main.mjs b/server/main.mjs index 0b219bd..c0f4319 100644 --- a/server/main.mjs +++ b/server/main.mjs @@ -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") { diff --git a/server/prompt.mjs b/server/prompt.mjs index ecfd583..4529d89 100644 --- a/server/prompt.mjs +++ b/server/prompt.mjs @@ -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) diff --git a/server/store.mjs b/server/store.mjs index b860f79..5f72bba 100644 --- a/server/store.mjs +++ b/server/store.mjs @@ -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; } diff --git a/server/transcribe.mjs b/server/transcribe.mjs index 6b7e1fd..b120abd 100644 --- a/server/transcribe.mjs +++ b/server/transcribe.mjs @@ -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 }; } diff --git a/tests/server.test.mjs b/tests/server.test.mjs index 39ba91c..fbafe39 100644 --- a/tests/server.test.mjs +++ b/tests/server.test.mjs @@ -8,14 +8,16 @@ import { config, createServer } from "../server/main.mjs"; import { createStore } from "../server/store.mjs"; const PASS = "tajne-heslo"; -const JPEG = Buffer.from([0xff, 0xd8, 0xff, 0xe0, 1, 2, 3]); -const replies = ["=-1-\n~JEDNÁNÍ PRVNÍ\n@LÍDA\nDobrý den.", "=2\nještě já.\n@Mise\nAno."]; -const provider = { name: "stub", model: "stub-model", transcribe: async () => replies.shift() }; +// photo n is a tiny "JPEG" ending in byte n; the stub answers by that byte +const jpeg = (n) => Buffer.from([0xff, 0xd8, 0xff, 0xe0, n]); +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; test.before(async () => { 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); await store.init(); 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/); }); +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 () => { const res = await call("/"); 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); 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); } 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); 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.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 }) })); assert.equal((await res.json()).published, true); assert.equal((await (await call("/api/plays")).json()).length, 2); 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; 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" })); diff --git a/tests/transcribe.test.mjs b/tests/transcribe.test.mjs index 7c2f6cd..f296ca6 100644 --- a/tests/transcribe.test.mjs +++ b/tests/transcribe.test.mjs @@ -17,19 +17,48 @@ test("speaker spellings are unified across pages", () => { }); test("assemble numbers pages, marks gaps and failed pages", () => { - const text = assemble([ + const { text, photos } = assemble([ { num: "5", body: "@Mise\nAno." }, { num: "?", body: "dál" }, { num: "9", body: "@Lída\nNe." }, { 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.deepEqual(photos, [1, 2, null, 3, 4]); const pages = parsePlay(text); 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.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 JPEG = Buffer.from([0xff, 0xd8, 1]); From 624090780962ddeb39e7e15adbb02331f09a7ff6 Mon Sep 17 00:00:00 2001 From: agent Date: Wed, 4 Nov 2026 16:15:27 +0000 Subject: [PATCH 2/3] Login button with show-password, skip identical photos on upload MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A Přihlásit/Odhlásit button in the top bar replaces logging in via Přidat hru. The dialog has an eye toggle, says when it is checking, and keeps the remember box as it was after a wrong password; nothing is stored until the server accepts it. A remembered password that no longer works is dropped on load. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HA82gVRDXpoukzgMFumoJt --- public/add.html | 10 +++++-- public/add.js | 43 ++++++++++++--------------- public/api.js | 75 ++++++++++++++++++++++++++++++++++++++++------- public/index.html | 1 - public/library.js | 17 +++++++---- public/photos.js | 36 +++++++++++++++++++++++ 6 files changed, 138 insertions(+), 44 deletions(-) create mode 100644 public/photos.js diff --git a/public/add.html b/public/add.html index 9f54e1e..6ad7c5a 100644 --- a/public/add.html +++ b/public/add.html @@ -9,8 +9,11 @@
- -

Přidat hru

+
+ +

Přidat hru

+
+
@@ -25,7 +28,8 @@ Vyberte fotky nebo je sem přetáhněte. Jedna fotka = jedna strana. -

Strany se seřadí podle názvu souboru; pořadí můžete změnit šipkami. Fotky se před nahráním zmenší.

+

Na pořadí nezáleží: po přepisu se strany seřadí podle čísel stran na fotkách a stejná strana nafocená dvakrát se použije jen jednou. Fotky se před nahráním zmenší.

+
    diff --git a/public/add.js b/public/add.js index 94c48e1..32068c7 100644 --- a/public/add.js +++ b/public/add.js @@ -1,22 +1,30 @@ -import { api, withLogin, getPassword, askPassword, esc, $ } from "./api.js"; +import { api, withLogin, getPassword, askPassword, authButton, esc, $ } from "./api.js"; +import { toJpeg, fingerprint } from "./photos.js"; -// The API reads images at most ~1.15 megapixels, so a bigger upload only costs bandwidth. -const MAX_PIXELS = 1.15e6; -const MAX_SIDE = 1568; - -let files = []; // [{ file, url }] +let files = []; // [{ file, url, hash }] let cfg; const collator = new Intl.Collator("cs", { numeric: true, sensitivity: "base" }); -function addFiles(list) { +// Add picked photos, skipping any that are byte-for-byte the same as one already +// picked. (Two different photos of the same page are sorted out after transcription.) +async function addFiles(list) { const imgs = [...list].filter((f) => f.type.startsWith("image/") || /\.(heic|heif)$/i.test(f.name)); - files.push(...imgs.map((file) => ({ file, url: URL.createObjectURL(file) }))); + const skipped = []; + for (const file of imgs) { + const hash = await fingerprint(file); + const same = files.find((f) => f.hash === hash); + if (same) { skipped.push(`„${file.name}“ je stejná fotka jako „${same.file.name}“`); continue; } + files.push({ file, hash, url: URL.createObjectURL(file) }); + } files.sort((a, b) => collator.compare(a.file.name, b.file.name)); + const notes = skipped.length ? [`Přeskočeno ${skipped.length === 1 ? "1 opakování" : `${skipped.length} opakování`}: ${skipped.join("; ")}.`] : []; if (files.length > cfg.maxPages) { - showError(`Najednou lze nahrát nejvýše ${cfg.maxPages} stran.`); + notes.push(`Najednou lze nahrát nejvýše ${cfg.maxPages} stran.`); files.splice(cfg.maxPages).forEach((f) => URL.revokeObjectURL(f.url)); } + $("notice").textContent = notes.join(" "); + $("notice").hidden = !notes.length; renderThumbs(); } @@ -35,20 +43,6 @@ function renderThumbs() { $("go").disabled = !files.length; } -// Decode, shrink and re-encode as JPEG (also strips EXIF, e.g. location). -async function toJpeg(file) { - let bitmap; - try { bitmap = await createImageBitmap(file, { imageOrientation: "from-image" }); } - catch { throw new Error(`Obrázek „${file.name}“ se nepodařilo otevřít${/\.hei[cf]$/i.test(file.name) ? " (formát HEIC – zkuste fotku uložit jako JPEG)" : ""}.`); } - const scale = Math.min(1, MAX_SIDE / Math.max(bitmap.width, bitmap.height), Math.sqrt(MAX_PIXELS / (bitmap.width * bitmap.height))); - const canvas = document.createElement("canvas"); - canvas.width = Math.round(bitmap.width * scale); - canvas.height = Math.round(bitmap.height * scale); - canvas.getContext("2d").drawImage(bitmap, 0, 0, canvas.width, canvas.height); - bitmap.close(); - return new Promise((resolve, reject) => canvas.toBlob((b) => (b ? resolve(b) : reject(new Error("Převod obrázku selhal."))), "image/jpeg", 0.88)); -} - function showError(msg) { $("error").textContent = msg; $("error").hidden = !msg; } function setStatus(text, value) { $("progress").hidden = false; @@ -108,7 +102,8 @@ async function main() { $("ai-note").textContent = "Automatický přepis není na serveru zapnutý (chybí klíč OPENROUTER_API_KEY nebo ANTHROPIC_API_KEY). Fotky se nahrají a text pak napíšete v editoru ručně."; $("go").textContent = "Nahrát"; } - if (!getPassword()) askPassword("Přidávat hry může jen ten, kdo zná heslo."); + await authButton($("auth"), { uploads: true, onChange: (inn) => { if (!inn) location.replace("./"); } }); + if (!getPassword() && !(await askPassword("Přidávat hry může jen ten, kdo zná heslo."))) { location.replace("./"); return; } $("files").addEventListener("change", (e) => { addFiles(e.target.files); e.target.value = ""; }); const drop = $("drop"); diff --git a/public/api.js b/public/api.js index d710afd..4ba0382 100644 --- a/public/api.js +++ b/public/api.js @@ -10,6 +10,7 @@ export function setPassword(pw, remember) { if (remember) localStorage.setItem(PASS_KEY, pw); else localStorage.removeItem(PASS_KEY); } catch { /* storage blocked: the password just won't be remembered */ } } +const isRemembered = () => { try { return Boolean(localStorage.getItem(PASS_KEY)); } catch { return false; } }; export function clearPassword() { try { sessionStorage.removeItem(PASS_KEY); localStorage.removeItem(PASS_KEY); } catch { /* ignore */ } } @@ -52,37 +53,91 @@ export const esc = (s) => String(s).replace(/[&<>"']/g, (c) => ({ "&": "&", export const $ = (id) => document.getElementById(id); // Ask for the upload password in a modal dialog; resolves true once logged in, false if cancelled. +// The password is stored only after the server accepted it, and only where the +// "stay logged in" box says (this tab, or this browser until "Odhlásit"). export function askPassword(reason = "") { return new Promise((resolve) => { const dlg = document.createElement("dialog"); dlg.className = "login"; - dlg.innerHTML = `
    -

    Heslo pro úpravy

    + dlg.innerHTML = ` +

    Přihlášení

    ${reason ? `

    ${esc(reason)}

    ` : ""} - - - -
    + + + +
    `; document.body.append(dlg); const form = dlg.querySelector("form"); + const pw = form.pw; const err = dlg.querySelector(".error"); + const ok = form.querySelector("button[type=submit]"); + const eye = form.querySelector(".eye"); + const showError = (msg) => { + err.textContent = msg; + err.hidden = !msg; + pw.toggleAttribute("aria-invalid", Boolean(msg)); + }; + eye.addEventListener("click", () => { + const show = pw.type === "password"; + pw.type = show ? "text" : "password"; + eye.innerHTML = show ? EYE_OFF : EYE; + eye.setAttribute("aria-pressed", String(show)); + eye.title = eye.ariaLabel = show ? "Skrýt heslo" : "Zobrazit heslo"; + pw.focus(); + }); + pw.addEventListener("input", () => showError("")); + form.querySelector("[data-cancel]").addEventListener("click", () => dlg.close("cancel")); form.addEventListener("submit", async (e) => { - if (e.submitter?.value !== "ok") return; e.preventDefault(); + if (!pw.value) { showError("Zadejte heslo."); pw.focus(); return; } + ok.disabled = true; + ok.textContent = "Ověřuji…"; try { - await login(form.pw.value, form.remember.checked); + await login(pw.value, form.remember.checked); dlg.close("ok"); } catch (ex) { - err.textContent = ex.message; - err.hidden = false; + showError(ex.status === 401 ? "Heslo nesouhlasí, zkuste to znovu." : ex.message); + pw.select(); + pw.focus(); + } finally { + ok.disabled = false; + ok.textContent = "Přihlásit"; } }); dlg.addEventListener("close", () => { dlg.remove(); resolve(dlg.returnValue === "ok"); }); dlg.showModal(); + pw.focus(); }); } +const EYE = ``; +const EYE_OFF = ``; + +// Log in/out button for a page's top bar. onChange runs after logging in or out. +export async function authButton(container, { uploads, onChange = () => location.reload() }) { + if (!uploads) return; + // a remembered password may have been changed on the server since + if (getPassword()) { + try { await login(getPassword(), isRemembered()); } + catch (err) { if (err.status === 401) clearPassword(); } + } + const btn = document.createElement("button"); + btn.className = "auth"; + const render = () => { btn.textContent = getPassword() ? "Odhlásit" : "Přihlásit"; }; + render(); + btn.addEventListener("click", async () => { + if (getPassword()) { clearPassword(); render(); onChange(false); return; } + if (await askPassword()) { render(); onChange(true); } + }); + container.append(btn); +} + // Run fn; on 401 ask for the password and retry once. export async function withLogin(fn, reason) { try { return await fn(); } diff --git a/public/index.html b/public/index.html index 5c63219..089fdc6 100644 --- a/public/index.html +++ b/public/index.html @@ -13,7 +13,6 @@

    Divadelní čtečka

    -
    diff --git a/public/library.js b/public/library.js index c3c4e3e..f9fd98a 100644 --- a/public/library.js +++ b/public/library.js @@ -1,4 +1,4 @@ -import { api, getPassword, clearPassword, esc, $ } from "./api.js"; +import { api, getPassword, authButton, esc, $ } from "./api.js"; // Old links (/?postava=Lída or /?hra=…) went straight to the reader. const q = new URLSearchParams(location.search); @@ -7,14 +7,19 @@ if (q.has("hra") || q.has("postava")) location.replace(`read.html${location.sear const fmtDate = (iso) => new Date(iso).toLocaleDateString("cs-CZ", { day: "numeric", month: "numeric", year: "numeric" }); async function main() { - const [cfg, plays] = await Promise.all([api("config"), api("plays")]); + const cfg = await api("config"); + await authButton(document.querySelector(".topbar-actions"), { uploads: cfg.uploads, onChange: render }); + await render(); +} + +// Logged in, the list also shows drafts, with buttons to add and edit plays. +async function render() { + const plays = await api("plays"); const loggedIn = Boolean(getPassword()); - $("add").hidden = !cfg.uploads; - $("logout").hidden = !loggedIn; - $("logout").addEventListener("click", () => { clearPassword(); location.reload(); }); + $("add").hidden = !loggedIn; if (!plays.length) { - $("plays").innerHTML = `
  1. Zatím tu není žádná hra.${cfg.uploads ? " Přidejte první tlačítkem nahoře." : ""}
  2. `; + $("plays").innerHTML = `
  3. Zatím tu není žádná hra.${loggedIn ? " Přidejte první tlačítkem nahoře." : ""}
  4. `; return; } $("plays").innerHTML = plays.map((p) => { diff --git a/public/photos.js b/public/photos.js new file mode 100644 index 0000000..a150cc9 --- /dev/null +++ b/public/photos.js @@ -0,0 +1,36 @@ +// Preparing page photos in the browser before upload. + +// The vision models read images at most ~1.15 megapixels, so a bigger upload only costs bandwidth. +const MAX_PIXELS = 1.15e6; +const MAX_SIDE = 1568; + +// Decode, shrink and re-encode as JPEG (also strips EXIF, e.g. location). +export async function toJpeg(file) { + let bitmap; + try { bitmap = await createImageBitmap(file, { imageOrientation: "from-image" }); } + catch { throw new Error(`Obrázek „${file.name}“ se nepodařilo otevřít${/\.hei[cf]$/i.test(file.name) ? " (formát HEIC – zkuste fotku uložit jako JPEG)" : ""}.`); } + const scale = Math.min(1, MAX_SIDE / Math.max(bitmap.width, bitmap.height), Math.sqrt(MAX_PIXELS / (bitmap.width * bitmap.height))); + const canvas = document.createElement("canvas"); + canvas.width = Math.round(bitmap.width * scale); + canvas.height = Math.round(bitmap.height * scale); + canvas.getContext("2d").drawImage(bitmap, 0, 0, canvas.width, canvas.height); + bitmap.close(); + return new Promise((resolve, reject) => canvas.toBlob((b) => (b ? resolve(b) : reject(new Error("Převod obrázku selhal."))), "image/jpeg", 0.88)); +} + +// Fingerprint of a file's bytes, to spot the same photo picked twice. +// crypto.subtle exists only on https/localhost, so fall back to FNV-1a there. +export async function fingerprint(file) { + const buf = await file.arrayBuffer(); + if (globalThis.crypto?.subtle) { + const h = new Uint8Array(await crypto.subtle.digest("SHA-256", buf)); + return [...h].map((b) => b.toString(16).padStart(2, "0")).join(""); + } + const bytes = new Uint8Array(buf); + let h1 = 0x811c9dc5, h2 = 0x01000193 ^ bytes.length; + for (let i = 0; i < bytes.length; i++) { + h1 = Math.imul(h1 ^ bytes[i], 0x01000193); + h2 = Math.imul(h2 ^ bytes[bytes.length - 1 - i], 0x01000193); + } + return `${bytes.length}-${(h1 >>> 0).toString(16)}-${(h2 >>> 0).toString(16)}`; +} From debf1aa8bc061201cbe6ba27a477fd925a94e917 Mon Sep 17 00:00:00 2001 From: agent Date: Wed, 4 Nov 2026 16:15:27 +0000 Subject: [PATCH 3/3] Edit plays page by page, with a review of uncertain words The editor shows one original page next to its photo, with a page list, page number and missing toggle, and highlights {uncertain} words. The review dialog steps through them with the photo zoomed to about the right line. Pages can be re-read from their photo or added from a new photo, which fills a !N missing marker. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HA82gVRDXpoukzgMFumoJt --- AGENTS.md | 14 +- README.md | 5 +- public/app.css | 157 ++++++++++++-- public/edit.html | 113 +++++++--- public/edit.js | 542 ++++++++++++++++++++++++++++++++++++++--------- 5 files changed, 679 insertions(+), 152 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 2ebe005..7b989d2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -10,15 +10,17 @@ UI language is Czech. - `server/main.mjs`: HTTP server, routing, static files, auth (`x-upload-password` header vs `UPLOAD_PASSWORD`), daily page cap, background transcription job. - `server/store.mjs`: plays on disk, `DATA_DIR/plays//{meta.json,play.txt,img/NNN.jpg}`. Atomic writes; per-play lock for meta updates. - `server/providers.mjs`: `makeProvider(env)` returns `{ name, model, transcribe(jpeg) }` for OpenRouter or Anthropic. Errors become `PageError`s whose message is shown in the editor. OpenRouter retries 408/429/5xx and network errors itself. -- `server/transcribe.mjs`: `splitPage` → `normalizeSpeakers` → `assemble` turn the per-photo answers into one play file. `server/prompt.mjs` holds the prompt (shared by both providers), which teaches the markup below. -- `public/`: four pages: `index.html` library (`library.js`), `read.html` reader (`reader.js`), `add.html` upload (`add.js`: shrinks photos to ≤1.15 MP JPEG in the browser), `edit.html` editor (`edit.js`). `api.js` holds the fetch and password helpers. `parse.js` is the markup parser, shared with the server tests. +- `server/transcribe.mjs`: `splitPage` → `normalizeSpeakers` → `assemble` turn the per-photo answers into one play file: sorted by the page number read off each photo, repeats of a page dropped (kept in `meta.duplicates`), and `meta.photos` recording which photo belongs to which page marker. `server/prompt.mjs` holds the prompt (shared by both providers), which teaches the markup below. +- `public/`: four pages: `index.html` library (`library.js`), `read.html` reader (`reader.js`), `add.html` upload (`add.js`: shrinks photos to ≤1.15 MP JPEG in the browser), `edit.html` editor (`edit.js`: splits the text at page markers and edits one page at a time beside its photo; review dialog for `{uncertain}` words). `api.js` holds the fetch, password and login-button helpers, `photos.js` the in-browser JPEG shrinking and duplicate-photo fingerprint. `parse.js` is the markup parser, shared with the server tests. - `seed/`: plays copied into an empty data volume on first start. - `public/fonts/`: self-hosted woff2 + OFL licences, made by `tools/fetch_fonts.py` (keep its `FAMILIES` and `FONTS` in `reader.js` in step). ## API `GET /api/config`, `POST /api/login`, `GET|POST /api/plays`, `GET|PATCH|DELETE /api/plays/:id`, `GET|PUT /api/plays/:id/text`, -`GET|PUT /api/plays/:id/images/:n` (raw `image/jpeg` body), `POST /api/plays/:id/transcribe` (202, then poll the meta's `progress`). +`GET|PUT /api/plays/:id/images/:n` (raw `image/jpeg` body), `POST /api/plays/:id/transcribe` (202, then poll the meta's `progress`), +`POST /api/plays/:id/images/:n/transcribe` (one photo, answers `{ num, body }` and leaves the text alone; the editor inserts it). +`PATCH` takes `title`, `note`, `published`, `photos` (photo number or `null` per page marker, in text order) and `duplicates`. Everything that writes needs the password. Unpublished plays answer 404 without it. Transcription refuses once the text has been edited by hand, so it can't overwrite corrections. @@ -49,6 +51,8 @@ One directive per line; blank lines are ignored. The text keeps the typescript's line breaks, spelling and missing spaces ("dobře.Ale"). The "running text" mode joins hyphenated words (`nepří-` / `jemné`, also the typist's `ne -` / `spokojenců`) and adds the missing spaces. **A dash that really is punctuation at the end of a line must be typed as `–` (en dash)**, or it gets joined to the next word. -`[?]` after a word marks an uncertain reading. The editor lists them. +`{word}` marks an uncertain reading and `{word|other}` adds the model's alternative; the reader shows the first one, and the +editor's review dialog steps through them. (The older `word[?]` form is converted when transcribing.) -To add a missing page to a play, e.g. page 7 of the 1931 play, open it in the editor and replace `!7` with `=7` and the page's text. +To add a missing page to a play, e.g. page 7 of the 1931 play, open it in the editor and use *+ Z fotky*: the photo is +transcribed and fills the `!7` marker. Without a photo, select page 7, untick *v originále chybí* and type the text. diff --git a/README.md b/README.md index 8811c46..161dab8 100644 --- a/README.md +++ b/README.md @@ -14,9 +14,10 @@ A link like `read.html?hra=hra-1931&postava=Lída` opens a play with the charact **Adding plays** (anyone with the upload password): -1. *Přidat hru*: give the title and pick a photo of each page. +1. *Přihlásit* (top right) with the upload password, then *+ Přidat hru*: give the title and pick a photo of each page. The same photo picked twice is skipped. 2. Each photo is read by a vision model, through OpenRouter (default `google/gemini-3.1-flash-lite`) or the Anthropic API (`claude-haiku-5-5`), and turned into the script markup: speakers, stage directions, page numbers. Missing pages are noticed from gaps in the page numbers. -3. The editor shows the text next to the photos and lists things to check (uncertain words marked `[?]`, characters who speak only once, pages that failed). Fix, tick *Zveřejněno*, save. +3. Pages are put in order by the page number on each photo, so upload order doesn't matter, and a page photographed twice is used once (the clearer transcription wins; the editor lets you switch to the other one). +4. The editor shows one page at a time next to its photo. Words the model wasn't sure of are highlighted, and *Projít nejistá slova* steps through them one by one with the photo zoomed to about the right line: Enter accepts, a click picks the model's other reading. A page that failed or a page found later (*+ Z fotky*, which fills a `!7` "missing" marker) can be transcribed on its own. Fix, tick *Zveřejněno*, save. ## Deploying diff --git a/public/app.css b/public/app.css index 438ea44..1654ea7 100644 --- a/public/app.css +++ b/public/app.css @@ -290,7 +290,7 @@ button.link { border: 0; background: none; padding: 0; font: inherit; color: var .play-meta { font-size: 12.5px; color: var(--muted); } .badge { font-size: 12px; font-weight: 600; padding: 1px 8px; border-radius: 999px; background: var(--hl); color: var(--fg); vertical-align: 2px; } -dialog.login { border: 1px solid var(--line); border-radius: 12px; background: var(--bg); color: var(--fg); padding: 20px; width: min(380px, calc(100vw - 32px)); } +dialog.login { border: 1px solid var(--line); border-radius: 12px; background: var(--bg); color: var(--fg); padding: 20px; width: min(400px, calc(100vw - 32px)); } dialog.login h2 { margin: 0 0 8px; font-size: 18px; } dialog::backdrop { background: rgba(0, 0, 0, 0.4); } @@ -320,31 +320,144 @@ form.busy .dropzone, form.busy .thumb-tools { pointer-events: none; opacity: 0.6 .meta-row .grow { flex: 1 1 260px; } .field.toggle { display: flex; align-items: center; gap: 8px; padding-bottom: 8px; } .field.toggle span { margin: 0; } -.editor { display: grid; grid-template-columns: minmax(0, 1fr) minmax(300px, 0.8fr); gap: 16px; align-items: start; } -.editor textarea { - height: calc(100vh - 230px); - min-height: 360px; - font-family: "Courier Prime", ui-monospace, monospace; - font-size: 15px; - line-height: 1.45; - resize: vertical; - tab-size: 4; +.field.toggle input { accent-color: var(--accent); } +.check { display: inline-flex; align-items: center; gap: 8px; cursor: pointer; } +.check input { width: 18px; height: 18px; margin: 0; accent-color: var(--accent); } +.notice { background: var(--hl); border-radius: 8px; padding: 8px 12px; font-size: 14px; } +button.quiet { border-color: transparent; background: transparent; color: var(--muted); } +button.quiet:hover { color: var(--accent); } + +/* login dialog */ +dialog.login .field { margin-bottom: 12px; } +.pw-field { position: relative; display: block; } +.pw-field input { padding-right: 44px; } +.pw-field input[aria-invalid] { border-color: var(--accent); box-shadow: 0 0 0 1px var(--accent); } +.pw-field .eye { + position: absolute; right: 4px; top: 50%; transform: translateY(-50%); + display: grid; place-items: center; width: 36px; height: 32px; padding: 0; + border: 0; background: transparent; color: var(--muted); } -.editor-side { position: sticky; top: 12px; display: grid; gap: 14px; } -.photo-nav { display: flex; align-items: center; gap: 6px; margin-bottom: 6px; font-size: 14px; } -.photo-nav span { flex: 1; text-align: center; color: var(--muted); } -.photo-nav button { padding: 4px 10px; font-size: 13px; } -.photo img { display: block; width: 100%; max-height: calc(100vh - 330px); object-fit: contain; background: var(--panel); border: 1px solid var(--line); border-radius: 8px; } -.checks h2 { font-size: 16px; margin: 0 0 4px; } -.checks ul { margin: 6px 0 10px; padding-left: 18px; max-height: 220px; overflow-y: auto; font-size: 14px; } +.pw-field .eye:hover, .pw-field .eye[aria-pressed="true"] { color: var(--accent); } +dialog.login .check { margin: 2px 0 4px; font-size: 14.5px; } +dialog.login .error { margin: 10px 0 0; font-size: 14px; } +dialog.login .actions { margin-top: 16px; } + +/* editor */ +.review-bar { + display: flex; align-items: center; gap: 12px; flex-wrap: wrap; + margin: 4px 0 12px; padding: 10px 14px; border-radius: 10px; + background: var(--hl); border: 1px solid var(--hl-edge); +} +.review-bar span { flex: 1; font-weight: 600; } +details.checks { margin: 0 0 14px; font-size: 14px; } +details.checks summary { cursor: pointer; } +details.checks ul { margin: 6px 0 10px; padding-left: 18px; max-height: 220px; overflow-y: auto; } + +.editor { + display: grid; + grid-template-columns: 88px minmax(0, 1fr) minmax(0, 1.1fr); + gap: 16px; + align-items: start; +} +.editor.no-photos { grid-template-columns: 88px minmax(0, 1fr); } +.editor.busy { opacity: 0.5; pointer-events: none; } +.page-list { position: sticky; top: 12px; display: grid; gap: 8px; } +.page-list ol { + list-style: none; margin: 0; padding: 0; + display: grid; gap: 4px; max-height: calc(100vh - 140px); overflow-y: auto; +} +.page-list ol button { + position: relative; width: 100%; padding: 6px 4px; font-size: 14px; text-align: center; + display: flex; justify-content: center; align-items: center; gap: 4px; +} +.page-list ol button.current { border-color: var(--accent); box-shadow: inset 0 0 0 1px var(--accent); color: var(--accent); } +.page-list ol button.missing { border-style: dashed; color: var(--muted); font-weight: 400; } +.page-list ol button.failed { border-color: var(--accent); } +.page-list .count { + min-width: 18px; padding: 0 5px; border-radius: 999px; font-size: 11px; line-height: 18px; + background: var(--hl); color: var(--fg); border: 1px solid var(--hl-edge); +} +.page-list .count.bad { background: var(--accent); border-color: var(--accent); color: #fff; } +.page-list-tools { display: grid; gap: 4px; } +.page-list-tools > * { padding: 6px 4px; font-size: 13px; text-align: center; } +.page-list-tools .busy { opacity: 0.6; pointer-events: none; } + +.page-photo { position: sticky; top: 12px; } +.photo-frame { + max-height: calc(100vh - 80px); overflow: auto; cursor: zoom-in; + background: var(--panel); border: 1px solid var(--line); border-radius: 8px; +} +.photo-frame img { display: block; width: 100%; height: auto; } +.photo-frame.zoomed { cursor: zoom-out; } +.photo-frame.zoomed img { width: 220%; max-width: none; } +.photo-empty { padding: 48px 16px; text-align: center; margin: 0; } +.photo-pick { display: inline-flex; align-items: center; gap: 6px; margin-top: 6px; } +.photo-pick select { width: auto; padding: 2px 6px; } + +.page-head { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; margin-bottom: 8px; } +.page-head .grow { flex: 1; } +.page-head > button { padding: 6px 10px; font-size: 14px; } +.page-num { display: inline-flex; align-items: center; gap: 6px; font-weight: 700; } +.page-num input { width: 5.5em; padding: 5px 8px; font-weight: 700; text-align: center; } +.page-head .check { font-size: 14px; color: var(--muted); } +.dup-note { margin-bottom: 8px; padding: 8px 12px; border-radius: 8px; background: var(--panel); border: 1px solid var(--line); font-size: 14px; } +.missing-hint { padding: 24px; border: 1px dashed var(--line); border-radius: 8px; text-align: center; } + +/* textarea over a layer that paints the {uncertain} words; both must wrap identically */ +.hl-wrap { position: relative; } +.hl-back, .hl-wrap textarea { + margin: 0; padding: 12px 14px; border: 1px solid var(--line); border-radius: 8px; + font-family: "Courier Prime", ui-monospace, monospace; font-size: 15px; line-height: 1.5; + white-space: pre-wrap; overflow-wrap: break-word; word-break: normal; tab-size: 4; letter-spacing: 0; +} +.hl-back { position: absolute; inset: 0; color: transparent; border-color: transparent; pointer-events: none; overflow: hidden; } +.hl-back mark { color: transparent; background: var(--hl); border-radius: 3px; box-shadow: 0 0 0 1px var(--hl-edge); } +.hl-wrap textarea { + position: relative; display: block; width: 100%; min-height: 320px; + background: transparent; color: var(--fg); resize: none; overflow: hidden; +} +.hl-wrap { background: var(--bg); border-radius: 8px; } .help { font-size: 14px; margin-top: 8px; } .help td { padding: 2px 10px 2px 0; vertical-align: top; } +.danger { margin-top: 32px; } .danger button { color: var(--accent); border-color: var(--accent); background: transparent; } -@media (max-width: 900px) { - .editor { grid-template-columns: minmax(0, 1fr); } - .editor-side { position: static; order: -1; } - .photo img { max-height: 60vh; } - .editor textarea { height: 70vh; } + +/* review of uncertain words */ +dialog.review { + width: min(1100px, calc(100vw - 24px)); max-height: calc(100vh - 24px); padding: 0; + border: 1px solid var(--line); border-radius: 12px; background: var(--bg); color: var(--fg); +} +.review-grid { display: grid; grid-template-columns: minmax(0, 1.2fr) minmax(300px, 1fr); min-height: min(640px, calc(100vh - 26px)); } +.review-photo { position: relative; overflow: auto; background: var(--panel); border-right: 1px solid var(--line); max-height: calc(100vh - 26px); } +.review-photo img { display: block; width: 180%; max-width: none; } +.review-band { position: absolute; left: 0; width: 180%; background: rgba(224, 180, 0, 0.18); border-block: 2px solid var(--hl-edge); pointer-events: none; } +.review-card { padding: 18px 20px; display: flex; flex-direction: column; gap: 10px; } +.review-top { display: flex; align-items: center; justify-content: space-between; } +.review-top h2 { margin: 0; font-size: 18px; } +.review-context { + font-family: "Courier Prime", ui-monospace, monospace; font-size: 15px; line-height: 1.6; + padding: 10px 12px; border-radius: 8px; background: var(--panel); overflow-wrap: anywhere; +} +.ctx-line { color: var(--muted); } +.ctx-line.main { color: var(--fg); } +.review-context mark { background: var(--hl); color: var(--fg); padding: 0 2px; border-radius: 3px; box-shadow: 0 0 0 2px var(--hl-edge); } +#review-fix { font-size: 18px; font-family: "Courier Prime", ui-monospace, monospace; } +.review-alts { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; } +.chip { padding: 4px 10px; border-radius: 999px; font-family: "Courier Prime", ui-monospace, monospace; font-weight: 400; } +.review-card .actions { margin-top: 6px; } +#review-item, #review-done { display: flex; flex-direction: column; gap: 10px; } +#review-item[hidden], #review-done[hidden] { display: none; } + +@media (max-width: 1000px) { + .editor, .editor.no-photos { grid-template-columns: minmax(0, 1fr); } + .page-list { position: static; } + .page-list ol { display: flex; overflow-x: auto; max-height: none; padding-bottom: 4px; } + .page-list ol button { min-width: 48px; } + .page-list-tools { display: flex; } + .page-photo { position: static; } + .photo-frame { max-height: 60vh; } + .review-grid { grid-template-columns: minmax(0, 1fr); } + .review-photo { max-height: 42vh; border-right: 0; border-bottom: 1px solid var(--line); } } /* ---- PDF export (print) ---- diff --git a/public/edit.html b/public/edit.html index fad656d..aa74500 100644 --- a/public/edit.html +++ b/public/edit.html @@ -11,9 +11,9 @@
    -
    - - +
    + +
    @@ -29,44 +29,101 @@ -
    -
    - + + +
    + Kontrola +
      + +
      + +
      + + +
      +
      + +

      Tato strana nemá fotku.

      +
      + +
      + +
      +
      + + + + + + + +
      + + +
      + + +
      Jak se text zapisuje - +
      =5začátek strany 5 (!7 = strana 7 chybí)
      @Lídareplika postavy Lída; další řádky jsou její text
      >(Odejde)scénická poznámka; pokračování na dalším řádku začíná >
      >  veršverš / píseň (dvě mezery za >)
      #Pokoj u Lysákůpopis scény u levého okraje
      ~O p o n ařádek na střed
      .prázdný řádek; ukončí repliku
      {slovo|slova}nejisté čtení (a jiná možnost); ve čtečce se ukáže jen první
      -

      Rozdělené slovo na konci řádku nechte se spojovníkem (nepří-), čtečka ho spojí. Pomlčku jako interpunkci na konci řádku pište jako –.

      +

      Text na začátku strany bez @Jméno pokračuje replikou z předchozí strany. Rozdělené slovo na konci řádku nechte se spojovníkem (nepří-), čtečka ho spojí. Pomlčku jako interpunkci na konci řádku pište jako –.

      - +
      + +
      +
      + + +
      +
      + Fotka strany +
      + +
      +
      +
      +

      Nejistá slova

      + +
      +
      +

      +
      + +
      +
      + + + +
      +

      Enter potvrdí, Esc zavře. Opravy se po zavření uloží.

      +
      + +
      +
      +
      diff --git a/public/edit.js b/public/edit.js index b7fb120..3e9f51f 100644 --- a/public/edit.js +++ b/public/edit.js @@ -1,98 +1,334 @@ -import { api, withLogin, getPassword, askPassword, esc, $ } from "./api.js"; -import { parsePlay, speakers, lint } from "./parse.js"; +// Play editor: one original page at a time, next to its photo, plus a +// click-through review of the words the model was unsure of. +// +// The play is still stored as one markup file; here it is split at the page +// markers (=N / !N) into page objects and joined back on save. meta.photos +// says which photo belongs to which page marker, in text order. +import { api, withLogin, getPassword, askPassword, authButton, esc, $ } from "./api.js"; +import { parsePlay, speakers, lint, plainText } from "./parse.js"; +import { toJpeg } from "./photos.js"; const id = new URLSearchParams(location.search).get("id"); const enc = encodeURIComponent(id); -let meta; -let savedText = ""; -let img = 1; +let cfg, meta; +let pages = []; // [{ key, num, missing, body, photo }] +let cur = 0; +let saved = { text: "", photos: "" }; let leaving = false; +let nextKey = 1; -const dirty = () => $("text").value !== savedText +// ---- text <-> pages +function splitPages(text, photos, images) { + const out = []; + let page = null; + for (const line of text.replace(/\r/g, "").split("\n")) { + if (/^[=!]/.test(line)) { + page = { key: nextKey++, num: line.slice(1).trim(), missing: line[0] === "!", lines: [] }; + out.push(page); + } else { + if (!page) { page = { key: nextKey++, num: "?", missing: false, lines: [] }; out.push(page); } + page.lines.push(line); + } + } + let k = 0; + for (const [i, p] of out.entries()) { + p.body = p.lines.join("\n").replace(/^\n+|\s+$/g, ""); + delete p.lines; + // plays transcribed before meta.photos existed: the n-th page is the n-th photo + p.photo = photos ? photos[i] ?? null : !p.missing && k < images ? ++k : null; + } + return out; +} +const joinPages = () => pages.map((p) => `${p.missing ? "!" : "="}${p.num}${p.body ? `\n${p.body}` : ""}`).join("\n") + "\n"; +const photoList = () => pages.map((p) => p.photo ?? null); +const isDirty = () => joinPages() !== saved.text || JSON.stringify(photoList()) !== saved.photos || $("title").value !== meta.title || $("note").value !== (meta.note || "") || $("published").checked !== meta.published; +const markSaved = () => { saved = { text: joinPages(), photos: JSON.stringify(photoList()) }; }; -function showError(msg) { $("error").textContent = msg; $("error").hidden = !msg; } +const UNC = /\{([^{}\n]*)\}/g; +const uncertainIn = (body) => [...body.matchAll(UNC)]; +const isFailed = (p) => /^>\(Stranu se nepodařilo přepsat/m.test(p.body); +const pageInt = (num) => (/^\d+/.test(num) ? parseInt(num, 10) : null); +const plural = (n, one, few, many) => `${n} ${n === 1 ? one : n >= 2 && n <= 4 ? few : many}`; +const label = (p) => (p.num && p.num !== "?" ? p.num : "?"); -function check() { - let pages; - try { pages = parsePlay($("text").value); } - catch (err) { $("summary").textContent = err.message; return; } - const real = pages.filter((p) => !p.missing); - const cast = speakers(pages); - $("summary").textContent = `${real.length} stran, ${cast.length} postav: ${cast.map((c) => c.name).join(", ") || "—"}`; - const issues = [ - ...(meta.failedPages || []).map((f) => ({ page: null, image: f.image, message: `Fotku ${f.image} se nepodařilo přepsat: ${f.error}` })), - ...lint(pages), - ]; - // Names used only once are often misreadings of another name. - for (const c of cast) if (c.count === 1 && cast.length > 2) issues.push({ page: null, find: `@${c.name}`, message: `Postava „${c.name}“ mluví jen jednou – překlep?` }); - $("issues").innerHTML = issues.length - ? issues.slice(0, 200).map((x, i) => `
    • `).join("") - : `
    • Žádné problémy nenalezeny.
    • `; - $("issues").onclick = (e) => { - const b = e.target.closest("button[data-i]"); - if (!b) return; - const x = issues[Number(b.dataset.i)]; - if (x.image) showImage(x.image); - else jumpTo(x.find || (x.page && x.page !== "?" ? `=${x.page}` : null), x.message.match(/„(.*)“/)?.[1]); - }; - $("retry").hidden = !(meta.failedPages?.length && !meta.edited); +function showError(msg) { $("error").textContent = msg; $("error").hidden = !msg; if (msg) $("error").scrollIntoView({ block: "nearest" }); } +function changed() { + $("saved").textContent = isDirty() ? "Neuložené změny" : $("saved").dataset.at || ""; } -// Select `needle` (or the line containing `inner`) in the textarea and scroll it into view. -function jumpTo(needle, inner) { +// ---- photos (drafts' photos need the password header, so fetch them as blobs) +const photoUrls = new Map(); +function photoUrl(n) { + if (!photoUrls.has(n)) + photoUrls.set(n, api(`plays/${enc}/images/${n}`, { raw: true }).then((r) => r.blob()).then((b) => URL.createObjectURL(b)) + .catch((err) => { photoUrls.delete(n); throw err; })); + return photoUrls.get(n); +} +async function setPhoto(imgEl, n) { + imgEl.removeAttribute("src"); + imgEl.dataset.n = n || ""; + if (!n) return; + try { + const url = await photoUrl(n); + if (imgEl.dataset.n === String(n)) imgEl.src = url; // still the wanted photo + } catch (err) { showError(`Fotku se nepodařilo načíst: ${err.message}`); } +} + +// ---- rendering +function renderList() { + $("page-list").innerHTML = pages.map((p, i) => { + const n = uncertainIn(p.body).length; + const cls = [i === cur && "current", p.missing && "missing", isFailed(p) && "failed"].filter(Boolean).join(" "); + const title = p.missing ? "chybí v originále" : isFailed(p) ? "přepis se nepovedl" : n ? `${n} nejistých slov` : ""; + return `
    • `; + }).join(""); + $("page-list").querySelector(".current")?.scrollIntoView({ block: "nearest", inline: "nearest" }); +} + +function renderPage() { + const p = pages[cur]; + const has = Boolean(p); + $("editor").classList.toggle("empty", !has); + if (!has) return; + $("num").value = p.num; + $("missing").checked = p.missing; + $("prev").disabled = cur === 0; + $("next").disabled = cur === pages.length - 1; + $("missing-hint").hidden = !p.missing || Boolean(p.body); + $("hl-wrap").hidden = p.missing && !p.body; + $("text").value = p.body; + paintText(); + $("reread").hidden = !(cfg.transcription && p.photo); + $("reread").textContent = isFailed(p) ? "Zkusit přepsat znovu" : "Přepsat znovu z fotky"; + $("reread").classList.toggle("primary", isFailed(p)); + + // photo + $("photo-select").innerHTML = `` + + Array.from({ length: meta.images }, (_, i) => ``).join(""); + $("photo-select").value = p.photo || ""; + $("photo-pane").hidden = !meta.images; + $("editor").classList.toggle("no-photos", !meta.images); + $("photo-empty").hidden = Boolean(p.photo); + $("img").hidden = !p.photo; + $("img").alt = `Fotka strany ${label(p)}`; + $("photo-frame").classList.remove("zoomed"); + setPhoto($("img"), p.photo); + + // other photos of the same page, left out after transcription + const dups = (meta.duplicates || []).filter((d) => d.page === p.num && d.image !== p.photo); + $("dup-note").hidden = !dups.length; + $("dup-note").innerHTML = dups.length ? `Tato strana byla nahraná vícekrát; použitá je fotka ${p.photo ?? "?"}. ` + + dups.map((d) => ``).join(" · ") : ""; +} + +// The highlight layer behind the textarea marks the {uncertain} words. +function paintText() { const ta = $("text"); const v = ta.value; - let at = -1; - if (needle) at = needle.startsWith("=") ? (`\n${v}`).indexOf(`\n${needle}\n`) : v.indexOf(needle); - if (at < 0 && inner) at = v.indexOf(inner); - if (at < 0) return; - const len = (needle && v.startsWith(needle, at) ? needle : inner || "").length; - ta.focus(); - ta.setSelectionRange(at, at + len); - // scroll: put the selected line about a third from the top - const lineNo = v.slice(0, at).split("\n").length - 1; - const lh = parseFloat(getComputedStyle(ta).lineHeight) || 20; - ta.scrollTop = Math.max(0, lineNo * lh - ta.clientHeight / 3); + let html = ""; + let last = 0; + for (const m of v.matchAll(UNC)) { + html += esc(v.slice(last, m.index)) + `${esc(m[0])}`; + last = m.index + m[0].length; + } + $("hl-back").innerHTML = html + esc(v.slice(last)) + "\n "; + ta.style.height = "auto"; + ta.style.height = `${Math.max(ta.scrollHeight, 320)}px`; } -// Drafts' photos need the password header, which can't send, so fetch them as blobs. -let imgUrl = null; -async function showImage(n) { - if (!meta.images) return; - img = Math.min(meta.images, Math.max(1, n)); - $("photo-box").hidden = false; - const shown = img; - api(`plays/${enc}/images/${img}`, { raw: true }).then((r) => r.blob()).then((b) => { - if (shown !== img) return; // user already moved on - if (imgUrl) URL.revokeObjectURL(imgUrl); - imgUrl = URL.createObjectURL(b); - $("img").src = imgUrl; - }).catch((err) => showError(`Fotku se nepodařilo načíst: ${err.message}`)); - $("img-label").textContent = `fotka ${img} / ${meta.images}`; - $("img-prev").disabled = img === 1; - $("img-next").disabled = img === meta.images; +function check() { + const text = joinPages(); + const parsed = parsePlay(text, { plain: true }); + const real = parsed.filter((p) => !p.missing); + const cast = speakers(parsed); + const unsure = pages.reduce((n, p) => n + (p.missing ? 0 : uncertainIn(p.body).length), 0); + const issues = [ + ...pages.flatMap((p, i) => (isFailed(p) ? [{ i, message: "přepis se nepovedl" }] : [])), + ...lint(parsePlay(text)).map((x) => ({ i: pages.findIndex((p) => p.num === x.page), message: x.message })), + ]; + // Names used only once are often misreadings of another name. + for (const c of cast) if (c.count === 1 && cast.length > 2) + issues.push({ i: pages.findIndex((p) => plainText(p.body).split("\n").some((l) => l.trim() === `@${c.name}`)), message: `postava „${c.name}“ mluví jen jednou – překlep?` }); + $("summary").textContent = `${plural(real.length, "strana", "strany", "stran")}, ${plural(cast.length, "postava", "postavy", "postav")}` + + `${cast.length ? `: ${cast.map((c) => c.name).join(", ")}` : ""}${issues.length ? ` · ${plural(issues.length, "upozornění", "upozornění", "upozornění")}` : ""}`; + $("issues").innerHTML = issues.length + ? issues.slice(0, 200).map((x, k) => `
    • `).join("") + : `
    • Žádné problémy nenalezeny.
    • `; + $("issues").onclick = (e) => { + const b = e.target.closest("button[data-k]"); + if (b && issues[b.dataset.k].i >= 0) go(issues[b.dataset.k].i); + }; + $("retry").hidden = !(meta.failedPages?.length && !meta.edited && cfg.transcription); + $("review-bar").hidden = !unsure; + $("review-count").textContent = unsure === 1 ? "Model si není jistý 1 slovem." : `Model si není jistý ${unsure} slovy.`; + changed(); } -// The page number the model read from photo n, to find it in the text. -function pageOfImage(n) { - const text = $("text").value; - const markers = [...text.matchAll(/^=(.+)$/gm)].map((m) => m[1]); - return markers[n - 1]; +function go(i) { + if (!pages.length) return; + cur = Math.max(0, Math.min(pages.length - 1, i)); + renderList(); + renderPage(); } +// Keep pages in page-number order; unnumbered ones stay after the page before them. +function sortPages() { + const keep = pages[cur]; + let anchor = -1; + const keyed = pages.map((p, idx) => { + const n = pageInt(p.num); + if (n !== null) anchor = n; + return { p, idx, key: n !== null ? n : anchor + 0.5 }; + }); + keyed.sort((a, b) => a.key - b.key || a.idx - b.idx); + pages = keyed.map((k) => k.p); + cur = pages.indexOf(keep); +} + +// Put a page in, filling a "missing" marker for its number if there is one +// (a range !5-8 is split around it). +function insertPage(page) { + const n = pageInt(page.num); + if (n !== null) { + const at = pages.findIndex((p) => p.missing && !p.body && rangeOf(p.num)?.includes(n)); + if (at >= 0) { + const [a, b] = rangeOf(pages[at].num).bounds; + const parts = []; + if (a < n) parts.push({ key: nextKey++, num: a === n - 1 ? `${a}` : `${a}-${n - 1}`, missing: true, body: "", photo: null }); + parts.push(page); + if (n < b) parts.push({ key: nextKey++, num: n + 1 === b ? `${b}` : `${n + 1}-${b}`, missing: true, body: "", photo: null }); + pages.splice(at, 1, ...parts); + cur = pages.indexOf(page); + return; + } + } + pages.splice(cur + 1, 0, page); + cur += 1; + sortPages(); +} +function rangeOf(num) { + const m = /^(\d+)(?:\s*-\s*(\d+))?$/.exec(num); + if (!m) return null; + const a = Number(m[1]), b = Number(m[2] || m[1]); + return { bounds: [a, b], includes: (n) => n >= a && n <= b }; +} + +// ---- review of uncertain words +let review = { items: [], i: 0, changed: false }; + +function collectUncertain() { + const items = []; + pages.forEach((p, pi) => { + if (p.missing) return; + for (const m of uncertainIn(p.body)) { + items.push({ pi, start: m.index, raw: m[0], options: m[1].split("|").map((s) => s.trim()).filter(Boolean) }); + } + }); + return items; +} + +// Starts at the current page; "again" goes back over the skipped ones from the top. +function openReview(again = false) { + review.items = collectUncertain(); + review.i = again ? 0 : Math.max(0, review.items.findIndex((x) => x.pi >= cur)); + review.changed = false; + if (!$("review").open) $("review").showModal(); + showReviewItem(); +} + +function showReviewItem() { + // skip over items already passed over in this round + const item = review.items[review.i]; + $("review-item").hidden = !item; + $("review-done").hidden = Boolean(item); + if (!item) { + const left = collectUncertain().length; + $("review-done-text").textContent = left ? `Hotovo. Označen${left === 1 ? "é zůstalo 1 přeskočené slovo" : `ých zůstává ${plural(left, "", "přeskočená slova", "přeskočených slov").trim()}`}.` : "Hotovo, všechna nejistá slova jsou zkontrolovaná."; + $("review-again").hidden = !left; + $("review-finish").focus(); + return; + } + const p = pages[item.pi]; + const remaining = review.items.length - review.i; + $("review-where").textContent = `Strana ${label(p)} · zbývá ${remaining}`; + + // context: the line with the word, and its neighbours + const body = p.body; + const lineStart = body.lastIndexOf("\n", item.start - 1) + 1; + let lineEnd = body.indexOf("\n", item.start); + if (lineEnd < 0) lineEnd = body.length; + const lines = body.split("\n"); + const lineNo = body.slice(0, item.start).split("\n").length - 1; + const show = (s) => esc(s.replace(UNC, (m, inner) => inner.split("|")[0])); + const before = lines[lineNo - 1], after = lines[lineNo + 1]; + $("review-context").innerHTML = + (before !== undefined ? `
      ${show(before)}
      ` : "") + + `
      ${show(body.slice(lineStart, item.start))}${esc(item.options[0] || "")}${show(body.slice(item.start + item.raw.length, lineEnd))}
      ` + + (after !== undefined ? `
      ${show(after)}
      ` : ""); + + $("review-fix").value = item.options[0] || ""; + $("review-alts").innerHTML = item.options.length > 1 + ? `Možnosti: ` + item.options.map((o) => ``).join("") + : ""; + $("review-prev").disabled = review.i === 0; + $("review-fix").focus(); + $("review-fix").select(); + + // photo, zoomed to about where the line is (typescript lines are evenly spaced) + const box = $("review-photo"); + $("review-nophoto").hidden = Boolean(p.photo); + $("review-img").hidden = !p.photo; + $("review-band").hidden = !p.photo; + const place = () => { + const img = $("review-img"); + if (!img.naturalHeight) return; + const frac = (lineNo + 1.5) / (lines.length + 3); // a little margin top and bottom + const y = frac * img.clientHeight; + $("review-band").style.top = `${y - 0.03 * img.clientHeight}px`; + $("review-band").style.height = `${0.06 * img.clientHeight}px`; + const col = (item.start - lineStart) / Math.max(1, Math.max(...lines.map((l) => l.length))); + box.scrollTo({ top: y - box.clientHeight / 2, left: (0.1 + 0.8 * col) * img.clientWidth - box.clientWidth / 2, behavior: "smooth" }); + }; + $("review-img").onload = place; + if ($("review-img").dataset.n === String(p.photo) && $("review-img").complete) place(); + else setPhoto($("review-img"), p.photo); +} + +function resolveItem(value) { + const item = review.items[review.i]; + const p = pages[item.pi]; + if (p.body.slice(item.start, item.start + item.raw.length) !== item.raw) return; // text changed underneath + p.body = p.body.slice(0, item.start) + value + p.body.slice(item.start + item.raw.length); + review.changed = true; + // later items on the same page moved + const shift = value.length - item.raw.length; + review.items.splice(review.i, 1); + for (const x of review.items) if (x.pi === item.pi && x.start > item.start) { x.start += shift; } + showReviewItem(); +} + +async function closeReview() { + if ($("review").open) $("review").close(); + renderList(); + renderPage(); + check(); + if (review.changed) { review.changed = false; await save(); } +} + +// ---- saving and server actions async function save() { showError(""); $("save").disabled = true; try { await withLogin(async () => { - if ($("text").value !== savedText) { - meta = await api(`plays/${enc}/text`, { method: "PUT", body: $("text").value, type: "text/plain; charset=utf-8" }); - savedText = $("text").value; - } - meta = await api(`plays/${enc}`, { method: "PATCH", body: { title: $("title").value, note: $("note").value, published: $("published").checked } }); + const text = joinPages(); + if (text !== saved.text) meta = await api(`plays/${enc}/text`, { method: "PUT", body: text, type: "text/plain; charset=utf-8" }); + meta = await api(`plays/${enc}`, { method: "PATCH", body: { title: $("title").value, note: $("note").value, published: $("published").checked, photos: photoList(), duplicates: meta.duplicates } }); + markSaved(); }); - $("saved").textContent = `Uloženo ${new Date().toLocaleTimeString("cs-CZ", { hour: "2-digit", minute: "2-digit" })}`; + $("saved").dataset.at = `Uloženo ${new Date().toLocaleTimeString("cs-CZ", { hour: "2-digit", minute: "2-digit" })}`; check(); } catch (err) { showError(`Uložení se nepovedlo: ${err.message}`); @@ -101,8 +337,48 @@ async function save() { } } +async function reread() { + const p = pages[cur]; + if (p.body && !isFailed(p) && !confirm("Text této strany se nahradí novým přepisem z fotky. Pokračovat?")) return; + const btn = $("reread"); + btn.disabled = true; + btn.textContent = "Přepisuji…"; + try { + const r = await withLogin(() => api(`plays/${enc}/images/${p.photo}/transcribe`, { method: "POST" })); + p.body = r.body; + if ((!p.num || p.num === "?") && r.num !== "?") { p.num = r.num; sortPages(); } + renderList(); renderPage(); check(); + } catch (err) { showError(err.message); } + finally { btn.disabled = false; renderPage(); } +} + +async function addFromPhoto(file) { + showError(""); + const lbl = $("add-photo-label"); + lbl.classList.add("busy"); + try { + const jpeg = await toJpeg(file); + const n = meta.images + 1; + meta = await withLogin(() => api(`plays/${enc}/images/${n}`, { method: "PUT", body: jpeg, type: "image/jpeg" })); + let page = { key: nextKey++, num: "?", missing: false, body: "", photo: n }; + if (cfg.transcription) { + lbl.firstChild.textContent = "Přepisuji…"; + const r = await api(`plays/${enc}/images/${n}/transcribe`, { method: "POST" }); + page = { ...page, num: r.num, body: r.body }; + } + const same = pages.findIndex((p) => !p.missing && p.num === page.num && page.num !== "?"); + if (same >= 0 && confirm(`Strana ${page.num} už v textu je. Nahradit ji novým přepisem? (Zrušit = přidat ji jako další stranu.)`)) { + pages[same] = { ...page, key: pages[same].key }; + cur = same; + } else insertPage(page); + renderList(); renderPage(); check(); + if (!cfg.transcription) $("num").focus(); + } catch (err) { showError(err.message); } + finally { lbl.classList.remove("busy"); lbl.firstChild.textContent = "+ Z fotky"; } +} + async function waitForJob() { - $("text").readOnly = true; + $("editor").classList.add("busy"); $("save").disabled = true; $("progress").hidden = false; while (meta.status === "processing") { @@ -113,37 +389,99 @@ async function waitForJob() { meta = await api(`plays/${enc}`); } $("progress").hidden = true; - $("text").readOnly = false; + $("editor").classList.remove("busy"); $("save").disabled = false; - savedText = await api(`plays/${enc}/text`); - $("text").value = savedText; + await loadText(); if (meta.jobError) showError(`Přepis se nepovedl: ${meta.jobError}`); +} + +async function loadText() { + const text = await api(`plays/${enc}/text`); + pages = splitPages(text, meta.photos, meta.images); + // uploaded without transcription: start with one empty page per photo + if (!text.trim() && meta.images) pages = Array.from({ length: meta.images }, (_, i) => ({ key: nextKey++, num: String(i + 1), missing: false, body: "", photo: i + 1 })); + markSaved(); + go(Math.min(cur, pages.length - 1)); check(); } -async function main() { - if (!id) { location.replace("./"); return; } - if (!getPassword() && !(await askPassword("Upravovat hry může jen ten, kdo zná heslo."))) { location.replace("./"); return; } - meta = await withLogin(() => api(`plays/${enc}`)); - $("preview").href = `read.html?hra=${enc}`; - $("title").value = meta.title; - $("note").value = meta.note || ""; - $("published").checked = meta.published; - document.title = `${meta.title} – úpravy`; - savedText = await api(`plays/${enc}/text`); - $("text").value = savedText; - if (meta.images) showImage(1); - check(); +// ---- wiring +function wire() { + $("page-list").addEventListener("click", (e) => { const b = e.target.closest("button[data-i]"); if (b) go(Number(b.dataset.i)); }); + $("prev").addEventListener("click", () => go(cur - 1)); + $("next").addEventListener("click", () => go(cur + 1)); let timer; - $("text").addEventListener("input", () => { clearTimeout(timer); timer = setTimeout(check, 400); }); - $("text").addEventListener("keydown", (e) => { - if ((e.ctrlKey || e.metaKey) && e.key === "s") { e.preventDefault(); save(); } + $("text").addEventListener("input", () => { + pages[cur].body = $("text").value; + paintText(); + clearTimeout(timer); + timer = setTimeout(() => { renderList(); check(); }, 400); + changed(); }); + $("num").addEventListener("change", () => { + pages[cur].num = $("num").value.trim().replace(/^[=!]/, "") || "?"; + sortPages(); + renderList(); renderPage(); check(); + }); + $("missing").addEventListener("change", () => { pages[cur].missing = $("missing").checked; renderList(); renderPage(); check(); }); + $("photo-select").addEventListener("change", () => { pages[cur].photo = Number($("photo-select").value) || null; renderPage(); changed(); }); + $("photo-frame").addEventListener("click", (e) => { + const f = $("photo-frame"); + if ($("img").hidden) return; + const r = $("img").getBoundingClientRect(); + const fx = (e.clientX - r.left) / r.width, fy = (e.clientY - r.top) / r.height; + f.classList.toggle("zoomed"); + if (f.classList.contains("zoomed")) f.scrollTo(fx * $("img").clientWidth - f.clientWidth / 2, fy * $("img").clientHeight - f.clientHeight / 2); + }); + $("dup-note").addEventListener("click", (e) => { + const b = e.target.closest("button[data-dup]"); + if (!b) return; + const p = pages[cur]; + const d = meta.duplicates.find((x) => x.image === Number(b.dataset.dup) && x.page === p.num); + // swap: the photo shown now becomes the left-out one + [d.image, p.photo] = [p.photo, d.image]; + [d.body, p.body] = [p.body, d.body]; + d.kept = p.photo; + renderList(); renderPage(); check(); + }); + $("reread").addEventListener("click", reread); + $("remove").addEventListener("click", () => { + const p = pages[cur]; + if (p.body && !confirm(`Smazat stranu ${label(p)} i s jejím textem?`)) return; + if (pages.length === 1) Object.assign(p, { num: "1", missing: false, body: "", photo: null }); // keep one page to type into + else pages.splice(cur, 1); + go(Math.min(cur, pages.length - 1)); + check(); + }); + $("add-blank").addEventListener("click", () => { + const n = pageInt(pages[cur]?.num || ""); + insertPage({ key: nextKey++, num: n !== null ? String(n + 1) : "?", missing: false, body: "", photo: null }); + renderList(); renderPage(); check(); + $("text").focus(); + }); + $("add-photo").addEventListener("change", (e) => { const f = e.target.files[0]; e.target.value = ""; if (f) addFromPhoto(f); }); + + $("title").addEventListener("input", changed); + $("note").addEventListener("input", changed); + $("published").addEventListener("change", changed); $("save").addEventListener("click", save); - $("img-prev").addEventListener("click", () => showImage(img - 1)); - $("img-next").addEventListener("click", () => showImage(img + 1)); - $("img-jump").addEventListener("click", () => { const p = pageOfImage(img); if (p) jumpTo(`=${p}`); }); + document.addEventListener("keydown", (e) => { + if ((e.ctrlKey || e.metaKey) && e.key === "s") { e.preventDefault(); save(); } + if (e.altKey && !$("review").open && (e.key === "ArrowLeft" || e.key === "ArrowRight")) { e.preventDefault(); go(cur + (e.key === "ArrowLeft" ? -1 : 1)); } + }); + + // review + $("review-start").addEventListener("click", () => openReview()); + $("review-form").addEventListener("submit", (e) => { e.preventDefault(); if (review.items[review.i]) resolveItem($("review-fix").value); }); + $("review-alts").addEventListener("click", (e) => { const b = e.target.closest("[data-alt]"); if (b) resolveItem(b.dataset.alt); }); + $("review-skip").addEventListener("click", () => { review.i++; showReviewItem(); }); + $("review-prev").addEventListener("click", () => { review.i = Math.max(0, review.i - 1); showReviewItem(); }); + $("review-again").addEventListener("click", () => openReview(true)); + $("review-finish").addEventListener("click", closeReview); + $("review-close").addEventListener("click", closeReview); + $("review").addEventListener("cancel", (e) => { e.preventDefault(); closeReview(); }); + $("retry").addEventListener("click", async () => { try { meta = await withLogin(() => api(`plays/${enc}/transcribe`, { method: "POST" })); @@ -158,8 +496,22 @@ async function main() { location.replace("./"); } catch (err) { showError(err.message); } }); - window.addEventListener("beforeunload", (e) => { if (!leaving && meta.status !== "processing" && dirty()) e.preventDefault(); }); + window.addEventListener("beforeunload", (e) => { if (!leaving && meta.status !== "processing" && isDirty()) e.preventDefault(); }); +} +async function main() { + if (!id) { location.replace("./"); return; } + cfg = await api("config"); + await authButton($("auth"), { uploads: cfg.uploads, onChange: (inn) => { if (!inn) { leaving = true; location.replace("./"); } } }); + if (!getPassword() && !(await askPassword("Upravovat hry může jen ten, kdo zná heslo."))) { location.replace("./"); return; } + meta = await withLogin(() => api(`plays/${enc}`)); + $("preview").href = `read.html?hra=${enc}`; + $("title").value = meta.title; + $("note").value = meta.note || ""; + $("published").checked = meta.published; + document.title = `${meta.title} – úpravy`; + wire(); + await loadText(); if (meta.status === "processing") await waitForJob(); }