Add plays from photos (OpenRouter or Claude), library, editor, compose; full-page PDF #2
33 changed files with 1928 additions and 160 deletions
|
|
@ -1,4 +1,6 @@
|
||||||
.git
|
.git
|
||||||
|
.env
|
||||||
|
node_modules
|
||||||
tests
|
tests
|
||||||
tools
|
tools
|
||||||
*.md
|
*.md
|
||||||
|
|
|
||||||
27
.env.example
Normal file
27
.env.example
Normal file
|
|
@ -0,0 +1,27 @@
|
||||||
|
# Copy to .env (chmod 600) and fill in. Never commit .env.
|
||||||
|
|
||||||
|
# Transcription of page photos. Set ONE of the two keys; OpenRouter wins if both are set.
|
||||||
|
# Without either the app still works; uploaded photos just have to be typed up by hand.
|
||||||
|
|
||||||
|
# OpenRouter key from https://openrouter.ai/settings/keys (prepaid credit).
|
||||||
|
OPENROUTER_API_KEY=
|
||||||
|
# Any OpenRouter model that accepts images. Default ~$0.0015 a page; google/gemini-2.5-flash-lite
|
||||||
|
# is cheaper (~$0.0005), anthropic/claude-haiku-5.5 or google/gemini-3.5-flash read hard pages better.
|
||||||
|
OPENROUTER_MODEL=google/gemini-3.1-flash-lite
|
||||||
|
|
||||||
|
# Or: Anthropic API key from https://platform.claude.com (billed separately from a Claude subscription).
|
||||||
|
ANTHROPIC_API_KEY=
|
||||||
|
|
||||||
|
# Password people need to add and edit plays. Without it uploading is switched off.
|
||||||
|
UPLOAD_PASSWORD=
|
||||||
|
|
||||||
|
# Claude model when using ANTHROPIC_API_KEY. 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
|
||||||
|
|
|
||||||
38
AGENTS.md
38
AGENTS.md
|
|
@ -1,22 +1,34 @@
|
||||||
# AGENTS.md — theater-reader
|
# 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. Page photos are transcribed by a vision model through OpenRouter (plain `fetch`, chosen when `OPENROUTER_API_KEY` is set) or the
|
||||||
|
Anthropic SDK (`@anthropic-ai/sdk`, the only dependency, used with `ANTHROPIC_API_KEY`).
|
||||||
|
UI language is Czech.
|
||||||
|
|
||||||
## Layout
|
## Layout
|
||||||
|
|
||||||
- `public/index.html`, `app.js`, `app.css` — the app. UI language is Czech.
|
- `server/main.mjs`: HTTP server, routing, static files, auth (`x-upload-password` header vs `UPLOAD_PASSWORD`), daily page cap, background transcription job.
|
||||||
- `public/parse.js` — parser for the play markup, also used by the tests.
|
- `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.
|
||||||
- `public/plays/index.json` — list of plays (`id`, `file`, `title`, `note`); a play selector appears once there is more than one.
|
- `server/providers.mjs`: `makeProvider(env)` returns `{ name, model, transcribe(jpeg) }` for OpenRouter or Anthropic. Errors become `PageError`s whose message is shown in the editor. OpenRouter retries 408/429/5xx and network errors itself.
|
||||||
- `public/plays/*.txt` — play texts in the markup below.
|
- `server/transcribe.mjs`: `splitPage` → `normalizeSpeakers` → `assemble` turn the per-photo answers into one play file. `server/prompt.mjs` holds the prompt (shared by both providers), which teaches the markup below.
|
||||||
- `public/fonts/` — self-hosted woff2 (latin + latin-ext) and their OFL licences, generated by `tools/fetch_fonts.py`.
|
- `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.
|
||||||
- `deploy/` — nginx config. `Dockerfile` at the root.
|
- `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
|
## 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`.
|
- Dev port **3010** on loopback. Preview with `ssh -p 14922 -L 3010:localhost:3010 <host>`.
|
||||||
The admin previews with `ssh -p 14922 -L 3010:localhost:3010 <host>`.
|
`podman-compose --env-file <file> up -d --build` (env file with `UPLOAD_PASSWORD`, and optionally `OPENROUTER_API_KEY` or `ANTHROPIC_API_KEY`, chmod 600, outside the repo).
|
||||||
- Tests (parser): `podman run --rm -v "$PWD":/app:ro,Z -w /app docker.io/library/node:22-alpine npm test`.
|
- Tests (parser, transcription assembly, API end to end with Claude stubbed):
|
||||||
- Fonts: `python3 tools/fetch_fonts.py` re-downloads them; edit `FAMILIES` there and the `FONTS` list in `app.js` together.
|
`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, use `ANTHROPIC_API_KEY=dummy` and point `ANTHROPIC_BASE_URL` at a stub server that returns a Messages response.
|
||||||
|
|
||||||
## Play markup
|
## Play markup
|
||||||
|
|
||||||
|
|
@ -37,6 +49,6 @@ One directive per line; blank lines are ignored.
|
||||||
The text keeps the typescript's line breaks, spelling and missing spaces ("dobře.Ale"). The "running text" mode joins
|
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
|
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.
|
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
|
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.
|
||||||
lines comes from whatever speech page 7 ends with.
|
|
||||||
|
|
|
||||||
25
Dockerfile
25
Dockerfile
|
|
@ -1,8 +1,23 @@
|
||||||
# Theater reader: a static site served by unprivileged nginx on port 8080.
|
# Theater reader: Node server for the app, the plays API and transcription.
|
||||||
FROM docker.io/nginxinc/nginx-unprivileged:1.27-alpine
|
FROM docker.io/library/node:22-alpine
|
||||||
|
|
||||||
COPY deploy/nginx.conf /etc/nginx/conf.d/default.conf
|
ENV NODE_ENV=production PORT=8080 DATA_DIR=/data
|
||||||
COPY deploy/security-headers.inc /etc/nginx/conf.d/security-headers.inc
|
WORKDIR /app
|
||||||
COPY public/ /usr/share/nginx/html/
|
|
||||||
|
|
||||||
|
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
|
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"]
|
||||||
|
|
|
||||||
43
README.md
43
README.md
|
|
@ -1,26 +1,47 @@
|
||||||
# Divadelní čtečka (theater reader)
|
# 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),
|
- 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),
|
- pick **your character**: your lines are highlighted and ▲ ▼ (or `J` / `K`) jump between them,
|
||||||
- switch between **running text** (hyphenation joined, spacing tidied) and the **original typescript lines**,
|
- **running text** (hyphenation joined, spacing tidied) or the **original typescript lines**,
|
||||||
- open **reading mode** (settings hidden, large text), or
|
- **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".
|
||||||
- **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".
|
|
||||||
|
|
||||||
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 vision model, through OpenRouter (default `google/gemini-3.1-flash-lite`) or the Anthropic API (`claude-haiku-5-5`), and turned into the script markup: speakers, stage directions, page numbers. Missing pages are noticed from gaps in the page numbers.
|
||||||
|
3. 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
|
```sh
|
||||||
podman build -t theater-reader .
|
cp .env.example .env && chmod 600 .env # then fill in the two secrets
|
||||||
podman run -d --name theater-reader -p 127.0.0.1:3010:8080 theater-reader
|
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 | |
|
||||||
|
|---|---|
|
||||||
|
| `OPENROUTER_API_KEY` | Key from [openrouter.ai](https://openrouter.ai/settings/keys) (prepaid credit). Used for transcription when set. |
|
||||||
|
| `OPENROUTER_MODEL` | Any OpenRouter model that accepts images. Default `google/gemini-3.1-flash-lite` (about $0.0015 a page). `google/gemini-2.5-flash-lite` is cheaper. `anthropic/claude-haiku-5.5` and `google/gemini-3.5-flash` are alternatives if pages come out badly. |
|
||||||
|
| `ANTHROPIC_API_KEY` | Instead of OpenRouter: an 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. |
|
||||||
|
| | Without either 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` | With the Anthropic key: `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
|
## 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`).
|
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;
|
|
||||||
24
docker-compose.yml
Normal file
24
docker-compose.yml
Normal file
|
|
@ -0,0 +1,24 @@
|
||||||
|
# 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:
|
||||||
|
OPENROUTER_API_KEY: ${OPENROUTER_API_KEY:-}
|
||||||
|
OPENROUTER_MODEL: ${OPENROUTER_MODEL:-google/gemini-3.1-flash-lite}
|
||||||
|
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",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"test": "node --test tests/*.test.mjs"
|
"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 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íč OPENROUTER_API_KEY nebo ANTHROPIC_API_KEY). Fotky se nahrají a text pak napíšete v editoru ručně.";
|
||||||
|
$("go").textContent = "Nahrát";
|
||||||
|
}
|
||||||
|
if (!getPassword()) askPassword("Přidávat hry může jen ten, kdo zná heslo.");
|
||||||
|
|
||||||
|
$("files").addEventListener("change", (e) => { addFiles(e.target.files); e.target.value = ""; });
|
||||||
|
const drop = $("drop");
|
||||||
|
drop.addEventListener("dragover", (e) => { e.preventDefault(); drop.classList.add("over"); });
|
||||||
|
drop.addEventListener("dragleave", () => drop.classList.remove("over"));
|
||||||
|
drop.addEventListener("drop", (e) => { e.preventDefault(); drop.classList.remove("over"); addFiles(e.dataTransfer.files); });
|
||||||
|
$("thumbs").addEventListener("click", (e) => {
|
||||||
|
const b = e.target.closest("button");
|
||||||
|
if (!b) return;
|
||||||
|
const i = Number(b.dataset.i);
|
||||||
|
if (b.hasAttribute("data-remove")) URL.revokeObjectURL(files.splice(i, 1)[0].url);
|
||||||
|
else {
|
||||||
|
const j = i + Number(b.dataset.move);
|
||||||
|
[files[i], files[j]] = [files[j], files[i]];
|
||||||
|
}
|
||||||
|
renderThumbs();
|
||||||
|
});
|
||||||
|
$("form").addEventListener("submit", submit);
|
||||||
|
window.addEventListener("beforeunload", warn);
|
||||||
|
renderThumbs();
|
||||||
|
}
|
||||||
|
|
||||||
|
main().catch((err) => showError(err.message));
|
||||||
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; }
|
:root[data-layout="original"] .stage { padding-left: 1.5em; }
|
||||||
}
|
}
|
||||||
|
|
||||||
/* ---- PDF export (print) ---- */
|
/* ---- shared bits for the library, upload and editor pages ---- */
|
||||||
@page { size: A4; margin: 18mm 16mm; }
|
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 {
|
@media print {
|
||||||
:root, :root[data-theme] {
|
:root, :root[data-theme] {
|
||||||
--bg: #fff; --fg: #000; --muted: #444; --line: #ccc; --accent: #000;
|
--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; }
|
body { background: #fff; }
|
||||||
.layout { display: block; }
|
.layout { display: block; }
|
||||||
.panel, .lines-nav { display: none !important; }
|
.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; }
|
.script > * { max-width: none; }
|
||||||
.page { border: 0; padding: 0; break-before: page; }
|
.page { border: 0; padding: 0; }
|
||||||
.page:first-child { break-before: auto; }
|
/* original page numbers stay as small markers in the margin of the flow */
|
||||||
.speech { margin: 0.6em 0; }
|
.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.current { outline: none; }
|
||||||
.speech.mine .say { -webkit-print-color-adjust: exact; print-color-adjust: exact; }
|
.speech.mine .say { -webkit-print-color-adjust: exact; print-color-adjust: exact; }
|
||||||
.speech.mine .who { text-decoration: underline; }
|
.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>
|
<title>Divadelní čtečka</title>
|
||||||
<link rel="stylesheet" href="fonts/fonts.css">
|
<link rel="stylesheet" href="fonts/fonts.css">
|
||||||
<link rel="stylesheet" href="app.css">
|
<link rel="stylesheet" href="app.css">
|
||||||
<script type="module" src="app.js"></script>
|
<script type="module" src="library.js"></script>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body class="page-library">
|
||||||
<div class="layout">
|
<header class="topbar">
|
||||||
<aside class="panel" aria-label="Nastavení">
|
<h1>Divadelní čtečka</h1>
|
||||||
<h1>Divadelní čtečka</h1>
|
<div class="topbar-actions">
|
||||||
|
<a class="button primary" id="add" href="add.html" hidden>+ Přidat hru</a>
|
||||||
<label class="field" id="play-field" hidden>
|
<button id="logout" hidden>Odhlásit</button>
|
||||||
<span>Hra</span>
|
</div>
|
||||||
<select id="play"></select>
|
</header>
|
||||||
</label>
|
<main class="wrap">
|
||||||
<p class="play-note" id="play-note"></p>
|
<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>
|
||||||
<label class="field">
|
</main>
|
||||||
<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 – 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>
|
</body>
|
||||||
</html>
|
</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();
|
close();
|
||||||
continue;
|
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("@")) {
|
if (raw.startsWith("@")) {
|
||||||
lastSpeaker = raw.slice(1).trim();
|
lastSpeaker = raw.slice(1).trim();
|
||||||
|
|
@ -63,8 +63,8 @@ export function parsePlay(source) {
|
||||||
} else {
|
} else {
|
||||||
// dialogue; after a page break or a standalone direction it belongs to the last speaker
|
// dialogue; after a page break or a standalone direction it belongs to the last speaker
|
||||||
if (!block || block.type !== "speech") {
|
if (!block || block.type !== "speech") {
|
||||||
if (!lastSpeaker) throw new Error(`Dialogue without a speaker on page ${page.num}`);
|
// speaker "" = we don't know who says it (e.g. the first page is missing)
|
||||||
block = { type: "speech", speaker: lastSpeaker, cont: true, parts: [] };
|
block = { type: "speech", speaker: lastSpeaker || "", cont: true, parts: [] };
|
||||||
page.blocks.push(block);
|
page.blocks.push(block);
|
||||||
}
|
}
|
||||||
addPart("text", raw, false);
|
addPart("text", raw, false);
|
||||||
|
|
@ -78,7 +78,7 @@ export function speakers(pages) {
|
||||||
const counts = new Map();
|
const counts = new Map();
|
||||||
for (const p of pages)
|
for (const p of pages)
|
||||||
for (const b of p.blocks)
|
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 }));
|
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(/\( +/g, "(")
|
||||||
.replace(/\s{2,}/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 { parsePlay, speakers, joinLines, tidySpacing } from "./parse.js";
|
||||||
|
import { api, getPassword, esc, $ } from "./api.js";
|
||||||
|
|
||||||
const FONTS = [
|
const FONTS = [
|
||||||
{ id: "courier", label: "Psací stroj", family: "'Courier Prime', 'Courier New', monospace", mono: true },
|
{ 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" },
|
{ id: "system", label: "Systémové", family: "system-ui, -apple-system, 'Segoe UI', sans-serif" },
|
||||||
];
|
];
|
||||||
const STORE_KEY = "theater-reader:v1";
|
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 settings = loadSettings();
|
||||||
let plays = [];
|
let play = null; // meta of the open play
|
||||||
let pages = [];
|
let pages = [];
|
||||||
let mine = []; // the selected role's speech elements, in order
|
let mine = []; // the selected role's speech elements, in order
|
||||||
let current = -1;
|
let current = -1;
|
||||||
|
|
@ -23,21 +23,21 @@ function loadSettings() {
|
||||||
const s = { ...DEFAULTS, ...saved };
|
const s = { ...DEFAULTS, ...saved };
|
||||||
// ?postava=Lída lets a director send each actor a ready link
|
// ?postava=Lída lets a director send each actor a ready link
|
||||||
const q = new URLSearchParams(location.search);
|
const q = new URLSearchParams(location.search);
|
||||||
if (q.has("postava")) s.role = q.get("postava");
|
s.urlRole = q.get("postava"); // the role is remembered per play, a link can override it
|
||||||
if (q.has("hra")) s.play = q.get("hra");
|
|
||||||
return s;
|
return s;
|
||||||
}
|
}
|
||||||
|
|
||||||
function save() {
|
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);
|
const q = new URLSearchParams(location.search);
|
||||||
if (settings.role) q.set("postava", settings.role); else q.delete("postava");
|
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();
|
const qs = q.toString();
|
||||||
history.replaceState(null, "", qs ? `?${qs}` : location.pathname);
|
history.replaceState(null, "", qs ? `?${qs}` : location.pathname);
|
||||||
}
|
}
|
||||||
|
|
||||||
const esc = (s) => s.replace(/[&<>"]/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """ })[c]);
|
|
||||||
|
|
||||||
function renderPart(part, flow) {
|
function renderPart(part, flow) {
|
||||||
const cls = { text: "t", stage: "stage", verse: "verse" }[part.kind];
|
const cls = { text: "t", stage: "stage", verse: "verse" }[part.kind];
|
||||||
|
|
@ -139,13 +139,17 @@ function fillRoles() {
|
||||||
.join("");
|
.join("");
|
||||||
}
|
}
|
||||||
|
|
||||||
async function loadPlay() {
|
async function loadPlay(id) {
|
||||||
const play = plays.find((p) => p.id === settings.play) || plays[0];
|
play = await api(`plays/${encodeURIComponent(id)}`);
|
||||||
settings.play = play.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 || "";
|
$("play-note").textContent = play.note || "";
|
||||||
const res = await fetch(`plays/${play.file}`);
|
if (getPassword()) {
|
||||||
if (!res.ok) throw new Error(`plays/${play.file}: HTTP ${res.status}`);
|
$("edit-link").href = `edit.html?id=${encodeURIComponent(play.id)}`;
|
||||||
pages = parsePlay(await res.text());
|
$("edit-link").hidden = false;
|
||||||
|
}
|
||||||
|
pages = parsePlay(await api(`plays/${encodeURIComponent(id)}/text`));
|
||||||
fillRoles();
|
fillRoles();
|
||||||
renderScript();
|
renderScript();
|
||||||
save();
|
save();
|
||||||
|
|
@ -158,7 +162,6 @@ function setReading(on) {
|
||||||
}
|
}
|
||||||
|
|
||||||
function exportPdf() {
|
function exportPdf() {
|
||||||
const play = plays.find((p) => p.id === settings.play);
|
|
||||||
const before = document.title;
|
const before = document.title;
|
||||||
// the browser proposes the document title as the PDF file name
|
// the browser proposes the document title as the PDF file name
|
||||||
document.title = [play?.title.replace(/\s*\(.*\)/, ""), settings.role].filter(Boolean).join(" – ");
|
document.title = [play?.title.replace(/\s*\(.*\)/, ""), settings.role].filter(Boolean).join(" – ");
|
||||||
|
|
@ -168,7 +171,6 @@ function exportPdf() {
|
||||||
|
|
||||||
function wire() {
|
function wire() {
|
||||||
$("role").addEventListener("change", (e) => { settings.role = e.target.value; renderScript(); save(); });
|
$("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(); });
|
$("fonts").addEventListener("change", (e) => { settings.font = e.target.value; applyLook(); save(); });
|
||||||
$("size").addEventListener("input", (e) => { settings.size = +e.target.value; applyLook(); save(); });
|
$("size").addEventListener("input", (e) => { settings.size = +e.target.value; applyLook(); save(); });
|
||||||
document.querySelectorAll("input[name=layout]").forEach((r) =>
|
document.querySelectorAll("input[name=layout]").forEach((r) =>
|
||||||
|
|
@ -195,16 +197,18 @@ async function main() {
|
||||||
applyLook();
|
applyLook();
|
||||||
fillControls();
|
fillControls();
|
||||||
wire();
|
wire();
|
||||||
|
const id = new URLSearchParams(location.search).get("hra");
|
||||||
try {
|
try {
|
||||||
plays = await (await fetch("plays/index.json")).json();
|
if (id) await loadPlay(id);
|
||||||
if (plays.length > 1) {
|
else {
|
||||||
$("play-field").hidden = false;
|
// no play chosen (old link): open the first one
|
||||||
$("play").innerHTML = plays.map((p) => `<option value="${esc(p.id)}">${esc(p.title)}</option>`).join("");
|
const plays = await api("plays");
|
||||||
$("play").value = settings.play || plays[0].id;
|
if (!plays.length) { location.replace("./"); return; }
|
||||||
|
await loadPlay(plays[0].id);
|
||||||
}
|
}
|
||||||
await loadPlay();
|
|
||||||
} catch (err) {
|
} 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
|
||||||
|
}
|
||||||
286
server/main.mjs
Normal file
286
server/main.mjs
Normal file
|
|
@ -0,0 +1,286 @@
|
||||||
|
// 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 OPENROUTER_API_KEY or 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 { splitPage, assemble } from "./transcribe.mjs";
|
||||||
|
import { makeProvider } from "./providers.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"),
|
||||||
|
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, provider) {
|
||||||
|
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 {
|
||||||
|
result = splitPage(await provider.transcribe(await store.getImage(id, i + 1)));
|
||||||
|
} catch (err) {
|
||||||
|
const reason = String(err?.message || err);
|
||||||
|
console.error(`[${id}] page ${i + 1}: ${reason}`);
|
||||||
|
result = { num: "?", error: reason };
|
||||||
|
}
|
||||||
|
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: `${provider.name}:${provider.model}` }));
|
||||||
|
} catch (err) {
|
||||||
|
console.error(`[${id}] job failed:`, err);
|
||||||
|
await store.updateMeta(id, () => ({ status: "draft", progress: null, jobError: String(err?.message || err) })).catch(() => {});
|
||||||
|
} 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, provider, 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(provider), model: provider?.model || null, 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 (!provider) throw new HttpError(503, "Přepis není nastavený: na serveru chybí OPENROUTER_API_KEY nebo ANTHROPIC_API_KEY.");
|
||||||
|
if (running.has(id)) throw new HttpError(409, "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, provider);
|
||||||
|
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, provider) {
|
||||||
|
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, provider, 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 provider = makeProvider(env);
|
||||||
|
|
||||||
|
// Resume transcriptions interrupted by a restart.
|
||||||
|
for (const meta of await store.list())
|
||||||
|
if (meta.status === "processing") {
|
||||||
|
if (provider) runJob(store, meta.id, provider);
|
||||||
|
else await store.updateMeta(meta.id, () => ({ status: "draft", progress: null, jobError: "přepis přerušen" }));
|
||||||
|
}
|
||||||
|
|
||||||
|
createServer(store, provider).listen(config.port, () => {
|
||||||
|
console.log(`theater-reader on :${config.port} (data ${config.dataDir}; uploads ${config.password ? "on" : "off"}; transcription ${provider ? `${provider.name} ${provider.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.";
|
||||||
144
server/providers.mjs
Normal file
144
server/providers.mjs
Normal file
|
|
@ -0,0 +1,144 @@
|
||||||
|
// Vision model backends. Each provider is { name, model, transcribe(jpeg) -> markup text }.
|
||||||
|
// OpenRouter is used when OPENROUTER_API_KEY is set, otherwise the Anthropic API
|
||||||
|
// when ANTHROPIC_API_KEY is set, otherwise transcription is off.
|
||||||
|
import Anthropic from "@anthropic-ai/sdk";
|
||||||
|
import { SYSTEM_PROMPT, USER_PROMPT } from "./prompt.mjs";
|
||||||
|
|
||||||
|
export const DEFAULT_CLAUDE_MODEL = "claude-haiku-5-5";
|
||||||
|
export const DEFAULT_OPENROUTER_MODEL = "google/gemini-3.1-flash-lite";
|
||||||
|
const OPENROUTER_URL = "https://openrouter.ai/api/v1/chat/completions";
|
||||||
|
|
||||||
|
// A failure with a message fit to show in the editor.
|
||||||
|
export class PageError extends Error {}
|
||||||
|
|
||||||
|
export function makeProvider(env) {
|
||||||
|
if (env.OPENROUTER_API_KEY)
|
||||||
|
return openRouterProvider({ apiKey: env.OPENROUTER_API_KEY, model: env.OPENROUTER_MODEL || DEFAULT_OPENROUTER_MODEL });
|
||||||
|
if (env.ANTHROPIC_API_KEY)
|
||||||
|
return anthropicProvider({ client: new Anthropic({ apiKey: env.ANTHROPIC_API_KEY, maxRetries: 4 }), model: env.CLAUDE_MODEL || DEFAULT_CLAUDE_MODEL });
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Anthropic Messages API (via the official SDK)
|
||||||
|
export function anthropicProvider({ client, model }) {
|
||||||
|
return {
|
||||||
|
name: "anthropic",
|
||||||
|
model,
|
||||||
|
async transcribe(jpeg) {
|
||||||
|
let response;
|
||||||
|
try {
|
||||||
|
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 },
|
||||||
|
],
|
||||||
|
}],
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
throw new PageError(describeAnthropicError(err));
|
||||||
|
}
|
||||||
|
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;
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function describeAnthropicError(err) {
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- OpenRouter (OpenAI-style chat completions over plain fetch)
|
||||||
|
const RETRYABLE = new Set([408, 429, 500, 502, 503, 504]);
|
||||||
|
|
||||||
|
export function openRouterProvider({ apiKey, model, fetchImpl = fetch, retries = 3, retryDelayMs = 2000 }) {
|
||||||
|
async function post(body) {
|
||||||
|
for (let attempt = 0; ; attempt++) {
|
||||||
|
let res;
|
||||||
|
try {
|
||||||
|
res = await fetchImpl(OPENROUTER_URL, {
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
Authorization: `Bearer ${apiKey}`,
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
"X-Title": "Divadelni ctecka", // shown in the OpenRouter activity log
|
||||||
|
},
|
||||||
|
body: JSON.stringify(body),
|
||||||
|
signal: AbortSignal.timeout(180_000),
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
if (attempt < retries) { await sleep(retryDelayMs * 2 ** attempt); continue; }
|
||||||
|
throw new PageError(`could not reach OpenRouter: ${err.message}`);
|
||||||
|
}
|
||||||
|
let data = null;
|
||||||
|
try { data = await res.json(); } catch { /* not JSON */ }
|
||||||
|
if (res.ok && !data?.error) return data;
|
||||||
|
const status = data?.error?.code && Number.isInteger(data.error.code) ? data.error.code : res.status;
|
||||||
|
if (RETRYABLE.has(status) && attempt < retries) {
|
||||||
|
const wait = Number(res.headers.get("retry-after")) * 1000 || retryDelayMs * 2 ** attempt;
|
||||||
|
await sleep(wait);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
throw new PageError(describeOpenRouterError(status, data?.error?.message));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
name: "openrouter",
|
||||||
|
model,
|
||||||
|
async transcribe(jpeg) {
|
||||||
|
const data = await post({
|
||||||
|
model,
|
||||||
|
max_tokens: 16000,
|
||||||
|
messages: [
|
||||||
|
{ role: "system", content: SYSTEM_PROMPT },
|
||||||
|
{
|
||||||
|
role: "user",
|
||||||
|
content: [
|
||||||
|
{ type: "image_url", image_url: { url: `data:image/jpeg;base64,${jpeg.toString("base64")}` } },
|
||||||
|
{ type: "text", text: USER_PROMPT },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
const choice = data?.choices?.[0];
|
||||||
|
if (!choice) throw new PageError("OpenRouter returned no answer");
|
||||||
|
if (choice.error) throw new PageError(`model error: ${choice.error.message || "unknown"}`);
|
||||||
|
if (choice.finish_reason === "content_filter") throw new PageError("model declined to transcribe this page");
|
||||||
|
if (choice.finish_reason === "length") throw new PageError("transcription was cut off (page too long)");
|
||||||
|
const content = choice.message?.content;
|
||||||
|
const text = (Array.isArray(content) ? content.map((c) => c.text || "").join("") : content || "").trim();
|
||||||
|
if (!text) throw new PageError("model returned no text");
|
||||||
|
return text;
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function describeOpenRouterError(status, message = "") {
|
||||||
|
const detail = message ? `: ${message}` : "";
|
||||||
|
switch (status) {
|
||||||
|
case 401: return "OpenRouter key rejected (check OPENROUTER_API_KEY)";
|
||||||
|
case 402: return "OpenRouter account is out of credit";
|
||||||
|
case 403: return `OpenRouter refused the request${detail}`;
|
||||||
|
case 404: return `model not found or can't read images (check OPENROUTER_MODEL)${detail}`;
|
||||||
|
case 429: return "rate limited by OpenRouter, try again later";
|
||||||
|
default: return `OpenRouter error ${status}${detail}`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||||
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;
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
79
server/transcribe.mjs
Normal file
79
server/transcribe.mjs
Normal file
|
|
@ -0,0 +1,79 @@
|
||||||
|
// Stitch per-page transcriptions (see providers.mjs) into one play file.
|
||||||
|
|
||||||
|
// 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 { readFileSync } from "node:fs";
|
||||||
import { parsePlay, speakers, joinLines, tidySpacing } from "../public/parse.js";
|
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", () => {
|
test("pages are in order and missing ones are marked", () => {
|
||||||
const nums = play.map((p) => p.num);
|
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("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ý");
|
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 provider = { name: "stub", model: "stub-model", transcribe: async () => replies.shift() };
|
||||||
|
|
||||||
|
let dir, server, base;
|
||||||
|
test.before(async () => {
|
||||||
|
dir = await mkdtemp(path.join(tmpdir(), "tr-"));
|
||||||
|
Object.assign(config, { dataDir: dir, password: PASS, dailyPageLimit: 3 });
|
||||||
|
const store = createStore(dir);
|
||||||
|
await store.init();
|
||||||
|
await store.seed(config.seedDir);
|
||||||
|
server = createServer(store, provider).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);
|
||||||
|
});
|
||||||
101
tests/transcribe.test.mjs
Normal file
101
tests/transcribe.test.mjs
Normal file
|
|
@ -0,0 +1,101 @@
|
||||||
|
import test from "node:test";
|
||||||
|
import assert from "node:assert/strict";
|
||||||
|
import { splitPage, normalizeSpeakers, assemble } from "../server/transcribe.mjs";
|
||||||
|
import { anthropicProvider, openRouterProvider, makeProvider, PageError } from "../server/providers.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; } } });
|
||||||
|
const JPEG = Buffer.from([0xff, 0xd8, 1]);
|
||||||
|
|
||||||
|
test("anthropic: 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 anthropicProvider({ client, model: "claude-haiku-5-5" }).transcribe(JPEG);
|
||||||
|
assert.equal(text, "=1\n@A\nx");
|
||||||
|
assert.equal(stub.last.messages[0].content[0].source.media_type, "image/jpeg");
|
||||||
|
assert.equal(stub.last.model, "claude-haiku-5-5");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("anthropic: refusals and truncation become page errors", async () => {
|
||||||
|
const p = (r) => anthropicProvider({ client: stub(r), model: "m" }).transcribe(JPEG);
|
||||||
|
await assert.rejects(p({ stop_reason: "refusal", content: [] }), PageError);
|
||||||
|
await assert.rejects(p({ stop_reason: "max_tokens", content: [{ type: "text", text: "x" }] }), PageError);
|
||||||
|
});
|
||||||
|
|
||||||
|
// fake fetch: returns the queued responses in order and records the requests
|
||||||
|
function fakeFetch(...responses) {
|
||||||
|
const calls = [];
|
||||||
|
const f = async (url, init) => {
|
||||||
|
calls.push({ url, init, body: JSON.parse(init.body) });
|
||||||
|
const r = responses.shift();
|
||||||
|
if (r instanceof Error) throw r;
|
||||||
|
return new Response(JSON.stringify(r.body), { status: r.status || 200, headers: { "content-type": "application/json" } });
|
||||||
|
};
|
||||||
|
f.calls = calls;
|
||||||
|
return f;
|
||||||
|
}
|
||||||
|
const ok = (text, finish = "stop") => ({ body: { choices: [{ finish_reason: finish, message: { role: "assistant", content: text } }] } });
|
||||||
|
|
||||||
|
test("openrouter: sends a data-URL image with the key and reads the answer", async () => {
|
||||||
|
const f = fakeFetch(ok("=2\n@Lída\nAno."));
|
||||||
|
const p = openRouterProvider({ apiKey: "sk-or-test", model: "google/gemini-3.1-flash-lite", fetchImpl: f });
|
||||||
|
assert.equal(await p.transcribe(JPEG), "=2\n@Lída\nAno.");
|
||||||
|
const [{ url, init, body }] = f.calls;
|
||||||
|
assert.equal(url, "https://openrouter.ai/api/v1/chat/completions");
|
||||||
|
assert.equal(init.headers.Authorization, "Bearer sk-or-test");
|
||||||
|
assert.equal(body.model, "google/gemini-3.1-flash-lite");
|
||||||
|
assert.equal(body.messages[0].role, "system");
|
||||||
|
assert.match(body.messages[1].content[0].image_url.url, /^data:image\/jpeg;base64,/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("openrouter: retries rate limits and network errors, then gives up with a readable message", async () => {
|
||||||
|
const f = fakeFetch({ status: 429, body: { error: { code: 429, message: "slow down" } } }, new Error("ECONNRESET"), ok("=1\nx"));
|
||||||
|
assert.equal(await openRouterProvider({ apiKey: "k", model: "m", fetchImpl: f, retryDelayMs: 1 }).transcribe(JPEG), "=1\nx");
|
||||||
|
assert.equal(f.calls.length, 3);
|
||||||
|
|
||||||
|
const g = fakeFetch({ status: 402, body: { error: { code: 402, message: "Insufficient credits" } } });
|
||||||
|
await assert.rejects(openRouterProvider({ apiKey: "k", model: "m", fetchImpl: g, retryDelayMs: 1 }).transcribe(JPEG), /out of credit/);
|
||||||
|
assert.equal(g.calls.length, 1); // not retried
|
||||||
|
|
||||||
|
// an error inside a 200 body counts too
|
||||||
|
const h = fakeFetch({ body: { error: { code: 401, message: "No auth" } } });
|
||||||
|
await assert.rejects(openRouterProvider({ apiKey: "k", model: "m", fetchImpl: h }).transcribe(JPEG), /key rejected/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("openrouter: truncated, filtered or empty answers are page errors", async () => {
|
||||||
|
for (const r of [ok("x", "length"), ok("x", "content_filter"), ok(""), { body: { choices: [] } }])
|
||||||
|
await assert.rejects(openRouterProvider({ apiKey: "k", model: "m", fetchImpl: fakeFetch(r) }).transcribe(JPEG), PageError);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("provider choice: OpenRouter first, then Anthropic, else off", () => {
|
||||||
|
assert.equal(makeProvider({}), null);
|
||||||
|
assert.equal(makeProvider({ ANTHROPIC_API_KEY: "a" }).name, "anthropic");
|
||||||
|
const p = makeProvider({ ANTHROPIC_API_KEY: "a", OPENROUTER_API_KEY: "o" });
|
||||||
|
assert.deepEqual([p.name, p.model], ["openrouter", "google/gemini-3.1-flash-lite"]);
|
||||||
|
assert.equal(makeProvider({ OPENROUTER_API_KEY: "o", OPENROUTER_MODEL: "qwen/x" }).model, "qwen/x");
|
||||||
|
});
|
||||||
Loading…
Add table
Add a link
Reference in a new issue