theater-reader/public/add.js
agent f353c14619 Transcribe through OpenRouter when OPENROUTER_API_KEY is set
A Claude subscription can't be used by the app, so let it use any cheap
vision model on OpenRouter instead (default google/gemini-3.1-flash-lite,
OPENROUTER_MODEL to change). The Anthropic API stays available as the
second choice. Both providers share the prompt and live behind one
{ name, model, transcribe } interface in server/providers.mjs; OpenRouter
retries 408/429/5xx and network errors and turns 401/402/404 into
messages the editor can show.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HA82gVRDXpoukzgMFumoJt
2026-11-04 15:38:24 +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íč OPENROUTER_API_KEY nebo ANTHROPIC_API_KEY). Fotky se nahrají a text pak napíšete v editoru ručně.";
$("go").textContent = "Nahrát";
}
if (!getPassword()) askPassword("Přidávat hry může jen ten, kdo zná heslo.");
$("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));