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
|
|
@ -1,4 +1,6 @@
|
|||
.git
|
||||
.env
|
||||
node_modules
|
||||
tests
|
||||
tools
|
||||
*.md
|
||||
|
|
|
|||
19
.env.example
Normal file
19
.env.example
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
# Copy to .env (chmod 600) and fill in. Never commit .env.
|
||||
|
||||
# API key from https://platform.claude.com (Anthropic API, billed separately from a Claude subscription).
|
||||
# Without it the app still works; uploaded photos just have to be typed up by hand.
|
||||
ANTHROPIC_API_KEY=
|
||||
|
||||
# Password people need to add and edit plays. Without it uploading is switched off.
|
||||
UPLOAD_PASSWORD=
|
||||
|
||||
# Vision model used for transcription. claude-sonnet-5-5 reads hard pages better at ~20x the price.
|
||||
CLAUDE_MODEL=claude-haiku-5-5
|
||||
|
||||
# Safety cap on pages transcribed per day (all users together), and pages per play.
|
||||
DAILY_PAGE_LIMIT=300
|
||||
MAX_PAGES=80
|
||||
|
||||
# Host port, and the address it is published on.
|
||||
PORT=3010
|
||||
BIND_ADDRESS=127.0.0.1
|
||||
3
.gitignore
vendored
3
.gitignore
vendored
|
|
@ -1 +1,2 @@
|
|||
node_modules/
|
||||
node_modules
|
||||
.env
|
||||
|
|
|
|||
36
AGENTS.md
36
AGENTS.md
|
|
@ -1,22 +1,32 @@
|
|||
# AGENTS.md — theater-reader
|
||||
|
||||
A static web app (plain HTML/CSS/ES modules, no build step) served by unprivileged nginx in a container.
|
||||
A Node 22 server (`server/`) serving a no-build front end (`public/`, plain HTML/CSS/ES modules) and a JSON API for plays
|
||||
kept on a volume. Transcription of page photos goes through the Anthropic SDK (`@anthropic-ai/sdk`, the only dependency).
|
||||
UI language is Czech.
|
||||
|
||||
## Layout
|
||||
|
||||
- `public/index.html`, `app.js`, `app.css` — the app. UI language is Czech.
|
||||
- `public/parse.js` — parser for the play markup, also used by the tests.
|
||||
- `public/plays/index.json` — list of plays (`id`, `file`, `title`, `note`); a play selector appears once there is more than one.
|
||||
- `public/plays/*.txt` — play texts in the markup below.
|
||||
- `public/fonts/` — self-hosted woff2 (latin + latin-ext) and their OFL licences, generated by `tools/fetch_fonts.py`.
|
||||
- `deploy/` — nginx config. `Dockerfile` at the root.
|
||||
- `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/transcribe.mjs`: one Claude request per photo (`transcribePage`), then `splitPage` → `normalizeSpeakers` → `assemble` into one play file. `server/prompt.mjs` holds the prompt, 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`).
|
||||
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.
|
||||
|
||||
## Run / test
|
||||
|
||||
- Dev port: **3010** on loopback. `podman build -t theater-reader . && podman run -d --name theater-reader -p 127.0.0.1:3010:8080 theater-reader`.
|
||||
The admin previews with `ssh -p 14922 -L 3010:localhost:3010 <host>`.
|
||||
- Tests (parser): `podman run --rm -v "$PWD":/app:ro,Z -w /app docker.io/library/node:22-alpine npm test`.
|
||||
- Fonts: `python3 tools/fetch_fonts.py` re-downloads them; edit `FAMILIES` there and the `FONTS` list in `app.js` together.
|
||||
- Dev port **3010** on loopback. Preview with `ssh -p 14922 -L 3010:localhost:3010 <host>`.
|
||||
`podman-compose --env-file <file> up -d --build` (env file with `UPLOAD_PASSWORD`, and optionally `ANTHROPIC_API_KEY`, chmod 600, outside the repo).
|
||||
- Tests (parser, transcription assembly, API end to end with Claude stubbed):
|
||||
`podman run --rm -v "$PWD":/app:ro,Z -w /app docker.io/library/node:22-alpine npm test` (run `npm ci` in the same image first if `node_modules` is missing).
|
||||
- To exercise the full UI without spending API credit, point `ANTHROPIC_BASE_URL` at a stub server that returns a Messages response.
|
||||
|
||||
## Play markup
|
||||
|
||||
|
|
@ -37,6 +47,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.
|
||||
`[?]` after a word marks an uncertain reading. The editor lists them.
|
||||
|
||||
To add a missing page, e.g. page 7, replace the `!7` line in `hra.txt` with `=7` and its content; the speaker on page 8's first
|
||||
lines comes from whatever speech page 7 ends with.
|
||||
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.
|
||||
|
|
|
|||
25
Dockerfile
25
Dockerfile
|
|
@ -1,8 +1,23 @@
|
|||
# Theater reader: a static site served by unprivileged nginx on port 8080.
|
||||
FROM docker.io/nginxinc/nginx-unprivileged:1.27-alpine
|
||||
# Theater reader: Node server for the app, the plays API and transcription.
|
||||
FROM docker.io/library/node:22-alpine
|
||||
|
||||
COPY deploy/nginx.conf /etc/nginx/conf.d/default.conf
|
||||
COPY deploy/security-headers.inc /etc/nginx/conf.d/security-headers.inc
|
||||
COPY public/ /usr/share/nginx/html/
|
||||
ENV NODE_ENV=production PORT=8080 DATA_DIR=/data
|
||||
WORKDIR /app
|
||||
|
||||
COPY package.json package-lock.json ./
|
||||
RUN npm ci --omit=dev && npm cache clean --force
|
||||
|
||||
COPY server/ server/
|
||||
COPY public/ public/
|
||||
COPY seed/ seed/
|
||||
|
||||
# Plays and uploaded photos live on the /data volume, owned by the unprivileged user.
|
||||
RUN mkdir -p /data && chown node:node /data
|
||||
USER node
|
||||
VOLUME /data
|
||||
EXPOSE 8080
|
||||
|
||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s \
|
||||
CMD wget -q -O /dev/null http://127.0.0.1:8080/healthz || exit 1
|
||||
|
||||
CMD ["node", "server/main.mjs"]
|
||||
|
|
|
|||
40
README.md
40
README.md
|
|
@ -1,26 +1,44 @@
|
|||
# Divadelní čtečka (theater reader)
|
||||
|
||||
A small web app for reading a play script during rehearsals. An actor can:
|
||||
A small web app for reading play scripts during rehearsals.
|
||||
|
||||
**Reading** (anyone):
|
||||
|
||||
- a **library** of plays to choose from,
|
||||
- choose a **font** (typewriter, Atkinson Hyperlegible, Lexend, Literata or the system font), the text size and colours (light, sepia, dark),
|
||||
- pick **their character**, which highlights their lines and lets them jump from one line to the next (▲ ▼, or `J` / `K` on a keyboard),
|
||||
- switch between **running text** (hyphenation joined, spacing tidied) and the **original typescript lines**,
|
||||
- open **reading mode** (settings hidden, large text), or
|
||||
- **export a PDF** of their own copy, one page per page of the original. This goes through the print dialog, so choose "Save as PDF".
|
||||
- pick **your character**: your lines are highlighted and ▲ ▼ (or `J` / `K`) jump between them,
|
||||
- **running text** (hyphenation joined, spacing tidied) or the **original typescript lines**,
|
||||
- **reading mode** (settings hidden), or **export a PDF** of your own copy: A4 sheets filled edge to edge at the size you chose, your lines highlighted. It goes through the print dialog, so choose "Save as PDF".
|
||||
|
||||
A link like `http://localhost:3010/?postava=Lída` opens the app with that character already chosen, so a director can send each actor their own link.
|
||||
A link like `read.html?hra=hra-1931&postava=Lída` opens a play with the character already chosen, so a director can send each actor their own link.
|
||||
|
||||
## Running it
|
||||
**Adding plays** (anyone with the upload password):
|
||||
|
||||
1. *Přidat hru*: give the title and pick a photo of each page.
|
||||
2. Each photo is read by a Claude vision model (Claude Haiku 5.5 by default) and turned into the script markup: speakers, stage directions, page numbers. Missing pages are noticed from gaps in the page numbers.
|
||||
3. The editor shows the text next to the photos and lists things to check (uncertain words marked `[?]`, characters who speak only once, pages that failed). Fix, tick *Zveřejněno*, save.
|
||||
|
||||
## Deploying
|
||||
|
||||
```sh
|
||||
podman build -t theater-reader .
|
||||
podman run -d --name theater-reader -p 127.0.0.1:3010:8080 theater-reader
|
||||
cp .env.example .env && chmod 600 .env # then fill in the two secrets
|
||||
docker compose up -d # or: podman compose up -d
|
||||
```
|
||||
|
||||
Then open <http://localhost:3010>. The Dockerfile works with `docker` as well.
|
||||
The app listens on port 3010 on loopback (`PORT` and `BIND_ADDRESS` change that). Plays and photos are kept in the `plays` volume. On first start the volume is seeded with the 1931 play.
|
||||
|
||||
| Variable | |
|
||||
|---|---|
|
||||
| `ANTHROPIC_API_KEY` | API key from [platform.claude.com](https://platform.claude.com). **A Claude Pro/Max subscription can't be used for this.** The API is billed separately, pay as you go. Without a key the app still works, but uploaded pages have to be typed up by hand. |
|
||||
| `UPLOAD_PASSWORD` | Shared password for adding, editing and deleting plays. Unset = uploading switched off. |
|
||||
| `CLAUDE_MODEL` | `claude-haiku-5-5` (default, around $0.001 a page) or `claude-sonnet-5-5` (reads hard pages better, roughly 20× the price). |
|
||||
| `DAILY_PAGE_LIMIT` | Cap on pages transcribed per day, for all users together (default 300), so a leaked password can't run up a bill. |
|
||||
| `MAX_PAGES` | Maximum photos per play (default 80). |
|
||||
|
||||
Without compose: `docker build -t theater-reader . && docker run -d -p 127.0.0.1:3010:8080 -v plays:/data --env-file .env theater-reader`.
|
||||
|
||||
## The play included
|
||||
|
||||
`public/plays/hra.txt` is a transcription of a 1931 typescript, pages 5–27. Pages 1–4 (presumably the title page and cast list) and page 7 are missing from the original, and the text breaks off at the end of page 27. See `AGENTS.md` for the text format and how to add the missing pages.
|
||||
`seed/hra-1931/play.txt` is a transcription of a 1931 typescript, pages 5–27. Pages 1–4 (probably the title page and cast list) and page 7 are missing from the original, and the text breaks off at the end of page 27. Once deployed, the play is edited in the app. The seed file is only copied into an empty volume.
|
||||
|
||||
Fonts are self-hosted under the SIL Open Font License (see `public/fonts/OFL-*.txt`).
|
||||
|
|
|
|||
|
|
@ -1,22 +0,0 @@
|
|||
# Static file server for the reader. Plays are UTF-8 text; say so explicitly.
|
||||
server {
|
||||
listen 8080;
|
||||
server_name _;
|
||||
root /usr/share/nginx/html;
|
||||
|
||||
charset utf-8;
|
||||
charset_types text/plain text/css application/javascript application/json;
|
||||
|
||||
location / {
|
||||
try_files $uri $uri/ /index.html;
|
||||
include /etc/nginx/conf.d/security-headers.inc;
|
||||
}
|
||||
location /plays/ {
|
||||
add_header Cache-Control "no-cache";
|
||||
include /etc/nginx/conf.d/security-headers.inc;
|
||||
}
|
||||
location /fonts/ {
|
||||
add_header Cache-Control "public, max-age=2592000";
|
||||
include /etc/nginx/conf.d/security-headers.inc;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,4 +0,0 @@
|
|||
# Included in every location: nginx drops inherited add_header once a location sets its own.
|
||||
add_header X-Content-Type-Options nosniff always;
|
||||
add_header Referrer-Policy no-referrer always;
|
||||
add_header Content-Security-Policy "default-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:" always;
|
||||
22
docker-compose.yml
Normal file
22
docker-compose.yml
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
# One-click deploy: `docker compose up -d` (or `podman compose up -d`).
|
||||
# Settings come from the environment or a .env file next to this one; see .env.example.
|
||||
services:
|
||||
theater-reader:
|
||||
build: .
|
||||
image: theater-reader:latest
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
ANTHROPIC_API_KEY: ${ANTHROPIC_API_KEY:-}
|
||||
UPLOAD_PASSWORD: ${UPLOAD_PASSWORD:-}
|
||||
CLAUDE_MODEL: ${CLAUDE_MODEL:-claude-haiku-5-5}
|
||||
DAILY_PAGE_LIMIT: ${DAILY_PAGE_LIMIT:-300}
|
||||
MAX_PAGES: ${MAX_PAGES:-80}
|
||||
ports:
|
||||
# Loopback by default. Behind a panel's reverse proxy this is usually fine;
|
||||
# set BIND_ADDRESS=0.0.0.0 only if the app itself must be reachable from outside.
|
||||
- "${BIND_ADDRESS:-127.0.0.1}:${PORT:-3010}:8080"
|
||||
volumes:
|
||||
- plays:/data
|
||||
|
||||
volumes:
|
||||
plays:
|
||||
94
package-lock.json
generated
Normal file
94
package-lock.json
generated
Normal file
|
|
@ -0,0 +1,94 @@
|
|||
{
|
||||
"name": "theater-reader",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "theater-reader",
|
||||
"dependencies": {
|
||||
"@anthropic-ai/sdk": "1.4.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@anthropic-ai/sdk": {
|
||||
"version": "1.4.0",
|
||||
"resolved": "https://registry.npmjs.org/@anthropic-ai/sdk/-/sdk-1.4.0.tgz",
|
||||
"integrity": "sha512-tyuibnhQL57kLOx5oomY4Ld7jOVOPNC5v3IiyRtR3l+Friv66tI4VbuZYF2NMel/T0WMuQMBFOMKDBUbUh8gPA==",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@opentelemetry/api": "^1.4.1",
|
||||
"json-schema-to-ts": "^3.1.1",
|
||||
"standardwebhooks": "^1.0.0"
|
||||
},
|
||||
"bin": {
|
||||
"anthropic-ai-sdk": "bin/cli"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"zod": "^3.25.0 || ^4.0.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"zod": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/@babel/runtime": {
|
||||
"version": "7.29.10",
|
||||
"resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.10.tgz",
|
||||
"integrity": "sha512-NpugTzbKgGrNe45Ui32cN8vCFFMxVtP/9rtfwv0nP5FRDAjvYBxJcLVpYA9mr1jxP6cnIT7x9LUzuDTbWYYNRA==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=6.9.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@opentelemetry/api": {
|
||||
"version": "1.10.0",
|
||||
"resolved": "https://registry.npmjs.org/@opentelemetry/api/-/api-1.10.0.tgz",
|
||||
"integrity": "sha512-lMkyes8iHrG+mk6WH7X70MdCLI2RS0FwNBY1PyQ8UemaijE2m5mv5A0Niy3HtbYTFrgkUEQjFMXmSAk2hQDuPQ==",
|
||||
"license": "Apache-2.0",
|
||||
"engines": {
|
||||
"node": ">=8.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@stablelib/base64": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/@stablelib/base64/-/base64-1.0.1.tgz",
|
||||
"integrity": "sha512-1bnPQqSxSuc3Ii6MhBysoWCg58j97aUjuCSZrGSmDxNqtytIi0k8utUenAwTZN4V5mXXYGsVUI9zeBqy+jBOSQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/fast-sha256": {
|
||||
"version": "1.3.0",
|
||||
"resolved": "https://registry.npmjs.org/fast-sha256/-/fast-sha256-1.3.0.tgz",
|
||||
"integrity": "sha512-n11RGP/lrWEFI/bWdygLxhI+pVeo1ZYIVwvvPkW7azl/rOy+F3HYRZ2K5zeE9mmkhQppyv9sQFx0JM9UabnpPQ==",
|
||||
"license": "Unlicense"
|
||||
},
|
||||
"node_modules/json-schema-to-ts": {
|
||||
"version": "3.1.1",
|
||||
"resolved": "https://registry.npmjs.org/json-schema-to-ts/-/json-schema-to-ts-3.1.1.tgz",
|
||||
"integrity": "sha512-+DWg8jCJG2TEnpy7kOm/7/AxaYoaRbjVB4LFZLySZlWn8exGs3A4OLJR966cVvU26N7X9TWxl+Jsw7dzAqKT6g==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.18.3",
|
||||
"ts-algebra": "^2.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=16"
|
||||
}
|
||||
},
|
||||
"node_modules/standardwebhooks": {
|
||||
"version": "1.1.1",
|
||||
"resolved": "https://registry.npmjs.org/standardwebhooks/-/standardwebhooks-1.1.1.tgz",
|
||||
"integrity": "sha512-bCbX9ZEyFkWPsRz7Bl3NuQUJohmwGSev/yhr7vhaGPlc4AfIrspIRa6cPTBuI1ItmrTDJ4d/S2hCsfe4+vQGnQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@stablelib/base64": "^1.0.0",
|
||||
"fast-sha256": "^1.3.0"
|
||||
}
|
||||
},
|
||||
"node_modules/ts-algebra": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/ts-algebra/-/ts-algebra-2.0.0.tgz",
|
||||
"integrity": "sha512-FPAhNPFMrkwz76P7cdjdmiShwMynZYN6SgOujD1urY4oNm80Ou9oMdmbR45LotcKOXoy7wSmHkRFE6Mxbrhefw==",
|
||||
"license": "MIT"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -4,5 +4,8 @@
|
|||
"type": "module",
|
||||
"scripts": {
|
||||
"test": "node --test tests/*.test.mjs"
|
||||
},
|
||||
"dependencies": {
|
||||
"@anthropic-ai/sdk": "1.4.0"
|
||||
}
|
||||
}
|
||||
|
|
|
|||
43
public/add.html
Normal file
43
public/add.html
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
<!doctype html>
|
||||
<html lang="cs">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Přidat hru – Divadelní čtečka</title>
|
||||
<link rel="stylesheet" href="app.css">
|
||||
<script type="module" src="add.js"></script>
|
||||
</head>
|
||||
<body class="page-add">
|
||||
<header class="topbar">
|
||||
<nav class="crumbs"><a href="./">← Všechny hry</a></nav>
|
||||
<h1>Přidat hru</h1>
|
||||
</header>
|
||||
<main class="wrap">
|
||||
<p class="error" id="disabled" hidden></p>
|
||||
<form id="form" class="stack">
|
||||
<label class="field"><span>Název hry</span><input id="title" required maxlength="200" placeholder="např. Lucerna"></label>
|
||||
<label class="field"><span>Poznámka <small class="muted">(nepovinné)</small></span><input id="note" maxlength="500" placeholder="autor, rok, co chybí…"></label>
|
||||
|
||||
<fieldset class="field">
|
||||
<legend>Fotky stran</legend>
|
||||
<p class="muted" id="ai-note">Každou stranu přečte umělá inteligence (Claude) a přepíše ji do textu. Text pak zkontrolujete a opravíte v editoru, než hru zveřejníte.</p>
|
||||
<label class="dropzone" id="drop">
|
||||
<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">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>
|
||||
|
||||
<div class="actions">
|
||||
<button class="primary" id="go" type="submit">Nahrát a přepsat</button>
|
||||
</div>
|
||||
<div class="progress" id="progress" hidden>
|
||||
<progress id="bar" max="1" value="0"></progress>
|
||||
<p id="status"></p>
|
||||
</div>
|
||||
<p class="error" id="error" hidden></p>
|
||||
</form>
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
134
public/add.js
Normal file
134
public/add.js
Normal file
|
|
@ -0,0 +1,134 @@
|
|||
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));
|
||||
95
public/api.js
Normal file
95
public/api.js
Normal file
|
|
@ -0,0 +1,95 @@
|
|||
// Small helpers shared by the pages: API calls and the upload password.
|
||||
const PASS_KEY = "theater-reader:password";
|
||||
|
||||
export function getPassword() {
|
||||
try { return sessionStorage.getItem(PASS_KEY) || localStorage.getItem(PASS_KEY) || ""; } catch { return ""; }
|
||||
}
|
||||
export function setPassword(pw, remember) {
|
||||
try {
|
||||
sessionStorage.setItem(PASS_KEY, pw);
|
||||
if (remember) localStorage.setItem(PASS_KEY, pw); else localStorage.removeItem(PASS_KEY);
|
||||
} catch { /* storage blocked: the password just won't be remembered */ }
|
||||
}
|
||||
export function clearPassword() {
|
||||
try { sessionStorage.removeItem(PASS_KEY); localStorage.removeItem(PASS_KEY); } catch { /* ignore */ }
|
||||
}
|
||||
|
||||
export class ApiError extends Error {
|
||||
constructor(status, message) { super(message); this.status = status; }
|
||||
}
|
||||
|
||||
// fetch wrapper: sends the password when we have one, throws ApiError with the server's message.
|
||||
export async function api(path, { method = "GET", body, type, raw = false } = {}) {
|
||||
const headers = {};
|
||||
const pw = getPassword();
|
||||
if (pw) headers["x-upload-password"] = pw;
|
||||
if (body !== undefined && !(body instanceof Blob) && typeof body !== "string") {
|
||||
body = JSON.stringify(body);
|
||||
headers["content-type"] = "application/json";
|
||||
} else if (type) headers["content-type"] = type;
|
||||
const res = await fetch(`api/${path}`, { method, headers, body });
|
||||
if (!res.ok) {
|
||||
let msg = `HTTP ${res.status}`;
|
||||
try { msg = (await res.json()).error || msg; } catch { /* not JSON */ }
|
||||
throw new ApiError(res.status, msg);
|
||||
}
|
||||
if (raw) return res;
|
||||
return (res.headers.get("content-type") || "").includes("json") ? res.json() : res.text();
|
||||
}
|
||||
|
||||
export async function login(pw, remember) {
|
||||
const headers = { "x-upload-password": pw };
|
||||
const res = await fetch("api/login", { method: "POST", headers });
|
||||
if (!res.ok) {
|
||||
let msg = "Přihlášení se nepovedlo.";
|
||||
try { msg = (await res.json()).error || msg; } catch { /* ignore */ }
|
||||
throw new ApiError(res.status, msg);
|
||||
}
|
||||
setPassword(pw, remember);
|
||||
}
|
||||
|
||||
export const esc = (s) => String(s).replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c]);
|
||||
export const $ = (id) => document.getElementById(id);
|
||||
|
||||
// Ask for the upload password in a modal dialog; resolves true once logged in, false if cancelled.
|
||||
export function askPassword(reason = "") {
|
||||
return new Promise((resolve) => {
|
||||
const dlg = document.createElement("dialog");
|
||||
dlg.className = "login";
|
||||
dlg.innerHTML = `<form method="dialog">
|
||||
<h2>Heslo pro úpravy</h2>
|
||||
${reason ? `<p class="muted">${esc(reason)}</p>` : ""}
|
||||
<label class="field"><span>Heslo</span><input type="password" name="pw" autocomplete="current-password" required></label>
|
||||
<label class="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 err = dlg.querySelector(".error");
|
||||
form.addEventListener("submit", async (e) => {
|
||||
if (e.submitter?.value !== "ok") return;
|
||||
e.preventDefault();
|
||||
try {
|
||||
await login(form.pw.value, form.remember.checked);
|
||||
dlg.close("ok");
|
||||
} catch (ex) {
|
||||
err.textContent = ex.message;
|
||||
err.hidden = false;
|
||||
}
|
||||
});
|
||||
dlg.addEventListener("close", () => { dlg.remove(); resolve(dlg.returnValue === "ok"); });
|
||||
dlg.showModal();
|
||||
});
|
||||
}
|
||||
|
||||
// Run fn; on 401 ask for the password and retry once.
|
||||
export async function withLogin(fn, reason) {
|
||||
try { return await fn(); }
|
||||
catch (err) {
|
||||
if (!(err instanceof ApiError) || err.status !== 401) throw err;
|
||||
clearPassword();
|
||||
if (!(await askPassword(reason || "Pro tuto akci je potřeba heslo."))) throw err;
|
||||
return fn();
|
||||
}
|
||||
}
|
||||
143
public/app.css
143
public/app.css
|
|
@ -224,8 +224,137 @@ body.reading .lines-nav .read-only { display: inline-block; }
|
|||
:root[data-layout="original"] .stage { padding-left: 1.5em; }
|
||||
}
|
||||
|
||||
/* ---- PDF export (print) ---- */
|
||||
@page { size: A4; margin: 18mm 16mm; }
|
||||
/* ---- shared bits for the library, upload and editor pages ---- */
|
||||
a { color: var(--accent); }
|
||||
.muted { color: var(--muted); }
|
||||
.small { font-size: 13px; }
|
||||
.error { color: var(--accent); font-weight: 600; }
|
||||
.crumbs { display: flex; gap: 16px; flex-wrap: wrap; font-size: 14px; margin-bottom: 10px; }
|
||||
.crumbs a { text-decoration: none; }
|
||||
.crumbs a:hover { text-decoration: underline; }
|
||||
input:not([type]), input[type="text"], input[type="password"], textarea {
|
||||
width: 100%;
|
||||
padding: 8px 10px;
|
||||
border-radius: 8px;
|
||||
border: 1px solid var(--line);
|
||||
background: var(--bg);
|
||||
}
|
||||
button, .button {
|
||||
display: inline-block;
|
||||
padding: 8px 14px;
|
||||
border-radius: 8px;
|
||||
border: 1px solid var(--line);
|
||||
background: var(--bg);
|
||||
cursor: pointer;
|
||||
font-weight: 600;
|
||||
font-size: 15px;
|
||||
text-decoration: none;
|
||||
color: var(--fg);
|
||||
}
|
||||
button:disabled { opacity: 0.5; cursor: default; }
|
||||
.primary, .button.primary { background: var(--accent); border-color: var(--accent); color: #fff; }
|
||||
:root[data-theme="dark"] .primary { color: #17171a; }
|
||||
button.link { border: 0; background: none; padding: 0; font: inherit; color: var(--accent); text-align: left; cursor: pointer; }
|
||||
|
||||
.topbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px 16px;
|
||||
padding: 14px 24px;
|
||||
background: var(--panel);
|
||||
border-bottom: 1px solid var(--line);
|
||||
}
|
||||
.topbar h1 { font-size: 20px; margin: 0; }
|
||||
.topbar .crumbs { margin: 0; }
|
||||
.topbar-actions { display: flex; align-items: center; gap: 10px; }
|
||||
.wrap { max-width: 760px; margin: 0 auto; padding: 20px 16px 60px; }
|
||||
.wrap.wide { max-width: 1400px; }
|
||||
.stack > * + * { margin-top: 12px; }
|
||||
|
||||
.play-list { list-style: none; padding: 0; margin: 16px 0; display: grid; gap: 10px; }
|
||||
.play-card {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
padding: 14px 16px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 10px;
|
||||
background: var(--panel);
|
||||
}
|
||||
.play-main { flex: 1; min-width: 0; text-decoration: none; color: inherit; display: grid; gap: 2px; }
|
||||
.play-main:hover .play-title { color: var(--accent); }
|
||||
.play-title { font-weight: 700; font-size: 17px; }
|
||||
.play-card .play-note { margin: 0; }
|
||||
.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(380px, calc(100vw - 32px)); }
|
||||
dialog.login h2 { margin: 0 0 8px; font-size: 18px; }
|
||||
dialog::backdrop { background: rgba(0, 0, 0, 0.4); }
|
||||
|
||||
.dropzone {
|
||||
display: block;
|
||||
padding: 28px 16px;
|
||||
border: 2px dashed var(--line);
|
||||
border-radius: 10px;
|
||||
text-align: center;
|
||||
cursor: pointer;
|
||||
background: var(--panel);
|
||||
}
|
||||
.dropzone.over { border-color: var(--accent); }
|
||||
.dropzone input { position: absolute; opacity: 0; width: 1px; height: 1px; }
|
||||
.dropzone:has(input:focus-visible) { outline: 2px solid var(--accent); outline-offset: 2px; }
|
||||
.thumbs { list-style: none; padding: 0; display: grid; grid-template-columns: repeat(auto-fill, minmax(120px, 1fr)); gap: 10px; }
|
||||
.thumb { position: relative; border: 1px solid var(--line); border-radius: 8px; overflow: hidden; background: var(--panel); font-size: 12px; }
|
||||
.thumb img { display: block; width: 100%; aspect-ratio: 3 / 4; object-fit: cover; }
|
||||
.thumb-num { position: absolute; top: 4px; left: 4px; background: var(--accent); color: #fff; border-radius: 999px; padding: 0 7px; font-weight: 700; }
|
||||
.thumb-name { display: block; padding: 4px 6px 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; color: var(--muted); }
|
||||
.thumb-tools { display: flex; justify-content: space-between; padding: 4px; }
|
||||
.thumb-tools button { padding: 2px 8px; font-size: 12px; }
|
||||
.progress progress { width: 100%; accent-color: var(--accent); }
|
||||
form.busy .dropzone, form.busy .thumb-tools { pointer-events: none; opacity: 0.6; }
|
||||
|
||||
.meta-row { display: flex; gap: 12px; align-items: end; flex-wrap: wrap; }
|
||||
.meta-row .grow { flex: 1 1 260px; }
|
||||
.field.toggle { display: flex; align-items: center; gap: 8px; padding-bottom: 8px; }
|
||||
.field.toggle span { margin: 0; }
|
||||
.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;
|
||||
}
|
||||
.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 button { color: var(--accent); border-color: var(--accent); background: transparent; }
|
||||
@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) ----
|
||||
The text runs on from one original page to the next so every sheet is full,
|
||||
at the size chosen on screen (1 CSS px = 0.75 pt, so the default 19 px is ~14 pt). */
|
||||
@page {
|
||||
size: A4;
|
||||
margin: 14mm 15mm 16mm;
|
||||
@bottom-center { content: counter(page) " / " counter(pages); font-family: system-ui, sans-serif; font-size: 9pt; color: #666; }
|
||||
}
|
||||
@media print {
|
||||
:root, :root[data-theme] {
|
||||
--bg: #fff; --fg: #000; --muted: #444; --line: #ccc; --accent: #000;
|
||||
|
|
@ -234,11 +363,13 @@ body.reading .lines-nav .read-only { display: inline-block; }
|
|||
body { background: #fff; }
|
||||
.layout { display: block; }
|
||||
.panel, .lines-nav { display: none !important; }
|
||||
.script { padding: 0; font-size: calc(var(--script-size) * 0.7); line-height: 1.35; orphans: 3; widows: 3; }
|
||||
.script { padding: 0; font-size: var(--script-size); line-height: 1.4; orphans: 2; widows: 2; }
|
||||
.script > * { max-width: none; }
|
||||
.page { border: 0; padding: 0; break-before: page; }
|
||||
.page:first-child { break-before: auto; }
|
||||
.speech { margin: 0.6em 0; }
|
||||
.page { border: 0; padding: 0; }
|
||||
/* original page numbers stay as small markers in the margin of the flow */
|
||||
.pnum { font-size: 0.65em; margin: 0.6em 0 0.2em; text-align: right; }
|
||||
.missing-note { padding: 0.4em 0; }
|
||||
.speech { margin: 0.5em 0; }
|
||||
.speech.current { outline: none; }
|
||||
.speech.mine .say { -webkit-print-color-adjust: exact; print-color-adjust: exact; }
|
||||
.speech.mine .who { text-decoration: underline; }
|
||||
|
|
|
|||
72
public/edit.html
Normal file
72
public/edit.html
Normal file
|
|
@ -0,0 +1,72 @@
|
|||
<!doctype html>
|
||||
<html lang="cs">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Upravit hru – Divadelní čtečka</title>
|
||||
<link rel="stylesheet" href="fonts/fonts.css">
|
||||
<link rel="stylesheet" href="app.css">
|
||||
<script type="module" src="edit.js"></script>
|
||||
</head>
|
||||
<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">
|
||||
<span class="muted small" id="saved"></span>
|
||||
<button id="save" class="primary">Uložit</button>
|
||||
</div>
|
||||
</header>
|
||||
<main class="wrap wide">
|
||||
<p class="error" id="error" hidden></p>
|
||||
<div class="progress" id="progress" hidden>
|
||||
<progress id="bar" max="1" value="0"></progress>
|
||||
<p id="status"></p>
|
||||
</div>
|
||||
|
||||
<div class="meta-row">
|
||||
<label class="field grow"><span>Název</span><input id="title" maxlength="200"></label>
|
||||
<label class="field grow"><span>Poznámka</span><input id="note" maxlength="500"></label>
|
||||
<label class="field toggle"><input type="checkbox" id="published"> <span>Zveřejněno</span></label>
|
||||
</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>>(Odejde)</code></td><td>scénická poznámka; pokračování na dalším řádku začíná <code>> </code></td></tr>
|
||||
<tr><td><code>> verš</code></td><td>verš / píseň (dvě mezery za <code>></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>
|
||||
</table>
|
||||
<p>Rozdělené slovo na konci řádku nechte se spojovníkem (<code>nepří-</code>), čtečka ho spojí. Pomlčku jako interpunkci na konci řádku pište jako <code>–</code>.</p>
|
||||
</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 hru</button>
|
||||
</div>
|
||||
</aside>
|
||||
</div>
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
166
public/edit.js
Normal file
166
public/edit.js
Normal file
|
|
@ -0,0 +1,166 @@
|
|||
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 meta;
|
||||
let savedText = "";
|
||||
let img = 1;
|
||||
let leaving = false;
|
||||
|
||||
const dirty = () => $("text").value !== savedText
|
||||
|| $("title").value !== meta.title || $("note").value !== (meta.note || "") || $("published").checked !== meta.published;
|
||||
|
||||
function showError(msg) { $("error").textContent = msg; $("error").hidden = !msg; }
|
||||
|
||||
function check() {
|
||||
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 = [
|
||||
...(meta.failedPages || []).map((f) => ({ page: null, image: f.image, message: `Fotku ${f.image} se nepodařilo přepsat: ${f.error}` })),
|
||||
...lint(pages),
|
||||
];
|
||||
// Names used only once are often misreadings of another name.
|
||||
for (const c of cast) if (c.count === 1 && cast.length > 2) issues.push({ page: null, find: `@${c.name}`, message: `Postava „${c.name}“ mluví jen jednou – překlep?` });
|
||||
$("issues").innerHTML = issues.length
|
||||
? issues.slice(0, 200).map((x, i) => `<li><button class="link" data-i="${i}">${x.page && x.page !== "?" ? `str. ${esc(x.page)}: ` : ""}${esc(x.message)}</button></li>`).join("")
|
||||
: `<li class="muted">Žádné problémy nenalezeny.</li>`;
|
||||
$("issues").onclick = (e) => {
|
||||
const b = e.target.closest("button[data-i]");
|
||||
if (!b) return;
|
||||
const x = issues[Number(b.dataset.i)];
|
||||
if (x.image) showImage(x.image);
|
||||
else jumpTo(x.find || (x.page && x.page !== "?" ? `=${x.page}` : null), x.message.match(/„(.*)“/)?.[1]);
|
||||
};
|
||||
$("retry").hidden = !(meta.failedPages?.length && !meta.edited);
|
||||
}
|
||||
|
||||
// Select `needle` (or the line containing `inner`) in the textarea and scroll it into view.
|
||||
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);
|
||||
}
|
||||
|
||||
// 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;
|
||||
}
|
||||
|
||||
// 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];
|
||||
}
|
||||
|
||||
async function save() {
|
||||
showError("");
|
||||
$("save").disabled = true;
|
||||
try {
|
||||
await withLogin(async () => {
|
||||
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").textContent = `Uloženo ${new Date().toLocaleTimeString("cs-CZ", { hour: "2-digit", minute: "2-digit" })}`;
|
||||
check();
|
||||
} catch (err) {
|
||||
showError(`Uložení se nepovedlo: ${err.message}`);
|
||||
} finally {
|
||||
$("save").disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function waitForJob() {
|
||||
$("text").readOnly = true;
|
||||
$("save").disabled = true;
|
||||
$("progress").hidden = false;
|
||||
while (meta.status === "processing") {
|
||||
const p = meta.progress || { done: 0, total: meta.images };
|
||||
$("status").textContent = `Přepisuji stranu ${Math.min(p.done + 1, p.total)} z ${p.total}… (stránku můžete zavřít, přepis poběží dál)`;
|
||||
$("bar").value = p.total ? p.done / p.total : 0;
|
||||
await new Promise((r) => setTimeout(r, 2000));
|
||||
meta = await api(`plays/${enc}`);
|
||||
}
|
||||
$("progress").hidden = true;
|
||||
$("text").readOnly = false;
|
||||
$("save").disabled = false;
|
||||
savedText = await api(`plays/${enc}/text`);
|
||||
$("text").value = savedText;
|
||||
if (meta.jobError) showError(`Přepis se nepovedl: ${meta.jobError}`);
|
||||
check();
|
||||
}
|
||||
|
||||
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", () => { clearTimeout(timer); timer = setTimeout(check, 400); });
|
||||
$("text").addEventListener("keydown", (e) => {
|
||||
if ((e.ctrlKey || e.metaKey) && e.key === "s") { e.preventDefault(); save(); }
|
||||
});
|
||||
$("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" }));
|
||||
await waitForJob();
|
||||
} catch (err) { showError(err.message); }
|
||||
});
|
||||
$("delete").addEventListener("click", async () => {
|
||||
if (!confirm(`Opravdu smazat hru „${meta.title}“ i s fotkami? Nejde to vrátit.`)) return;
|
||||
try {
|
||||
await withLogin(() => api(`plays/${enc}`, { method: "DELETE" }));
|
||||
leaving = true;
|
||||
location.replace("./");
|
||||
} catch (err) { showError(err.message); }
|
||||
});
|
||||
window.addEventListener("beforeunload", (e) => { if (!leaving && meta.status !== "processing" && dirty()) e.preventDefault(); });
|
||||
|
||||
if (meta.status === "processing") await waitForJob();
|
||||
}
|
||||
|
||||
main().catch((err) => showError(err.status === 404 ? "Hra nenalezena." : err.message));
|
||||
|
|
@ -6,68 +6,19 @@
|
|||
<title>Divadelní čtečka</title>
|
||||
<link rel="stylesheet" href="fonts/fonts.css">
|
||||
<link rel="stylesheet" href="app.css">
|
||||
<script type="module" src="app.js"></script>
|
||||
<script type="module" src="library.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div class="layout">
|
||||
<aside class="panel" aria-label="Nastavení">
|
||||
<body class="page-library">
|
||||
<header class="topbar">
|
||||
<h1>Divadelní čtečka</h1>
|
||||
|
||||
<label class="field" id="play-field" hidden>
|
||||
<span>Hra</span>
|
||||
<select id="play"></select>
|
||||
</label>
|
||||
<p class="play-note" id="play-note"></p>
|
||||
|
||||
<label class="field">
|
||||
<span>Moje postava</span>
|
||||
<select id="role"><option value="">— žádná —</option></select>
|
||||
</label>
|
||||
|
||||
<fieldset class="field">
|
||||
<legend>Písmo</legend>
|
||||
<div class="fonts" id="fonts"></div>
|
||||
</fieldset>
|
||||
|
||||
<label class="field">
|
||||
<span>Velikost písma <output id="size-out"></output></span>
|
||||
<input type="range" id="size" min="14" max="30" step="1">
|
||||
</label>
|
||||
|
||||
<fieldset class="field">
|
||||
<legend>Podoba textu</legend>
|
||||
<label class="radio"><input type="radio" name="layout" value="flow"> Plynulý text <small>čitelnější, doplněné mezery</small></label>
|
||||
<label class="radio"><input type="radio" name="layout" value="original"> Jako v originále <small>řádky strojopisu</small></label>
|
||||
</fieldset>
|
||||
|
||||
<fieldset class="field">
|
||||
<legend>Barvy</legend>
|
||||
<div class="seg" id="theme">
|
||||
<label><input type="radio" name="theme" value="light"> Světlé</label>
|
||||
<label><input type="radio" name="theme" value="sepia"> Sépie</label>
|
||||
<label><input type="radio" name="theme" value="dark"> Tmavé</label>
|
||||
<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>
|
||||
</fieldset>
|
||||
|
||||
<div class="actions">
|
||||
<button id="read" class="primary">Číst</button>
|
||||
<button id="export">Exportovat PDF</button>
|
||||
</div>
|
||||
<p class="hint">PDF se ukládá přes dialog tisku – jako tiskárnu zvolte <b>Uložit jako PDF</b>. Pro barevné zvýraznění zapněte „Grafika na pozadí“, pokud ji prohlížeč nabídne.</p>
|
||||
</aside>
|
||||
|
||||
<main class="script" id="script" tabindex="-1">
|
||||
<p class="loading">Načítám text…</p>
|
||||
</header>
|
||||
<main class="wrap">
|
||||
<p class="muted">Vyberte hru, zvolte svou postavu a čtěte nebo si stáhněte vlastní PDF se zvýrazněnými replikami.</p>
|
||||
<ul class="play-list" id="plays"><li class="muted">Načítám…</li></ul>
|
||||
</main>
|
||||
</div>
|
||||
|
||||
<nav class="lines-nav" id="lines-nav" hidden aria-label="Moje repliky">
|
||||
<button id="exit-read" class="exit" title="Konec čtení (Esc)">✕</button>
|
||||
<button id="prev" title="Předchozí replika (K)">▲</button>
|
||||
<span id="counter"></span>
|
||||
<button id="next" title="Další replika (J)">▼</button>
|
||||
<button id="smaller" class="read-only" title="Menší písmo">A−</button>
|
||||
<button id="larger" class="read-only" title="Větší písmo">A+</button>
|
||||
</nav>
|
||||
</body>
|
||||
</html>
|
||||
|
|
|
|||
34
public/library.js
Normal file
34
public/library.js
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
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);
|
||||
if (q.has("hra") || q.has("postava")) location.replace(`read.html${location.search}`);
|
||||
|
||||
const fmtDate = (iso) => new Date(iso).toLocaleDateString("cs-CZ", { day: "numeric", month: "numeric", year: "numeric" });
|
||||
|
||||
async function main() {
|
||||
const [cfg, plays] = await Promise.all([api("config"), api("plays")]);
|
||||
const loggedIn = Boolean(getPassword());
|
||||
$("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.${cfg.uploads ? " Přidejte první tlačítkem nahoře." : ""}</li>`;
|
||||
return;
|
||||
}
|
||||
$("plays").innerHTML = plays.map((p) => {
|
||||
const badge = p.status === "processing" ? `<span class="badge">přepisuje se ${p.progress ? `${p.progress.done}/${p.progress.total}` : ""}</span>`
|
||||
: !p.published ? `<span class="badge">koncept</span>` : "";
|
||||
return `<li class="play-card">
|
||||
<a class="play-main" href="read.html?hra=${encodeURIComponent(p.id)}">
|
||||
<span class="play-title">${esc(p.title)} ${badge}</span>
|
||||
${p.note ? `<span class="play-note">${esc(p.note)}</span>` : ""}
|
||||
<span class="play-meta">upraveno ${fmtDate(p.updated)}</span>
|
||||
</a>
|
||||
${loggedIn ? `<a class="button" href="edit.html?id=${encodeURIComponent(p.id)}">Upravit</a>` : ""}
|
||||
</li>`;
|
||||
}).join("");
|
||||
}
|
||||
|
||||
main().catch((err) => { $("plays").innerHTML = `<li class="error">Seznam her se nepodařilo načíst: ${esc(err.message)}</li>`; });
|
||||
|
|
@ -33,7 +33,7 @@ export function parsePlay(source) {
|
|||
close();
|
||||
continue;
|
||||
}
|
||||
if (!page) throw new Error(`Text before the first page marker: ${raw}`);
|
||||
if (!page) { page = { num: "?", missing: false, blocks: [] }; pages.push(page); }
|
||||
|
||||
if (raw.startsWith("@")) {
|
||||
lastSpeaker = raw.slice(1).trim();
|
||||
|
|
@ -63,8 +63,8 @@ export function parsePlay(source) {
|
|||
} else {
|
||||
// dialogue; after a page break or a standalone direction it belongs to the last speaker
|
||||
if (!block || block.type !== "speech") {
|
||||
if (!lastSpeaker) throw new Error(`Dialogue without a speaker on page ${page.num}`);
|
||||
block = { type: "speech", speaker: lastSpeaker, cont: true, parts: [] };
|
||||
// speaker "" = we don't know who says it (e.g. the first page is missing)
|
||||
block = { type: "speech", speaker: lastSpeaker || "", cont: true, parts: [] };
|
||||
page.blocks.push(block);
|
||||
}
|
||||
addPart("text", raw, false);
|
||||
|
|
@ -78,7 +78,7 @@ export function speakers(pages) {
|
|||
const counts = new Map();
|
||||
for (const p of pages)
|
||||
for (const b of p.blocks)
|
||||
if (b.type === "speech" && !b.cont) counts.set(b.speaker, (counts.get(b.speaker) || 0) + 1);
|
||||
if (b.type === "speech" && !b.cont && b.speaker) counts.set(b.speaker, (counts.get(b.speaker) || 0) + 1);
|
||||
return [...counts].sort((a, b) => b[1] - a[1]).map(([name, count]) => ({ name, count }));
|
||||
}
|
||||
|
||||
|
|
@ -106,3 +106,22 @@ export function tidySpacing(text) {
|
|||
.replace(/\( +/g, "(")
|
||||
.replace(/\s{2,}/g, " ");
|
||||
}
|
||||
|
||||
// Problems worth showing in the editor: [{ page, message }].
|
||||
export function lint(pages) {
|
||||
const out = [];
|
||||
const seen = new Set();
|
||||
for (const p of pages) {
|
||||
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) {
|
||||
if (b.type === "speech" && !b.speaker) out.push({ page: p.num, message: "Replika bez postavy (chybí řádek @Jméno)." });
|
||||
if (!b.parts) continue;
|
||||
for (const part of b.parts)
|
||||
for (const line of part.lines)
|
||||
if (line.includes("[?]")) out.push({ page: p.num, message: `Nejisté čtení: „${line.trim()}“` });
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,8 +0,0 @@
|
|||
[
|
||||
{
|
||||
"id": "hra-1931",
|
||||
"file": "hra.txt",
|
||||
"title": "Hra bez názvu (Mise, Lída, Lysák…)",
|
||||
"note": "Strojopis, děj roku 1931. Titulní strany 1–4 a strana 7 v předloze chybí."
|
||||
}
|
||||
]
|
||||
69
public/read.html
Normal file
69
public/read.html
Normal file
|
|
@ -0,0 +1,69 @@
|
|||
<!doctype html>
|
||||
<html lang="cs">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Divadelní čtečka</title>
|
||||
<link rel="stylesheet" href="fonts/fonts.css">
|
||||
<link rel="stylesheet" href="app.css">
|
||||
<script type="module" src="reader.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div class="layout">
|
||||
<aside class="panel" aria-label="Nastavení">
|
||||
<nav class="crumbs"><a href="./">← Všechny hry</a><a id="edit-link" hidden>Upravit text</a></nav>
|
||||
<h1 id="play-title">Divadelní čtečka</h1>
|
||||
<p class="play-note" id="play-note"></p>
|
||||
|
||||
<label class="field">
|
||||
<span>Moje postava</span>
|
||||
<select id="role"><option value="">— žádná —</option></select>
|
||||
</label>
|
||||
|
||||
<fieldset class="field">
|
||||
<legend>Písmo</legend>
|
||||
<div class="fonts" id="fonts"></div>
|
||||
</fieldset>
|
||||
|
||||
<label class="field">
|
||||
<span>Velikost písma <output id="size-out"></output></span>
|
||||
<input type="range" id="size" min="14" max="30" step="1">
|
||||
</label>
|
||||
|
||||
<fieldset class="field">
|
||||
<legend>Podoba textu</legend>
|
||||
<label class="radio"><input type="radio" name="layout" value="flow"> Plynulý text <small>čitelnější, doplněné mezery</small></label>
|
||||
<label class="radio"><input type="radio" name="layout" value="original"> Jako v originále <small>řádky strojopisu</small></label>
|
||||
</fieldset>
|
||||
|
||||
<fieldset class="field">
|
||||
<legend>Barvy</legend>
|
||||
<div class="seg" id="theme">
|
||||
<label><input type="radio" name="theme" value="light"> Světlé</label>
|
||||
<label><input type="radio" name="theme" value="sepia"> Sépie</label>
|
||||
<label><input type="radio" name="theme" value="dark"> Tmavé</label>
|
||||
</div>
|
||||
</fieldset>
|
||||
|
||||
<div class="actions">
|
||||
<button id="read" class="primary">Číst</button>
|
||||
<button id="export">Exportovat PDF</button>
|
||||
</div>
|
||||
<p class="hint">PDF se ukládá přes dialog tisku (text vyplní celé stránky A4) – jako tiskárnu zvolte <b>Uložit jako PDF</b>. Pro barevné zvýraznění zapněte „Grafika na pozadí“, pokud ji prohlížeč nabídne.</p>
|
||||
</aside>
|
||||
|
||||
<main class="script" id="script" tabindex="-1">
|
||||
<p class="loading">Načítám text…</p>
|
||||
</main>
|
||||
</div>
|
||||
|
||||
<nav class="lines-nav" id="lines-nav" hidden aria-label="Moje repliky">
|
||||
<button id="exit-read" class="exit" title="Konec čtení (Esc)">✕</button>
|
||||
<button id="prev" title="Předchozí replika (K)">▲</button>
|
||||
<span id="counter"></span>
|
||||
<button id="next" title="Další replika (J)">▼</button>
|
||||
<button id="smaller" class="read-only" title="Menší písmo">A−</button>
|
||||
<button id="larger" class="read-only" title="Větší písmo">A+</button>
|
||||
</nav>
|
||||
</body>
|
||||
</html>
|
||||
|
|
@ -1,4 +1,5 @@
|
|||
import { parsePlay, speakers, joinLines, tidySpacing } from "./parse.js";
|
||||
import { api, getPassword, esc, $ } from "./api.js";
|
||||
|
||||
const FONTS = [
|
||||
{ id: "courier", label: "Psací stroj", family: "'Courier Prime', 'Courier New', monospace", mono: true },
|
||||
|
|
@ -8,11 +9,10 @@ const FONTS = [
|
|||
{ id: "system", label: "Systémové", family: "system-ui, -apple-system, 'Segoe UI', sans-serif" },
|
||||
];
|
||||
const STORE_KEY = "theater-reader:v1";
|
||||
const DEFAULTS = { play: "", role: "", font: "atkinson", size: 19, layout: "flow", theme: "light" };
|
||||
const DEFAULTS = { roles: {}, role: "", font: "atkinson", size: 19, layout: "flow", theme: "light" };
|
||||
|
||||
const $ = (id) => document.getElementById(id);
|
||||
let settings = loadSettings();
|
||||
let plays = [];
|
||||
let play = null; // meta of the open play
|
||||
let pages = [];
|
||||
let mine = []; // the selected role's speech elements, in order
|
||||
let current = -1;
|
||||
|
|
@ -23,21 +23,21 @@ function loadSettings() {
|
|||
const s = { ...DEFAULTS, ...saved };
|
||||
// ?postava=Lída lets a director send each actor a ready link
|
||||
const q = new URLSearchParams(location.search);
|
||||
if (q.has("postava")) s.role = q.get("postava");
|
||||
if (q.has("hra")) s.play = q.get("hra");
|
||||
s.urlRole = q.get("postava"); // the role is remembered per play, a link can override it
|
||||
return s;
|
||||
}
|
||||
|
||||
function save() {
|
||||
try { localStorage.setItem(STORE_KEY, JSON.stringify(settings)); } catch { /* ignore */ }
|
||||
if (play) settings.roles = { ...settings.roles, [play.id]: settings.role };
|
||||
const { role, urlRole, ...stored } = settings;
|
||||
try { localStorage.setItem(STORE_KEY, JSON.stringify(stored)); } catch { /* ignore */ }
|
||||
const q = new URLSearchParams(location.search);
|
||||
if (settings.role) q.set("postava", settings.role); else q.delete("postava");
|
||||
if (plays.length > 1 && settings.play) q.set("hra", settings.play); else q.delete("hra");
|
||||
if (play) q.set("hra", play.id);
|
||||
const qs = q.toString();
|
||||
history.replaceState(null, "", qs ? `?${qs}` : location.pathname);
|
||||
}
|
||||
|
||||
const esc = (s) => s.replace(/[&<>"]/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """ })[c]);
|
||||
|
||||
function renderPart(part, flow) {
|
||||
const cls = { text: "t", stage: "stage", verse: "verse" }[part.kind];
|
||||
|
|
@ -139,13 +139,17 @@ function fillRoles() {
|
|||
.join("");
|
||||
}
|
||||
|
||||
async function loadPlay() {
|
||||
const play = plays.find((p) => p.id === settings.play) || plays[0];
|
||||
settings.play = play.id;
|
||||
async function loadPlay(id) {
|
||||
play = await api(`plays/${encodeURIComponent(id)}`);
|
||||
settings.role = settings.urlRole ?? settings.roles?.[play.id] ?? "";
|
||||
document.title = `${play.title} – Divadelní čtečka`;
|
||||
$("play-title").textContent = play.title;
|
||||
$("play-note").textContent = play.note || "";
|
||||
const res = await fetch(`plays/${play.file}`);
|
||||
if (!res.ok) throw new Error(`plays/${play.file}: HTTP ${res.status}`);
|
||||
pages = parsePlay(await res.text());
|
||||
if (getPassword()) {
|
||||
$("edit-link").href = `edit.html?id=${encodeURIComponent(play.id)}`;
|
||||
$("edit-link").hidden = false;
|
||||
}
|
||||
pages = parsePlay(await api(`plays/${encodeURIComponent(id)}/text`));
|
||||
fillRoles();
|
||||
renderScript();
|
||||
save();
|
||||
|
|
@ -158,7 +162,6 @@ function setReading(on) {
|
|||
}
|
||||
|
||||
function exportPdf() {
|
||||
const play = plays.find((p) => p.id === settings.play);
|
||||
const before = document.title;
|
||||
// the browser proposes the document title as the PDF file name
|
||||
document.title = [play?.title.replace(/\s*\(.*\)/, ""), settings.role].filter(Boolean).join(" – ");
|
||||
|
|
@ -168,7 +171,6 @@ function exportPdf() {
|
|||
|
||||
function wire() {
|
||||
$("role").addEventListener("change", (e) => { settings.role = e.target.value; renderScript(); save(); });
|
||||
$("play").addEventListener("change", (e) => { settings.play = e.target.value; loadPlay(); });
|
||||
$("fonts").addEventListener("change", (e) => { settings.font = e.target.value; applyLook(); save(); });
|
||||
$("size").addEventListener("input", (e) => { settings.size = +e.target.value; applyLook(); save(); });
|
||||
document.querySelectorAll("input[name=layout]").forEach((r) =>
|
||||
|
|
@ -195,16 +197,18 @@ async function main() {
|
|||
applyLook();
|
||||
fillControls();
|
||||
wire();
|
||||
const id = new URLSearchParams(location.search).get("hra");
|
||||
try {
|
||||
plays = await (await fetch("plays/index.json")).json();
|
||||
if (plays.length > 1) {
|
||||
$("play-field").hidden = false;
|
||||
$("play").innerHTML = plays.map((p) => `<option value="${esc(p.id)}">${esc(p.title)}</option>`).join("");
|
||||
$("play").value = settings.play || plays[0].id;
|
||||
if (id) await loadPlay(id);
|
||||
else {
|
||||
// no play chosen (old link): open the first one
|
||||
const plays = await api("plays");
|
||||
if (!plays.length) { location.replace("./"); return; }
|
||||
await loadPlay(plays[0].id);
|
||||
}
|
||||
await loadPlay();
|
||||
} catch (err) {
|
||||
$("script").innerHTML = `<p class="error">Text se nepodařilo načíst: ${esc(String(err.message || err))}</p>`;
|
||||
const msg = err.status === 404 ? "Tato hra neexistuje nebo ještě není zveřejněná." : `Text se nepodařilo načíst: ${err.message || err}`;
|
||||
$("script").innerHTML = `<p class="error">${esc(msg)} <a href="./">Zpět na seznam her</a></p>`;
|
||||
}
|
||||
}
|
||||
|
||||
13
seed/hra-1931/meta.json
Normal file
13
seed/hra-1931/meta.json
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
{
|
||||
"id": "hra-1931",
|
||||
"title": "Hra bez názvu (Mise, Lída, Lysák…)",
|
||||
"note": "Strojopis, děj roku 1931. Titulní strany 1–4 a strana 7 v předloze chybí.",
|
||||
"published": true,
|
||||
"status": "draft",
|
||||
"created": "2026-11-02T00:00:00.000Z",
|
||||
"updated": "2026-11-02T00:00:00.000Z",
|
||||
"images": 0,
|
||||
"pages": [],
|
||||
"progress": null,
|
||||
"edited": true
|
||||
}
|
||||
287
server/main.mjs
Normal file
287
server/main.mjs
Normal file
|
|
@ -0,0 +1,287 @@
|
|||
// Theater reader server: serves the app from public/ and a small JSON API for
|
||||
// plays stored on a volume. Uploading and editing need UPLOAD_PASSWORD;
|
||||
// transcription additionally needs ANTHROPIC_API_KEY.
|
||||
import http from "node:http";
|
||||
import { readFile, writeFile, stat } from "node:fs/promises";
|
||||
import { createHash, timingSafeEqual } from "node:crypto";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { createStore, NotFound } from "./store.mjs";
|
||||
import { DEFAULT_MODEL, makeClient, transcribePage, describeError, splitPage, assemble } from "./transcribe.mjs";
|
||||
|
||||
const here = path.dirname(fileURLToPath(import.meta.url));
|
||||
const env = process.env;
|
||||
export const config = {
|
||||
port: Number(env.PORT || 8080),
|
||||
dataDir: env.DATA_DIR || "/data",
|
||||
publicDir: path.resolve(here, "../public"),
|
||||
seedDir: path.resolve(here, "../seed"),
|
||||
apiKey: env.ANTHROPIC_API_KEY || "",
|
||||
model: env.CLAUDE_MODEL || DEFAULT_MODEL,
|
||||
password: env.UPLOAD_PASSWORD || "",
|
||||
dailyPageLimit: Number(env.DAILY_PAGE_LIMIT || 300),
|
||||
maxPages: Number(env.MAX_PAGES || 80),
|
||||
maxImageBytes: 8 * 1024 * 1024,
|
||||
maxTextBytes: 2 * 1024 * 1024,
|
||||
concurrency: 3,
|
||||
};
|
||||
|
||||
const MIME = {
|
||||
".html": "text/html; charset=utf-8", ".js": "text/javascript; charset=utf-8", ".css": "text/css; charset=utf-8",
|
||||
".json": "application/json; charset=utf-8", ".txt": "text/plain; charset=utf-8", ".woff2": "font/woff2",
|
||||
".svg": "image/svg+xml", ".png": "image/png", ".ico": "image/x-icon",
|
||||
};
|
||||
const SECURITY_HEADERS = {
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
"Referrer-Policy": "no-referrer",
|
||||
"Content-Security-Policy": "default-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' blob: data:; frame-ancestors 'none'",
|
||||
};
|
||||
|
||||
class HttpError extends Error {
|
||||
constructor(status, message) { super(message); this.status = status; }
|
||||
}
|
||||
|
||||
function send(res, status, body, type = "application/json; charset=utf-8", extra = {}) {
|
||||
const data = typeof body === "string" || Buffer.isBuffer(body) ? body : JSON.stringify(body);
|
||||
res.writeHead(status, { "Content-Type": type, "Cache-Control": "no-cache", ...SECURITY_HEADERS, ...extra });
|
||||
res.end(data);
|
||||
}
|
||||
|
||||
async function readBody(req, limit) {
|
||||
const chunks = [];
|
||||
let size = 0;
|
||||
for await (const chunk of req) {
|
||||
size += chunk.length;
|
||||
if (size > limit) throw new HttpError(413, "Soubor je příliš velký.");
|
||||
chunks.push(chunk);
|
||||
}
|
||||
return Buffer.concat(chunks);
|
||||
}
|
||||
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."); }
|
||||
}
|
||||
|
||||
const digest = (s) => createHash("sha256").update(String(s)).digest();
|
||||
function isAuthed(req) {
|
||||
const given = req.headers["x-upload-password"];
|
||||
return Boolean(config.password && given && timingSafeEqual(digest(given), digest(config.password)));
|
||||
}
|
||||
async function requireAuth(req) {
|
||||
if (!config.password) throw new HttpError(403, "Nahrávání je vypnuté: na serveru není nastavené UPLOAD_PASSWORD.");
|
||||
if (!isAuthed(req)) {
|
||||
await new Promise((r) => setTimeout(r, 1000)); // slow down password guessing
|
||||
throw new HttpError(401, "Špatné heslo.");
|
||||
}
|
||||
}
|
||||
|
||||
// ---- usage cap: pages transcribed per UTC day, so a leaked password can't run up a big bill
|
||||
async function takePages(n) {
|
||||
const file = path.join(config.dataDir, "usage.json");
|
||||
const day = new Date().toISOString().slice(0, 10);
|
||||
let usage = {};
|
||||
try { usage = JSON.parse(await readFile(file, "utf8")); } catch { /* first use */ }
|
||||
const used = usage.day === day ? usage.pages : 0;
|
||||
if (used + n > config.dailyPageLimit)
|
||||
throw new HttpError(429, `Denní limit ${config.dailyPageLimit} stran je vyčerpán (dnes už ${used}). Zkuste to zítra.`);
|
||||
await writeFile(file, JSON.stringify({ day, pages: used + n }));
|
||||
}
|
||||
|
||||
// ---- transcription job (runs in the background; progress lives in meta.json)
|
||||
const running = new Set();
|
||||
export async function runJob(store, id, client) {
|
||||
if (running.has(id)) return;
|
||||
running.add(id);
|
||||
try {
|
||||
const meta = await store.getMeta(id);
|
||||
const results = meta.pages.slice(0, meta.images);
|
||||
const todo = [];
|
||||
for (let i = 0; i < meta.images; i++) if (!results[i] || results[i].error) todo.push(i);
|
||||
let done = meta.images - todo.length;
|
||||
await store.updateMeta(id, () => ({ status: "processing", progress: { done, total: meta.images } }));
|
||||
|
||||
const worker = async () => {
|
||||
while (todo.length) {
|
||||
const i = todo.shift();
|
||||
let result;
|
||||
try {
|
||||
const { text } = await transcribePage(client, config.model, await store.getImage(id, i + 1));
|
||||
result = splitPage(text);
|
||||
} catch (err) {
|
||||
console.error(`[${id}] page ${i + 1}: ${describeError(err)}`);
|
||||
result = { num: "?", error: describeError(err) };
|
||||
}
|
||||
results[i] = result;
|
||||
done++;
|
||||
await store.updateMeta(id, (m) => {
|
||||
const pages = m.pages.slice();
|
||||
pages[i] = result;
|
||||
return { pages, progress: { done, total: meta.images } };
|
||||
});
|
||||
}
|
||||
};
|
||||
await Promise.all(Array.from({ length: config.concurrency }, worker));
|
||||
|
||||
const failed = results.filter((r) => r.error).length;
|
||||
await store.setText(id, assemble(results));
|
||||
await store.updateMeta(id, () => ({ status: "draft", progress: null, failed, model: config.model }));
|
||||
} catch (err) {
|
||||
console.error(`[${id}] job failed:`, err);
|
||||
await store.updateMeta(id, () => ({ status: "draft", progress: null, jobError: describeError(err) })).catch(() => {});
|
||||
} finally {
|
||||
running.delete(id);
|
||||
}
|
||||
}
|
||||
|
||||
// ---- API
|
||||
const publicMeta = ({ pages, ...m }) => ({ ...m, failedPages: (pages || []).flatMap((p, i) => (p?.error ? [{ image: i + 1, error: p.error }] : [])) });
|
||||
|
||||
async function api(req, res, store, client, parts) {
|
||||
const method = req.method;
|
||||
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(config.apiKey), model: config.model, maxPages: config.maxPages });
|
||||
|
||||
if (parts[1] === "login" && method === "POST") { await requireAuth(req); return send(res, 200, { ok: true }); }
|
||||
|
||||
if (parts[1] !== "plays") throw new HttpError(404, "Nenalezeno.");
|
||||
|
||||
if (!id) {
|
||||
if (method === "GET") {
|
||||
const authed = isAuthed(req);
|
||||
const plays = (await store.list()).filter((p) => p.published || authed).map(publicMeta);
|
||||
return send(res, 200, plays);
|
||||
}
|
||||
if (method === "POST") {
|
||||
await requireAuth(req);
|
||||
const { title, note } = await readJson(req);
|
||||
if (typeof title !== "string" || !title.trim()) throw new HttpError(400, "Chybí název hry.");
|
||||
const meta = await store.create({ title: title.trim().slice(0, 200), note: String(note || "").trim().slice(0, 500) });
|
||||
return send(res, 201, publicMeta(meta));
|
||||
}
|
||||
throw new HttpError(405, "Metoda není povolena.");
|
||||
}
|
||||
|
||||
const meta = await store.getMeta(id);
|
||||
// Unpublished plays are visible only with the password.
|
||||
if (!meta.published && !isAuthed(req)) throw new NotFound(id);
|
||||
|
||||
if (!sub) {
|
||||
if (method === "GET") return send(res, 200, publicMeta(meta));
|
||||
if (method === "PATCH") {
|
||||
await requireAuth(req);
|
||||
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;
|
||||
return send(res, 200, publicMeta(await store.updateMeta(id, () => patch)));
|
||||
}
|
||||
if (method === "DELETE") {
|
||||
await requireAuth(req);
|
||||
if (running.has(id)) throw new HttpError(409, "Hra se právě přepisuje, chvíli počkejte.");
|
||||
await store.remove(id);
|
||||
return send(res, 200, { ok: true });
|
||||
}
|
||||
}
|
||||
|
||||
if (sub === "text") {
|
||||
if (method === "GET") return send(res, 200, await store.getText(id), MIME[".txt"]);
|
||||
if (method === "PUT") {
|
||||
await requireAuth(req);
|
||||
if (running.has(id)) throw new HttpError(409, "Hra se právě přepisuje, chvíli počkejte.");
|
||||
const text = (await readBody(req, config.maxTextBytes)).toString("utf8");
|
||||
await store.setText(id, text);
|
||||
return send(res, 200, publicMeta(await store.updateMeta(id, () => ({ edited: true }))));
|
||||
}
|
||||
}
|
||||
|
||||
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") {
|
||||
await requireAuth(req);
|
||||
if (running.has(id)) throw new HttpError(409, "Hra se právě přepisuje.");
|
||||
if (!Number.isInteger(num) || num < 1 || num > config.maxPages) throw new HttpError(400, `Nejvýše ${config.maxPages} stran.`);
|
||||
if (!/^image\/jpeg\b/.test(req.headers["content-type"] || "")) throw new HttpError(415, "Očekávám JPEG.");
|
||||
const buf = await readBody(req, config.maxImageBytes);
|
||||
if (buf[0] !== 0xff || buf[1] !== 0xd8) throw new HttpError(415, "Soubor není JPEG.");
|
||||
await store.putImage(id, num, buf);
|
||||
return send(res, 200, publicMeta(await store.updateMeta(id, (m) => {
|
||||
const pages = m.pages.slice();
|
||||
pages[num - 1] = null; // a replaced photo gets transcribed again
|
||||
return { images: Math.max(m.images, num), pages };
|
||||
})));
|
||||
}
|
||||
}
|
||||
|
||||
if (sub === "transcribe" && method === "POST") {
|
||||
await requireAuth(req);
|
||||
if (!config.apiKey) throw new HttpError(503, "Přepis není nastavený: na serveru chybí ANTHROPIC_API_KEY.");
|
||||
if (running.has(id)) throw new HttpError(409, "Přepis už běží.");
|
||||
if (!meta.images) throw new HttpError(400, "Nejdřív nahrajte fotky stran.");
|
||||
if (meta.edited) throw new HttpError(409, "Text už byl ručně upraven; nový přepis by úpravy přepsal.");
|
||||
const pending = Array.from({ length: meta.images }, (_, i) => meta.pages[i]).filter((p) => !p || p.error).length;
|
||||
if (!pending) throw new HttpError(400, "Všechny strany už jsou přepsané.");
|
||||
await takePages(pending);
|
||||
const next = await store.updateMeta(id, () => ({ status: "processing", progress: { done: meta.images - pending, total: meta.images }, jobError: null }));
|
||||
runJob(store, id, client);
|
||||
return send(res, 202, publicMeta(next));
|
||||
}
|
||||
|
||||
throw new HttpError(405, "Metoda není povolena.");
|
||||
}
|
||||
|
||||
// ---- static files
|
||||
async function serveStatic(req, res, pathname) {
|
||||
if (req.method !== "GET" && req.method !== "HEAD") throw new HttpError(405, "Metoda není povolena.");
|
||||
const rel = pathname === "/" ? "index.html" : decodeURIComponent(pathname).replace(/^\/+/, "");
|
||||
const file = path.resolve(config.publicDir, rel);
|
||||
if (!file.startsWith(config.publicDir + path.sep)) throw new HttpError(404, "Nenalezeno.");
|
||||
let info;
|
||||
try { info = await stat(file); } catch { throw new HttpError(404, "Nenalezeno."); }
|
||||
if (!info.isFile()) throw new HttpError(404, "Nenalezeno.");
|
||||
const ext = path.extname(file);
|
||||
const cache = rel.startsWith("fonts/") ? "public, max-age=2592000" : "no-cache";
|
||||
res.writeHead(200, { "Content-Type": MIME[ext] || "application/octet-stream", "Content-Length": info.size, "Cache-Control": cache, ...SECURITY_HEADERS });
|
||||
if (req.method === "HEAD") return res.end();
|
||||
res.end(await readFile(file));
|
||||
}
|
||||
|
||||
export function createServer(store, client) {
|
||||
return http.createServer(async (req, res) => {
|
||||
const { pathname } = new URL(req.url, "http://localhost");
|
||||
try {
|
||||
if (pathname === "/healthz") return send(res, 200, "ok", MIME[".txt"]);
|
||||
if (pathname.startsWith("/api/")) return await api(req, res, store, client, pathname.slice(4).split("/"));
|
||||
return await serveStatic(req, res, pathname);
|
||||
} catch (err) {
|
||||
if (err instanceof NotFound) return send(res, 404, { error: "Nenalezeno." });
|
||||
if (err instanceof HttpError) return send(res, err.status, { error: err.message });
|
||||
console.error(`${req.method} ${pathname}:`, err);
|
||||
if (!res.headersSent) send(res, 500, { error: "Chyba serveru." });
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const store = createStore(config.dataDir);
|
||||
await store.init();
|
||||
const seeded = await store.seed(config.seedDir);
|
||||
if (seeded) console.log(`seeded ${seeded} play(s) into ${store.root}`);
|
||||
const client = config.apiKey ? makeClient(config.apiKey) : null;
|
||||
|
||||
// Resume transcriptions interrupted by a restart.
|
||||
for (const meta of await store.list())
|
||||
if (meta.status === "processing") {
|
||||
if (client) runJob(store, meta.id, client);
|
||||
else await store.updateMeta(meta.id, () => ({ status: "draft", progress: null, jobError: "přepis přerušen" }));
|
||||
}
|
||||
|
||||
createServer(store, client).listen(config.port, () => {
|
||||
console.log(`theater-reader on :${config.port} (data ${config.dataDir}; uploads ${config.password ? "on" : "off"}; transcription ${client ? config.model : "off"})`);
|
||||
});
|
||||
}
|
||||
|
||||
if (process.argv[1] === fileURLToPath(import.meta.url)) main();
|
||||
37
server/prompt.mjs
Normal file
37
server/prompt.mjs
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
// Instructions for transcribing one photographed page of a play into the
|
||||
// reader's markup (documented in AGENTS.md). Kept byte-stable so the prompt
|
||||
// prefix can be cached across the pages of an upload.
|
||||
|
||||
export const SYSTEM_PROMPT = `You transcribe photographed pages of theatre play scripts (often old typescripts, often in Czech) into a plain-text markup used by a script-reading app.
|
||||
|
||||
Transcribe exactly what is on the page: keep the original spelling, punctuation, missing spaces ("dobře.Ale"), and line breaks. Do not translate, modernise, correct or summarise. Do not invent text you cannot read; if a word is illegible, write your best reading followed by [?].
|
||||
|
||||
Output only the markup, nothing else: no commentary, no code fences.
|
||||
|
||||
First line of output: "=" followed by the page number exactly as printed on the page (e.g. "-5-" gives "=5"). If no page number is visible, write "=?".
|
||||
|
||||
Markup, one directive per line:
|
||||
- "@Name" starts a new speech by Name. Write the character name the way the script writes it, in normal capitalisation (LÍDA -> Lída), without a trailing colon or period. Always spell the same character the same way.
|
||||
- A line with no prefix is dialogue belonging to the current speech. If the page starts in the middle of a speech continued from the previous page, start directly with the dialogue lines, without any "@" line.
|
||||
- ">(text" starts a stage direction (usually written in parentheses and indented); each further line of the same direction starts with "> " (greater-than, one space).
|
||||
- "> text" (greater-than, two spaces) is a verse or song line.
|
||||
- "#text" is a scene description written at the left margin (e.g. at the start of an act: where the scene takes place).
|
||||
- "~text" is a centred line: act or scene titles, "Opona" / "O p o n a", character lists centred on the page.
|
||||
- "." on its own line is a blank line. Put it before and after a stage direction that stands on its own between speeches (not inside one character's speech).
|
||||
- A hyphen that splits a word at the end of a line stays as "-" ("nepří-" then "jemné" on the next line). A dash that is punctuation at the end of a line must be written as an en dash "–".
|
||||
|
||||
Example:
|
||||
=12
|
||||
dobře.Ale proč právě já ?
|
||||
@Továrník
|
||||
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)
|
||||
.
|
||||
@Lída
|
||||
Jsem jen tak –
|
||||
~O p o n a`;
|
||||
|
||||
export const USER_PROMPT = "Transcribe this page into the markup.";
|
||||
120
server/store.mjs
Normal file
120
server/store.mjs
Normal file
|
|
@ -0,0 +1,120 @@
|
|||
// Plays on disk, one directory each under DATA_DIR/plays/<id>/:
|
||||
// meta.json { id, title, note, published, status, created, updated, images, pages, progress, model }
|
||||
// play.txt the markup
|
||||
// img/NNN.jpg the uploaded page photos, in upload order
|
||||
// Writes go to a temp file and are renamed into place so a crash never leaves half a file.
|
||||
import { mkdir, readFile, writeFile, rename, readdir, rm, cp, stat } from "node:fs/promises";
|
||||
import { randomBytes } from "node:crypto";
|
||||
import path from "node:path";
|
||||
|
||||
const ID_RE = /^[a-z0-9][a-z0-9-]{0,79}$/;
|
||||
|
||||
export class NotFound extends Error {}
|
||||
|
||||
export function slugify(title) {
|
||||
const base = title.normalize("NFD").replace(/\p{M}/gu, "").toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 50) || "hra";
|
||||
return `${base}-${randomBytes(3).toString("hex")}`;
|
||||
}
|
||||
|
||||
export function createStore(dataDir) {
|
||||
const root = path.join(dataDir, "plays");
|
||||
const dir = (id) => {
|
||||
if (!ID_RE.test(id)) throw new NotFound(id);
|
||||
return path.join(root, id);
|
||||
};
|
||||
|
||||
async function atomicWrite(file, data) {
|
||||
const tmp = `${file}.${randomBytes(4).toString("hex")}.tmp`;
|
||||
await writeFile(tmp, data);
|
||||
await rename(tmp, file);
|
||||
}
|
||||
|
||||
async function getMeta(id) {
|
||||
try {
|
||||
return JSON.parse(await readFile(path.join(dir(id), "meta.json"), "utf8"));
|
||||
} catch (err) {
|
||||
if (err.code === "ENOENT") throw new NotFound(id);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
// Serialise read-modify-write of one play's meta (the transcription job and
|
||||
// HTTP requests both update it).
|
||||
const locks = new Map();
|
||||
function updateMeta(id, fn) {
|
||||
const run = (locks.get(id) || Promise.resolve()).then(async () => {
|
||||
const meta = await getMeta(id);
|
||||
const next = { ...meta, ...(await fn(meta)), updated: new Date().toISOString() };
|
||||
await atomicWrite(path.join(dir(id), "meta.json"), JSON.stringify(next, null, 2));
|
||||
return next;
|
||||
});
|
||||
locks.set(id, run.catch(() => {}));
|
||||
return run;
|
||||
}
|
||||
|
||||
return {
|
||||
root,
|
||||
async init() { await mkdir(root, { recursive: true }); },
|
||||
|
||||
async list() {
|
||||
const ids = (await readdir(root, { withFileTypes: true })).filter((d) => d.isDirectory() && ID_RE.test(d.name));
|
||||
const metas = await Promise.all(ids.map((d) => getMeta(d.name).catch(() => null)));
|
||||
return metas.filter(Boolean).sort((a, b) => a.title.localeCompare(b.title, "cs"));
|
||||
},
|
||||
|
||||
getMeta,
|
||||
updateMeta,
|
||||
|
||||
async create({ title, note = "", id = slugify(title), text = "", published = false, status = "draft" }) {
|
||||
const d = dir(id);
|
||||
await mkdir(path.join(d, "img"), { recursive: true });
|
||||
const now = new Date().toISOString();
|
||||
const meta = { id, title, note, published, status, created: now, updated: now, images: 0, pages: [], progress: null };
|
||||
await atomicWrite(path.join(d, "play.txt"), text);
|
||||
await atomicWrite(path.join(d, "meta.json"), JSON.stringify(meta, null, 2));
|
||||
return meta;
|
||||
},
|
||||
|
||||
async getText(id) {
|
||||
try { return await readFile(path.join(dir(id), "play.txt"), "utf8"); }
|
||||
catch (err) { if (err.code === "ENOENT") throw new NotFound(id); throw err; }
|
||||
},
|
||||
async setText(id, text) {
|
||||
await getMeta(id);
|
||||
await atomicWrite(path.join(dir(id), "play.txt"), text);
|
||||
},
|
||||
|
||||
imagePath(id, n) {
|
||||
if (!Number.isInteger(n) || n < 1 || n > 999) throw new NotFound(`${id}/${n}`);
|
||||
return path.join(dir(id), "img", `${String(n).padStart(3, "0")}.jpg`);
|
||||
},
|
||||
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; }
|
||||
},
|
||||
async clearImages(id) {
|
||||
const d = path.join(dir(id), "img");
|
||||
await rm(d, { recursive: true, force: true });
|
||||
await mkdir(d);
|
||||
},
|
||||
|
||||
async remove(id) {
|
||||
await getMeta(id);
|
||||
await rm(dir(id), { recursive: true, force: true });
|
||||
},
|
||||
|
||||
// First start with an empty volume: copy in the plays bundled with the image.
|
||||
async seed(seedDir) {
|
||||
if ((await readdir(root)).length) return 0;
|
||||
let n = 0;
|
||||
for (const d of await readdir(seedDir).catch(() => [])) {
|
||||
if (!ID_RE.test(d) || !(await stat(path.join(seedDir, d))).isDirectory()) continue;
|
||||
await cp(path.join(seedDir, d), path.join(root, d), { recursive: true });
|
||||
n++;
|
||||
}
|
||||
return n;
|
||||
},
|
||||
};
|
||||
}
|
||||
125
server/transcribe.mjs
Normal file
125
server/transcribe.mjs
Normal file
|
|
@ -0,0 +1,125 @@
|
|||
// Turn page photos into play markup with a Claude vision model, one request
|
||||
// per page, then stitch the pages together.
|
||||
import Anthropic from "@anthropic-ai/sdk";
|
||||
import { SYSTEM_PROMPT, USER_PROMPT } from "./prompt.mjs";
|
||||
|
||||
export const DEFAULT_MODEL = "claude-haiku-5-5";
|
||||
|
||||
export class PageError extends Error {}
|
||||
|
||||
// Transcribe one JPEG. `client` is an Anthropic client (injected so tests can stub it).
|
||||
export async function transcribePage(client, model, jpeg) {
|
||||
const response = await client.messages.create({
|
||||
model,
|
||||
max_tokens: 16000,
|
||||
// Copying text off a page needs little reasoning; low effort keeps it cheap.
|
||||
output_config: { effort: "low" },
|
||||
system: [{ type: "text", text: SYSTEM_PROMPT, cache_control: { type: "ephemeral" } }],
|
||||
messages: [{
|
||||
role: "user",
|
||||
content: [
|
||||
{ type: "image", source: { type: "base64", media_type: "image/jpeg", data: jpeg.toString("base64") } },
|
||||
{ type: "text", text: USER_PROMPT },
|
||||
],
|
||||
}],
|
||||
});
|
||||
if (response.stop_reason === "refusal") throw new PageError("model declined to transcribe this page");
|
||||
if (response.stop_reason === "max_tokens") throw new PageError("transcription was cut off (page too long)");
|
||||
const text = response.content.filter((b) => b.type === "text").map((b) => b.text).join("").trim();
|
||||
if (!text) throw new PageError("model returned no text");
|
||||
return { text, usage: response.usage };
|
||||
}
|
||||
|
||||
export function makeClient(apiKey) {
|
||||
return new Anthropic({ apiKey, maxRetries: 4 });
|
||||
}
|
||||
|
||||
// A short, human-readable reason for a failed page (shown in the editor).
|
||||
export function describeError(err) {
|
||||
if (err instanceof PageError) return err.message;
|
||||
if (err instanceof Anthropic.AuthenticationError) return "API key rejected (check ANTHROPIC_API_KEY)";
|
||||
if (err instanceof Anthropic.PermissionDeniedError) return "API key not allowed to use this model";
|
||||
if (err instanceof Anthropic.NotFoundError) return "model not found (check CLAUDE_MODEL)";
|
||||
if (err instanceof Anthropic.RateLimitError) return "rate limited by the API, try again later";
|
||||
if (err instanceof Anthropic.BadRequestError) return `API rejected the request: ${err.message}`;
|
||||
if (err instanceof Anthropic.APIError) return `API error ${err.status ?? ""}: ${err.message}`.trim();
|
||||
return String(err?.message || err);
|
||||
}
|
||||
|
||||
// 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");
|
||||
let num = "?";
|
||||
const first = lines.findIndex((l) => l.trim() !== "");
|
||||
if (first >= 0 && /^=/.test(lines[first].trim())) {
|
||||
num = lines[first].trim().slice(1).replace(/^[-–\s]+|[-–.\s]+$/g, "") || "?";
|
||||
lines.splice(0, first + 1);
|
||||
}
|
||||
// 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 };
|
||||
}
|
||||
|
||||
const nameKey = (n) => n.normalize("NFD").replace(/\p{M}/gu, "").toLowerCase().replace(/[^\p{L}\p{N}]+/gu, " ").trim();
|
||||
|
||||
// Different pages may spell a name differently (LÍDA / Lída / Lida:). Map every
|
||||
// variant to one spelling: an ALL-CAPS name counts as its Title-case form, and a
|
||||
// spelling with diacritics wins over one without (OCR drops accents far more
|
||||
// often than it invents them), then the most frequent one.
|
||||
const titleCase = (s) => s.toLocaleLowerCase("cs").replace(/(^|[\s-])(\p{L})/gu, (m, a, b) => a + b.toLocaleUpperCase("cs"));
|
||||
const accents = (s) => s.normalize("NFD").match(/\p{M}/gu)?.length || 0;
|
||||
|
||||
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) => {
|
||||
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);
|
||||
}
|
||||
return n;
|
||||
};
|
||||
for (const body of bodies)
|
||||
for (const line of body.split("\n"))
|
||||
if (line.startsWith("@")) {
|
||||
const name = clean(line.slice(1));
|
||||
const key = nameKey(name);
|
||||
if (!key) continue;
|
||||
if (!variants.has(key)) variants.set(key, new Map());
|
||||
const m = variants.get(key);
|
||||
m.set(name, (m.get(name) || 0) + 1);
|
||||
}
|
||||
const best = new Map();
|
||||
for (const [key, m] of variants) {
|
||||
const asWritten = (s) => (fromCaps.has(s) ? 0 : 1);
|
||||
const rank = [...m.keys()].sort((a, b) => accents(b) - accents(a) || m.get(b) - m.get(a) || asWritten(b) - asWritten(a));
|
||||
best.set(key, rank[0]);
|
||||
}
|
||||
return bodies.map((body) => body.split("\n").map((line) => {
|
||||
if (!line.startsWith("@")) return line;
|
||||
const key = nameKey(clean(line.slice(1)));
|
||||
return best.has(key) ? `@${best.get(key)}` : line;
|
||||
}).join("\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 = [];
|
||||
let prev = 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}`);
|
||||
if (p.error) out.push(`>(Stranu se nepodařilo přepsat: ${p.error})`);
|
||||
else out.push(bodies[i]);
|
||||
});
|
||||
return out.join("\n") + "\n";
|
||||
}
|
||||
|
|
@ -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