Compare commits

..

4 commits

Author SHA1 Message Date
39e1e1043b Merge pull request 'Login button, sorted and de-duplicated pages, page-by-page editor with uncertain-word review' (#3) from feat/page-editor into main
Reviewed-on: #3
2026-11-04 17:16:32 +01:00
debf1aa8bc 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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HA82gVRDXpoukzgMFumoJt
2026-11-04 16:15:27 +00:00
6240907809 Login button with show-password, skip identical photos on upload
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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HA82gVRDXpoukzgMFumoJt
2026-11-04 16:15:27 +00:00
ab842a1d73 Sort pages by their number, drop repeated photos, mark uncertain words
The model now wraps words it isn't sure of in {word} or {word|other}; the
reader shows the first reading. Pages are ordered by the number on each
photo and a page photographed twice is kept once (fewer uncertain words,
then more text). meta.photos records which photo goes with which page.
New POST /images/:n/transcribe re-reads a single photo for the editor.
Seeded plays get an img/ folder on their first photo.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HA82gVRDXpoukzgMFumoJt
2026-11-04 16:15:27 +00:00
19 changed files with 1004 additions and 239 deletions

View file

@ -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/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/<id>/{meta.json,play.txt,img/NNN.jpg}`. Atomic writes; per-play lock for meta updates. - `server/store.mjs`: plays on disk, `DATA_DIR/plays/<id>/{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/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. - `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`). `api.js` holds the fetch and password helpers. `parse.js` is the markup parser, shared with the server tests. - `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. - `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). - `public/fonts/`: self-hosted woff2 + OFL licences, made by `tools/fetch_fonts.py` (keep its `FAMILIES` and `FONTS` in `reader.js` in step).
## API ## API
`GET /api/config`, `POST /api/login`, `GET|POST /api/plays`, `GET|PATCH|DELETE /api/plays/:id`, `GET|PUT /api/plays/:id/text`, `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 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. 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 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 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. 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.

View file

@ -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): **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. 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 ## Deploying

View file

@ -9,8 +9,11 @@
</head> </head>
<body class="page-add"> <body class="page-add">
<header class="topbar"> <header class="topbar">
<div>
<nav class="crumbs"><a href="./">← Všechny hry</a></nav> <nav class="crumbs"><a href="./">← Všechny hry</a></nav>
<h1>Přidat hru</h1> <h1>Přidat hru</h1>
</div>
<div class="topbar-actions" id="auth"></div>
</header> </header>
<main class="wrap"> <main class="wrap">
<p class="error" id="disabled" hidden></p> <p class="error" id="disabled" hidden></p>
@ -25,7 +28,8 @@
<input type="file" id="files" accept="image/*" multiple> <input type="file" id="files" accept="image/*" multiple>
<span><b>Vyberte fotky</b> nebo je sem přetáhněte. Jedna fotka = jedna strana.</span> <span><b>Vyberte fotky</b> nebo je sem přetáhněte. Jedna fotka = jedna strana.</span>
</label> </label>
<p class="muted small">Strany se seřadí podle názvu souboru; pořadí můžete změnit šipkami. Fotky se před nahráním zmenší.</p> <p class="muted small">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ší.</p>
<p class="notice" id="notice" role="status" hidden></p>
<ol class="thumbs" id="thumbs"></ol> <ol class="thumbs" id="thumbs"></ol>
</fieldset> </fieldset>

View file

@ -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. let files = []; // [{ file, url, hash }]
const MAX_PIXELS = 1.15e6;
const MAX_SIDE = 1568;
let files = []; // [{ file, url }]
let cfg; let cfg;
const collator = new Intl.Collator("cs", { numeric: true, sensitivity: "base" }); 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)); 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)); 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) { 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)); files.splice(cfg.maxPages).forEach((f) => URL.revokeObjectURL(f.url));
} }
$("notice").textContent = notes.join(" ");
$("notice").hidden = !notes.length;
renderThumbs(); renderThumbs();
} }
@ -35,20 +43,6 @@ function renderThumbs() {
$("go").disabled = !files.length; $("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 showError(msg) { $("error").textContent = msg; $("error").hidden = !msg; }
function setStatus(text, value) { function setStatus(text, value) {
$("progress").hidden = false; $("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ě."; $("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"; $("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 = ""; }); $("files").addEventListener("change", (e) => { addFiles(e.target.files); e.target.value = ""; });
const drop = $("drop"); const drop = $("drop");

View file

@ -10,6 +10,7 @@ export function setPassword(pw, remember) {
if (remember) localStorage.setItem(PASS_KEY, pw); else localStorage.removeItem(PASS_KEY); if (remember) localStorage.setItem(PASS_KEY, pw); else localStorage.removeItem(PASS_KEY);
} catch { /* storage blocked: the password just won't be remembered */ } } 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() { export function clearPassword() {
try { sessionStorage.removeItem(PASS_KEY); localStorage.removeItem(PASS_KEY); } catch { /* ignore */ } try { sessionStorage.removeItem(PASS_KEY); localStorage.removeItem(PASS_KEY); } catch { /* ignore */ }
} }
@ -52,37 +53,91 @@ export const esc = (s) => String(s).replace(/[&<>"']/g, (c) => ({ "&": "&amp;",
export const $ = (id) => document.getElementById(id); export const $ = (id) => document.getElementById(id);
// Ask for the upload password in a modal dialog; resolves true once logged in, false if cancelled. // 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 = "") { export function askPassword(reason = "") {
return new Promise((resolve) => { return new Promise((resolve) => {
const dlg = document.createElement("dialog"); const dlg = document.createElement("dialog");
dlg.className = "login"; dlg.className = "login";
dlg.innerHTML = `<form method="dialog"> dlg.innerHTML = `<form method="dialog" novalidate>
<h2>Heslo pro úpravy</h2> <h2>Přihlášení</h2>
${reason ? `<p class="muted">${esc(reason)}</p>` : ""} ${reason ? `<p class="muted">${esc(reason)}</p>` : ""}
<label class="field"><span>Heslo</span><input type="password" name="pw" autocomplete="current-password" required></label> <label class="field"><span>Heslo</span>
<label class="radio"><input type="checkbox" name="remember"> Zapamatovat na tomto zařízení</label> <span class="pw-field">
<p class="error" hidden></p> <input type="password" name="pw" autocomplete="current-password" autocapitalize="off" spellcheck="false" aria-describedby="login-error">
<div class="actions"><button value="cancel" formnovalidate>Zrušit</button><button class="primary" value="ok">Přihlásit</button></div> <button type="button" class="eye" aria-label="Zobrazit heslo" aria-pressed="false" title="Zobrazit heslo">${EYE}</button>
</span>
</label>
<label class="check"><input type="checkbox" name="remember"> Zůstat přihlášen v tomto prohlížeči</label>
<p class="error" id="login-error" role="alert" hidden></p>
<div class="actions"><button value="cancel" type="button" data-cancel>Zrušit</button><button class="primary" value="ok" type="submit">Přihlásit</button></div>
</form>`; </form>`;
document.body.append(dlg); document.body.append(dlg);
const form = dlg.querySelector("form"); const form = dlg.querySelector("form");
const pw = form.pw;
const err = dlg.querySelector(".error"); 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) => { form.addEventListener("submit", async (e) => {
if (e.submitter?.value !== "ok") return;
e.preventDefault(); e.preventDefault();
if (!pw.value) { showError("Zadejte heslo."); pw.focus(); return; }
ok.disabled = true;
ok.textContent = "Ověřuji…";
try { try {
await login(form.pw.value, form.remember.checked); await login(pw.value, form.remember.checked);
dlg.close("ok"); dlg.close("ok");
} catch (ex) { } catch (ex) {
err.textContent = ex.message; showError(ex.status === 401 ? "Heslo nesouhlasí, zkuste to znovu." : ex.message);
err.hidden = false; pw.select();
pw.focus();
} finally {
ok.disabled = false;
ok.textContent = "Přihlásit";
} }
}); });
dlg.addEventListener("close", () => { dlg.remove(); resolve(dlg.returnValue === "ok"); }); dlg.addEventListener("close", () => { dlg.remove(); resolve(dlg.returnValue === "ok"); });
dlg.showModal(); dlg.showModal();
pw.focus();
}); });
} }
const EYE = `<svg viewBox="0 0 24 24" width="20" height="20" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7S2 12 2 12z"/><circle cx="12" cy="12" r="3"/></svg>`;
const EYE_OFF = `<svg viewBox="0 0 24 24" width="20" height="20" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10.6 5.1A10.9 10.9 0 0 1 12 5c6.5 0 10 7 10 7a17.6 17.6 0 0 1-2.9 3.8M6.6 6.6C3.6 8.4 2 12 2 12s3.5 7 10 7c1.8 0 3.4-.5 4.8-1.3"/><path d="M9.9 9.9a3 3 0 0 0 4.2 4.2"/><path d="M3 3l18 18"/></svg>`;
// 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. // Run fn; on 401 ask for the password and retry once.
export async function withLogin(fn, reason) { export async function withLogin(fn, reason) {
try { return await fn(); } try { return await fn(); }

View file

@ -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); } .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; } .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.login h2 { margin: 0 0 8px; font-size: 18px; }
dialog::backdrop { background: rgba(0, 0, 0, 0.4); } 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; } .meta-row .grow { flex: 1 1 260px; }
.field.toggle { display: flex; align-items: center; gap: 8px; padding-bottom: 8px; } .field.toggle { display: flex; align-items: center; gap: 8px; padding-bottom: 8px; }
.field.toggle span { margin: 0; } .field.toggle span { margin: 0; }
.editor { display: grid; grid-template-columns: minmax(0, 1fr) minmax(300px, 0.8fr); gap: 16px; align-items: start; } .field.toggle input { accent-color: var(--accent); }
.editor textarea { .check { display: inline-flex; align-items: center; gap: 8px; cursor: pointer; }
height: calc(100vh - 230px); .check input { width: 18px; height: 18px; margin: 0; accent-color: var(--accent); }
min-height: 360px; .notice { background: var(--hl); border-radius: 8px; padding: 8px 12px; font-size: 14px; }
font-family: "Courier Prime", ui-monospace, monospace; button.quiet { border-color: transparent; background: transparent; color: var(--muted); }
font-size: 15px; button.quiet:hover { color: var(--accent); }
line-height: 1.45;
resize: vertical; /* login dialog */
tab-size: 4; 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; } .pw-field .eye:hover, .pw-field .eye[aria-pressed="true"] { color: var(--accent); }
.photo-nav { display: flex; align-items: center; gap: 6px; margin-bottom: 6px; font-size: 14px; } dialog.login .check { margin: 2px 0 4px; font-size: 14.5px; }
.photo-nav span { flex: 1; text-align: center; color: var(--muted); } dialog.login .error { margin: 10px 0 0; font-size: 14px; }
.photo-nav button { padding: 4px 10px; font-size: 13px; } dialog.login .actions { margin-top: 16px; }
.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; } /* editor */
.checks ul { margin: 6px 0 10px; padding-left: 18px; max-height: 220px; overflow-y: auto; font-size: 14px; } .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 { font-size: 14px; margin-top: 8px; }
.help td { padding: 2px 10px 2px 0; vertical-align: top; } .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; } .danger button { color: var(--accent); border-color: var(--accent); background: transparent; }
@media (max-width: 900px) {
.editor { grid-template-columns: minmax(0, 1fr); } /* review of uncertain words */
.editor-side { position: static; order: -1; } dialog.review {
.photo img { max-height: 60vh; } width: min(1100px, calc(100vw - 24px)); max-height: calc(100vh - 24px); padding: 0;
.editor textarea { height: 70vh; } 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) ---- /* ---- PDF export (print) ----

View file

@ -11,9 +11,9 @@
<body class="page-edit"> <body class="page-edit">
<header class="topbar"> <header class="topbar">
<nav class="crumbs"><a href="./">← Všechny hry</a><a id="preview" target="_blank">Otevřít ve čtečce ↗</a></nav> <nav class="crumbs"><a href="./">← Všechny hry</a><a id="preview" target="_blank">Otevřít ve čtečce ↗</a></nav>
<div class="topbar-actions"> <div class="topbar-actions" id="auth">
<span class="muted small" id="saved"></span> <span class="muted small" id="saved" role="status"></span>
<button id="save" class="primary">Uložit</button> <button id="save" class="primary" title="Uložit (Ctrl+S)">Uložit</button>
</div> </div>
</header> </header>
<main class="wrap wide"> <main class="wrap wide">
@ -29,44 +29,101 @@
<label class="field toggle"><input type="checkbox" id="published"> <span>Zveřejněno</span></label> <label class="field toggle"><input type="checkbox" id="published"> <span>Zveřejněno</span></label>
</div> </div>
<div class="editor"> <div class="review-bar" id="review-bar" hidden>
<section class="editor-text"> <span id="review-count"></span>
<textarea id="text" spellcheck="false" aria-label="Text hry"></textarea> <button class="primary" id="review-start">Projít nejistá slova</button>
</div>
<details class="checks" id="checks">
<summary><b>Kontrola</b> <span id="summary" class="muted"></span></summary>
<ul id="issues"></ul>
<button id="retry" hidden>Přepsat nepovedené strany znovu</button>
</details>
<div class="editor" id="editor">
<nav class="page-list" aria-label="Strany">
<ol id="page-list"></ol>
<div class="page-list-tools">
<button id="add-blank" title="Vložit prázdnou stranu za vybranou">+ Strana</button>
<label class="button" id="add-photo-label" title="Nahrát fotku další strany (třeba té, která chyběla)">+ Z fotky<input type="file" id="add-photo" accept="image/*" hidden></label>
</div>
</nav>
<section class="page-photo" id="photo-pane">
<div class="photo-frame" id="photo-frame" title="Kliknutím přiblížíte">
<img id="img" alt="">
<p class="muted photo-empty" id="photo-empty">Tato strana nemá fotku.</p>
</div>
<label class="photo-pick small muted">Fotka: <select id="photo-select"></select></label>
</section>
<section class="page-text">
<div class="page-head">
<button id="prev" title="Předchozí strana (Alt+←)" aria-label="Předchozí strana">◀</button>
<label class="page-num">Strana <input id="num" size="5" maxlength="20" autocomplete="off"></label>
<button id="next" title="Další strana (Alt+→)" aria-label="Další strana">▶</button>
<label class="check"><input type="checkbox" id="missing"> v originále chybí</label>
<span class="grow"></span>
<button id="reread" hidden>Přepsat znovu z fotky</button>
<button id="remove" class="quiet" title="Smazat tuto stranu">Smazat stranu</button>
</div>
<div class="dup-note" id="dup-note" hidden></div>
<p class="missing-hint muted" id="missing-hint" hidden>Strana v originále chybí. Až ji najdete, přidejte ji tlačítkem „+ Z fotky“ nebo zrušte zaškrtnutí a napište text.</p>
<div class="hl-wrap" id="hl-wrap">
<div class="hl-back" id="hl-back" aria-hidden="true"></div>
<textarea id="text" spellcheck="false" aria-label="Text strany"></textarea>
</div>
<details class="help"> <details class="help">
<summary>Jak se text zapisuje</summary> <summary>Jak se text zapisuje</summary>
<table> <table>
<tr><td><code>=5</code></td><td>začátek strany 5 (<code>!7</code> = strana 7 chybí)</td></tr>
<tr><td><code>@Lída</code></td><td>replika postavy Lída; další řádky jsou její text</td></tr> <tr><td><code>@Lída</code></td><td>replika postavy Lída; další řádky jsou její text</td></tr>
<tr><td><code>&gt;(Odejde)</code></td><td>scénická poznámka; pokračování na dalším řádku začíná <code>&gt; </code></td></tr> <tr><td><code>&gt;(Odejde)</code></td><td>scénická poznámka; pokračování na dalším řádku začíná <code>&gt; </code></td></tr>
<tr><td><code>&gt;&nbsp;&nbsp;verš</code></td><td>verš / píseň (dvě mezery za <code>&gt;</code>)</td></tr> <tr><td><code>&gt;&nbsp;&nbsp;verš</code></td><td>verš / píseň (dvě mezery za <code>&gt;</code>)</td></tr>
<tr><td><code>#Pokoj u Lysáků</code></td><td>popis scény u levého okraje</td></tr> <tr><td><code>#Pokoj u Lysáků</code></td><td>popis scény u levého okraje</td></tr>
<tr><td><code>~O p o n a</code></td><td>řádek na střed</td></tr> <tr><td><code>~O p o n a</code></td><td>řádek na střed</td></tr>
<tr><td><code>.</code></td><td>prázdný řádek; ukončí repliku</td></tr> <tr><td><code>.</code></td><td>prázdný řádek; ukončí repliku</td></tr>
<tr><td><code>{slovo|slova}</code></td><td>nejisté čtení (a jiná možnost); ve čtečce se ukáže jen první</td></tr>
</table> </table>
<p>Rozdělené slovo na konci řádku nechte se spojovníkem (<code>nepří-</code>), čtečka ho spojí. Pomlčku jako interpunkci na konci řádku pište jako <code>–</code>.</p> <p>Text na začátku strany bez <code>@Jméno</code> pokračuje replikou z předchozí strany. Rozdělené slovo na konci řádku nechte se spojovníkem (<code>nepří-</code>), čtečka ho spojí. Pomlčku jako interpunkci na konci řádku pište jako <code>–</code>.</p>
</details> </details>
</section> </section>
<aside class="editor-side">
<div class="photo" id="photo-box" hidden>
<div class="photo-nav">
<button id="img-prev" title="Předchozí fotka">◀</button>
<span id="img-label"></span>
<button id="img-next" title="Další fotka">▶</button>
<button id="img-jump" title="Najít tuto stranu v textu">Najít v textu</button>
</div>
<img id="img" alt="Fotka strany">
</div>
<div class="checks">
<h2>Kontrola</h2>
<p id="summary" class="muted"></p>
<ul id="issues"></ul>
<button id="retry" hidden>Přepsat nepovedené strany znovu</button>
</div> </div>
<div class="danger"> <div class="danger">
<button id="delete">Smazat hru</button> <button id="delete">Smazat celou hru</button>
</div>
</aside>
</div> </div>
</main> </main>
<dialog class="review" id="review" aria-labelledby="review-title">
<div class="review-grid">
<div class="review-photo" id="review-photo">
<img id="review-img" alt="Fotka strany">
<div class="review-band" id="review-band" title="Slovo je přibližně tady"></div>
<p class="muted photo-empty" id="review-nophoto" hidden>Ke straně není fotka.</p>
</div>
<form class="review-card" id="review-form" method="dialog">
<div class="review-top">
<h2 id="review-title">Nejistá slova</h2>
<button type="button" class="quiet" id="review-close" aria-label="Zavřít">✕</button>
</div>
<div id="review-item">
<p class="muted small" id="review-where"></p>
<div class="review-context" id="review-context"></div>
<label class="field"><span>Správně je</span><input id="review-fix" autocomplete="off" spellcheck="false"></label>
<div class="review-alts" id="review-alts"></div>
<div class="actions">
<button type="button" id="review-prev" title="Předchozí">←</button>
<button type="button" id="review-skip" title="Nechat označené a jít dál">Přeskočit</button>
<button class="primary" id="review-ok" type="submit">Potvrdit</button>
</div>
<p class="muted small">Enter potvrdí, Esc zavře. Opravy se po zavření uloží.</p>
</div>
<div id="review-done" hidden>
<p id="review-done-text"></p>
<div class="actions"><button type="button" id="review-again" hidden>Projít přeskočená</button><button type="button" class="primary" id="review-finish">Hotovo</button></div>
</div>
</form>
</div>
</dialog>
</body> </body>
</html> </html>

View file

@ -1,98 +1,334 @@
import { api, withLogin, getPassword, askPassword, esc, $ } from "./api.js"; // Play editor: one original page at a time, next to its photo, plus a
import { parsePlay, speakers, lint } from "./parse.js"; // 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 id = new URLSearchParams(location.search).get("id");
const enc = encodeURIComponent(id); const enc = encodeURIComponent(id);
let meta; let cfg, meta;
let savedText = ""; let pages = []; // [{ key, num, missing, body, photo }]
let img = 1; let cur = 0;
let saved = { text: "", photos: "" };
let leaving = false; 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; || $("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() { function showError(msg) { $("error").textContent = msg; $("error").hidden = !msg; if (msg) $("error").scrollIntoView({ block: "nearest" }); }
let pages; function changed() {
try { pages = parsePlay($("text").value); } $("saved").textContent = isDirty() ? "Neuložené změny" : $("saved").dataset.at || "";
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) => `<li><button class="link" data-i="${i}">${x.page && x.page !== "?" ? `str. ${esc(x.page)}: ` : ""}${esc(x.message)}</button></li>`).join("")
: `<li class="muted">Žádné problémy nenalezeny.</li>`;
$("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);
} }
// Select `needle` (or the line containing `inner`) in the textarea and scroll it into view. // ---- photos (drafts' photos need the password header, so fetch them as blobs)
function jumpTo(needle, inner) { 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 `<li><button class="${cls}" data-i="${i}" title="${esc(title)}" ${i === cur ? 'aria-current="page"' : ""}>
<span>${esc(label(p))}</span>${n && !p.missing ? `<span class="count">${n}</span>` : ""}${isFailed(p) ? `<span class="count bad">!</span>` : ""}</button></li>`;
}).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 = `<option value="">bez fotky</option>` +
Array.from({ length: meta.images }, (_, i) => `<option value="${i + 1}">${i + 1}</option>`).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) => `<button class="link" data-dup="${d.image}">Použít místo ní přepis z fotky ${d.image}</button>`).join(" · ") : "";
}
// The highlight layer behind the textarea marks the {uncertain} words.
function paintText() {
const ta = $("text"); const ta = $("text");
const v = ta.value; const v = ta.value;
let at = -1; let html = "";
if (needle) at = needle.startsWith("=") ? (`\n${v}`).indexOf(`\n${needle}\n`) : v.indexOf(needle); let last = 0;
if (at < 0 && inner) at = v.indexOf(inner); for (const m of v.matchAll(UNC)) {
if (at < 0) return; html += esc(v.slice(last, m.index)) + `<mark>${esc(m[0])}</mark>`;
const len = (needle && v.startsWith(needle, at) ? needle : inner || "").length; last = m.index + m[0].length;
ta.focus(); }
ta.setSelectionRange(at, at + len); $("hl-back").innerHTML = html + esc(v.slice(last)) + "\n ";
// scroll: put the selected line about a third from the top ta.style.height = "auto";
const lineNo = v.slice(0, at).split("\n").length - 1; ta.style.height = `${Math.max(ta.scrollHeight, 320)}px`;
const lh = parseFloat(getComputedStyle(ta).lineHeight) || 20;
ta.scrollTop = Math.max(0, lineNo * lh - ta.clientHeight / 3);
} }
// Drafts' photos need the password header, which <img src> can't send, so fetch them as blobs. function check() {
let imgUrl = null; const text = joinPages();
async function showImage(n) { const parsed = parsePlay(text, { plain: true });
if (!meta.images) return; const real = parsed.filter((p) => !p.missing);
img = Math.min(meta.images, Math.max(1, n)); const cast = speakers(parsed);
$("photo-box").hidden = false; const unsure = pages.reduce((n, p) => n + (p.missing ? 0 : uncertainIn(p.body).length), 0);
const shown = img; const issues = [
api(`plays/${enc}/images/${img}`, { raw: true }).then((r) => r.blob()).then((b) => { ...pages.flatMap((p, i) => (isFailed(p) ? [{ i, message: "přepis se nepovedl" }] : [])),
if (shown !== img) return; // user already moved on ...lint(parsePlay(text)).map((x) => ({ i: pages.findIndex((p) => p.num === x.page), message: x.message })),
if (imgUrl) URL.revokeObjectURL(imgUrl); ];
imgUrl = URL.createObjectURL(b); // Names used only once are often misreadings of another name.
$("img").src = imgUrl; for (const c of cast) if (c.count === 1 && cast.length > 2)
}).catch((err) => showError(`Fotku se nepodařilo načíst: ${err.message}`)); 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?` });
$("img-label").textContent = `fotka ${img} / ${meta.images}`; $("summary").textContent = `${plural(real.length, "strana", "strany", "stran")}, ${plural(cast.length, "postava", "postavy", "postav")}`
$("img-prev").disabled = img === 1; + `${cast.length ? `: ${cast.map((c) => c.name).join(", ")}` : ""}${issues.length ? ` · ${plural(issues.length, "upozornění", "upozornění", "upozornění")}` : ""}`;
$("img-next").disabled = img === meta.images; $("issues").innerHTML = issues.length
? issues.slice(0, 200).map((x, k) => `<li><button class="link" data-k="${k}">${x.i >= 0 ? `str. ${esc(label(pages[x.i]))}: ` : ""}${esc(x.message)}</button></li>`).join("")
: `<li class="muted">Žádné problémy nenalezeny.</li>`;
$("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 go(i) {
function pageOfImage(n) { if (!pages.length) return;
const text = $("text").value; cur = Math.max(0, Math.min(pages.length - 1, i));
const markers = [...text.matchAll(/^=(.+)$/gm)].map((m) => m[1]); renderList();
return markers[n - 1]; 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 ? `<div class="ctx-line">${show(before)}</div>` : "") +
`<div class="ctx-line main">${show(body.slice(lineStart, item.start))}<mark>${esc(item.options[0] || "")}</mark>${show(body.slice(item.start + item.raw.length, lineEnd))}</div>` +
(after !== undefined ? `<div class="ctx-line">${show(after)}</div>` : "");
$("review-fix").value = item.options[0] || "";
$("review-alts").innerHTML = item.options.length > 1
? `<span class="muted small">Možnosti:</span> ` + item.options.map((o) => `<button type="button" class="chip" data-alt="${esc(o)}">${esc(o)}</button>`).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() { async function save() {
showError(""); showError("");
$("save").disabled = true; $("save").disabled = true;
try { try {
await withLogin(async () => { await withLogin(async () => {
if ($("text").value !== savedText) { const text = joinPages();
meta = await api(`plays/${enc}/text`, { method: "PUT", body: $("text").value, type: "text/plain; charset=utf-8" }); if (text !== saved.text) meta = await api(`plays/${enc}/text`, { method: "PUT", body: text, 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, photos: photoList(), duplicates: meta.duplicates } });
} markSaved();
meta = await api(`plays/${enc}`, { method: "PATCH", body: { title: $("title").value, note: $("note").value, published: $("published").checked } });
}); });
$("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(); check();
} catch (err) { } catch (err) {
showError(`Uložení se nepovedlo: ${err.message}`); 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() { async function waitForJob() {
$("text").readOnly = true; $("editor").classList.add("busy");
$("save").disabled = true; $("save").disabled = true;
$("progress").hidden = false; $("progress").hidden = false;
while (meta.status === "processing") { while (meta.status === "processing") {
@ -113,37 +389,99 @@ async function waitForJob() {
meta = await api(`plays/${enc}`); meta = await api(`plays/${enc}`);
} }
$("progress").hidden = true; $("progress").hidden = true;
$("text").readOnly = false; $("editor").classList.remove("busy");
$("save").disabled = false; $("save").disabled = false;
savedText = await api(`plays/${enc}/text`); await loadText();
$("text").value = savedText;
if (meta.jobError) showError(`Přepis se nepovedl: ${meta.jobError}`); 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(); check();
} }
async function main() { // ---- wiring
if (!id) { location.replace("./"); return; } function wire() {
if (!getPassword() && !(await askPassword("Upravovat hry může jen ten, kdo zná heslo."))) { location.replace("./"); return; } $("page-list").addEventListener("click", (e) => { const b = e.target.closest("button[data-i]"); if (b) go(Number(b.dataset.i)); });
meta = await withLogin(() => api(`plays/${enc}`)); $("prev").addEventListener("click", () => go(cur - 1));
$("preview").href = `read.html?hra=${enc}`; $("next").addEventListener("click", () => go(cur + 1));
$("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();
let timer; let timer;
$("text").addEventListener("input", () => { clearTimeout(timer); timer = setTimeout(check, 400); }); $("text").addEventListener("input", () => {
$("text").addEventListener("keydown", (e) => { pages[cur].body = $("text").value;
if ((e.ctrlKey || e.metaKey) && e.key === "s") { e.preventDefault(); save(); } 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); $("save").addEventListener("click", save);
$("img-prev").addEventListener("click", () => showImage(img - 1)); document.addEventListener("keydown", (e) => {
$("img-next").addEventListener("click", () => showImage(img + 1)); if ((e.ctrlKey || e.metaKey) && e.key === "s") { e.preventDefault(); save(); }
$("img-jump").addEventListener("click", () => { const p = pageOfImage(img); if (p) jumpTo(`=${p}`); }); 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 () => { $("retry").addEventListener("click", async () => {
try { try {
meta = await withLogin(() => api(`plays/${enc}/transcribe`, { method: "POST" })); meta = await withLogin(() => api(`plays/${enc}/transcribe`, { method: "POST" }));
@ -158,8 +496,22 @@ async function main() {
location.replace("./"); location.replace("./");
} catch (err) { showError(err.message); } } 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(); if (meta.status === "processing") await waitForJob();
} }

View file

@ -13,7 +13,6 @@
<h1>Divadelní čtečka</h1> <h1>Divadelní čtečka</h1>
<div class="topbar-actions"> <div class="topbar-actions">
<a class="button primary" id="add" href="add.html" hidden>+ Přidat hru</a> <a class="button primary" id="add" href="add.html" hidden>+ Přidat hru</a>
<button id="logout" hidden>Odhlásit</button>
</div> </div>
</header> </header>
<main class="wrap"> <main class="wrap">

View file

@ -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. // Old links (/?postava=Lída or /?hra=…) went straight to the reader.
const q = new URLSearchParams(location.search); 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" }); const fmtDate = (iso) => new Date(iso).toLocaleDateString("cs-CZ", { day: "numeric", month: "numeric", year: "numeric" });
async function main() { 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()); const loggedIn = Boolean(getPassword());
$("add").hidden = !cfg.uploads; $("add").hidden = !loggedIn;
$("logout").hidden = !loggedIn;
$("logout").addEventListener("click", () => { clearPassword(); location.reload(); });
if (!plays.length) { if (!plays.length) {
$("plays").innerHTML = `<li class="muted">Zatím tu není žádná hra.${cfg.uploads ? " Přidejte první tlačítkem nahoře." : ""}</li>`; $("plays").innerHTML = `<li class="muted">Zatím tu není žádná hra.${loggedIn ? " Přidejte první tlačítkem nahoře." : ""}</li>`;
return; return;
} }
$("plays").innerHTML = plays.map((p) => { $("plays").innerHTML = plays.map((p) => {

View file

@ -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;

36
public/photos.js Normal file
View file

@ -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)}`;
}

View file

@ -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();

View file

@ -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") {

View file

@ -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)

View file

@ -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; }

View file

@ -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 };
} }

View file

@ -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" }));

View file

@ -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]);