theater-reader/public/add.js
agent 46aa1236ed Let people add plays from photos; library, editor, compose; full-page PDF
- Replace the static nginx site with a small Node server: serves public/,
  stores plays on a /data volume and exposes a JSON API. Writes need a
  shared UPLOAD_PASSWORD; unpublished plays are hidden without it.
- Page photos (shrunk to <=1.15 MP JPEG in the browser) are transcribed
  one request per page by a Claude vision model (claude-haiku-5-5 by
  default, CLAUDE_MODEL to change) into the play markup, then stitched
  together: speaker spellings unified, gaps in page numbers marked as
  missing pages, failed pages flagged. DAILY_PAGE_LIMIT caps spend.
- New pages: library (play menu), add (upload + progress), editor (text
  next to the photos, checks for [?] readings and one-off names, publish,
  delete). The reader loads plays from the API and remembers the chosen
  role per play; old /?postava= links still work.
- PDF export: text now flows across original pages and prints at the
  on-screen size, so A4 sheets are full instead of half empty; page
  numbers in the footer.
- docker-compose.yml + .env.example for one-click deploys; the 1931 play
  moves to seed/ and is copied into an empty volume on first start.
- Tests: parser leniency, transcription assembly, API end to end with a
  stubbed Claude client.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HA82gVRDXpoukzgMFumoJt
2026-11-03 09:43:32 +00:00

134 lines
5.7 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

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

import { api, withLogin, getPassword, askPassword, esc, $ } from "./api.js";
// The API reads images at most ~1.15 megapixels, so a bigger upload only costs bandwidth.
const MAX_PIXELS = 1.15e6;
const MAX_SIDE = 1568;
let files = []; // [{ file, url }]
let cfg;
const collator = new Intl.Collator("cs", { numeric: true, sensitivity: "base" });
function addFiles(list) {
const imgs = [...list].filter((f) => f.type.startsWith("image/") || /\.(heic|heif)$/i.test(f.name));
files.push(...imgs.map((file) => ({ file, url: URL.createObjectURL(file) })));
files.sort((a, b) => collator.compare(a.file.name, b.file.name));
if (files.length > cfg.maxPages) {
showError(`Najednou lze nahrát nejvýše ${cfg.maxPages} stran.`);
files.splice(cfg.maxPages).forEach((f) => URL.revokeObjectURL(f.url));
}
renderThumbs();
}
function renderThumbs() {
$("thumbs").innerHTML = files.map((f, i) => `
<li class="thumb">
<img src="${f.url}" alt="">
<span class="thumb-num">${i + 1}</span>
<span class="thumb-name" title="${esc(f.file.name)}">${esc(f.file.name)}</span>
<span class="thumb-tools">
<button type="button" data-move="-1" data-i="${i}" title="Dříve" ${i === 0 ? "disabled" : ""}>◀</button>
<button type="button" data-move="1" data-i="${i}" title="Později" ${i === files.length - 1 ? "disabled" : ""}>▶</button>
<button type="button" data-remove data-i="${i}" title="Odebrat">✕</button>
</span>
</li>`).join("");
$("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;
$("status").textContent = text;
if (value !== undefined) $("bar").value = value;
}
async function waitForTranscription(id) {
for (;;) {
const meta = await api(`plays/${id}`);
if (meta.progress) setStatus(`Přepisuji stranu ${Math.min(meta.progress.done + 1, meta.progress.total)} z ${meta.progress.total}…`, meta.progress.done / meta.progress.total);
if (meta.status !== "processing") return meta;
await new Promise((r) => setTimeout(r, 2000));
}
}
async function submit(e) {
e.preventDefault();
showError("");
if (!files.length) return;
$("go").disabled = true;
$("form").classList.add("busy");
try {
const meta = await withLogin(() => api("plays", { method: "POST", body: { title: $("title").value, note: $("note").value } }));
const id = encodeURIComponent(meta.id);
for (let i = 0; i < files.length; i++) {
setStatus(`Nahrávám stranu ${i + 1} z ${files.length}…`, i / files.length);
await api(`plays/${id}/images/${i + 1}`, { method: "PUT", body: await toJpeg(files[i].file), type: "image/jpeg" });
}
if (cfg.transcription) {
setStatus("Začínám přepis…", 0);
await api(`plays/${id}/transcribe`, { method: "POST" });
// leaving the page is fine: the server keeps going and the editor shows progress
window.removeEventListener("beforeunload", warn);
await waitForTranscription(id);
}
location.href = `edit.html?id=${id}`;
} catch (err) {
showError(err.message);
$("go").disabled = false;
} finally {
$("form").classList.remove("busy");
}
}
const warn = (e) => { if (files.length && !$("progress").hidden) e.preventDefault(); };
async function main() {
cfg = await api("config");
if (!cfg.uploads) {
$("disabled").textContent = "Přidávání her je na tomto serveru vypnuté (správce nenastavil UPLOAD_PASSWORD).";
$("disabled").hidden = false;
$("form").hidden = true;
return;
}
if (!cfg.transcription) {
$("ai-note").textContent = "Automatický přepis není na serveru zapnutý (chybí klíč k API). Fotky se nahrají a text pak napíšete v editoru ručně.";
$("go").textContent = "Nahrát";
}
if (!getPassword()) askPassword("Přidávat hry může jen ten, kdo zná heslo.");
$("files").addEventListener("change", (e) => { addFiles(e.target.files); e.target.value = ""; });
const drop = $("drop");
drop.addEventListener("dragover", (e) => { e.preventDefault(); drop.classList.add("over"); });
drop.addEventListener("dragleave", () => drop.classList.remove("over"));
drop.addEventListener("drop", (e) => { e.preventDefault(); drop.classList.remove("over"); addFiles(e.dataTransfer.files); });
$("thumbs").addEventListener("click", (e) => {
const b = e.target.closest("button");
if (!b) return;
const i = Number(b.dataset.i);
if (b.hasAttribute("data-remove")) URL.revokeObjectURL(files.splice(i, 1)[0].url);
else {
const j = i + Number(b.dataset.move);
[files[i], files[j]] = [files[j], files[i]];
}
renderThumbs();
});
$("form").addEventListener("submit", submit);
window.addEventListener("beforeunload", warn);
renderThumbs();
}
main().catch((err) => showError(err.message));