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
This commit is contained in:
parent
2608d10dd2
commit
46aa1236ed
32 changed files with 1761 additions and 160 deletions
|
|
@ -4,7 +4,7 @@ import assert from "node:assert/strict";
|
|||
import { readFileSync } from "node:fs";
|
||||
import { parsePlay, speakers, joinLines, tidySpacing } from "../public/parse.js";
|
||||
|
||||
const play = parsePlay(readFileSync(new URL("../public/plays/hra.txt", import.meta.url), "utf8"));
|
||||
const play = parsePlay(readFileSync(new URL("../seed/hra-1931/play.txt", import.meta.url), "utf8"));
|
||||
|
||||
test("pages are in order and missing ones are marked", () => {
|
||||
const nums = play.map((p) => p.num);
|
||||
|
|
@ -41,3 +41,10 @@ test("spacing is tidied without touching numbers", () => {
|
|||
assert.equal(tidySpacing("Ano, roky.Nyní je rok 1931.Jaké ?"), "Ano, roky. Nyní je rok 1931. Jaké?");
|
||||
assert.equal(tidySpacing("nadějí .Jsem směšný"), "nadějí. Jsem směšný");
|
||||
});
|
||||
|
||||
test("machine output without a speaker or page marker still parses", () => {
|
||||
const pages = parsePlay("úvodní řádek\n=2\n@Lída\nAno.\n");
|
||||
assert.equal(pages[0].num, "?");
|
||||
assert.equal(pages[0].blocks[0].speaker, "");
|
||||
assert.deepEqual(speakers(pages).map((s) => s.name), ["Lída"]);
|
||||
});
|
||||
|
|
|
|||
98
tests/server.test.mjs
Normal file
98
tests/server.test.mjs
Normal file
|
|
@ -0,0 +1,98 @@
|
|||
// End-to-end API test against a real server on a temp data dir, with Claude stubbed out.
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdtemp, rm } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { config, createServer } from "../server/main.mjs";
|
||||
import { createStore } from "../server/store.mjs";
|
||||
|
||||
const PASS = "tajne-heslo";
|
||||
const JPEG = Buffer.from([0xff, 0xd8, 0xff, 0xe0, 1, 2, 3]);
|
||||
const replies = ["=-1-\n~JEDNÁNÍ PRVNÍ\n@LÍDA\nDobrý den.", "=2\nještě já.\n@Mise\nAno."];
|
||||
const client = { messages: { create: async (p) => ({ stop_reason: "end_turn", content: [{ type: "text", text: replies.shift() }], usage: {} }) } };
|
||||
|
||||
let dir, server, base;
|
||||
test.before(async () => {
|
||||
dir = await mkdtemp(path.join(tmpdir(), "tr-"));
|
||||
Object.assign(config, { dataDir: dir, password: PASS, apiKey: "test", dailyPageLimit: 3 });
|
||||
const store = createStore(dir);
|
||||
await store.init();
|
||||
await store.seed(config.seedDir);
|
||||
server = createServer(store, client).listen(0);
|
||||
base = `http://127.0.0.1:${server.address().port}`;
|
||||
});
|
||||
test.after(async () => { server.close(); await rm(dir, { recursive: true, force: true }); });
|
||||
|
||||
const call = (p, opts = {}) => fetch(base + p, opts);
|
||||
const authed = (opts = {}) => ({ ...opts, headers: { "x-upload-password": PASS, ...(opts.headers || {}) } });
|
||||
|
||||
test("seeded play is listed and readable", async () => {
|
||||
const plays = await (await call("/api/plays")).json();
|
||||
assert.deepEqual(plays.map((p) => p.id), ["hra-1931"]);
|
||||
const text = await (await call("/api/plays/hra-1931/text")).text();
|
||||
assert.match(text, /^!1-4\n=5\n@Mise/);
|
||||
});
|
||||
|
||||
test("static files are served with security headers, traversal is refused", async () => {
|
||||
const res = await call("/");
|
||||
assert.equal(res.status, 200);
|
||||
assert.match(res.headers.get("content-type"), /text\/html/);
|
||||
assert.match(res.headers.get("content-security-policy"), /default-src 'self'/);
|
||||
assert.equal((await call("/../server/main.mjs")).status, 404);
|
||||
assert.equal((await call("/%2e%2e/package.json")).status, 404);
|
||||
assert.equal((await call("/api/plays/..%2fx")).status, 404);
|
||||
});
|
||||
|
||||
test("writing needs the password", async () => {
|
||||
const res = await call("/api/plays", { method: "POST", body: JSON.stringify({ title: "X" }) });
|
||||
assert.equal(res.status, 401);
|
||||
assert.equal((await call("/api/plays", { method: "POST", headers: { "x-upload-password": "nope" }, body: "{}" })).status, 401);
|
||||
});
|
||||
|
||||
test("upload → transcribe → draft → publish", async () => {
|
||||
let res = await call("/api/plays", authed({ method: "POST", body: JSON.stringify({ title: "Nová hra", note: "zkouška" }) }));
|
||||
assert.equal(res.status, 201);
|
||||
const { id } = await res.json();
|
||||
assert.match(id, /^nova-hra-[0-9a-f]{6}$/);
|
||||
|
||||
// drafts are hidden from the public
|
||||
assert.equal((await (await call("/api/plays")).json()).length, 1);
|
||||
assert.equal((await call(`/api/plays/${id}`)).status, 404);
|
||||
|
||||
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 }));
|
||||
assert.equal(res.status, 200);
|
||||
}
|
||||
res = await call(`/api/plays/${id}/transcribe`, authed({ method: "POST" }));
|
||||
assert.equal(res.status, 202);
|
||||
// wait for the background job
|
||||
let meta;
|
||||
for (let i = 0; i < 50; i++) {
|
||||
meta = await (await call(`/api/plays/${id}`, authed())).json();
|
||||
if (meta.status === "draft") break;
|
||||
await new Promise((r) => setTimeout(r, 20));
|
||||
}
|
||||
assert.equal(meta.status, "draft");
|
||||
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");
|
||||
|
||||
res = await call(`/api/plays/${id}`, authed({ method: "PATCH", body: JSON.stringify({ published: true }) }));
|
||||
assert.equal((await res.json()).published, true);
|
||||
assert.equal((await (await call("/api/plays")).json()).length, 2);
|
||||
assert.equal((await call(`/api/plays/${id}/images/2`)).status, 200);
|
||||
|
||||
// the daily cap (3 pages) is now nearly used up
|
||||
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" }));
|
||||
assert.equal(res.status, 429);
|
||||
|
||||
// editing the text, then deleting
|
||||
res = await call(`/api/plays/${id}/text`, authed({ method: "PUT", body: "=1\n@Lída\nUpraveno.\n" }));
|
||||
assert.equal((await res.json()).edited, true);
|
||||
assert.equal((await call(`/api/plays/${id}`, authed({ method: "DELETE" }))).status, 200);
|
||||
assert.equal((await call(`/api/plays/${id}`, authed())).status, 404);
|
||||
});
|
||||
46
tests/transcribe.test.mjs
Normal file
46
tests/transcribe.test.mjs
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { splitPage, normalizeSpeakers, assemble, transcribePage, PageError } from "../server/transcribe.mjs";
|
||||
import { parsePlay, lint } from "../public/parse.js";
|
||||
|
||||
test("splitPage takes the page number from the first line", () => {
|
||||
assert.deepEqual(splitPage("=-12-\n@Lída\nAno."), { num: "12", body: "@Lída\nAno." });
|
||||
assert.deepEqual(splitPage("=?\ntext"), { num: "?", body: "text" });
|
||||
assert.deepEqual(splitPage("```\n=3\n@A\nx\n=4\n```"), { num: "3", body: "@A\nx" });
|
||||
assert.equal(splitPage("@A\nx").num, "?");
|
||||
});
|
||||
|
||||
test("speaker spellings are unified across pages", () => {
|
||||
const out = normalizeSpeakers(["@LÍDA\nx\n@Lida\ny", "@Lida:\nz\n@PANÍ BÁBA\nw\n@Paní bába\nv"]);
|
||||
assert.deepEqual(out, ["@Lída\nx\n@Lída\ny", "@Lída\nz\n@Paní bába\nw\n@Paní bába\nv"]);
|
||||
});
|
||||
|
||||
test("assemble numbers pages, marks gaps and failed pages", () => {
|
||||
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");
|
||||
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), []);
|
||||
});
|
||||
|
||||
const stub = (response) => ({ messages: { create: async (params) => { stub.last = params; return response; } } });
|
||||
|
||||
test("transcribePage sends the image and reads text blocks", async () => {
|
||||
const client = stub({ stop_reason: "end_turn", content: [{ type: "thinking", thinking: "" }, { type: "text", text: "=1\n@A\nx" }], usage: {} });
|
||||
const { text } = await transcribePage(client, "claude-haiku-5-5", Buffer.from([0xff, 0xd8, 1]));
|
||||
assert.equal(text, "=1\n@A\nx");
|
||||
const img = stub.last.messages[0].content[0];
|
||||
assert.equal(img.source.media_type, "image/jpeg");
|
||||
assert.equal(stub.last.model, "claude-haiku-5-5");
|
||||
});
|
||||
|
||||
test("transcribePage reports refusals and truncation", async () => {
|
||||
await assert.rejects(transcribePage(stub({ stop_reason: "refusal", content: [] }), "m", Buffer.alloc(2)), PageError);
|
||||
await assert.rejects(transcribePage(stub({ stop_reason: "max_tokens", content: [{ type: "text", text: "x" }] }), "m", Buffer.alloc(2)), PageError);
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue