Compare commits

..

No commits in common. "39e1e1043bb30e541aba9a4a85ffb7002095ebb1" and "3f2cf95f1d1fb3213c6f76c31e9822665e832051" have entirely different histories.

19 changed files with 233 additions and 998 deletions

View file

@ -10,17 +10,15 @@ UI language is Czech.
- `server/main.mjs`: HTTP server, routing, static files, auth (`x-upload-password` header vs `UPLOAD_PASSWORD`), daily page cap, background transcription job.
- `server/store.mjs`: plays on disk, `DATA_DIR/plays/<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/transcribe.mjs`: `splitPage` → `normalizeSpeakers` → `assemble` turn the per-photo answers into one play file: sorted by the page number read off each photo, repeats of a page dropped (kept in `meta.duplicates`), and `meta.photos` recording which photo belongs to which page marker. `server/prompt.mjs` holds the prompt (shared by both providers), which teaches the markup below.
- `public/`: four pages: `index.html` library (`library.js`), `read.html` reader (`reader.js`), `add.html` upload (`add.js`: shrinks photos to ≤1.15 MP JPEG in the browser), `edit.html` editor (`edit.js`: splits the text at page markers and edits one page at a time beside its photo; review dialog for `{uncertain}` words). `api.js` holds the fetch, password and login-button helpers, `photos.js` the in-browser JPEG shrinking and duplicate-photo fingerprint. `parse.js` is the markup parser, shared with the server tests.
- `server/transcribe.mjs`: `splitPage` → `normalizeSpeakers` → `assemble` turn the per-photo answers into one play file. `server/prompt.mjs` holds the prompt (shared by both providers), which teaches the markup below.
- `public/`: four pages: `index.html` library (`library.js`), `read.html` reader (`reader.js`), `add.html` upload (`add.js`: shrinks photos to ≤1.15 MP JPEG in the browser), `edit.html` editor (`edit.js`). `api.js` holds the fetch and password helpers. `parse.js` is the markup parser, shared with the server tests.
- `seed/`: plays copied into an empty data volume on first start.
- `public/fonts/`: self-hosted woff2 + OFL licences, made by `tools/fetch_fonts.py` (keep its `FAMILIES` and `FONTS` in `reader.js` in step).
## API
`GET /api/config`, `POST /api/login`, `GET|POST /api/plays`, `GET|PATCH|DELETE /api/plays/:id`, `GET|PUT /api/plays/:id/text`,
`GET|PUT /api/plays/:id/images/:n` (raw `image/jpeg` body), `POST /api/plays/:id/transcribe` (202, then poll the meta's `progress`),
`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`.
`GET|PUT /api/plays/:id/images/:n` (raw `image/jpeg` body), `POST /api/plays/:id/transcribe` (202, then poll the meta's `progress`).
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.
@ -51,8 +49,6 @@ One directive per line; blank lines are ignored.
The text keeps the typescript's line breaks, spelling and missing spaces ("dobře.Ale"). The "running text" mode joins
hyphenated words (`nepří-` / `jemné`, also the typist's `ne -` / `spokojenců`) and adds the missing spaces. **A dash that
really is punctuation at the end of a line must be typed as `–` (en dash)**, or it gets joined to the next word.
`{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.)
`[?]` after a word marks an uncertain reading. The editor lists them.
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.
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.

View file

@ -14,10 +14,9 @@ A link like `read.html?hra=hra-1931&postava=Lída` opens a play with the charact
**Adding plays** (anyone with the upload password):
1. *Př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.
1. *Přidat hru*: give the title and pick a photo of each page.
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. 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.
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.
## Deploying

View file

@ -9,11 +9,8 @@
</head>
<body class="page-add">
<header class="topbar">
<div>
<nav class="crumbs"><a href="./">← Všechny hry</a></nav>
<h1>Přidat hru</h1>
</div>
<div class="topbar-actions" id="auth"></div>
</header>
<main class="wrap">
<p class="error" id="disabled" hidden></p>
@ -28,8 +25,7 @@
<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>
</label>
<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>
<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>
<ol class="thumbs" id="thumbs"></ol>
</fieldset>

View file

@ -1,30 +1,22 @@
import { api, withLogin, getPassword, askPassword, authButton, esc, $ } from "./api.js";
import { toJpeg, fingerprint } from "./photos.js";
import { api, withLogin, getPassword, askPassword, esc, $ } from "./api.js";
let files = []; // [{ file, url, hash }]
// The API reads images at most ~1.15 megapixels, so a bigger upload only costs bandwidth.
const MAX_PIXELS = 1.15e6;
const MAX_SIDE = 1568;
let files = []; // [{ file, url }]
let cfg;
const collator = new Intl.Collator("cs", { numeric: true, sensitivity: "base" });
// 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) {
function addFiles(list) {
const imgs = [...list].filter((f) => f.type.startsWith("image/") || /\.(heic|heif)$/i.test(f.name));
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.push(...imgs.map((file) => ({ file, url: URL.createObjectURL(file) })));
files.sort((a, b) => collator.compare(a.file.name, b.file.name));
const notes = skipped.length ? [`Přeskočeno ${skipped.length === 1 ? "1 opakování" : `${skipped.length} opakování`}: ${skipped.join("; ")}.`] : [];
if (files.length > cfg.maxPages) {
notes.push(`Najednou lze nahrát nejvýše ${cfg.maxPages} stran.`);
showError(`Najednou lze nahrát nejvýše ${cfg.maxPages} stran.`);
files.splice(cfg.maxPages).forEach((f) => URL.revokeObjectURL(f.url));
}
$("notice").textContent = notes.join(" ");
$("notice").hidden = !notes.length;
renderThumbs();
}
@ -43,6 +35,20 @@ function renderThumbs() {
$("go").disabled = !files.length;
}
// Decode, shrink and re-encode as JPEG (also strips EXIF, e.g. location).
async function toJpeg(file) {
let bitmap;
try { bitmap = await createImageBitmap(file, { imageOrientation: "from-image" }); }
catch { throw new Error(`Obrázek „${file.name}“ se nepodařilo otevřít${/\.hei[cf]$/i.test(file.name) ? " (formát HEIC – zkuste fotku uložit jako JPEG)" : ""}.`); }
const scale = Math.min(1, MAX_SIDE / Math.max(bitmap.width, bitmap.height), Math.sqrt(MAX_PIXELS / (bitmap.width * bitmap.height)));
const canvas = document.createElement("canvas");
canvas.width = Math.round(bitmap.width * scale);
canvas.height = Math.round(bitmap.height * scale);
canvas.getContext("2d").drawImage(bitmap, 0, 0, canvas.width, canvas.height);
bitmap.close();
return new Promise((resolve, reject) => canvas.toBlob((b) => (b ? resolve(b) : reject(new Error("Převod obrázku selhal."))), "image/jpeg", 0.88));
}
function showError(msg) { $("error").textContent = msg; $("error").hidden = !msg; }
function setStatus(text, value) {
$("progress").hidden = false;
@ -102,8 +108,7 @@ async function main() {
$("ai-note").textContent = "Automatický přepis není na serveru zapnutý (chybí klíč OPENROUTER_API_KEY nebo ANTHROPIC_API_KEY). Fotky se nahrají a text pak napíšete v editoru ručně.";
$("go").textContent = "Nahrát";
}
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; }
if (!getPassword()) askPassword("Přidávat hry může jen ten, kdo zná heslo.");
$("files").addEventListener("change", (e) => { addFiles(e.target.files); e.target.value = ""; });
const drop = $("drop");

View file

@ -10,7 +10,6 @@ export function setPassword(pw, remember) {
if (remember) localStorage.setItem(PASS_KEY, pw); else localStorage.removeItem(PASS_KEY);
} catch { /* storage blocked: the password just won't be remembered */ }
}
const isRemembered = () => { try { return Boolean(localStorage.getItem(PASS_KEY)); } catch { return false; } };
export function clearPassword() {
try { sessionStorage.removeItem(PASS_KEY); localStorage.removeItem(PASS_KEY); } catch { /* ignore */ }
}
@ -53,91 +52,37 @@ export const esc = (s) => String(s).replace(/[&<>"']/g, (c) => ({ "&": "&amp;",
export const $ = (id) => document.getElementById(id);
// Ask for the upload password in a modal dialog; resolves true once logged in, false if cancelled.
// The password is stored only after the server accepted it, and only where the
// "stay logged in" box says (this tab, or this browser until "Odhlásit").
export function askPassword(reason = "") {
return new Promise((resolve) => {
const dlg = document.createElement("dialog");
dlg.className = "login";
dlg.innerHTML = `<form method="dialog" novalidate>
<h2>Přihlášení</h2>
dlg.innerHTML = `<form method="dialog">
<h2>Heslo pro úpravy</h2>
${reason ? `<p class="muted">${esc(reason)}</p>` : ""}
<label class="field"><span>Heslo</span>
<span class="pw-field">
<input type="password" name="pw" autocomplete="current-password" autocapitalize="off" spellcheck="false" aria-describedby="login-error">
<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>
<label class="field"><span>Heslo</span><input type="password" name="pw" autocomplete="current-password" required></label>
<label class="radio"><input type="checkbox" name="remember"> Zapamatovat na tomto zařízení</label>
<p class="error" hidden></p>
<div class="actions"><button value="cancel" formnovalidate>Zrušit</button><button class="primary" value="ok">Přihlásit</button></div>
</form>`;
document.body.append(dlg);
const form = dlg.querySelector("form");
const pw = form.pw;
const err = dlg.querySelector(".error");
const ok = form.querySelector("button[type=submit]");
const eye = form.querySelector(".eye");
const showError = (msg) => {
err.textContent = msg;
err.hidden = !msg;
pw.toggleAttribute("aria-invalid", Boolean(msg));
};
eye.addEventListener("click", () => {
const show = pw.type === "password";
pw.type = show ? "text" : "password";
eye.innerHTML = show ? EYE_OFF : EYE;
eye.setAttribute("aria-pressed", String(show));
eye.title = eye.ariaLabel = show ? "Skrýt heslo" : "Zobrazit heslo";
pw.focus();
});
pw.addEventListener("input", () => showError(""));
form.querySelector("[data-cancel]").addEventListener("click", () => dlg.close("cancel"));
form.addEventListener("submit", async (e) => {
if (e.submitter?.value !== "ok") return;
e.preventDefault();
if (!pw.value) { showError("Zadejte heslo."); pw.focus(); return; }
ok.disabled = true;
ok.textContent = "Ověřuji…";
try {
await login(pw.value, form.remember.checked);
await login(form.pw.value, form.remember.checked);
dlg.close("ok");
} catch (ex) {
showError(ex.status === 401 ? "Heslo nesouhlasí, zkuste to znovu." : ex.message);
pw.select();
pw.focus();
} finally {
ok.disabled = false;
ok.textContent = "Přihlásit";
err.textContent = ex.message;
err.hidden = false;
}
});
dlg.addEventListener("close", () => { dlg.remove(); resolve(dlg.returnValue === "ok"); });
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.
export async function withLogin(fn, reason) {
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); }
.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(400px, calc(100vw - 32px)); }
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 h2 { margin: 0 0 8px; font-size: 18px; }
dialog::backdrop { background: rgba(0, 0, 0, 0.4); }
@ -320,144 +320,31 @@ form.busy .dropzone, form.busy .thumb-tools { pointer-events: none; opacity: 0.6
.meta-row .grow { flex: 1 1 260px; }
.field.toggle { display: flex; align-items: center; gap: 8px; padding-bottom: 8px; }
.field.toggle span { margin: 0; }
.field.toggle input { accent-color: var(--accent); }
.check { display: inline-flex; align-items: center; gap: 8px; cursor: pointer; }
.check input { width: 18px; height: 18px; margin: 0; accent-color: var(--accent); }
.notice { background: var(--hl); border-radius: 8px; padding: 8px 12px; font-size: 14px; }
button.quiet { border-color: transparent; background: transparent; color: var(--muted); }
button.quiet:hover { color: var(--accent); }
/* login dialog */
dialog.login .field { margin-bottom: 12px; }
.pw-field { position: relative; display: block; }
.pw-field input { padding-right: 44px; }
.pw-field input[aria-invalid] { border-color: var(--accent); box-shadow: 0 0 0 1px var(--accent); }
.pw-field .eye {
position: absolute; right: 4px; top: 50%; transform: translateY(-50%);
display: grid; place-items: center; width: 36px; height: 32px; padding: 0;
border: 0; background: transparent; color: var(--muted);
.editor { display: grid; grid-template-columns: minmax(0, 1fr) minmax(300px, 0.8fr); gap: 16px; align-items: start; }
.editor textarea {
height: calc(100vh - 230px);
min-height: 360px;
font-family: "Courier Prime", ui-monospace, monospace;
font-size: 15px;
line-height: 1.45;
resize: vertical;
tab-size: 4;
}
.pw-field .eye:hover, .pw-field .eye[aria-pressed="true"] { color: var(--accent); }
dialog.login .check { margin: 2px 0 4px; font-size: 14.5px; }
dialog.login .error { margin: 10px 0 0; font-size: 14px; }
dialog.login .actions { margin-top: 16px; }
/* editor */
.review-bar {
display: flex; align-items: center; gap: 12px; flex-wrap: wrap;
margin: 4px 0 12px; padding: 10px 14px; border-radius: 10px;
background: var(--hl); border: 1px solid var(--hl-edge);
}
.review-bar span { flex: 1; font-weight: 600; }
details.checks { margin: 0 0 14px; font-size: 14px; }
details.checks summary { cursor: pointer; }
details.checks ul { margin: 6px 0 10px; padding-left: 18px; max-height: 220px; overflow-y: auto; }
.editor {
display: grid;
grid-template-columns: 88px minmax(0, 1fr) minmax(0, 1.1fr);
gap: 16px;
align-items: start;
}
.editor.no-photos { grid-template-columns: 88px minmax(0, 1fr); }
.editor.busy { opacity: 0.5; pointer-events: none; }
.page-list { position: sticky; top: 12px; display: grid; gap: 8px; }
.page-list ol {
list-style: none; margin: 0; padding: 0;
display: grid; gap: 4px; max-height: calc(100vh - 140px); overflow-y: auto;
}
.page-list ol button {
position: relative; width: 100%; padding: 6px 4px; font-size: 14px; text-align: center;
display: flex; justify-content: center; align-items: center; gap: 4px;
}
.page-list ol button.current { border-color: var(--accent); box-shadow: inset 0 0 0 1px var(--accent); color: var(--accent); }
.page-list ol button.missing { border-style: dashed; color: var(--muted); font-weight: 400; }
.page-list ol button.failed { border-color: var(--accent); }
.page-list .count {
min-width: 18px; padding: 0 5px; border-radius: 999px; font-size: 11px; line-height: 18px;
background: var(--hl); color: var(--fg); border: 1px solid var(--hl-edge);
}
.page-list .count.bad { background: var(--accent); border-color: var(--accent); color: #fff; }
.page-list-tools { display: grid; gap: 4px; }
.page-list-tools > * { padding: 6px 4px; font-size: 13px; text-align: center; }
.page-list-tools .busy { opacity: 0.6; pointer-events: none; }
.page-photo { position: sticky; top: 12px; }
.photo-frame {
max-height: calc(100vh - 80px); overflow: auto; cursor: zoom-in;
background: var(--panel); border: 1px solid var(--line); border-radius: 8px;
}
.photo-frame img { display: block; width: 100%; height: auto; }
.photo-frame.zoomed { cursor: zoom-out; }
.photo-frame.zoomed img { width: 220%; max-width: none; }
.photo-empty { padding: 48px 16px; text-align: center; margin: 0; }
.photo-pick { display: inline-flex; align-items: center; gap: 6px; margin-top: 6px; }
.photo-pick select { width: auto; padding: 2px 6px; }
.page-head { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; margin-bottom: 8px; }
.page-head .grow { flex: 1; }
.page-head > button { padding: 6px 10px; font-size: 14px; }
.page-num { display: inline-flex; align-items: center; gap: 6px; font-weight: 700; }
.page-num input { width: 5.5em; padding: 5px 8px; font-weight: 700; text-align: center; }
.page-head .check { font-size: 14px; color: var(--muted); }
.dup-note { margin-bottom: 8px; padding: 8px 12px; border-radius: 8px; background: var(--panel); border: 1px solid var(--line); font-size: 14px; }
.missing-hint { padding: 24px; border: 1px dashed var(--line); border-radius: 8px; text-align: center; }
/* textarea over a layer that paints the {uncertain} words; both must wrap identically */
.hl-wrap { position: relative; }
.hl-back, .hl-wrap textarea {
margin: 0; padding: 12px 14px; border: 1px solid var(--line); border-radius: 8px;
font-family: "Courier Prime", ui-monospace, monospace; font-size: 15px; line-height: 1.5;
white-space: pre-wrap; overflow-wrap: break-word; word-break: normal; tab-size: 4; letter-spacing: 0;
}
.hl-back { position: absolute; inset: 0; color: transparent; border-color: transparent; pointer-events: none; overflow: hidden; }
.hl-back mark { color: transparent; background: var(--hl); border-radius: 3px; box-shadow: 0 0 0 1px var(--hl-edge); }
.hl-wrap textarea {
position: relative; display: block; width: 100%; min-height: 320px;
background: transparent; color: var(--fg); resize: none; overflow: hidden;
}
.hl-wrap { background: var(--bg); border-radius: 8px; }
.editor-side { position: sticky; top: 12px; display: grid; gap: 14px; }
.photo-nav { display: flex; align-items: center; gap: 6px; margin-bottom: 6px; font-size: 14px; }
.photo-nav span { flex: 1; text-align: center; color: var(--muted); }
.photo-nav button { padding: 4px 10px; font-size: 13px; }
.photo img { display: block; width: 100%; max-height: calc(100vh - 330px); object-fit: contain; background: var(--panel); border: 1px solid var(--line); border-radius: 8px; }
.checks h2 { font-size: 16px; margin: 0 0 4px; }
.checks ul { margin: 6px 0 10px; padding-left: 18px; max-height: 220px; overflow-y: auto; font-size: 14px; }
.help { font-size: 14px; margin-top: 8px; }
.help td { padding: 2px 10px 2px 0; vertical-align: top; }
.danger { margin-top: 32px; }
.danger button { color: var(--accent); border-color: var(--accent); background: transparent; }
/* review of uncertain words */
dialog.review {
width: min(1100px, calc(100vw - 24px)); max-height: calc(100vh - 24px); padding: 0;
border: 1px solid var(--line); border-radius: 12px; background: var(--bg); color: var(--fg);
}
.review-grid { display: grid; grid-template-columns: minmax(0, 1.2fr) minmax(300px, 1fr); min-height: min(640px, calc(100vh - 26px)); }
.review-photo { position: relative; overflow: auto; background: var(--panel); border-right: 1px solid var(--line); max-height: calc(100vh - 26px); }
.review-photo img { display: block; width: 180%; max-width: none; }
.review-band { position: absolute; left: 0; width: 180%; background: rgba(224, 180, 0, 0.18); border-block: 2px solid var(--hl-edge); pointer-events: none; }
.review-card { padding: 18px 20px; display: flex; flex-direction: column; gap: 10px; }
.review-top { display: flex; align-items: center; justify-content: space-between; }
.review-top h2 { margin: 0; font-size: 18px; }
.review-context {
font-family: "Courier Prime", ui-monospace, monospace; font-size: 15px; line-height: 1.6;
padding: 10px 12px; border-radius: 8px; background: var(--panel); overflow-wrap: anywhere;
}
.ctx-line { color: var(--muted); }
.ctx-line.main { color: var(--fg); }
.review-context mark { background: var(--hl); color: var(--fg); padding: 0 2px; border-radius: 3px; box-shadow: 0 0 0 2px var(--hl-edge); }
#review-fix { font-size: 18px; font-family: "Courier Prime", ui-monospace, monospace; }
.review-alts { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; }
.chip { padding: 4px 10px; border-radius: 999px; font-family: "Courier Prime", ui-monospace, monospace; font-weight: 400; }
.review-card .actions { margin-top: 6px; }
#review-item, #review-done { display: flex; flex-direction: column; gap: 10px; }
#review-item[hidden], #review-done[hidden] { display: none; }
@media (max-width: 1000px) {
.editor, .editor.no-photos { grid-template-columns: minmax(0, 1fr); }
.page-list { position: static; }
.page-list ol { display: flex; overflow-x: auto; max-height: none; padding-bottom: 4px; }
.page-list ol button { min-width: 48px; }
.page-list-tools { display: flex; }
.page-photo { position: static; }
.photo-frame { max-height: 60vh; }
.review-grid { grid-template-columns: minmax(0, 1fr); }
.review-photo { max-height: 42vh; border-right: 0; border-bottom: 1px solid var(--line); }
@media (max-width: 900px) {
.editor { grid-template-columns: minmax(0, 1fr); }
.editor-side { position: static; order: -1; }
.photo img { max-height: 60vh; }
.editor textarea { height: 70vh; }
}
/* ---- PDF export (print) ----

View file

@ -11,9 +11,9 @@
<body class="page-edit">
<header class="topbar">
<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" id="auth">
<span class="muted small" id="saved" role="status"></span>
<button id="save" class="primary" title="Uložit (Ctrl+S)">Uložit</button>
<div class="topbar-actions">
<span class="muted small" id="saved"></span>
<button id="save" class="primary">Uložit</button>
</div>
</header>
<main class="wrap wide">
@ -29,101 +29,44 @@
<label class="field toggle"><input type="checkbox" id="published"> <span>Zveřejněno</span></label>
</div>
<div class="review-bar" id="review-bar" hidden>
<span id="review-count"></span>
<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>
<div class="editor">
<section class="editor-text">
<textarea id="text" spellcheck="false" aria-label="Text hry"></textarea>
<details class="help">
<summary>Jak se text zapisuje</summary>
<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>&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>#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>.</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>
<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>
<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>
</details>
</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 class="danger">
<button id="delete">Smazat celou hru</button>
<button id="delete">Smazat hru</button>
</div>
</aside>
</div>
</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>
</html>

View file

@ -1,334 +1,98 @@
// Play editor: one original page at a time, next to its photo, plus a
// click-through review of the words the model was unsure of.
//
// The play is still stored as one markup file; here it is split at the page
// markers (=N / !N) into page objects and joined back on save. meta.photos
// says which photo belongs to which page marker, in text order.
import { api, withLogin, getPassword, askPassword, authButton, esc, $ } from "./api.js";
import { parsePlay, speakers, lint, plainText } from "./parse.js";
import { toJpeg } from "./photos.js";
import { api, withLogin, getPassword, askPassword, esc, $ } from "./api.js";
import { parsePlay, speakers, lint } from "./parse.js";
const id = new URLSearchParams(location.search).get("id");
const enc = encodeURIComponent(id);
let cfg, meta;
let pages = []; // [{ key, num, missing, body, photo }]
let cur = 0;
let saved = { text: "", photos: "" };
let meta;
let savedText = "";
let img = 1;
let leaving = false;
let nextKey = 1;
// ---- 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
const dirty = () => $("text").value !== savedText
|| $("title").value !== meta.title || $("note").value !== (meta.note || "") || $("published").checked !== meta.published;
const markSaved = () => { saved = { text: joinPages(), photos: JSON.stringify(photoList()) }; };
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 showError(msg) { $("error").textContent = msg; $("error").hidden = !msg; if (msg) $("error").scrollIntoView({ block: "nearest" }); }
function changed() {
$("saved").textContent = isDirty() ? "Neuložené změny" : $("saved").dataset.at || "";
}
// ---- photos (drafts' photos need the password header, so fetch them as blobs)
const photoUrls = new Map();
function photoUrl(n) {
if (!photoUrls.has(n))
photoUrls.set(n, api(`plays/${enc}/images/${n}`, { raw: true }).then((r) => r.blob()).then((b) => URL.createObjectURL(b))
.catch((err) => { photoUrls.delete(n); throw err; }));
return photoUrls.get(n);
}
async function setPhoto(imgEl, n) {
imgEl.removeAttribute("src");
imgEl.dataset.n = n || "";
if (!n) return;
try {
const url = await photoUrl(n);
if (imgEl.dataset.n === String(n)) imgEl.src = url; // still the wanted photo
} catch (err) { showError(`Fotku se nepodařilo načíst: ${err.message}`); }
}
// ---- rendering
function renderList() {
$("page-list").innerHTML = pages.map((p, i) => {
const n = uncertainIn(p.body).length;
const cls = [i === cur && "current", p.missing && "missing", isFailed(p) && "failed"].filter(Boolean).join(" ");
const title = p.missing ? "chybí v originále" : isFailed(p) ? "přepis se nepovedl" : n ? `${n} nejistých slov` : "";
return `<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 v = ta.value;
let html = "";
let last = 0;
for (const m of v.matchAll(UNC)) {
html += esc(v.slice(last, m.index)) + `<mark>${esc(m[0])}</mark>`;
last = m.index + m[0].length;
}
$("hl-back").innerHTML = html + esc(v.slice(last)) + "\n ";
ta.style.height = "auto";
ta.style.height = `${Math.max(ta.scrollHeight, 320)}px`;
}
function showError(msg) { $("error").textContent = msg; $("error").hidden = !msg; }
function check() {
const text = joinPages();
const parsed = parsePlay(text, { plain: true });
const real = parsed.filter((p) => !p.missing);
const cast = speakers(parsed);
const unsure = pages.reduce((n, p) => n + (p.missing ? 0 : uncertainIn(p.body).length), 0);
let pages;
try { pages = parsePlay($("text").value); }
catch (err) { $("summary").textContent = err.message; return; }
const real = pages.filter((p) => !p.missing);
const cast = speakers(pages);
$("summary").textContent = `${real.length} stran, ${cast.length} postav: ${cast.map((c) => c.name).join(", ") || "—"}`;
const issues = [
...pages.flatMap((p, i) => (isFailed(p) ? [{ i, message: "přepis se nepovedl" }] : [])),
...lint(parsePlay(text)).map((x) => ({ i: pages.findIndex((p) => p.num === x.page), message: x.message })),
...(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({ i: pages.findIndex((p) => plainText(p.body).split("\n").some((l) => l.trim() === `@${c.name}`)), message: `postava „${c.name}“ mluví jen jednou – překlep?` });
$("summary").textContent = `${plural(real.length, "strana", "strany", "stran")}, ${plural(cast.length, "postava", "postavy", "postav")}`
+ `${cast.length ? `: ${cast.map((c) => c.name).join(", ")}` : ""}${issues.length ? ` · ${plural(issues.length, "upozornění", "upozornění", "upozornění")}` : ""}`;
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, k) => `<li><button class="link" data-k="${k}">${x.i >= 0 ? `str. ${esc(label(pages[x.i]))}: ` : ""}${esc(x.message)}</button></li>`).join("")
? 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-k]");
if (b && issues[b.dataset.k].i >= 0) go(issues[b.dataset.k].i);
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 && cfg.transcription);
$("review-bar").hidden = !unsure;
$("review-count").textContent = unsure === 1 ? "Model si není jistý 1 slovem." : `Model si není jistý ${unsure} slovy.`;
changed();
$("retry").hidden = !(meta.failedPages?.length && !meta.edited);
}
function go(i) {
if (!pages.length) return;
cur = Math.max(0, Math.min(pages.length - 1, i));
renderList();
renderPage();
// Select `needle` (or the line containing `inner`) in the textarea and scroll it into view.
function jumpTo(needle, inner) {
const ta = $("text");
const v = ta.value;
let at = -1;
if (needle) at = needle.startsWith("=") ? (`\n${v}`).indexOf(`\n${needle}\n`) : v.indexOf(needle);
if (at < 0 && inner) at = v.indexOf(inner);
if (at < 0) return;
const len = (needle && v.startsWith(needle, at) ? needle : inner || "").length;
ta.focus();
ta.setSelectionRange(at, at + len);
// scroll: put the selected line about a third from the top
const lineNo = v.slice(0, at).split("\n").length - 1;
const lh = parseFloat(getComputedStyle(ta).lineHeight) || 20;
ta.scrollTop = Math.max(0, lineNo * lh - ta.clientHeight / 3);
}
// 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);
// Drafts' photos need the password header, which <img src> can't send, so fetch them as blobs.
let imgUrl = null;
async function showImage(n) {
if (!meta.images) return;
img = Math.min(meta.images, Math.max(1, n));
$("photo-box").hidden = false;
const shown = img;
api(`plays/${enc}/images/${img}`, { raw: true }).then((r) => r.blob()).then((b) => {
if (shown !== img) return; // user already moved on
if (imgUrl) URL.revokeObjectURL(imgUrl);
imgUrl = URL.createObjectURL(b);
$("img").src = imgUrl;
}).catch((err) => showError(`Fotku se nepodařilo načíst: ${err.message}`));
$("img-label").textContent = `fotka ${img} / ${meta.images}`;
$("img-prev").disabled = img === 1;
$("img-next").disabled = img === meta.images;
}
// 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 };
// The page number the model read from photo n, to find it in the text.
function pageOfImage(n) {
const text = $("text").value;
const markers = [...text.matchAll(/^=(.+)$/gm)].map((m) => m[1]);
return markers[n - 1];
}
// ---- 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() {
showError("");
$("save").disabled = true;
try {
await withLogin(async () => {
const text = joinPages();
if (text !== saved.text) meta = await api(`plays/${enc}/text`, { method: "PUT", body: text, type: "text/plain; charset=utf-8" });
meta = await api(`plays/${enc}`, { method: "PATCH", body: { title: $("title").value, note: $("note").value, published: $("published").checked, photos: photoList(), duplicates: meta.duplicates } });
markSaved();
if ($("text").value !== savedText) {
meta = await api(`plays/${enc}/text`, { method: "PUT", body: $("text").value, type: "text/plain; charset=utf-8" });
savedText = $("text").value;
}
meta = await api(`plays/${enc}`, { method: "PATCH", body: { title: $("title").value, note: $("note").value, published: $("published").checked } });
});
$("saved").dataset.at = `Uloženo ${new Date().toLocaleTimeString("cs-CZ", { hour: "2-digit", minute: "2-digit" })}`;
$("saved").textContent = `Uloženo ${new Date().toLocaleTimeString("cs-CZ", { hour: "2-digit", minute: "2-digit" })}`;
check();
} catch (err) {
showError(`Uložení se nepovedlo: ${err.message}`);
@ -337,48 +101,8 @@ 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() {
$("editor").classList.add("busy");
$("text").readOnly = true;
$("save").disabled = true;
$("progress").hidden = false;
while (meta.status === "processing") {
@ -389,99 +113,37 @@ async function waitForJob() {
meta = await api(`plays/${enc}`);
}
$("progress").hidden = true;
$("editor").classList.remove("busy");
$("text").readOnly = false;
$("save").disabled = false;
await loadText();
savedText = await api(`plays/${enc}/text`);
$("text").value = savedText;
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();
}
// ---- wiring
function wire() {
$("page-list").addEventListener("click", (e) => { const b = e.target.closest("button[data-i]"); if (b) go(Number(b.dataset.i)); });
$("prev").addEventListener("click", () => go(cur - 1));
$("next").addEventListener("click", () => go(cur + 1));
async function main() {
if (!id) { location.replace("./"); return; }
if (!getPassword() && !(await askPassword("Upravovat hry může jen ten, kdo zná heslo."))) { location.replace("./"); return; }
meta = await withLogin(() => api(`plays/${enc}`));
$("preview").href = `read.html?hra=${enc}`;
$("title").value = meta.title;
$("note").value = meta.note || "";
$("published").checked = meta.published;
document.title = `${meta.title} – úpravy`;
savedText = await api(`plays/${enc}/text`);
$("text").value = savedText;
if (meta.images) showImage(1);
check();
let timer;
$("text").addEventListener("input", () => {
pages[cur].body = $("text").value;
paintText();
clearTimeout(timer);
timer = setTimeout(() => { renderList(); check(); }, 400);
changed();
});
$("num").addEventListener("change", () => {
pages[cur].num = $("num").value.trim().replace(/^[=!]/, "") || "?";
sortPages();
renderList(); renderPage(); check();
});
$("missing").addEventListener("change", () => { pages[cur].missing = $("missing").checked; renderList(); renderPage(); check(); });
$("photo-select").addEventListener("change", () => { pages[cur].photo = Number($("photo-select").value) || null; renderPage(); changed(); });
$("photo-frame").addEventListener("click", (e) => {
const f = $("photo-frame");
if ($("img").hidden) return;
const r = $("img").getBoundingClientRect();
const fx = (e.clientX - r.left) / r.width, fy = (e.clientY - r.top) / r.height;
f.classList.toggle("zoomed");
if (f.classList.contains("zoomed")) f.scrollTo(fx * $("img").clientWidth - f.clientWidth / 2, fy * $("img").clientHeight - f.clientHeight / 2);
});
$("dup-note").addEventListener("click", (e) => {
const b = e.target.closest("button[data-dup]");
if (!b) return;
const p = pages[cur];
const d = meta.duplicates.find((x) => x.image === Number(b.dataset.dup) && x.page === p.num);
// swap: the photo shown now becomes the left-out one
[d.image, p.photo] = [p.photo, d.image];
[d.body, p.body] = [p.body, d.body];
d.kept = p.photo;
renderList(); renderPage(); check();
});
$("reread").addEventListener("click", reread);
$("remove").addEventListener("click", () => {
const p = pages[cur];
if (p.body && !confirm(`Smazat stranu ${label(p)} i s jejím textem?`)) return;
if (pages.length === 1) Object.assign(p, { num: "1", missing: false, body: "", photo: null }); // keep one page to type into
else pages.splice(cur, 1);
go(Math.min(cur, pages.length - 1));
check();
});
$("add-blank").addEventListener("click", () => {
const n = pageInt(pages[cur]?.num || "");
insertPage({ key: nextKey++, num: n !== null ? String(n + 1) : "?", missing: false, body: "", photo: null });
renderList(); renderPage(); check();
$("text").focus();
});
$("add-photo").addEventListener("change", (e) => { const f = e.target.files[0]; e.target.value = ""; if (f) addFromPhoto(f); });
$("title").addEventListener("input", changed);
$("note").addEventListener("input", changed);
$("published").addEventListener("change", changed);
$("save").addEventListener("click", save);
document.addEventListener("keydown", (e) => {
$("text").addEventListener("input", () => { clearTimeout(timer); timer = setTimeout(check, 400); });
$("text").addEventListener("keydown", (e) => {
if ((e.ctrlKey || e.metaKey) && e.key === "s") { e.preventDefault(); save(); }
if (e.altKey && !$("review").open && (e.key === "ArrowLeft" || e.key === "ArrowRight")) { e.preventDefault(); go(cur + (e.key === "ArrowLeft" ? -1 : 1)); }
});
// review
$("review-start").addEventListener("click", () => openReview());
$("review-form").addEventListener("submit", (e) => { e.preventDefault(); if (review.items[review.i]) resolveItem($("review-fix").value); });
$("review-alts").addEventListener("click", (e) => { const b = e.target.closest("[data-alt]"); if (b) resolveItem(b.dataset.alt); });
$("review-skip").addEventListener("click", () => { review.i++; showReviewItem(); });
$("review-prev").addEventListener("click", () => { review.i = Math.max(0, review.i - 1); showReviewItem(); });
$("review-again").addEventListener("click", () => openReview(true));
$("review-finish").addEventListener("click", closeReview);
$("review-close").addEventListener("click", closeReview);
$("review").addEventListener("cancel", (e) => { e.preventDefault(); closeReview(); });
$("save").addEventListener("click", save);
$("img-prev").addEventListener("click", () => showImage(img - 1));
$("img-next").addEventListener("click", () => showImage(img + 1));
$("img-jump").addEventListener("click", () => { const p = pageOfImage(img); if (p) jumpTo(`=${p}`); });
$("retry").addEventListener("click", async () => {
try {
meta = await withLogin(() => api(`plays/${enc}/transcribe`, { method: "POST" }));
@ -496,22 +158,8 @@ function wire() {
location.replace("./");
} catch (err) { showError(err.message); }
});
window.addEventListener("beforeunload", (e) => { if (!leaving && meta.status !== "processing" && isDirty()) e.preventDefault(); });
}
window.addEventListener("beforeunload", (e) => { if (!leaving && meta.status !== "processing" && dirty()) 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();
}

View file

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

View file

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

View file

@ -1,4 +1,4 @@
// Parser for the play markup (format documented in AGENTS.md).
// Parser for the play markup in public/plays/*.txt (format documented in AGENTS.md).
//
// Result: [{ num, missing, blocks }] where a block is one of
// { type: "speech", speaker, cont, parts } cont = continues from the previous page
@ -8,12 +8,7 @@
// { type: "gap" } explicit blank line
// and a part is { kind: "text" | "stage" | "verse", lines: [string] }.
// Uncertain readings: "{word}" or "{word|other reading}" (the first one is used).
export const UNCERTAIN = /\{([^{}\n]*)\}/g;
export const plainText = (s) => s.replace(/\{([^{}|\n]*)(?:\|[^{}\n]*)?\}/g, "$1").replace(/ ?\[\?\]/g, "");
// plain: drop the uncertainty marks (for reading); the editor keeps them.
export function parsePlay(source, { plain = false } = {}) {
export function parsePlay(source) {
const pages = [];
let page = null;
let block = null; // block currently receiving lines
@ -28,8 +23,7 @@ export function parsePlay(source, { plain = false } = {}) {
else parts.push({ kind, lines: [line] });
};
for (let raw of source.replace(/\r/g, "").split("\n")) {
if (plain) raw = plainText(raw);
for (const raw of source.replace(/\r/g, "").split("\n")) {
if (raw.trim() === "") continue;
if (raw.startsWith("=") || raw.startsWith("!")) {
@ -118,7 +112,7 @@ export function lint(pages) {
const out = [];
const seen = new Set();
for (const p of pages) {
if (p.num === "?" || p.num === "") out.push({ page: p.num, message: "Strana nemá číslo." });
if (p.num === "?") out.push({ page: p.num, message: "Text před první značkou strany (=číslo)." });
if (seen.has(p.num)) out.push({ page: p.num, message: `Strana ${p.num} je v textu dvakrát.` });
seen.add(p.num);
for (const b of p.blocks) {
@ -126,7 +120,7 @@ export function lint(pages) {
if (!b.parts) continue;
for (const part of b.parts)
for (const line of part.lines)
if (/[{}]/.test(line.replace(UNCERTAIN, ""))) out.push({ page: p.num, message: `Neuzavřená složená závorka: „${line.trim()}“` });
if (line.includes("[?]")) out.push({ page: p.num, message: `Nejisté čtení: „${line.trim()}“` });
}
}
return out;

View file

@ -1,36 +0,0 @@
// 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").hidden = false;
}
pages = parsePlay(await api(`plays/${encodeURIComponent(id)}/text`), { plain: true });
pages = parsePlay(await api(`plays/${encodeURIComponent(id)}/text`));
fillRoles();
renderScript();
save();

View file

@ -7,7 +7,7 @@ import { createHash, timingSafeEqual } from "node:crypto";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { createStore, NotFound } from "./store.mjs";
import { splitPage, assemble, normalizeSpeakers } from "./transcribe.mjs";
import { splitPage, assemble } from "./transcribe.mjs";
import { makeProvider } from "./providers.mjs";
const here = path.dirname(fileURLToPath(import.meta.url));
@ -56,8 +56,8 @@ async function readBody(req, limit) {
}
return Buffer.concat(chunks);
}
async function readJson(req, limit = 64 * 1024) {
try { return JSON.parse((await readBody(req, limit)).toString("utf8") || "{}"); }
async function readJson(req) {
try { return JSON.parse((await readBody(req, 64 * 1024)).toString("utf8") || "{}"); }
catch (err) { if (err instanceof HttpError) throw err; throw new HttpError(400, "Neplatný JSON."); }
}
@ -122,9 +122,8 @@ export async function runJob(store, id, provider) {
await Promise.all(Array.from({ length: config.concurrency }, worker));
const failed = results.filter((r) => r.error).length;
const { text, photos, duplicates } = assemble(results);
await store.setText(id, text);
await store.updateMeta(id, () => ({ status: "draft", progress: null, failed, photos, duplicates, model: `${provider.name}:${provider.model}` }));
await store.setText(id, assemble(results));
await store.updateMeta(id, () => ({ status: "draft", progress: null, failed, model: `${provider.name}:${provider.model}` }));
} catch (err) {
console.error(`[${id}] job failed:`, err);
await store.updateMeta(id, () => ({ status: "draft", progress: null, jobError: String(err?.message || err) })).catch(() => {});
@ -134,16 +133,11 @@ export async function runJob(store, id, provider) {
}
// ---- API
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 }] : [])),
});
const publicMeta = ({ pages, ...m }) => ({ ...m, failedPages: (pages || []).flatMap((p, i) => (p?.error ? [{ image: i + 1, error: p.error }] : [])) });
async function api(req, res, store, provider, parts) {
const method = req.method;
const [, , id, sub, n] = parts; // ["", "plays", id, sub, n, action]
const [, , id, sub, n] = parts; // ["", "plays", id, sub, n]
if (parts[1] === "config" && method === "GET")
return send(res, 200, { uploads: Boolean(config.password), transcription: Boolean(provider), model: provider?.model || null, maxPages: config.maxPages });
@ -176,24 +170,11 @@ async function api(req, res, store, provider, parts) {
if (method === "GET") return send(res, 200, publicMeta(meta));
if (method === "PATCH") {
await requireAuth(req);
const body = await readJson(req, config.maxTextBytes);
const body = await readJson(req);
const patch = {};
if (typeof body.title === "string" && body.title.trim()) patch.title = body.title.trim().slice(0, 200);
if (typeof body.note === "string") patch.note = body.note.trim().slice(0, 500);
if (typeof body.published === "boolean") patch.published = body.published;
// which photo belongs to which page marker of the text (the editor keeps this in step)
if (Array.isArray(body.photos)) {
if (body.photos.length > 2000 || !body.photos.every((p) => p === null || (Number.isInteger(p) && p >= 1 && p <= meta.images)))
throw new HttpError(400, "Neplatné přiřazení fotek.");
patch.photos = body.photos;
}
// left-out repeat photos; the editor swaps them with the page's chosen photo
if (Array.isArray(body.duplicates)) {
const ok = (d) => d && Number.isInteger(d.image) && d.image >= 1 && d.image <= meta.images && Number.isInteger(d.kept)
&& typeof d.page === "string" && d.page.length <= 20 && typeof d.body === "string" && d.body.length <= 50_000;
if (body.duplicates.length > config.maxPages || !body.duplicates.every(ok)) throw new HttpError(400, "Neplatný seznam opakovaných fotek.");
patch.duplicates = body.duplicates.map(({ image, page, kept, body: text }) => ({ image, page, kept, body: text }));
}
return send(res, 200, publicMeta(await store.updateMeta(id, () => patch)));
}
if (method === "DELETE") {
@ -215,25 +196,7 @@ async function api(req, res, store, provider, parts) {
}
}
// 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]) {
if (sub === "images" && 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 === "PUT") {

View file

@ -4,9 +4,7 @@
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.
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.
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 [?].
Output only the markup, nothing else: no commentary, no code fences.
@ -26,8 +24,8 @@ Example:
=12
dobře.Ale proč právě já ?
@Továrník
Nu,vidíte, už to {začíná|začalo} ve vás fungovat.Ano,
roky.Nyní je rok {1931}.
Nu,vidíte, už to začíná ve vás fungovat.Ano,
roky.Nyní je rok 1931.
.
>(Rozhovor je přerušen příchodem strážníka
> a mladé dámy)

View file

@ -89,11 +89,7 @@ export function createStore(dataDir) {
if (!Number.isInteger(n) || n < 1 || n > 999) throw new NotFound(`${id}/${n}`);
return path.join(dir(id), "img", `${String(n).padStart(3, "0")}.jpg`);
},
async putImage(id, n, buf) {
const file = this.imagePath(id, n);
await mkdir(path.dirname(file), { recursive: true }); // seeded plays come without img/
await atomicWrite(file, buf);
},
async putImage(id, n, buf) { await atomicWrite(this.imagePath(id, n), buf); },
async getImage(id, n) {
try { return await readFile(this.imagePath(id, n)); }
catch (err) { if (err.code === "ENOENT") throw new NotFound(`${id}/${n}`); throw err; }

View file

@ -1,11 +1,5 @@
// Stitch per-page transcriptions (see providers.mjs) into one play file.
// Uncertain readings are marked "{word}" or "{word|other reading}". Older
// transcriptions used "word[?]"; convert those so the editor finds them too.
export function migrateUncertain(text) {
return text.replace(/([\p{L}\p{N}'’-]+)([.,;:!?…]*) ?\[\?\]/gu, "{$1}$2").replace(/ ?\[\?\]/g, "");
}
// Split model output into { num, body }: the first "=N" line is the page number.
export function splitPage(text) {
const lines = text.replace(/\r/g, "").replace(/^```\w*\n|\n```$/g, "").split("\n");
@ -17,7 +11,7 @@ export function splitPage(text) {
}
// The page structure is ours to set; drop any further page markers the model wrote.
const body = lines.filter((l) => !/^[=!]/.test(l)).join("\n").trim();
return { num, body: migrateUncertain(body) };
return { num, body };
}
const nameKey = (n) => n.normalize("NFD").replace(/\p{M}/gu, "").toLowerCase().replace(/[^\p{L}\p{N}]+/gu, " ").trim();
@ -33,8 +27,7 @@ export function normalizeSpeakers(bodies) {
const variants = new Map(); // key -> Map(spelling -> count)
const fromCaps = new Set(); // spellings we made up by Title-casing
const clean = (raw) => {
// an uncertain name "{Lída}" counts as "Lída"
const n = raw.replace(/\{([^{}|]*)(\|[^{}]*)?\}/g, "$1").trim().replace(/[:.]+$/, "").trim();
const n = raw.trim().replace(/[:.]+$/, "").trim();
if (n.length > 1 && n === n.toLocaleUpperCase("cs") && n !== n.toLocaleLowerCase("cs")) {
fromCaps.add(titleCase(n));
return titleCase(n);
@ -64,66 +57,23 @@ export function normalizeSpeakers(bodies) {
}).join("\n"));
}
export const countUncertain = (body) => (body.match(/\{[^{}\n]*\}/g) || []).length;
const pageInt = (num) => (/^\d+/.test(num || "") ? parseInt(num, 10) : null);
// Build the play from per-photo results [{ num, body } | { error } | null], in upload order.
//
// Pages are sorted by the number the model read off each photo, so upload order
// doesn't matter. A photo without a readable number stays right after the photo
// uploaded before it. Two photos of the same page (an accidental re-upload or a
// retake) keep only the better transcription: fewer uncertain words, then more text.
// Numeric gaps become "missing page" markers.
//
// Returns { text, photos, duplicates }:
// photos[i] the photo (1-based) shown with the i-th page marker of text, or null
// duplicates [{ image, page, kept, body }] photos left out as repeats of a page
export function assemble(results) {
const bodies = normalizeSpeakers(results.map((r) => r?.body || ""));
let entries = results.map((r, i) => ({ image: i + 1, num: r?.error ? null : r?.num, n: r?.error ? null : pageInt(r?.num), body: bodies[i], error: r?.error }));
// sort key: the page number; unnumbered photos follow their upload predecessor
let anchor = 0;
for (const e of entries) {
if (e.n !== null) anchor = e.n;
e.key = e.n !== null ? e.n : anchor + 0.5;
}
entries.sort((a, b) => a.key - b.key || (a.n === null) - (b.n === null) || a.image - b.image);
// drop repeats of the same page
const duplicates = [];
const byNum = new Map();
for (const e of entries) {
if (e.n === null) continue;
const kept = byNum.get(e.num);
if (!kept) { byNum.set(e.num, e); continue; }
const better = countUncertain(e.body) - countUncertain(kept.body) || kept.body.length - e.body.length;
const [keep, drop] = better < 0 ? [e, kept] : [kept, e];
byNum.set(e.num, keep);
drop.dropped = true;
duplicates.push({ image: drop.image, page: e.num, kept: keep.image, body: drop.body });
}
for (const d of duplicates) d.kept = byNum.get(d.page).image; // a later, better copy may have won
entries = entries.filter((e) => !e.dropped);
const taken = new Set(entries.filter((e) => e.n !== null).map((e) => e.n));
// Build the play file from per-page results [{ num, body } | { error }], in upload order.
// Pages without a readable number get the next number in sequence; numeric gaps
// between pages become "missing page" markers.
export function assemble(pages) {
const bodies = normalizeSpeakers(pages.map((p) => p.body || ""));
const out = [];
const photos = [];
let prev = null;
for (const e of entries) {
let num = e.num;
let n = e.n;
// guess the number of an unnumbered page if the next number is free
if (n === null && prev !== null && !taken.has(prev + 1)) { n = prev + 1; num = String(n); taken.add(n); }
if (n === null) num = "?";
if (n !== null && prev !== null && n > prev + 1) {
out.push(n === prev + 2 ? `!${prev + 1}` : `!${prev + 1}-${n - 1}`);
photos.push(null);
}
pages.forEach((p, i) => {
let num = p.num && p.num !== "?" ? p.num : null;
if (!num && prev !== null) num = String(prev + 1);
if (!num) num = String(i + 1);
const n = /^\d+$/.test(num) ? Number(num) : null;
if (n !== null && prev !== null && n > prev + 1) out.push(n === prev + 2 ? `!${prev + 1}` : `!${prev + 1}-${n - 1}`);
if (n !== null) prev = n;
out.push(`=${num}`);
photos.push(e.image);
out.push(e.error ? `>(Stranu se nepodařilo přepsat: ${e.error})` : e.body);
}
return { text: out.filter((l) => l !== "").join("\n") + "\n", photos, duplicates };
if (p.error) out.push(`>(Stranu se nepodařilo přepsat: ${p.error})`);
else out.push(bodies[i]);
});
return out.join("\n") + "\n";
}

View file

@ -8,16 +8,14 @@ import { config, createServer } from "../server/main.mjs";
import { createStore } from "../server/store.mjs";
const PASS = "tajne-heslo";
// photo n is a tiny "JPEG" ending in byte n; the stub answers by that byte
const jpeg = (n) => Buffer.from([0xff, 0xd8, 0xff, 0xe0, n]);
const JPEG = jpeg(1);
const replies = { 1: "=-1-\n~JEDNÁNÍ PRVNÍ\n@LÍDA\nDobrý den.", 2: "=2\nještě já.\n@Mise\nAno." };
const provider = { name: "stub", model: "stub-model", transcribe: async (img) => replies[img.at(-1)] };
const JPEG = Buffer.from([0xff, 0xd8, 0xff, 0xe0, 1, 2, 3]);
const replies = ["=-1-\n~JEDNÁNÍ PRVNÍ\n@LÍDA\nDobrý den.", "=2\nještě já.\n@Mise\nAno."];
const provider = { name: "stub", model: "stub-model", transcribe: async () => replies.shift() };
let dir, server, base;
test.before(async () => {
dir = await mkdtemp(path.join(tmpdir(), "tr-"));
Object.assign(config, { dataDir: dir, password: PASS, dailyPageLimit: 4 });
Object.assign(config, { dataDir: dir, password: PASS, dailyPageLimit: 3 });
const store = createStore(dir);
await store.init();
await store.seed(config.seedDir);
@ -36,12 +34,6 @@ test("seeded play is listed and readable", async () => {
assert.match(text, /^!1-4\n=5\n@Mise/);
});
test("a photo can be added to a seeded play (which has no img/ folder)", async () => {
const res = await call("/api/plays/hra-1931/images/1", authed({ method: "PUT", headers: { "content-type": "image/jpeg" }, body: JPEG }));
assert.equal(res.status, 200);
assert.equal((await res.json()).images, 1);
});
test("static files are served with security headers, traversal is refused", async () => {
const res = await call("/");
assert.equal(res.status, 200);
@ -70,7 +62,7 @@ test("upload → transcribe → draft → publish", async () => {
assert.equal((await call(`/api/plays/${id}/images/1`, authed({ method: "PUT", headers: { "content-type": "image/png" }, body: JPEG }))).status, 415);
for (const n of [1, 2]) {
res = await call(`/api/plays/${id}/images/${n}`, authed({ method: "PUT", headers: { "content-type": "image/jpeg" }, body: jpeg(n) }));
res = await call(`/api/plays/${id}/images/${n}`, authed({ method: "PUT", headers: { "content-type": "image/jpeg" }, body: JPEG }));
assert.equal(res.status, 200);
}
res = await call(`/api/plays/${id}/transcribe`, authed({ method: "POST" }));
@ -86,21 +78,13 @@ test("upload → transcribe → draft → publish", async () => {
assert.equal(meta.failed, 0);
const text = await (await call(`/api/plays/${id}/text`, authed())).text();
assert.equal(text, "=1\n~JEDNÁNÍ PRVNÍ\n@Lída\nDobrý den.\n=2\nještě já.\n@Mise\nAno.\n");
assert.deepEqual(meta.photos, [1, 2]);
// the editor can re-read one photo; speaker spellings follow the play
replies[2] = "=2\n@LÍDA\nZnovu {přečteno}.";
res = await call(`/api/plays/${id}/images/2/transcribe`, authed({ method: "POST" }));
assert.deepEqual(await res.json(), { num: "2", body: "@Lída\nZnovu {přečteno}." });
res = await call(`/api/plays/${id}`, authed({ method: "PATCH", body: JSON.stringify({ photos: [2, 9] }) }));
assert.equal(res.status, 400); // there is no photo 9
res = await call(`/api/plays/${id}`, authed({ method: "PATCH", body: JSON.stringify({ published: true }) }));
assert.equal((await res.json()).published, true);
assert.equal((await (await call("/api/plays")).json()).length, 2);
assert.equal((await call(`/api/plays/${id}/images/2`)).status, 200);
// the daily cap (4 pages) is now nearly used up
// the daily cap (3 pages) is now nearly used up
const id2 = (await (await call("/api/plays", authed({ method: "POST", body: JSON.stringify({ title: "Další" }) }))).json()).id;
for (const n of [1, 2]) await call(`/api/plays/${id2}/images/${n}`, authed({ method: "PUT", headers: { "content-type": "image/jpeg" }, body: JPEG }));
res = await call(`/api/plays/${id2}/transcribe`, authed({ method: "POST" }));

View file

@ -17,48 +17,19 @@ test("speaker spellings are unified across pages", () => {
});
test("assemble numbers pages, marks gaps and failed pages", () => {
const { text, photos } = assemble([
const text = assemble([
{ num: "5", body: "@Mise\nAno." },
{ num: "?", body: "dál" },
{ num: "9", body: "@Lída\nNe." },
{ error: "model declined" },
]);
assert.equal(text, "=5\n@Mise\nAno.\n=6\ndál\n!7-8\n=9\n@Lída\nNe.\n=10\n>(Stranu se nepodařilo přepsat: model declined)\n");
assert.deepEqual(photos, [1, 2, null, 3, 4]);
const pages = parsePlay(text);
assert.deepEqual(pages.map((p) => p.num), ["5", "6", "7-8", "9", "10"]);
assert.equal(pages[1].blocks[0].speaker, "Mise"); // continues across the page break
assert.deepEqual(lint(pages), []);
});
test("assemble sorts by page number and drops repeated photos of a page", () => {
const { text, photos, duplicates } = assemble([
{ num: "1", body: "{jedna}" },
{ num: "3", body: "tři" },
{ num: "?", body: "po trojce" }, // no number: stays after the photo uploaded before it
{ num: "2", body: "dva" },
{ num: "1", body: "jedna" }, // retake of page 1 with no uncertain words: wins
{ num: "3", body: "tři" }, // the same photo again
]);
assert.equal(text, "=1\njedna\n=2\ndva\n=3\ntři\n=4\npo trojce\n");
assert.deepEqual(photos, [5, 4, 2, 3]);
assert.deepEqual(duplicates.map((d) => [d.image, d.page, d.kept]), [[1, "1", 5], [6, "3", 2]]);
});
test("an unnumbered page whose guess is taken keeps no number", () => {
const { text } = assemble([{ num: "1", body: "a" }, { num: "?", body: "b" }, { num: "2", body: "c" }]);
assert.equal(text, "=1\na\n=?\nb\n=2\nc\n");
});
test("uncertain words: old [?] marks are converted, the reader drops the braces", () => {
assert.equal(splitPage("=1\nTo je divné[?] slovo, ne[?]?").body, "To je {divné} slovo, {ne}?");
const [page] = parsePlay("=1\n@{Lída}\nTo je {divné|dívčí} slovo.", { plain: true });
assert.equal(page.blocks[0].speaker, "Lída");
assert.deepEqual(page.blocks[0].parts[0].lines, ["To je divné slovo."]);
assert.equal(normalizeSpeakers(["@{LÍDA}\nx"])[0], "@Lída\nx");
assert.deepEqual(lint(parsePlay("=1\n@A\nnějaké {slovo")).map((x) => x.message), ["Neuzavřená složená závorka: „nějaké {slovo“"]);
});
const stub = (response) => ({ messages: { create: async (params) => { stub.last = params; return response; } } });
const JPEG = Buffer.from([0xff, 0xd8, 1]);