Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit fc1c340a2d9b03df62d753386dc910e77a004228
parent c057b28dd96f481a16978aa6ea45dcee3125522f
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sun, 11 Oct 2026 12:30:56 -0400

Merge r25/orpheus (release 25 T1b: Orpheus 3B as a second engine — tuned chunker, shared normalizer, best-of-3 takes, llama-server per batch) into r25/integration

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
MCOMMANDS.md | 4++--
MENVIRONMENT.md | 1+
MSETTINGS.md | 38++++++++++++++++++++++++++++++++++----
Mcommon/bin/archilyzer.ts | 2+-
Mcommon/bin/doctor.ts | 7++++++-
Mcommon/bin/tts-setup.test.ts | 14++++++++++++++
Mcommon/bin/tts-setup.ts | 21+++++++++++++++++----
Mcommon/controller/ttsFile.test.ts | 137+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/controller/ttsFile.ts | 131+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------------
Acommon/controller/ttsServer.test.ts | 172+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/ttsServer.ts | 310+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/envVars.ts | 1+
Mcommon/lib/settingsDocs.ts | 6++++++
Mcommon/lib/settingsSchema.ts | 2+-
Mcommon/lib/ttsApps.test.ts | 100++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------
Mcommon/lib/ttsApps.ts | 178+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------
Acommon/lib/ttsChunk.test.ts | 213+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/ttsChunk.ts | 130+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/ttsInstall.ts | 9++++++++-
Mcommon/lib/ttsSettings.test.ts | 40++++++++++++++++++++++++++++++++++++++--
Mcommon/lib/ttsSettings.ts | 124+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------
Mcommon/lib/ttsText.test.ts | 61++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----
Mcommon/lib/ttsText.ts | 251+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------
Meditor/CHANGELOG.md | 2++
Meditor/app/api/ops/tts/route.ts | 13++++++++-----
Mplans/release-25.md | 62++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mscripts/archilyzer-ops.mjs | 21++++++++++++---------
Mscripts/archilyzer-ops.test.mjs | 2+-
Mscripts/tts.mjs | 47+++++++++++++++++++++++++++++++++++++++++------
Mscripts/tts.test.mjs | 7++++++-
Ascripts/tts_orpheus.py | 460+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Ascripts/tts_orpheus.test.mjs | 49+++++++++++++++++++++++++++++++++++++++++++++++++
Msettings.json.example | 15++++++++++++++-
33 files changed, 2503 insertions(+), 127 deletions(-)

diff --git a/COMMANDS.md b/COMMANDS.md @@ -68,7 +68,7 @@ Run from the repo root (in the container: `docker compose exec editor pnpm archi | `archilyzer docs files` | `[--check]` | write SITE.md + CHANNEL.md + REPORT.md + CITATIONS.md from the file schemas | | `archilyzer docs cli` | `[--check]` | write COMMANDS.md from this command table and `pnpm ops --help` | | `archilyzer settings example` | `[--check]` | write settings.json.example + SETTINGS.md from the schema | -| `archilyzer tts setup` | `[--engine kokoro\|espeak-ng] [--from <dir>] [--python <py>] [--check]` | install a text-to-speech engine under settings.tts.home/&lt;engine&gt; (default ~/.local/share/archilyzer/tts/kokoro): a python venv with the pinned kokoro-onnx (uv venv --python 3.12 when uv is on PATH, else --python &lt;py&gt; -m venv) and the two model files, downloaded once from the kokoro-onnx project's model-files-v1.0 release (one stream, no retries) and verified by size and sha256; --from &lt;dir&gt; takes already-downloaded model files from &lt;dir&gt; instead (hard links where it can, else copies; verified the same way); --check installs nothing, lists what is missing and exits 1 when anything is | +| `archilyzer tts setup` | `[--engine kokoro\|orpheus\|espeak-ng] [--from <dir>] [--python <py>] [--check]` | install a text-to-speech engine under settings.tts.home/&lt;engine&gt; (default ~/.local/share/archilyzer/tts/&lt;engine&gt;): a python venv with its pinned packages (uv venv --python 3.12 when uv is on PATH, else --python &lt;py&gt; -m venv) — kokoro-onnx for kokoro, onnxruntime and numpy for orpheus — and its model files, downloaded once (kokoro: the kokoro-onnx model-files-v1.0 release; orpheus: the Q8\_0 GGUF and the SNAC decoder from Hugging Face, 3.5 GB) one stream at a time with no retries, verified by size and sha256; --from &lt;dir&gt; takes already-downloaded model files from &lt;dir&gt; instead (hard links where it can, else copies; verified the same way); orpheus's llama-server is not installed here (settings.tts.orpheus.serverBin) but is checked; --check installs nothing, lists what is missing and exits 1 when anything is | | `archilyzer doctor` | `[--json]` | read-only report: node, the checkout, the corpus, settings, every tool, the port block; exit 1 on a failure | | `archilyzer release show` | `[editor\|export]` | latest release, its date, how many bullets wait under \[Unreleased\] | | `archilyzer release cut` | `<editor\|export\|all> <X.Y.Z\|next\|next-minor> [--commit] [--date YYYY-MM-DD]` | \[Unreleased\] -&gt; a dated heading; all = both, one version, two commits | @@ -119,7 +119,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `fetch-windows` | fetch-windows fetches clip windows, one paced job per platform queue (YouTube and Rumble side by side): {"siteId"} fetches every window the site's published reports cite and the disk does not hold; {"items": \[{"slug", "id", "from", "to", "clipId"?, "reason"?, "pad"?, "webpageUrl"?}, ...\], "requestedBy", "manifest"?} fetches a list. "maxHeight" caps the source height (default 720). "dryRun": true lists the windows per platform, the ones already on disk ("cached") and the ones no fetch can fill ("unfetchable": deleted, off the site) and starts nothing. A platform cooling down or held is refused for its group; a 429, or two 403s in a row, backs the platform off and stops its job. Running the same body again resumes — fetched windows are cached, and a window a queued or running job will already write is answered in "inFlight" with that job, whose id joins "jobIds" (so --wait follows it) and no second job is queued. Windows run on the platform's clip queue (clips:youtube), never behind its long downloads. | `pnpm ops fetch-windows --json '{"siteId":"demo-site","dryRun":true}'`<br>`pnpm ops fetch-windows --file windows.json --wait` | | `cut-release` | cut-release turns a changelog's \[Unreleased\] into "## \[&lt;version&gt;\] - &lt;date&gt;": {"workspace": "editor" \| "export" \| "all", "version": "X.Y.Z" \| "next" \| "next-minor", "commit": boolean (default false), "date": "YYYY-MM-DD" (default today)}. "all" cuts both with ONE version and commits each ("Release &lt;workspace&gt; &lt;version&gt;") — or neither: every check runs before either file is written. Only an editor built from release 10 or later has the route (an older one answers 404); with no editor running, `archilyzer release cut` does the same locally. | `pnpm ops cut-release --json '{"workspace":"all","version":"next","commit":true}'` | | `transcribe` | transcribe runs ONE local file through a local transcription worker, as a job: {"path": "/abs/file"} (audio or video), "start"/"end" (seconds) for a window, "workerId" (a settings worker id; default: the one auto-transcribe would get), "out" (an absolute path for the result JSON, never inside the corpus). The result is {path, window, worker: {id, appId, model, device}, cues: \[{start, end, text}\], text, ...}, cue times on the file's own clock. "words": true adds words: \[{w, start, end, conf?}\] on the same clock -- from parakeet, which keeps its word timestamps; \[\] from an engine that does not. With --wait it is printed on stdout (the response and the log go to stderr), so `pnpm ops transcribe ... --wait \| jq -r .text` works. | `pnpm ops transcribe --json '{"path":"/abs/clip.mp4","start":120,"end":150}' --wait`<br>`pnpm ops transcribe --json '{"path":"/abs/a.wav","workerId":"parakeet-cpu","out":"/tmp/a.json"}' --wait` | -| `tts` | tts speaks a line with a local text-to-speech engine and a STOCK voice, as a job on the `tts` queue: {"text": "..."} or {"file": "/abs/script.txt"} (UTF-8, at most 20,000 characters), "engine" (kokoro \| espeak-ng), "voice" (one of the engine's stock voices; kokoro: af\_heart, bm\_george, ...), "speed" (0.5-2) — defaults from settings.tts (kokoro, af\_heart, 1) — and "out" (an absolute .wav path the result is copied to, never inside the corpus). The expressive tags &lt;laugh&gt; &lt;chuckle&gt; &lt;sigh&gt; &lt;cough&gt; &lt;sniffle&gt; &lt;groan&gt; &lt;yawn&gt; &lt;gasp&gt; are stripped for an engine that cannot perform them; any other &lt;...&gt; is refused. Years are spoken (2024: "twenty twenty-four"). The result is {wav, seconds, engine, voice, cached, durationMs, waitedMs, sha, sampleRate, speed, disclosure}: wav is the 48 kHz mono WAV the editor wrote (out, or its cache), disclosure the line a narrated export carries. The same ask again is answered from the cache (cached: true, no engine run). Kokoro needs `archilyzer tts setup` first. With --wait the result is printed on stdout. | `pnpm ops tts --json '{"text":"In 2024 the archive spoke."}' --wait`<br>`pnpm ops tts --json '{"file":"/abs/script.txt","voice":"bm_george","out":"/abs/line.wav"}' --wait` | +| `tts` | tts speaks a line with a local text-to-speech engine and a STOCK voice, as a job on the `tts` queue: {"text": "..."} or {"file": "/abs/script.txt"} (UTF-8, at most 20,000 characters), "engine" (kokoro \| orpheus \| espeak-ng), "voice" (one of the engine's stock voices; kokoro: af\_heart, bm\_george, ...; orpheus: leah, zac, ...), "speed" (0.5-2; orpheus has none) — defaults from settings.tts (kokoro, af\_heart, 1) — and "out" (an absolute .wav path the result is copied to, never inside the corpus). The expressive tags &lt;laugh&gt; &lt;chuckle&gt; &lt;sigh&gt; &lt;cough&gt; &lt;sniffle&gt; &lt;groan&gt; &lt;yawn&gt; &lt;gasp&gt; are performed by orpheus and stripped for the others; any other &lt;...&gt; is refused. Numbers, years, money and times are spoken (2024: "twenty twenty-four"). The result is {wav, seconds, engine, voice, cached, durationMs, waitedMs, sha, sampleRate, speed, disclosure}: wav is the 48 kHz mono WAV the editor wrote (out, or its cache), disclosure the line a narrated export carries. The same ask again is answered from the cache (cached: true, no engine run). Kokoro and orpheus need `archilyzer tts setup [--engine orpheus]` first; orpheus runs on the GPU (a local llama-server the editor starts and stops) and waits while a transcription holds it. With --wait the result is printed on stdout. | `pnpm ops tts --json '{"text":"In 2024 the archive spoke."}' --wait`<br>`pnpm ops tts --json '{"file":"/abs/script.txt","voice":"bm_george","out":"/abs/line.wav"}' --wait` | | `settings` | settings patches settings.json through the editor's one writer: {"patch": {"&lt;top-level key&gt;": value, …}} (SETTINGS.md). A block's keys merge one level; an array, a scalar or an object nested in a block replaces. Refused before anything is written: an unknown key; a key another writer owns (channelPriority, autoQueue, workers, storage — the refusal names it); a value the schema would not keep as sent (clamped, dropped), named with what would be saved. Answers the saved values. | `pnpm ops settings --json '{"patch":{"minFreeDiskGB":20}}'` | | `clear-platform-hold` | clear-platform-hold clears a platform's rate-limit hold, backoff and raised pace, as the lane strip's Clear hold: {"platform"}. Answers the sentence. | | | `workers` | workers switches transcription workers as /workers does: {"op": "enable" \| "disable" \| "drain", "ids": \[...\]} — the live pool; a restart restores the launch default. An unknown id is named; the others still apply. | `pnpm ops workers --json '{"op":"disable","ids":["parakeet-cpu"]}'` | diff --git a/ENVIRONMENT.md b/ENVIRONMENT.md @@ -151,6 +151,7 @@ The publish pipeline sets these for a process it spawns. Listed so a reader know | `BUILD_ARCHIVES` | on | `0` skips archive-zip generation for one build (`--skip-archives`). | common/bin/compose-site.ts, common/bin/build-archives.ts | | `REPORTS_ALLOW_MISSING_MEDIA` | off | `1` lets a report citation whose evidence media was not prepared through compose (`--allow-missing-media`): its moment page renders without a clip. Off, compose fails with the list. | common/bin/compose-site.ts | | `ARCHIVES_READONLY` | off | `1` inside a docker-mode build container: materialize archives, never write the shared cache. | common/bin/compose-site.ts | +| `GGML_BACKEND_PATH` | settings.tts.orpheus.ggmlBackendPath | The ggml backend llama-server loads (Vulkan by default), set for the Orpheus server the editor starts — from `settings.tts.orpheus.ggmlBackendPath`, never the environment. | common/lib/ttsApps.ts | | `HOMEPAGE_PUBLIC_DIR` | `<repo>/homepage/public` | Where `compose homepage` and `source publish` write. | common/bin/compose-homepage.ts, common/publish/source.ts | ## Docker diff --git a/SETTINGS.md b/SETTINGS.md @@ -897,11 +897,28 @@ Local text-to-speech (release 25): narration for report videos and podcasts, syn | Key | Default | Description | |---|---|---| -| `engine` | `"kokoro"` | The engine a synthesis uses when the request names none: `kokoro` (Kokoro-82M, Apache-2.0, CPU; installed by `archilyzer tts setup`) or `espeak-ng` (the zero-install fallback). An unknown id falls back to `kokoro`. | -| `voice` | `"af_heart"` | The engine's stock voice when the request names none (stock voices only: no cloning, no reference audio). For Kokoro, `a*` voices are American English and `b*` British; `af_heart` was picked by ear in the release 25 bake-off. A voice the engine does not have falls back to the engine's default. | -| `speed` | `1` | Speaking pace, 1 = the engine's natural pace (Kokoro speaks briskly; 0.9 slows it). Clamped to [0.5, 2]. In the cache key: a new speed is a new synthesis. | +| `engine` | `"kokoro"` | The engine a synthesis uses when the request names none: `kokoro` (Kokoro-82M, Apache-2.0, CPU; installed by `archilyzer tts setup`), `orpheus` (Orpheus 3B, Llama 3.2 Community License + Apache-2.0, "Built with Llama"; GPU, on a local llama-server — `tts.orpheus`; `archilyzer tts setup --engine orpheus`) or `espeak-ng` (the zero-install fallback). An unknown id falls back to `kokoro`. | +| `voice` | `"af_heart"` | The engine's stock voice when the request names none (stock voices only: no cloning, no reference audio). For Kokoro, `a*` voices are American English and `b*` British; `af_heart` was picked by ear in the release 25 bake-off. Orpheus: tara leah jess leo dan mia zac zoe — `leah` its default, `zac` the male option. A voice the engine does not have falls back to the engine's default. | +| `speed` | `1` | Speaking pace, 1 = the engine's natural pace (Kokoro speaks briskly; 0.9 slows it). Clamped to the engine's range: [0.5, 2] for Kokoro and espeak-ng; Orpheus has none (1). In the cache key: a new speed is a new synthesis. | | `home` | `""` | Where `archilyzer tts setup` installs engines, one directory per engine (`<home>/kokoro`: its python venv and model files). Blank = `~/.local/share/archilyzer/tts`. Absolute, or `~/`-relative. | | `dir` | `""` | The synthesis cache: `<sha256>.wav` (48 kHz mono 16-bit) and a `<sha256>.json` sidecar (engine, model, licence, voice, seconds, disclosure) per distinct (engine, model, voice, speed, normalized text) — a re-ask is free. Never inside the corpus (refused). Blank = `<repo>/.tts/cache` (gitignored). Absolute, or `~/`-relative. | +| `orpheus` | object — see below | Orpheus 3B's server and takes. See OrpheusTtsSettings (`tts.orpheus` below). | + +#### `tts.orpheus` + +| Key | Default | Description | +|---|---|---| +| `serverBin` | `"/usr/lib/ollama/llama-server"` | The llama.cpp server Orpheus runs on (`llama-server`). Default: Ollama's bundled build. Started for a batch of syntheses on the `tts` queue and stopped (SIGTERM, then SIGKILL after 15 s) once the queue has been idle `idleStopSeconds`, so its VRAM is freed. | +| `libraryPath` | `"/usr/lib/ollama"` | `LD_LIBRARY_PATH` for the server (Ollama's bundled libraries). Blank = not set. | +| `ggmlBackendPath` | `"/usr/lib/ollama/vulkan/libggml-vulkan.so"` | `GGML_BACKEND_PATH` for the server: the ggml backend it loads — Vulkan by default. Blank = not set. | +| `port` | `8799` | The port the server listens on, on 127.0.0.1. A port something else already answers on is refused, never shared. | +| `gpuLayers` | `99` | `-ngl`: layers on the GPU. 99 = all of them; 0 runs on the CPU (about 9× slower). | +| `contextSize` | `8192` | `-c`, the context in tokens; also the whole window the repeat penalty could see. | +| `startTimeoutSeconds` | `150` | How long the server may take to answer `/health` once it is running (it took 2.5–14 s in the tuning round). The wait for the machine's heavy slot before it starts is not counted. | +| `idleStopSeconds` | `5` | How long the server is kept after the last synthesis before it is stopped, so the next one in the queue reuses it. | +| `heavyEstimateMB` | `4000` | The memory the server is admitted to the heavy slot with (`queue-lock --heavy --estimate`): it starts only when that much is free above the floor, beside other estimated jobs, never beside a build. | +| `takes` | `3` | Takes per chunk, at most: the first that passes the checks (end token reached, no malformed frame, not truncated, words a second in band, no long silence) is kept. 1–6. | +| `tagCheck` | `false` | The tag-length check: a chunk with expressive tags must run at least 0.4 s a tag longer than the same voice reading it without them (one extra take of the stripped text per tagged chunk), else the take is taken to have skipped its tag. OFF by default. (The tuning round's UTMOS scorer is not offered: it needs torch.) | Default: @@ -911,6 +928,19 @@ Default: "voice": "af_heart", "speed": 1, "home": "", - "dir": "" + "dir": "", + "orpheus": { + "serverBin": "/usr/lib/ollama/llama-server", + "libraryPath": "/usr/lib/ollama", + "ggmlBackendPath": "/usr/lib/ollama/vulkan/libggml-vulkan.so", + "port": 8799, + "gpuLayers": 99, + "contextSize": 8192, + "startTimeoutSeconds": 150, + "idleStopSeconds": 5, + "heavyEstimateMB": 4000, + "takes": 3, + "tagCheck": false + } } ``` diff --git a/common/bin/archilyzer.ts b/common/bin/archilyzer.ts @@ -714,7 +714,7 @@ export const COMMANDS: Command[] = [ { path: ["tts", "setup"], usage: - "[--engine kokoro|espeak-ng] [--from <dir>] [--python <py>] [--check] install a text-to-speech engine under settings.tts.home/<engine> (default ~/.local/share/archilyzer/tts/kokoro): a python venv with the pinned kokoro-onnx (uv venv --python 3.12 when uv is on PATH, else --python <py> -m venv) and the two model files, downloaded once from the kokoro-onnx project's model-files-v1.0 release (one stream, no retries) and verified by size and sha256; --from <dir> takes already-downloaded model files from <dir> instead (hard links where it can, else copies; verified the same way); --check installs nothing, lists what is missing and exits 1 when anything is", + "[--engine kokoro|orpheus|espeak-ng] [--from <dir>] [--python <py>] [--check] install a text-to-speech engine under settings.tts.home/<engine> (default ~/.local/share/archilyzer/tts/<engine>): a python venv with its pinned packages (uv venv --python 3.12 when uv is on PATH, else --python <py> -m venv) — kokoro-onnx for kokoro, onnxruntime and numpy for orpheus — and its model files, downloaded once (kokoro: the kokoro-onnx model-files-v1.0 release; orpheus: the Q8_0 GGUF and the SNAC decoder from Hugging Face, 3.5 GB) one stream at a time with no retries, verified by size and sha256; --from <dir> takes already-downloaded model files from <dir> instead (hard links where it can, else copies; verified the same way); orpheus's llama-server is not installed here (settings.tts.orpheus.serverBin) but is checked; --check installs nothing, lists what is missing and exits 1 when anything is", flags: { engine: "string", from: "string", python: "string", check: "boolean" }, run: async ({ flags }) => (await import("./tts-setup")).main({ diff --git a/common/bin/doctor.ts b/common/bin/doctor.ts @@ -832,7 +832,12 @@ export async function collectDoctorReport(deps: DoctorDeps): Promise<DoctorRepor }); const voiceOk = engine.voices.includes(settings!.tts.voice); return { - ...ttsInstallState(engine, { home, paths: { espeakNgBin: paths.espeakNgBin ?? "espeak-ng" }, envPath: env.PATH }), + ...ttsInstallState(engine, { + home, + paths: { espeakNgBin: paths.espeakNgBin ?? "espeak-ng" }, + envPath: env.PATH, + tts: settings!.tts, + }), voice: settings!.tts.voice, voiceOk, }; diff --git a/common/bin/tts-setup.test.ts b/common/bin/tts-setup.test.ts @@ -113,3 +113,17 @@ test("an unknown engine is refused; espeak-ng has nothing to install", async () assert.equal(await main({ engine: "espeak-ng", envPath: path.join(ROOT, "no-bin"), log: (l) => missing.push(l) }), 1); assert.match(missing[0], /espeak-ng is not on PATH — install espeak-ng/); }); + +test("--check for orpheus names its files and the engine in its hint", async () => { + const home = path.join(ROOT, "empty-orpheus"); + await mkdir(home); + const lines: string[] = []; + const code = await main({ engine: "orpheus", check: true, home, log: (l) => lines.push(l), envPath: path.join(ROOT, "no-bin") }); + assert.equal(code, 1); + const text = lines.join("\n"); + assert.match(text, /Orpheus 3B at .*empty-orpheus\/orpheus — missing:/); + assert.match(text, /- orpheus-3b-0\.1-ft-Q8_0\.gguf/); + assert.match(text, /- snac_decoder\.onnx/); + assert.match(text, /Run `archilyzer tts setup --engine orpheus`/); + assert.deepEqual(await readdir(home), []); +}); diff --git a/common/bin/tts-setup.ts b/common/bin/tts-setup.ts @@ -21,6 +21,14 @@ // at its pinned version — by importing it — each model file at its size) and // exits 1 when anything is. // +// Orpheus (`--engine orpheus`) is the same shape: a venv with onnxruntime and +// numpy (the SNAC decoder; no torch), and its GGUF, decoder and decoder config +// from Hugging Face (unsloth/orpheus-3b-0.1-ft-GGUF, onnx-community/ +// snac_24khz-ONNX) — 3.5 GB, so `--from` a directory that holds them already is +// the polite way on a machine that has them. The llama-server it runs on is not +// installed here (settings.tts.orpheus.serverBin, Ollama's bundled build by +// default); setup and `--check` say when it is missing. +// // espeak-ng (a `system` engine) has nothing to install: setup says whether it // is on PATH. // @@ -161,13 +169,14 @@ export async function main(opts: TtsSetupOptions = {}): Promise<number> { return found ? 0 : 1; } - const home = opts.home ?? resolveTtsHome(getSettings().tts, paths); + const tts = getSettings().tts; + const home = opts.home ?? resolveTtsHome(tts, paths); const dir = ttsInstallDir(home, engine); const python = ttsVenvPython(dir); const [dist, pinned] = setup.packages[0].split("=="); if (opts.check) { - const state = ttsInstallState(engine, { home, paths, envPath }); + const state = ttsInstallState(engine, { home, paths, envPath, tts }); const missing = [...state.missing]; if (!missing.some((m) => m.startsWith("the python venv"))) { const v = await installedVersion(python, setup.importName, dist); @@ -179,7 +188,7 @@ export async function main(opts: TtsSetupOptions = {}): Promise<number> { } log(`${engine.label} at ${dir} — missing:`); for (const m of missing) log(` - ${m}`); - log("Run `archilyzer tts setup` to install it."); + log(`Run \`archilyzer tts setup${engine.id === DEFAULT_TTS_ENGINE_ID ? "" : ` --engine ${engine.id}`}\` to install it.`); return 1; } @@ -259,5 +268,9 @@ export async function main(opts: TtsSetupOptions = {}): Promise<number> { { indent: 2 }, ); log(`${engine.label} installed: ${dir}`); - return 0; + // What setup cannot install: a server binary the engine runs on (Orpheus's + // llama-server, settings.tts.orpheus.serverBin). + const absent = (engine.requires?.(tts) ?? []).filter((r) => !findOnPath(r.path, envPath)); + for (const r of absent) log(` but ${r.what} is not there: ${r.path} — install it, or point the setting at one`); + return absent.length ? 1 : 0; } diff --git a/common/controller/ttsFile.test.ts b/common/controller/ttsFile.test.ts @@ -39,6 +39,21 @@ const { spawnSync } = require("node:child_process"); fs.appendFileSync(${JSON.stringify(RUNS)}, JSON.stringify(process.argv.slice(2)) + "\\n"); const text = fs.readFileSync(process.argv[process.argv.length - 1], "utf8"); if (text.includes("explode")) { console.error("tts: engine exploded"); process.exit(3); } +const argv = process.argv.slice(2); +if (argv.includes("orpheus")) { + // Orpheus stand-in: keep its input, write a 1 s 48 kHz WAV, report one flagged chunk. + fs.writeFileSync(${JSON.stringify(path.join(ROOT, "orpheus-input.json"))}, text); + const out = argv[argv.indexOf("--output") + 1]; + const data = Buffer.alloc(96000); + const h = Buffer.alloc(44); + h.write("RIFF", 0); h.writeUInt32LE(36 + data.length, 4); h.write("WAVE", 8); h.write("fmt ", 12); + h.writeUInt32LE(16, 16); h.writeUInt16LE(1, 20); h.writeUInt16LE(1, 22); h.writeUInt32LE(48000, 24); + h.writeUInt32LE(96000, 28); h.writeUInt16LE(2, 32); h.writeUInt16LE(16, 34); h.write("data", 36); h.writeUInt32LE(data.length, 40); + fs.writeFileSync(out, Buffer.concat([h, data])); + console.error("orpheus: chunk 1/2 take 1 seed 1234: PASS"); + console.log(JSON.stringify({ engine: "orpheus", voice: "zac", sampleRate: 48000, seconds: 1, engineStats: { flagged: [{ chunk: 2, take: 3, why: "internal silence 1.40s > 1.3s" }] } })); + process.exit(0); +} const r = spawnSync(process.execPath, [${JSON.stringify(WRAPPER)}, ...process.argv.slice(2)], { stdio: "inherit" }); process.exit(r.status ?? 1); `, @@ -57,6 +72,8 @@ process.env.SETTINGS_FILE = SETTINGS_FILE; process.env.TTS_BIN = shim; const { + runTtsSynthesis, + waitForGpu, TTS_FILE_BODY_KEYS, TTS_MAX_CHARS, TTS_RESULT_MARKER, @@ -69,6 +86,7 @@ const { } = await import("./ttsFile"); const { getPaths } = await import("../lib/paths"); const { getTtsEngine } = await import("../lib/ttsApps"); +const { DEFAULT_TTS_SETTINGS, sanitizeTts } = await import("../lib/ttsSettings"); const paths = getPaths(); function has(bin: string, flag: string): boolean { @@ -283,3 +301,122 @@ test("a failing engine fails the job with its words, and leaves no cache entry", assert.equal(await engineRuns(), runs + 1); assert.deepEqual((await readdir(CACHE).catch(() => [] as string[])).sort(), before); }); + +// --- Orpheus (T1b): the refusals, the GPU wait, the server, the input ------------ + +test("Orpheus requests: leah by default, a stock voice, no speed but 1", () => { + const tts = { engine: "orpheus", voice: "leah", speed: 1 }; + const r = resolveTtsRequest({}, "Back in 2024 <chuckle> it ended.", tts); + assert.ok(r.ok); + if (r.ok) { + assert.equal(r.value.voice, "leah"); + assert.equal(r.value.spoken, "Back in twenty twenty-four <chuckle> it ended."); + } + const k = resolveTtsRequest({ engine: "orpheus" }, "x", { engine: "kokoro", voice: "af_heart", speed: 0.9 }); + assert.ok(k.ok && k.value.voice === "leah" && k.value.speed === 1, "Kokoro's speed setting is not Orpheus's"); + const cases: [Parameters<typeof resolveTtsRequest>[0], string, RegExp][] = [ + [{ engine: "orpheus", voice: "af_heart" }, "x", /orpheus has no stock voice "af_heart" — its voices: tara, leah, jess, leo, dan, mia, zac, zoe/], + [{ engine: "orpheus", voice: "/home/someone/reference.wav" }, "x", /orpheus has no stock voice/], + [{ engine: "orpheus", speed: 0.9 }, "x", /"speed" must be between 1 and 1 for orpheus/], + [{ engine: "orpheus" }, "a <smirk>", /a tag no engine knows: <smirk>/], + ]; + for (const [body, text, re] of cases) { + const x = resolveTtsRequest(body, text, tts); + assert.equal(x.ok, false); + if (!x.ok) assert.match(x.error, re); + } +}); + +test("Orpheus not installed: the venv, the model files and the server binary are named", async () => { + const r = resolveTtsRequest({ engine: "orpheus" }, "x", { engine: "kokoro", voice: "af_heart", speed: 1 }); + assert.ok(r.ok); + if (!r.ok) return; + const tts = sanitizeTts({ orpheus: { serverBin: path.join(ROOT, "no-llama-server") } }); + const c = await checkTtsRequest(r.value, { paths, cacheDir: CACHE, home: HOME, tts }); + assert.ok(!c.ok); + if (!c.ok) { + assert.match(c.error, /Orpheus 3B is not installed \(.*tts-home\/orpheus\): missing the python venv/); + assert.match(c.error, /orpheus-3b-0\.1-ft-Q8_0\.gguf; snac_decoder\.onnx; snac_config\.json/); + assert.match(c.error, /llama-server \(settings\.tts\.orpheus\.serverBin\): .*no-llama-server/); + assert.match(c.error, /run `archilyzer tts setup --engine orpheus`/); + } +}); + +test("a GPU engine waits while a transcription holds the GPU, and can be cancelled while it waits", async () => { + const lines: string[] = []; + assert.equal(await waitForGpu({ busy: () => false, onLog: (l) => lines.push(l) }), 0); + assert.equal(lines.length, 0); + let polls = 0; + const waited = await waitForGpu({ busy: () => polls++ < 3, onLog: (l) => lines.push(l), pollMs: 10 }); + assert.ok(waited >= 20); + assert.match(lines[0], /Waiting for the GPU: a transcription is running/); + assert.match(lines[1], /The GPU is free/); + const ac = new AbortController(); + setTimeout(() => ac.abort(), 30); + await assert.rejects(waitForGpu({ busy: () => true, onLog: () => {}, signal: ac.signal, pollMs: 10 }), /cancelled while waiting for the GPU/); +}); + +test("an Orpheus synthesis: GPU wait, then its server, then the wrapper with the server's URL; released after", async () => { + const r = resolveTtsRequest({ engine: "orpheus", voice: "zac" }, "One file. No title. <sigh>\n\nThen in 2024, it came back.", { + engine: "kokoro", voice: "af_heart", speed: 1, + }); + assert.ok(r.ok); + if (!r.ok) return; + const events: string[] = []; + let gpuPolls = 0; + const servers = { + acquire: async (key: string, cmd: { port: number }) => { + events.push(`acquire ${key} ${cmd.port}`); + return { url: "http://127.0.0.1:8799", release: () => events.push("release") }; + }, + }; + const lines: string[] = []; + const sha = ttsCacheKey(r.value, DEFAULT_TTS_SETTINGS); + const side = await runTtsSynthesis({ + paths, + req: r.value, + sha, + cacheDir: CACHE, + home: HOME, + tts: DEFAULT_TTS_SETTINGS, + onLog: (l) => lines.push(l), + servers: servers as never, + gpuBusy: () => (events.push("gpu?"), gpuPolls++ < 1), + gpuPollMs: 5, + }); + assert.deepEqual(events, ["gpu?", "gpu?", "acquire orpheus 8799", "release"]); + const runs = (await readFile(RUNS, "utf8")).trim().split("\n").map((l) => JSON.parse(l) as string[]); + const argv = runs[runs.length - 1]; + assert.equal(argv[argv.indexOf("--server") + 1], "http://127.0.0.1:8799"); + assert.ok(argv[argv.indexOf("--python") + 1].endsWith("tts-home/orpheus/venv/bin/python")); + // The wrapper read the chunks, not the text. + const input = JSON.parse(await readFile(path.join(ROOT, "orpheus-input.json"), "utf8")); + assert.equal(input.voice, "zac"); + assert.deepEqual(input.chunks.map((c: { text: string }) => c.text), ["One file. No title. <sigh>", "Then in twenty twenty-four, it came back."]); + // Disclosed with its attribution; the flagged chunk recorded and logged. + assert.equal(side.disclosure, "Narration: synthetic voice (Orpheus 3B · zac). Built with Llama"); + assert.equal(side.attribution, "Built with Llama"); + assert.equal(side.license, "Llama 3.2 Community License + Apache-2.0"); + assert.deepEqual(side.flagged, [{ chunk: 2, take: 3, why: "internal silence 1.40s > 1.3s" }]); + assert.ok(lines.some((l) => /1 chunk\(s\) FLAGGED — no take passed the checks: chunk 2/.test(l)), lines.join("\n")); + assert.ok(lines.some((l) => /Waiting for the GPU/.test(l))); + // The takes and tag check are in the key: another setting is another synthesis. + assert.notEqual(ttsCacheKey(r.value, sanitizeTts({ orpheus: { takes: 1 } })), sha); + assert.equal(ttsCacheKey(r.value, sanitizeTts({ orpheus: { port: 9000 } })), sha); +}); + +test("a failing Orpheus wrapper still releases the server", async () => { + const r = resolveTtsRequest({ engine: "orpheus" }, "Please explode now.", { engine: "orpheus", voice: "leah", speed: 1 }); + assert.ok(r.ok); + if (!r.ok) return; + const events: string[] = []; + const servers = { acquire: async () => ({ url: "http://127.0.0.1:1", release: () => events.push("release") }) }; + await assert.rejects( + runTtsSynthesis({ + paths, req: r.value, sha: ttsCacheKey(r.value), cacheDir: CACHE, home: HOME, onLog: () => {}, + servers: servers as never, gpuBusy: () => false, + }), + /the orpheus synthesis failed/, + ); + assert.deepEqual(events, ["release"]); +}); diff --git a/common/controller/ttsFile.ts b/common/controller/ttsFile.ts @@ -49,10 +49,13 @@ import { import { unknownTtsTagsError } from "../lib/ttsText"; import { ttsInstallState } from "../lib/ttsInstall"; import { + DEFAULT_TTS_SETTINGS, resolveTtsCacheDir, resolveTtsHome, type TtsSettings, } from "../lib/ttsSettings"; +import { getWorkerPool } from "../jobs/workerPool"; +import { getTtsServerHolder, type TtsServerHolder } from "./ttsServer"; import { TTS_QUEUE } from "../lib/queueKeys"; import { copyFileAtomic, writeJsonAtomic } from "../lib/jsonFile-server"; import { getSettings } from "../lib/settings"; @@ -177,7 +180,8 @@ export function resolveTtsRequest( error: `${engine.id} has no stock voice "${voice}" — its voices: ${engine.voices.join(", ")}`, }; } - const speed = body.speed ?? tts.speed; + // settings.tts.speed, like its voice, belongs to settings.tts.engine. + const speed = body.speed ?? (engine.id === tts.engine ? tts.speed : 1); const [lo, hi] = engine.speedRange; if (speed < lo || speed > hi) { return { ok: false, error: `"speed" must be between ${lo} and ${hi} for ${engine.id} (got ${speed})` }; @@ -206,20 +210,18 @@ export function resolveTtsRequest( }; } -/** The cache key: sha256 of (format version, engine, model, voice, speed, spoken text). */ -export function ttsCacheKey(req: Pick<TtsRequest, "engine" | "voice" | "speed" | "spoken">): string { - return createHash("sha256") - .update( - JSON.stringify([ - CACHE_KEY_VERSION, - req.engine.id, - req.engine.model, - req.voice, - req.speed, - req.spoken, - ]), - ) - .digest("hex"); +/** + * The cache key: sha256 of (format version, engine, model, voice, speed, spoken + * text) — plus, for an engine with `keyExtra` (Orpheus: its takes and tag + * check), the settings that change its output. + */ +export function ttsCacheKey( + req: Pick<TtsRequest, "engine" | "voice" | "speed" | "spoken">, + tts: TtsSettings = DEFAULT_TTS_SETTINGS, +): string { + const key: unknown[] = [CACHE_KEY_VERSION, req.engine.id, req.engine.model, req.voice, req.speed, req.spoken]; + if (req.engine.keyExtra) key.push(req.engine.keyExtra(tts)); + return createHash("sha256").update(JSON.stringify(key)).digest("hex"); } // --- the disk checks ----------------------------------------------------------- @@ -228,6 +230,7 @@ export type TtsFileContext = { paths: Paths; cacheDir: string; home: string; + tts?: TtsSettings; locations?: readonly Pick<StorageLocation, "root">[]; }; @@ -288,7 +291,11 @@ export async function checkTtsRequest( return { ok: false, error: `"out": the directory ${path.dirname(req.out)} does not exist` }; } } - const install = ttsInstallState(req.engine, { home: ctx.home, paths: ctx.paths }); + const install = ttsInstallState(req.engine, { + home: ctx.home, + paths: ctx.paths, + tts: ctx.tts ?? DEFAULT_TTS_SETTINGS, + }); if (!install.installed) { return { ok: false, @@ -324,6 +331,8 @@ export type TtsSidecar = { createdAt: string; // The engine's time to make it. durationMs: number; + // Orpheus: the chunks no take passed the checks for (the kept take named). + flagged?: Flagged[]; }; export type TtsResult = { @@ -361,7 +370,13 @@ export async function readTtsCacheHit(cacheDir: string, sha: string): Promise<Tt // --- the work ------------------------------------------------------------------ -type WrapperResult = { seconds?: number; sampleRate?: number; engineMs?: number }; +type Flagged = { chunk: number; take: number; why: string }; +type WrapperResult = { + seconds?: number; + sampleRate?: number; + engineMs?: number; + engineStats?: { flagged?: Flagged[]; takes?: number; chunks?: number }; +}; export type RunTtsOpts = { paths: Paths; @@ -369,10 +384,45 @@ export type RunTtsOpts = { sha: string; cacheDir: string; home: string; + tts?: TtsSettings; onLog: (line: string) => void; signal?: AbortSignal; + // Injected by tests: the server holder, and whether a transcription is + // running on a GPU worker. + servers?: TtsServerHolder; + gpuBusy?: () => boolean; + gpuPollMs?: number; }; +// A transcription running on a local worker that is not explicitly on the CPU +// (an unknown device may be the GPU: parakeet-cli's default can be). +export function transcriptionOnGpu(): boolean { + return getWorkerPool() + .summary() + .some((w) => w.busy && w.kind === "local" && (w.device ?? "").toLowerCase() !== "cpu"); +} + +// A GPU engine waits while a transcription holds the GPU — the `tts` queue +// yields to transcription. It only waits to START; a synthesis running is +// never interrupted. +export async function waitForGpu(opts: { + busy: () => boolean; + onLog: (line: string) => void; + signal?: AbortSignal; + pollMs?: number; +}): Promise<number> { + const t0 = Date.now(); + if (!opts.busy()) return 0; + opts.onLog("Waiting for the GPU: a transcription is running…"); + while (opts.busy()) { + if (opts.signal?.aborted) throw new Error("cancelled while waiting for the GPU"); + await new Promise((r) => setTimeout(r, opts.pollMs ?? 5000)); + } + const waited = Date.now() - t0; + opts.onLog(`The GPU is free (waited ${(waited / 1000).toFixed(1)}s)`); + return waited; +} + // Run the engine through the wrapper into the cache; write the sidecar after // the WAV is in place, so a sidecar always means a complete file. export async function runTtsSynthesis(opts: RunTtsOpts): Promise<TtsSidecar> { @@ -380,20 +430,40 @@ export async function runTtsSynthesis(opts: RunTtsOpts): Promise<TtsSidecar> { await mkdir(cacheDir, { recursive: true }); const target = ttsCachePaths(cacheDir, sha); const textFile = path.join(cacheDir, `.${sha}.${randomBytes(4).toString("hex")}.txt`); - await writeFile(textFile, req.spoken, "utf8"); - const started = Date.now(); + const tts = opts.tts ?? DEFAULT_TTS_SETTINGS; + const installDir = ttsInstallDir(opts.home, req.engine); + await writeFile( + textFile, + req.engine.prepareInput ? req.engine.prepareInput(req.spoken, req.voice, tts) : req.spoken, + "utf8", + ); + let started = Date.now(); + let server: { url: string; release: () => void } | null = null; try { - // T1b: a `device: "gpu"` engine waits here for the transcription pool to - // be idle, and a `runtime: "server"` one takes the engine's server holder - // (started for the batch, stopped when the `tts` queue has been idle) and - // passes its URL as `server`. Kokoro and espeak-ng need neither. + // A GPU engine waits while a transcription holds the GPU; a server engine + // takes its server (started for the batch behind the heavy slot, stopped + // once the `tts` queue has been idle) and hands its URL to the wrapper. + // The engine's time starts once both are in hand. + if (req.engine.device === "gpu") { + await waitForGpu({ busy: opts.gpuBusy ?? transcriptionOnGpu, onLog, signal: opts.signal, pollMs: opts.gpuPollMs }); + } + if (req.engine.runtime === "server" && req.engine.serverCommand) { + const holder = opts.servers ?? getTtsServerHolder(paths.monorepoRoot); + server = await holder.acquire(req.engine.id, req.engine.serverCommand(installDir, tts), { + onLog, + signal: opts.signal, + logFile: path.join(installDir, "server.log"), + }); + } + started = Date.now(); const build = req.engine.build({ textFile, outWav: target.wav, voice: req.voice, speed: req.speed, - installDir: ttsInstallDir(opts.home, req.engine), + installDir, bins: { ffmpegBin: paths.ffmpegBin, espeakNgBin: paths.espeakNgBin }, + ...(server ? { server: server.url } : {}), }); const child = execa(paths.ttsBin, build.argv, { cancelSignal: opts.signal, @@ -449,10 +519,18 @@ export async function runTtsSynthesis(opts: RunTtsOpts): Promise<TtsSidecar> { text: req.spoken, createdAt: new Date().toISOString(), durationMs: Date.now() - started, + ...(res.engineStats?.flagged?.length ? { flagged: res.engineStats.flagged } : {}), }; + if (sidecar.flagged) { + onLog( + `${sidecar.flagged.length} chunk(s) FLAGGED — no take passed the checks: ` + + sidecar.flagged.map((f) => `chunk ${f.chunk} (${f.why})`).join("; "), + ); + } await writeJsonAtomic(target.json, sidecar, { indent: 2 }); return sidecar; } finally { + server?.release(); await rm(textFile, { force: true }).catch(() => {}); } } @@ -483,11 +561,12 @@ export async function enqueueTtsFile( paths: opts.paths, cacheDir, home, + tts: settings.tts, locations: settings.storage?.locations ?? [], }); if (!checked.ok) return checked; const req = checked.value; - const sha = ttsCacheKey(req); + const sha = ttsCacheKey(req, settings.tts); const hitAtEnqueue = await readTtsCacheHit(cacheDir, sha); const asked = Date.now(); return runManagedFunction({ @@ -504,7 +583,7 @@ export async function enqueueTtsFile( if (side) { onLog(`Cached: ${ttsCachePaths(cacheDir, sha).wav} (${side.seconds}s) — no engine run`); } else { - side = await runTtsSynthesis({ paths: opts.paths, req, sha, cacheDir, home, onLog, signal }); + side = await runTtsSynthesis({ paths: opts.paths, req, sha, cacheDir, home, tts: settings.tts, onLog, signal }); onLog( `Synthesized ${side.seconds}s of audio in ${(side.durationMs / 1000).toFixed(1)}s` + ` (RTF ${side.seconds > 0 ? (side.durationMs / 1000 / side.seconds).toFixed(2) : "n/a"})`, diff --git a/common/controller/ttsServer.test.ts b/common/controller/ttsServer.test.ts @@ -0,0 +1,172 @@ +import { test, after } from "node:test"; +import assert from "node:assert/strict"; +import { chmod, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import http from "node:http"; +import net from "node:net"; +import os from "node:os"; +import path from "node:path"; +import { TtsServerHolder, portAnswers } from "./ttsServer"; +import type { TtsServerCommand } from "../lib/ttsApps"; + +// Run with: +// pnpm --filter yt-dlp-transcript-common exec tsx --test controller/ttsServer.test.ts +// +// The server lifecycle against a FAKE llama-server (a node script that answers +// /health): started once for a batch, reused, stopped after the idle window +// (SIGTERM to its group), stopped at once when the start fails or is +// cancelled, SIGKILLed when it ignores SIGTERM, and never started beside +// something already answering on its port. No GPU, no model. + +const ROOT = await mkdtemp(path.join(os.tmpdir(), "tts-server-")); +after(() => rm(ROOT, { recursive: true, force: true })); + +// The fake: `--port <p>`; answers /health 200 after DELAY_MS (503 before); +// writes "started"/"term" lines to EVENTS; IGNORE_TERM ignores SIGTERM; +// EXIT_AT_ONCE exits 3 before listening. +const fake = path.join(ROOT, "fake-llama-server"); +await writeFile( + fake, + `#!/usr/bin/env node +const http = require("node:http"); +const fs = require("node:fs"); +const args = process.argv.slice(2); +const port = Number(args[args.indexOf("--port") + 1]); +const ev = (l) => fs.appendFileSync(process.env.EVENTS, l + " " + process.pid + "\\n"); +console.error("fake llama-server: loading model " + args[args.indexOf("-m") + 1]); +if (process.env.EXIT_AT_ONCE) { console.error("fake: cannot load the model"); process.exit(3); } +ev("started"); +const t0 = Date.now(); +http.createServer((q, r) => { + const ready = Date.now() - t0 >= Number(process.env.DELAY_MS || 0); + r.statusCode = q.url === "/health" && ready ? 200 : 503; + r.end("{}"); +}).listen(port, "127.0.0.1"); +process.on("SIGTERM", () => { ev("term"); if (!process.env.IGNORE_TERM) process.exit(0); }); +`, +); +await chmod(fake, 0o755); + +async function freePort(): Promise<number> { + return new Promise((resolve) => { + const s = net.createServer().listen(0, "127.0.0.1", () => { + const p = (s.address() as net.AddressInfo).port; + s.close(() => resolve(p)); + }); + }); +} + +let n = 0; +async function cmd(env: Record<string, string> = {}, over: Partial<TtsServerCommand> = {}) { + const port = await freePort(); + const events = path.join(ROOT, `events-${n++}.log`); + const c: TtsServerCommand = { + bin: fake, + args: ["-m", "/models/x.gguf", "--host", "127.0.0.1", "--port", String(port)], + env: { EVENTS: events, ...env }, + host: "127.0.0.1", + port, + estimateMB: 0, + startTimeoutMs: 10_000, + idleStopMs: 150, + ...over, + }; + return { c, events, port }; +} +const events = async (f: string) => (await readFile(f, "utf8").catch(() => "")).split("\n").filter(Boolean); +const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); +async function until(pred: () => Promise<boolean>, ms = 5000) { + const t0 = Date.now(); + while (!(await pred())) { + if (Date.now() - t0 > ms) throw new Error("timed out"); + await sleep(25); + } +} + +test("one server for a batch: started once, reused, stopped once the queue is idle", async () => { + const holder = new TtsServerHolder({ gate: null, pollMs: 25 }); + const { c, events: ev, port } = await cmd({ DELAY_MS: "200" }); + const lines: string[] = []; + const logFile = path.join(ROOT, "server-a.log"); + const a = await holder.acquire("orpheus", c, { onLog: (l) => lines.push(l), logFile }); + assert.equal(a.url, `http://127.0.0.1:${port}`); + assert.equal((await fetch(`${a.url}/health`)).status, 200); + assert.match(lines[0], /Starting the orpheus server on 127\.0\.0\.1:\d+…/); + assert.match(lines[lines.length - 1], /The orpheus server is up/); + // The server's own lines go to its log, not the job's. + assert.match(await readFile(logFile, "utf8"), /fake llama-server: loading model \/models\/x\.gguf/); + a.release(); + // The next synthesis arrives inside the idle window: the same server. + await sleep(50); + const b = await holder.acquire("orpheus", c, { onLog: () => {} }); + assert.equal((await events(ev)).filter((l) => l.startsWith("started")).length, 1); + b.release(); + b.release(); // a second release is a no-op + assert.equal(holder.running("orpheus"), true); + await until(async () => !holder.running("orpheus")); + await until(async () => !(await portAnswers("127.0.0.1", port))); + assert.deepEqual((await events(ev)).map((l) => l.split(" ")[0]), ["started", "term"]); +}); + +test("changed settings restart it; idleStopMs 0 stops it at once", async () => { + const holder = new TtsServerHolder({ gate: null, pollMs: 25 }); + const one = await cmd(); + const a = await holder.acquire("orpheus", one.c, { onLog: () => {} }); + a.release(); + const two = await cmd({}, { idleStopMs: 0 }); + const b = await holder.acquire("orpheus", two.c, { onLog: () => {} }); + assert.deepEqual((await events(one.events)).map((l) => l.split(" ")[0]), ["started", "term"]); + b.release(); + await until(async () => (await events(two.events)).length === 2); + assert.equal(holder.running("orpheus"), false); + assert.deepEqual((await events(two.events)).map((l) => l.split(" ")[0]), ["started", "term"]); +}); + +test("a port something else answers on is refused, never shared", async () => { + const { c, port } = await cmd(); + const other = http.createServer((_q, r) => r.end("ok")).listen(port, "127.0.0.1"); + await new Promise((r) => other.once("listening", r)); + try { + const holder = new TtsServerHolder({ gate: null }); + await assert.rejects( + holder.acquire("orpheus", c, { onLog: () => {} }), + /something already answers on 127\.0\.0\.1:\d+ — refusing to start a second orpheus server/, + ); + assert.equal(holder.running("orpheus"), false); + } finally { + other.close(); + } +}); + +test("a server that dies before it answers fails with its last words", async () => { + const holder = new TtsServerHolder({ gate: null, pollMs: 25 }); + const { c } = await cmd({ EXIT_AT_ONCE: "1" }); + await assert.rejects( + holder.acquire("orpheus", c, { onLog: () => {}, logFile: path.join(ROOT, "dead.log") }), + /the orpheus server exited \(3\) before it answered — see .*dead\.log: .*cannot load the model/, + ); + assert.equal(holder.running("orpheus"), false); +}); + +test("a start that times out, or is cancelled, stops the server", async () => { + const holder = new TtsServerHolder({ gate: null, pollMs: 25 }); + const slow = await cmd({ DELAY_MS: "60000" }, { startTimeoutMs: 300 }); + await assert.rejects(holder.acquire("orpheus", slow.c, { onLog: () => {} }), /did not answer .*\/health within 0s/); + await until(async () => (await events(slow.events)).some((l) => l.startsWith("term"))); + const ac = new AbortController(); + const late = await cmd({ DELAY_MS: "60000" }); + setTimeout(() => ac.abort(), 200); + await assert.rejects(holder.acquire("orpheus", late.c, { onLog: () => {}, signal: ac.signal }), /start was cancelled/); + await until(async () => (await events(late.events)).some((l) => l.startsWith("term"))); + assert.equal(holder.running("orpheus"), false); +}); + +test("a server that ignores SIGTERM is SIGKILLed after the grace", async () => { + const holder = new TtsServerHolder({ gate: null, pollMs: 25, killGraceMs: 300 }); + const { c, port } = await cmd({ IGNORE_TERM: "1" }); + const a = await holder.acquire("orpheus", c, { onLog: () => {} }); + a.release(); + const t0 = Date.now(); + await holder.stop("orpheus"); + assert.ok(Date.now() - t0 >= 250, "it waited for the grace"); + await until(async () => !(await portAnswers("127.0.0.1", port))); +}); diff --git a/common/controller/ttsServer.ts b/common/controller/ttsServer.ts @@ -0,0 +1,310 @@ +// THE SERVER A `runtime: "server"` SPEECH ENGINE RUNS ON (release 25 T1b: +// Orpheus 3B on llama.cpp's server, on the GPU). +// +// One holder per engine, process-wide. The first synthesis on the `tts` queue +// starts the server and waits for `GET /health`; the next ones reuse it; once +// the last one has released it and `idleStopMs` passes with no other taking it +// — the queue has gone idle — it is stopped: SIGTERM to its process group, +// SIGKILL after 15 s. That is what frees its VRAM (4–5 GB for Orpheus), so it +// is also done on every way out: a failed start, a cancelled job, the editor +// exiting. +// +// BEHIND THE HEAVY SLOT. The server is started through scripts/queue-lock.mjs +// --heavy --estimate <MB> (the gate `pnpm heavy`, e2e and the publish builds +// share), so it waits for the machine's memory floor and never starts beside a +// build; the gate's own lines ("waiting for the heavy slot — held by …") go to +// the job's log, the server's to `<install dir>/server.log`. The start timeout +// counts from the server's first line of output, not from the wait. A checkout +// without the gate (a test's temp root) starts the server directly; HEAVY=0 +// bypasses the gate. +// +// NEVER SHARED: a port something else already answers on is refused, not +// used — a server this holder did not start may be another session's, with +// another model. + +import { spawn, type ChildProcess } from "node:child_process"; +import { createWriteStream, existsSync, type WriteStream } from "node:fs"; +import net from "node:net"; +import path from "node:path"; +import type { TtsServerCommand } from "../lib/ttsApps"; + +export type TtsServerHandle = { url: string; release: () => void }; + +export type TtsServerDeps = { + // scripts/queue-lock.mjs, or null to start the server directly. + gate?: string | null; + killGraceMs?: number; + pollMs?: number; +}; + +type Entry = { + sig: string; + child: ChildProcess; + url: string; + users: number; + timer: ReturnType<typeof setTimeout> | null; + ready: Promise<void>; + exited: Promise<void>; + isExited: () => boolean; + log: WriteStream | null; +}; + +const GATE_LINE = /^(queue-lock:|heavy:|\s+\(heavy jobs)/; + +/** True when something accepts a TCP connection on host:port. */ +export function portAnswers(host: string, port: number, timeoutMs = 1000): Promise<boolean> { + return new Promise((resolve) => { + const sock = net.connect({ host, port }); + const done = (v: boolean) => { + sock.destroy(); + resolve(v); + }; + sock.setTimeout(timeoutMs, () => done(false)); + sock.once("connect", () => done(true)); + sock.once("error", () => done(false)); + }); +} + +async function healthy(url: string): Promise<boolean> { + try { + const res = await fetch(`${url}/health`, { signal: AbortSignal.timeout(1000) }); + return res.status === 200; + } catch { + return false; + } +} + +const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); + +function killGroup(child: ChildProcess, sig: NodeJS.Signals): void { + if (child.pid === undefined) return; + try { + process.kill(-child.pid, sig); + } catch { + try { + child.kill(sig); + } catch { + /* gone */ + } + } +} + +export class TtsServerHolder { + private entries = new Map<string, Entry>(); + private exitHooked = false; + constructor(private deps: TtsServerDeps = {}) {} + + /** Whether the server for `key` is running (started, not yet stopped). */ + running(key: string): boolean { + const e = this.entries.get(key); + return e !== undefined && !e.isExited(); + } + + /** The server for `key`: the running one, or a new one started from `cmd`. */ + async acquire( + key: string, + cmd: TtsServerCommand, + opts: { onLog: (line: string) => void; signal?: AbortSignal; logFile?: string }, + ): Promise<TtsServerHandle> { + const sig = JSON.stringify(cmd); + let e = this.entries.get(key); + if (e && (e.sig !== sig || e.isExited())) { + // Its settings changed, or it died between syntheses: start afresh. + if (e.users === 0) await this.stop(key); + else throw new Error(`the ${key} server is in use with other settings`); + e = undefined; + } + if (e) { + if (e.timer) clearTimeout(e.timer); + e.timer = null; + e.users++; + try { + await e.ready; + } catch (err) { + e.users--; + throw err; + } + return this.handle(key, e, cmd); + } + e = await this.start(key, cmd, sig, opts); + e.users = 1; + try { + await e.ready; + } catch (err) { + await this.stop(key); + throw err; + } + return this.handle(key, e, cmd); + } + + private handle(key: string, e: Entry, cmd: TtsServerCommand): TtsServerHandle { + let released = false; + return { + url: e.url, + release: () => { + if (released) return; + released = true; + e.users = Math.max(0, e.users - 1); + if (e.users > 0 || this.entries.get(key) !== e) return; + if (cmd.idleStopMs <= 0) { + void this.stop(key); + return; + } + e.timer = setTimeout(() => void this.stop(key), cmd.idleStopMs); + e.timer.unref?.(); + }, + }; + } + + private async start( + key: string, + cmd: TtsServerCommand, + sig: string, + opts: { onLog: (line: string) => void; signal?: AbortSignal; logFile?: string }, + ): Promise<Entry> { + const url = `http://${cmd.host}:${cmd.port}`; + if (await portAnswers(cmd.host, cmd.port)) { + throw new Error( + `something already answers on ${cmd.host}:${cmd.port} — refusing to start a second ${key} server ` + + `beside it; stop it, or set another port (settings.tts.${key}.port)`, + ); + } + const gate = this.deps.gate ?? null; + const gated = gate !== null && existsSync(gate); + const [bin, args] = gated + ? [ + process.execPath, + [gate, "--heavy", ...(cmd.estimateMB > 0 ? ["--estimate", String(cmd.estimateMB)] : []), "--", cmd.bin, ...cmd.args], + ] + : [cmd.bin, cmd.args]; + opts.onLog(`Starting the ${key} server on ${cmd.host}:${cmd.port}${gated ? " (behind the heavy slot)" : ""}…`); + const child = spawn(bin, args, { + env: { ...process.env, ...cmd.env }, + // Its own process group: the gate, the server and anything they start + // are stopped together. + detached: true, + stdio: ["ignore", "pipe", "pipe"], + }); + const log = opts.logFile ? createWriteStream(opts.logFile, { flags: "a" }) : null; + log?.on("error", () => {}); + let serverSince: number | null = null; + let tail: string[] = []; + let exitedFlag = false; + let exitCode: string | null = null; + const exited = new Promise<void>((resolve) => { + child.once("exit", (code, signal) => { + exitedFlag = true; + exitCode = code === null ? String(signal) : String(code); + resolve(); + }); + child.once("error", (err) => { + exitedFlag = true; + exitCode = err.message; + resolve(); + }); + }); + const onData = (buf: Buffer) => { + for (const line of buf.toString("utf8").split("\n")) { + if (!line.trim()) continue; + if (GATE_LINE.test(line)) { + opts.onLog(line.trimEnd()); + continue; + } + serverSince ??= Date.now(); + tail = [...tail.slice(-4), line.trimEnd()]; + log?.write(`${line}\n`); + } + }; + child.stdout?.on("data", onData); + child.stderr?.on("data", onData); + this.hookExit(); + + const pollMs = this.deps.pollMs ?? 250; + const started = Date.now(); + const ready = (async () => { + for (;;) { + if (exitedFlag) { + throw new Error( + `the ${key} server exited (${exitCode}) before it answered${opts.logFile ? ` — see ${opts.logFile}` : ""}` + + (tail.length ? `: ${tail.slice(-2).join(" | ")}` : ""), + ); + } + if (opts.signal?.aborted) throw new Error(`the ${key} server's start was cancelled`); + if (serverSince !== null && Date.now() - serverSince > cmd.startTimeoutMs) { + throw new Error(`the ${key} server did not answer ${url}/health within ${Math.round(cmd.startTimeoutMs / 1000)}s`); + } + if (await healthy(url)) { + opts.onLog(`The ${key} server is up (${((Date.now() - started) / 1000).toFixed(1)}s)`); + return; + } + await sleep(pollMs); + } + })(); + ready.catch(() => {}); + const entry: Entry = { + sig, + child, + url, + users: 0, + timer: null, + ready, + exited, + isExited: () => exitedFlag, + log, + }; + this.entries.set(key, entry); + return entry; + } + + /** Stop the server for `key`: SIGTERM to its group, SIGKILL after the grace. */ + async stop(key: string): Promise<void> { + const e = this.entries.get(key); + if (!e) return; + this.entries.delete(key); + if (e.timer) clearTimeout(e.timer); + if (!e.isExited()) { + killGroup(e.child, "SIGTERM"); + const grace = this.deps.killGraceMs ?? 15_000; + let timer: ReturnType<typeof setTimeout> | undefined; + const t = new Promise<"timeout">((r) => { + timer = setTimeout(() => r("timeout"), grace); + }); + const won = await Promise.race([e.exited.then(() => "exited" as const), t]); + clearTimeout(timer); + if (won === "timeout") { + killGroup(e.child, "SIGKILL"); + await e.exited; + } + } + e.log?.end(); + } + + async stopAll(): Promise<void> { + await Promise.all([...this.entries.keys()].map((k) => this.stop(k))); + } + + // The editor exiting stops every server it started (synchronously: an exit + // handler cannot wait), so no VRAM is left held by an orphan. + private hookExit(): void { + if (this.exitHooked) return; + this.exitHooked = true; + process.once("exit", () => { + for (const e of this.entries.values()) if (!e.isExited()) killGroup(e.child, "SIGTERM"); + }); + } +} + +declare global { + // eslint-disable-next-line no-var + var __yttTtsServers__: TtsServerHolder | undefined; +} + +/** The process-wide holder; its gate is `<repo>/scripts/queue-lock.mjs`. */ +export function getTtsServerHolder(monorepoRoot: string): TtsServerHolder { + if (!globalThis.__yttTtsServers__) { + globalThis.__yttTtsServers__ = new TtsServerHolder({ + gate: path.join(monorepoRoot, "scripts", "queue-lock.mjs"), + }); + } + return globalThis.__yttTtsServers__; +} diff --git a/common/lib/envVars.ts b/common/lib/envVars.ts @@ -159,6 +159,7 @@ const DECLARED: EnvVarDecl[] = [ { name: "BUILD_ARCHIVES", audience: "internal", default: "on", readBy: "common/bin/compose-site.ts, common/bin/build-archives.ts", doc: "`0` skips archive-zip generation for one build (`--skip-archives`)." }, { name: "REPORTS_ALLOW_MISSING_MEDIA", audience: "internal", default: "off", readBy: "common/bin/compose-site.ts", doc: "`1` lets a report citation whose evidence media was not prepared through compose (`--allow-missing-media`): its moment page renders without a clip. Off, compose fails with the list." }, { name: "ARCHIVES_READONLY", audience: "internal", default: "off", readBy: "common/bin/compose-site.ts", doc: "`1` inside a docker-mode build container: materialize archives, never write the shared cache." }, + { name: "GGML_BACKEND_PATH", audience: "internal", default: "settings.tts.orpheus.ggmlBackendPath", readBy: "common/lib/ttsApps.ts", doc: "The ggml backend llama-server loads (Vulkan by default), set for the Orpheus server the editor starts — from `settings.tts.orpheus.ggmlBackendPath`, never the environment." }, { name: "HOMEPAGE_PUBLIC_DIR", audience: "internal", default: "`<repo>/homepage/public`", readBy: "common/bin/compose-homepage.ts, common/publish/source.ts", doc: "Where `compose homepage` and `source publish` write." }, // ── docker: the container's set ──────────────────────────────────────── diff --git a/common/lib/settingsDocs.ts b/common/lib/settingsDocs.ts @@ -23,6 +23,7 @@ import { SAVED_VIDEO_BACKUP_SETTINGS_FIELD_DOCS, SEEDER_SETTINGS_FIELD_DOCS, TTS_SETTINGS_FIELD_DOCS, + ORPHEUS_TTS_SETTINGS_FIELD_DOCS, SOCIAL_LINK_FIELD_DOCS, SOCIAL_SETTINGS_FIELD_DOCS, X_SOCIAL_SETTINGS_FIELD_DOCS, @@ -267,6 +268,11 @@ export function blockTables(d: SiteSettings): Partial<Record<keyof SiteSettings, docs: TTS_SETTINGS_FIELD_DOCS, defaults: fromObject(d.tts), }, + { + path: "tts.orpheus", + docs: ORPHEUS_TTS_SETTINGS_FIELD_DOCS, + defaults: fromObject(d.tts.orpheus), + }, ], }; } diff --git a/common/lib/settingsSchema.ts b/common/lib/settingsSchema.ts @@ -79,7 +79,7 @@ import { import { sanitizeSeeder, type SeederSettings } from "./seederSettings"; export { SEEDER_SETTINGS_FIELD_DOCS, type SeederSettings } from "./seederSettings"; import { sanitizeTts, type TtsSettings } from "./ttsSettings"; -export { TTS_SETTINGS_FIELD_DOCS, type TtsSettings } from "./ttsSettings"; +export { ORPHEUS_TTS_SETTINGS_FIELD_DOCS, TTS_SETTINGS_FIELD_DOCS, type TtsSettings } from "./ttsSettings"; import { DEFAULT_COOKIE_MODE, isCookieMode, diff --git a/common/lib/ttsApps.test.ts b/common/lib/ttsApps.test.ts @@ -11,15 +11,18 @@ import { ttsEngineIds, ttsInstallDir, ttsVenvPython, + ORPHEUS_FILES, + ORPHEUS_SAMPLER, } from "./ttsApps"; +import { DEFAULT_TTS_SETTINGS, sanitizeTts } from "./ttsSettings"; // Run with: // pnpm --filter yt-dlp-transcript-common exec tsx --test lib/ttsApps.test.ts const BINS = { ffmpegBin: "/bin/ffmpeg", espeakNgBin: "/bin/espeak-ng" }; -test("the registry: kokoro (af_heart) is the default, espeak-ng the zero-install fallback", () => { - assert.deepEqual(ttsEngineIds(), ["kokoro", "espeak-ng"]); +test("the registry: kokoro (af_heart) is the default, espeak-ng the zero-install fallback, orpheus the GPU one", () => { + assert.deepEqual(ttsEngineIds(), ["kokoro", "espeak-ng", "orpheus"]); assert.equal(DEFAULT_TTS_ENGINE_ID, "kokoro"); assert.equal(DEFAULT_TTS_VOICE, "af_heart"); assert.equal(getTtsEngine("kokoro")!.defaultVoice, "af_heart"); @@ -30,13 +33,13 @@ test("the registry: kokoro (af_heart) is the default, espeak-ng the zero-install assert.ok(e.voices.includes(e.defaultVoice), e.id); assert.ok(e.license.length > 0, e.id); assert.ok(e.model.length > 0, e.id); - assert.equal(e.device, "cpu", e.id); - assert.equal(e.runtime, "process", e.id); - assert.ok(e.speedRange[0] < 1 && e.speedRange[1] > 1, e.id); + assert.equal(e.device, e.id === "orpheus" ? "gpu" : "cpu", e.id); + assert.equal(e.runtime, e.id === "orpheus" ? "server" : "process", e.id); + assert.ok(e.speedRange[0] <= 1 && e.speedRange[1] >= 1, e.id); } assert.deepEqual( listTtsEngines().map((e) => [e.id, e.defaultVoice]), - [["kokoro", "af_heart"], ["espeak-ng", "en-us"]], + [["kokoro", "af_heart"], ["espeak-ng", "en-us"], ["orpheus", "leah"]], ); }); @@ -86,8 +89,8 @@ test("each engine builds the wrapper's command line from its install dir", () => ]); }); -test("both engines strip the expressive tags and speak years", () => { - for (const id of ttsEngineIds()) { +test("Kokoro and espeak-ng strip the expressive tags and speak years", () => { + for (const id of ["kokoro", "espeak-ng"]) { assert.equal( getTtsEngine(id)!.normalize("Back in 1999 <laugh> we said\nso."), "Back in nineteen ninety-nine we said so.", @@ -106,3 +109,84 @@ test("the disclosure names the engine and voice, plus any attribution its licenc "Narration: synthetic voice (Some Engine · v1). Built with Something.", ); }); + +test("Orpheus: eight stock voices, leah by default, no speed control, the Llama licence and attribution", () => { + const o = getTtsEngine("orpheus")!; + assert.deepEqual([...o.voices], ["tara", "leah", "jess", "leo", "dan", "mia", "zac", "zoe"]); + assert.equal(o.defaultVoice, "leah"); + assert.ok(o.voices.includes("zac")); + assert.deepEqual([...o.speedRange], [1, 1]); + assert.equal(o.license, "Llama 3.2 Community License + Apache-2.0"); + assert.equal(ttsDisclosure(o, "leah"), "Narration: synthetic voice (Orpheus 3B · leah). Built with Llama"); + assert.equal(o.setup.kind, "python-venv"); + if (o.setup.kind === "python-venv") { + assert.deepEqual(o.setup.packages, ["onnxruntime==1.31.0", "numpy==2.5.4"]); + assert.deepEqual(o.setup.files.map((f) => f.name), ["orpheus-3b-0.1-ft-Q8_0.gguf", "snac_decoder.onnx", "snac_config.json"]); + } + for (const f of ORPHEUS_FILES) assert.match(f.sha256, /^[0-9a-f]{64}$/); + // Tags are performed, so kept; the guarded year rule; paragraphs kept for the chunker. + assert.equal( + o.normalize("Back in 1999 <laugh> 1950 people\n\nsaid so."), + "Back in nineteen ninety-nine <laugh> one thousand nine hundred fifty people\n\nsaid so.", + ); +}); + +test("Orpheus's server command comes from settings.tts.orpheus, never hard-coded", () => { + const o = getTtsEngine("orpheus")!; + const cmd = o.serverCommand!("/h/tts/orpheus", DEFAULT_TTS_SETTINGS); + assert.equal(cmd.bin, "/usr/lib/ollama/llama-server"); + assert.deepEqual(cmd.env, { + LD_LIBRARY_PATH: "/usr/lib/ollama", + GGML_BACKEND_PATH: "/usr/lib/ollama/vulkan/libggml-vulkan.so", + }); + assert.deepEqual(cmd.args, [ + "-m", "/h/tts/orpheus/orpheus-3b-0.1-ft-Q8_0.gguf", + "--host", "127.0.0.1", "--port", "8799", "-ngl", "99", "-c", "8192", "-np", "1", "--no-webui", + ]); + assert.equal(cmd.estimateMB, 4000); + const mine = sanitizeTts({ + engine: "orpheus", + orpheus: { serverBin: "/opt/llama/llama-server", libraryPath: "", ggmlBackendPath: "", port: 9001, gpuLayers: 0, idleStopSeconds: 30 }, + }); + const c2 = o.serverCommand!("/h/tts/orpheus", mine); + assert.equal(c2.bin, "/opt/llama/llama-server"); + assert.deepEqual(c2.env, {}); + assert.equal(c2.port, 9001); + assert.ok(c2.args.includes("0")); + assert.equal(c2.idleStopMs, 30_000); + assert.deepEqual(o.requires!(mine), [{ what: "llama-server (settings.tts.orpheus.serverBin)", path: "/opt/llama/llama-server" }]); +}); + +test("Orpheus's input is the editor's chunks, budgets, sampler and takes; the wrapper gets the server", () => { + const o = getTtsEngine("orpheus")!; + const spoken = o.normalize("One file. No title. Just a date.\n\nAnd then... there it was. <gasp>"); + const input = JSON.parse(o.prepareInput!(spoken, "zac", DEFAULT_TTS_SETTINGS)); + assert.equal(input.voice, "zac"); + assert.deepEqual(input.sampler, { ...ORPHEUS_SAMPLER }); + assert.equal(input.sampler.repeat_last_n, 64); + assert.equal(input.seedBase, 1234); + assert.equal(input.takes, 3); + assert.equal(input.tagCheck, false); + assert.deepEqual( + input.chunks.map((c: { text: string; ends: string; pauseAfter: number }) => [c.text, c.ends, c.pauseAfter]), + [ + ["One file. No title. Just a date.", "paragraph", 0.6], + ["And then... there it was. <gasp>", "end", 0], + ], + ); + assert.ok(input.chunks.every((c: { nPredict: number }) => c.nPredict > 0 && c.nPredict % 7 === 0)); + assert.deepEqual(o.keyExtra!(DEFAULT_TTS_SETTINGS), { takes: 3, tagCheck: false }); + const b = o.build({ + textFile: "/c/x.json", outWav: "/c/x.wav", voice: "zac", speed: 1, installDir: "/h/tts/orpheus", + bins: BINS, server: "http://127.0.0.1:8799", + }); + assert.deepEqual(b.argv, [ + "--engine-kind", "orpheus", + "--python", "/h/tts/orpheus/venv/bin/python", + "--snac", "/h/tts/orpheus/snac_decoder.onnx", + "--server", "http://127.0.0.1:8799", + "--ffmpeg", "/bin/ffmpeg", + "--output", "/c/x.wav", + "/c/x.json", + ]); +}); diff --git a/common/lib/ttsApps.ts b/common/lib/ttsApps.ts @@ -13,23 +13,29 @@ // Pure definitions: no I/O. Both the controller (controller/ttsFile.ts) and the // CLI (bin/tts-setup.ts) import it. // -// ADDING AN ENGINE (release 25 T1b is Orpheus 3B; the doors it needs are here): -// - `device: "gpu"` declares it contends for the GPU. ttsFile.ts's -// runTtsFile is where such an engine waits for the transcription pool to -// be idle before it runs (the `tts` queue then yields to transcription). -// - `runtime: "server"` declares it drives a local server (llama-server on -// Vulkan) started for a batch of syntheses and stopped after, to free the -// VRAM. The server's lifecycle belongs to the controller (one holder per -// engine, opened by the first job on the `tts` queue and closed once the -// queue has been idle); `build` then receives its URL in `input.server`. -// - `normalize` is the engine's own pre-pass: Orpheus keeps the expressive -// tags (`tags: "keep"`) and wants numbers and ordinals spelled out — a new -// option on normalizeTtsText, not a second normalizer. -// - `attribution` is a sentence its licence requires beside the disclosure +// THE THREE ENGINES: Kokoro-82M (the default; CPU), espeak-ng (zero-install) +// and Orpheus 3B (release 25 T1b; GPU). What Orpheus added, and any engine like +// it uses: +// - `device: "gpu"`: ttsFile.ts's runTtsSynthesis waits while a +// transcription runs on a non-CPU worker before it starts one. +// - `runtime: "server"` + `serverCommand`: a local server +// (controller/ttsServer.ts) started for a batch of syntheses behind the +// heavy slot and stopped (SIGTERM, SIGKILL after 15 s) once the `tts` +// queue has been idle, so its VRAM is freed; `build` gets its URL. +// - `prepareInput`: what the wrapper's text file holds when it is not the +// spoken text (Orpheus: the chunks of lib/ttsChunk.ts, each with its token +// budget, the sampler, the takes), and `keyExtra`: the settings that change +// the output, in the cache key. +// - `normalize`: one shared normalizer (lib/ttsText.ts), options per engine. +// - `attribution`: a sentence its licence requires beside the disclosure // (Llama 3.2: "Built with Llama"); ttsDisclosure appends it. +// - `requires`: binaries outside the install dir (the server), checked with +// the install. import path from "node:path"; import { normalizeTtsText } from "./ttsText"; +import { chunkTtsText, nPredictFor } from "./ttsChunk"; +import type { TtsSettings } from "./ttsSettings"; export type TtsDevice = "cpu" | "gpu"; @@ -64,10 +70,26 @@ export type TtsBuildInput = { // The engine's install dir: `<settings.tts.home>/<engine id>`. installDir: string; bins: { ffmpegBin: string; espeakNgBin: string }; - // A `runtime: "server"` engine's base URL (T1b). Undefined for the rest. + // A `runtime: "server"` engine's base URL. Undefined for the rest. server?: string; }; +// A `runtime: "server"` engine's server: how to start it, from settings. +export type TtsServerCommand = { + bin: string; + args: string[]; + env: Record<string, string>; + host: string; + port: number; + // The memory it is admitted to the heavy slot with (scripts/queue-lock.mjs). + estimateMB: number; + startTimeoutMs: number; + idleStopMs: number; +}; + +// A binary the engine needs that is not in its install dir (the server). +export type TtsRequirement = { what: string; path: string }; + export type TtsBuild = { // Args to paths.ttsBin (scripts/tts.mjs). argv: string[]; @@ -91,6 +113,15 @@ export type TtsEngine = { normalize: (text: string) => string; setup: TtsSetup; build: (input: TtsBuildInput) => TtsBuild; + // What the text file the wrapper reads holds, when it is not the spoken text + // itself (Orpheus: its chunks, budgets, sampler and takes, as JSON). + prepareInput?: (spoken: string, voice: string, tts: TtsSettings) => string; + // Settings that change the output, beside the model: in the cache key. + keyExtra?: (tts: TtsSettings) => unknown; + // A `runtime: "server"` engine's server. + serverCommand?: (installDir: string, tts: TtsSettings) => TtsServerCommand; + // Binaries outside the install dir it needs (checked with the install). + requires?: (tts: TtsSettings) => TtsRequirement[]; }; // The wrapper always writes this. @@ -143,7 +174,7 @@ const kokoro: TtsEngine = { voices: KOKORO_VOICES, defaultVoice: "af_heart", speedRange: [0.5, 2], - normalize: (text) => normalizeTtsText(text, { tags: "strip", years: true }), + normalize: (text) => normalizeTtsText(text, { tags: "strip", years: "plain", paragraphs: "join" }), setup: { kind: "python-venv", python: "3.12", @@ -166,6 +197,120 @@ const kokoro: TtsEngine = { }), }; +// --- orpheus ------------------------------------------------------------------ + +// Orpheus 3B 0.1-ft (Q8_0 GGUF) on llama.cpp's server, its SNAC 24 kHz codes +// decoded by the ONNX decoder on the CPU — the tuned round of 2026-10-11. GPU +// (Vulkan) by default, behind the machine's heavy slot. Its eight stock +// speakers; leah the default, zac the male option. Tags are performed, so they +// are kept; numbers, years and the rest are spoken by the shared normalizer +// with the guarded year rule ("1950 people" is a count). No speed control. +export const ORPHEUS_VOICES = ["tara", "leah", "jess", "leo", "dan", "mia", "zac", "zoe"] as const; + +// The tuned round's sampler (its report, "Sampler choice"): the repeat penalty +// on with a 64-token window — `repeat_last_n` 0 would DISABLE it in llama.cpp, +// and -1 is refused by the bundled build. +export const ORPHEUS_SAMPLER = { + temperature: 0.7, + top_p: 0.9, + top_k: 50, + min_p: 0, + repeat_penalty: 1.1, + repeat_last_n: 64, + presence_penalty: 0, + frequency_penalty: 0, +} as const; +export const ORPHEUS_SEED_BASE = 1234; + +export const ORPHEUS_FILES: readonly TtsModelFile[] = [ + { + name: "orpheus-3b-0.1-ft-Q8_0.gguf", + url: "https://huggingface.co/unsloth/orpheus-3b-0.1-ft-GGUF/resolve/main/orpheus-3b-0.1-ft-Q8_0.gguf", + bytes: 3_516_431_616, + sha256: "9a01ea76b66dd66d08a0952ed72932f0ecce59db3d5c9b1a33621ff7200ba531", + }, + { + name: "snac_decoder.onnx", + url: "https://huggingface.co/onnx-community/snac_24khz-ONNX/resolve/main/onnx/decoder_model.onnx", + bytes: 52_600_822, + sha256: "9e2991fce96c3b49c508304e656052f4f6b860fe8432164fcd976eee195fd4f0", + }, + { + name: "snac_config.json", + url: "https://huggingface.co/onnx-community/snac_24khz-ONNX/resolve/main/config.json", + bytes: 301, + sha256: "47a469c3b6ac9a9c940338d82f7a1ad05b92254d9aa05249cb6b81b7938f69bb", + }, +]; + +const orpheus: TtsEngine = { + id: "orpheus", + label: "Orpheus 3B", + model: "orpheus-3b-0.1-ft Q8_0 + snac_24khz decoder (tuned 2026-10-11)", + license: "Llama 3.2 Community License + Apache-2.0", + attribution: "Built with Llama", + device: "gpu", + runtime: "server", + voices: ORPHEUS_VOICES, + defaultVoice: "leah", + speedRange: [1, 1], + normalize: (text) => normalizeTtsText(text, { tags: "keep", years: "guarded", paragraphs: "keep" }), + setup: { + kind: "python-venv", + python: "3.12", + packages: ["onnxruntime==1.31.0", "numpy==2.5.4"], + importName: "onnxruntime", + files: ORPHEUS_FILES, + }, + prepareInput: (spoken, voice, tts) => + JSON.stringify({ + version: 1, + voice, + sampler: ORPHEUS_SAMPLER, + seedBase: ORPHEUS_SEED_BASE, + takes: tts.orpheus.takes, + tagCheck: tts.orpheus.tagCheck, + chunks: chunkTtsText(spoken).map((c) => ({ ...c, nPredict: nPredictFor(c.text) })), + }), + keyExtra: (tts) => ({ takes: tts.orpheus.takes, tagCheck: tts.orpheus.tagCheck }), + serverCommand: (installDir, tts) => { + const o = tts.orpheus; + const env: Record<string, string> = {}; + if (o.libraryPath) env.LD_LIBRARY_PATH = o.libraryPath; + if (o.ggmlBackendPath) env.GGML_BACKEND_PATH = o.ggmlBackendPath; + return { + bin: o.serverBin, + args: [ + "-m", path.join(installDir, ORPHEUS_FILES[0].name), + "--host", "127.0.0.1", + "--port", String(o.port), + "-ngl", String(o.gpuLayers), + "-c", String(o.contextSize), + "-np", "1", + "--no-webui", + ], + env, + host: "127.0.0.1", + port: o.port, + estimateMB: o.heavyEstimateMB, + startTimeoutMs: o.startTimeoutSeconds * 1000, + idleStopMs: o.idleStopSeconds * 1000, + }; + }, + requires: (tts) => [{ what: "llama-server (settings.tts.orpheus.serverBin)", path: tts.orpheus.serverBin }], + build: ({ textFile, outWav, installDir, bins, server }) => ({ + argv: [ + "--engine-kind", "orpheus", + "--python", ttsVenvPython(installDir), + "--snac", path.join(installDir, ORPHEUS_FILES[1].name), + "--server", server ?? "", + "--ffmpeg", bins.ffmpegBin, + "--output", outWav, + textFile, + ], + }), +}; + // --- espeak-ng --------------------------------------------------------------- // The zero-install fallback: a formant synthesizer every Linux has, robotic @@ -181,7 +326,7 @@ const espeakNg: TtsEngine = { voices: ["en-us", "en-gb", "en"], defaultVoice: "en-us", speedRange: [0.5, 2], - normalize: (text) => normalizeTtsText(text, { tags: "strip", years: true }), + normalize: (text) => normalizeTtsText(text, { tags: "strip", years: "plain", paragraphs: "join" }), setup: { kind: "system", bin: "espeakNgBin", hint: "install espeak-ng from the system's packages" }, build: ({ textFile, outWav, voice, speed, bins }) => ({ argv: [ @@ -199,6 +344,7 @@ const espeakNg: TtsEngine = { export const TTS_ENGINES: Record<string, TtsEngine> = { [kokoro.id]: kokoro, [espeakNg.id]: espeakNg, + [orpheus.id]: orpheus, }; export const DEFAULT_TTS_ENGINE_ID = "kokoro"; diff --git a/common/lib/ttsChunk.test.ts b/common/lib/ttsChunk.test.ts @@ -0,0 +1,213 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { CHUNK_MAX_CHARS, chunkTtsText, nPredictFor, splitLong, splitSentences, wordsIn } from "./ttsChunk"; +import { normalizeTtsText } from "./ttsText"; + +// Run with: +// pnpm --filter yt-dlp-transcript-common exec tsx --test lib/ttsChunk.test.ts +// +// The chunker against the tuned round's own (run_orpheus2.py chunk(normalize())): +// the bake-off lines (synthetic text written for the bake-off) and the +// chunks, endings, pauses and token budgets that pipeline produced for them, +// pasted here as data. + +const ORPHEUS = { tags: "keep", years: "guarded", paragraphs: "keep" } as const; +const LINES: Record<string, string> = { + "card": "Two weeks later, the same channel posted the opposite claim — and deleted the first video.", + "numbers": "On March 14th, 2024, he said fifteen thousand people watched; the stream's own counter showed 3,812.", + "quote": "In his words: \"I never said that.\" The clip below is from forty minutes earlier.", + "podcast": "Welcome back to the archive. Every video we cover here has a transcript on file, saved the day it was published, so when a claim changes we can show exactly what was said before. That matters, because memories drift and old uploads quietly disappear. Each clip you hear comes with a citation: the channel, the date, and the minute it was spoken, so you can check it yourself. Nothing is paraphrased when the original words are available, and if you are new here, every source we use is linked in the description. Today, we follow one story across three years of streams, and let the record speak for itself.", + "podcast-tagged": "Welcome back to the archive. <chuckle> Every video we cover here has a transcript on file, saved the day it was published, so when a claim changes we can show exactly what was said before. That matters, because memories drift and old uploads quietly disappear. <sigh> Each clip you hear comes with a citation: the channel, the date, and the minute it was spoken, so you can check it yourself. Nothing is paraphrased when the original words are available, and if you are new here, every source we use is linked in the description. Today, we follow one story across three years of streams, and let the record speak for itself.", + "quote-tagged": "In his words: \"I never said that.\" <chuckle> The clip below is from forty minutes earlier.", + "story": "Nobody was supposed to find it. <sigh> The video had been gone for three years. Deleted on a quiet Tuesday night... without a single word.\n\nThe channel moved on. The comments moved on. And honestly? So did I.\n\nThen, one rainy afternoon, I was clearing out an old hard drive. Folders inside folders. Files called final, and final two, and final-final. <chuckle> You know the kind.\n\nAnd then... there it was. One file. No title. Just a date.\n\nI almost deleted it. Why wouldn't I? But something made me press play.\n\n<gasp> It was the video. The whole thing. Every word, every pause, exactly the way it was said the first time.\n\nHere's the thing about the internet. It feels like it forgets. It doesn't. Not always. Somewhere, somebody hit save.\n\nSo the next time someone tells you it never happened... ask them one simple question. Are you sure?", + "story-card": "Three years ago, it vanished without a word. Everyone said it was gone for good... They were wrong.", + "story-plain": "An archivist found a copy of a video that had been deleted three years earlier. The video was removed on a Tuesday night without explanation, and the channel and its audience moved on. The copy was found while the archivist was clearing out an old hard drive that contained many nested folders, with files named final, final two, and final-final. One untitled file was labelled only with a date. The archivist considered deleting it, but played it first. It was the deleted video, complete, with every statement intact as it was originally recorded. This shows that online content is not always permanently lost, because copies are sometimes saved. Claims that something never happened can therefore be checked against preserved records." +}; +const EXPECTED: Record<string, { text: string; ends: string; pauseAfter: number }[]> = { + "card": [ + { + "text": "Two weeks later, the same channel posted the opposite claim, and deleted the first video.", + "ends": "end", + "pauseAfter": 0.0 + } + ], + "numbers": [ + { + "text": "On March fourteenth, twenty twenty-four, he said fifteen thousand people watched; the stream's own counter showed three thousand eight hundred twelve.", + "ends": "end", + "pauseAfter": 0.0 + } + ], + "quote": [ + { + "text": "In his words: \"I never said that.\" The clip below is from forty minutes earlier.", + "ends": "end", + "pauseAfter": 0.0 + } + ], + "podcast": [ + { + "text": "Welcome back to the archive. Every video we cover here has a transcript on file, saved the day it was published, so when a claim changes we can show exactly what was said before.", + "ends": "sentence", + "pauseAfter": 0.3 + }, + { + "text": "That matters, because memories drift and old uploads quietly disappear. Each clip you hear comes with a citation: the channel, the date, and the minute it was spoken, so you can check it yourself.", + "ends": "sentence", + "pauseAfter": 0.3 + }, + { + "text": "Nothing is paraphrased when the original words are available, and if you are new here, every source we use is linked in the description. Today, we follow one story across three years of streams, and let the record speak for itself.", + "ends": "end", + "pauseAfter": 0.0 + } + ], + "podcast-tagged": [ + { + "text": "Welcome back to the archive. <chuckle> Every video we cover here has a transcript on file, saved the day it was published, so when a claim changes we can show exactly what was said before.", + "ends": "sentence", + "pauseAfter": 0.3 + }, + { + "text": "That matters, because memories drift and old uploads quietly disappear. <sigh> Each clip you hear comes with a citation: the channel, the date, and the minute it was spoken, so you can check it yourself.", + "ends": "sentence", + "pauseAfter": 0.3 + }, + { + "text": "Nothing is paraphrased when the original words are available, and if you are new here, every source we use is linked in the description. Today, we follow one story across three years of streams, and let the record speak for itself.", + "ends": "end", + "pauseAfter": 0.0 + } + ], + "quote-tagged": [ + { + "text": "In his words: \"I never said that.\" <chuckle> The clip below is from forty minutes earlier.", + "ends": "end", + "pauseAfter": 0.0 + } + ], + "story": [ + { + "text": "Nobody was supposed to find it. <sigh> The video had been gone for three years. Deleted on a quiet Tuesday night... without a single word.", + "ends": "paragraph", + "pauseAfter": 0.6 + }, + { + "text": "The channel moved on. The comments moved on. And honestly? So did I.", + "ends": "paragraph", + "pauseAfter": 0.6 + }, + { + "text": "Then, one rainy afternoon, I was clearing out an old hard drive. Folders inside folders. Files called final, and final two, and final-final. <chuckle> You know the kind.", + "ends": "paragraph", + "pauseAfter": 0.6 + }, + { + "text": "And then... there it was. One file. No title. Just a date.", + "ends": "paragraph", + "pauseAfter": 0.6 + }, + { + "text": "I almost deleted it. Why wouldn't I? But something made me press play.", + "ends": "paragraph", + "pauseAfter": 0.6 + }, + { + "text": "<gasp> It was the video. The whole thing. Every word, every pause, exactly the way it was said the first time.", + "ends": "paragraph", + "pauseAfter": 0.6 + }, + { + "text": "Here's the thing about the internet. It feels like it forgets. It doesn't. Not always. Somewhere, somebody hit save.", + "ends": "paragraph", + "pauseAfter": 0.6 + }, + { + "text": "So the next time someone tells you it never happened... ask them one simple question. Are you sure?", + "ends": "end", + "pauseAfter": 0.0 + } + ], + "story-card": [ + { + "text": "Three years ago, it vanished without a word. Everyone said it was gone for good... They were wrong.", + "ends": "end", + "pauseAfter": 0.0 + } + ], + "story-plain": [ + { + "text": "An archivist found a copy of a video that had been deleted three years earlier. The video was removed on a Tuesday night without explanation, and the channel and its audience moved on.", + "ends": "sentence", + "pauseAfter": 0.3 + }, + { + "text": "The copy was found while the archivist was clearing out an old hard drive that contained many nested folders, with files named final, final two, and final-final.", + "ends": "sentence", + "pauseAfter": 0.3 + }, + { + "text": "One untitled file was labelled only with a date. The archivist considered deleting it, but played it first. It was the deleted video, complete, with every statement intact as it was originally recorded.", + "ends": "sentence", + "pauseAfter": 0.3 + }, + { + "text": "This shows that online content is not always permanently lost, because copies are sometimes saved. Claims that something never happened can therefore be checked against preserved records.", + "ends": "end", + "pauseAfter": 0.0 + } + ] +}; +const N_PREDICT: Record<string, number> = { + "Nobody was supposed to find it. <sigh> The video had been gone for three years. Deleted on a quiet Tuesday night... without a single word.": 1498, + "The channel moved on. The comments moved on. And honestly? So did I.": 763, + "Then, one rainy afternoon, I was clearing out an old hard drive. Folders inside folders. Files called final, and final two, and final-final. <chuckle> You know the kind.": 1673, + "And then... there it was. One file. No title. Just a date.": 749, + "I almost deleted it. Why wouldn't I? But something made me press play.": 763, + "<gasp> It was the video. The whole thing. Every word, every pause, exactly the way it was said the first time.": 1253, + "Here's the thing about the internet. It feels like it forgets. It doesn't. Not always. Somewhere, somebody hit save.": 1078, + "So the next time someone tells you it never happened... ask them one simple question. Are you sure?": 1064 +}; + +test("every bake-off line chunks exactly as the tuned pipeline did", () => { + for (const [key, text] of Object.entries(LINES)) { + assert.deepEqual(chunkTtsText(normalizeTtsText(text, ORPHEUS)), EXPECTED[key], key); + } +}); + +test("the pipeline's own chunker assertions", () => { + const pod = chunkTtsText(normalizeTtsText(LINES.podcast, ORPHEUS)); + assert.ok(pod.every((c) => c.text.length <= CHUNK_MAX_CHARS)); + assert.ok(pod.length >= 2 && pod.length <= 4); + assert.equal(pod[pod.length - 1].ends, "end"); + assert.ok(pod.slice(0, -1).every((c) => c.ends === "sentence")); + const q = chunkTtsText(normalizeTtsText(LINES["quote-tagged"], ORPHEUS)); + assert.equal(q.length, 1); + assert.ok(q[0].text.includes("<chuckle>")); + const st = chunkTtsText(normalizeTtsText(LINES.story, ORPHEUS)); + assert.equal(st.filter((c) => c.ends === "paragraph").length, LINES.story.split("\n\n").length - 1); + assert.ok(st.map((c) => c.text).join("").includes("<gasp>")); + assert.ok(st.every((c) => c.pauseAfter === { sentence: 0.3, clause: 0.15, paragraph: 0.6, end: 0 }[c.ends])); +}); + +test("a long sentence is cut at clause boundaries, never mid-phrase", () => { + const long = "word ".repeat(20) + "and this keeps going; " + "more words here, ".repeat(12) + "but then it ends."; + const parts = splitLong(long); + assert.deepEqual(parts, ["word word word word word word word word word word word word word word word word word word word word and this keeps going;", "more words here, more words here, more words here, more words here, more words here, more words here, more words here, more words here, more words here, more words here, more words here, more words here, but then it ends."]); + assert.ok(parts.every((p) => p.length <= CHUNK_MAX_CHARS)); +}); + +test("sentences: a reaction tag joins the sentence before it; an ellipsis continues one", () => { + assert.deepEqual(splitSentences("It was gone. <sigh> Then... it was back. And then... there it was."), [ + "It was gone. <sigh>", + "Then... it was back.", + "And then... there it was.", + ]); + assert.deepEqual(splitSentences("Deleted on a Tuesday night... without a word."), ["Deleted on a Tuesday night... without a word."]); + assert.equal(wordsIn("It's <laugh> one file."), 3); +}); + +test("the token budget follows the words, tags and beats", () => { + for (const [text, n] of Object.entries(N_PREDICT)) assert.equal(nPredictFor(text), n, text); + assert.equal(nPredictFor("x") % 7, 0); +}); diff --git a/common/lib/ttsChunk.ts b/common/lib/ttsChunk.ts @@ -0,0 +1,130 @@ +// THE CHUNKER for an engine that speaks a few sentences per call (release 25 +// T1b: Orpheus), ported from the tuned round's pipeline (run_orpheus2.py +// `chunk()`), with its expected-length budget. +// +// Normalized text (lib/ttsText.ts, paragraphs kept as "\n\n") → chunks of 1–3 +// sentences, at most 250 characters, packed for the fewest chunks first and +// then the most even lengths. A fragment under six words ("No title.") counts +// as half a sentence. A sentence over the limit is cut at `; :` first, then at +// a comma before a conjunction, then at any comma — never mid-phrase. A blank +// line always ends a chunk. Each chunk carries the pause that follows it, by +// how it ended: a sentence 0.30 s, a clause 0.15 s, a paragraph 0.60 s, +// nothing after the last. +// +// Pure, no imports beyond the tag set. scripts/tts_orpheus.py renders what +// this returns; it does not chunk. + +import { TTS_EXPRESSIVE_TAGS } from "./ttsText"; + +export const CHUNK_MAX_CHARS = 250; +export const CHUNK_MAX_SENTENCES = 3; +export const CHUNK_PAUSE = { sentence: 0.3, clause: 0.15, paragraph: 0.6, end: 0 } as const; +export type ChunkEnding = keyof typeof CHUNK_PAUSE; + +export type TtsChunk = { text: string; ends: ChunkEnding; pauseAfter: number }; + +const TAG = `<(?:${TTS_EXPRESSIVE_TAGS.join("|")})>`; +const TAG_G = new RegExp(TAG, "g"); +const CONJ = + "(?:and|but|so|because|which|while|or|yet|when|although|though|where|since|until|unless|then)"; + +/** Words in a chunk, tags not counted. */ +export function wordsIn(text: string): number { + return (text.replace(TAG_G, " ").match(/[A-Za-z0-9]+(?:'[A-Za-z]+)?/g) ?? []).length; +} + +/** A paragraph's sentences. A reaction tag after a sentence joins it; a lowercase start is an ellipsis continuation. */ +export function splitSentences(par: string): string[] { + const pieces = par.trim().split(/(?<=[.!?]["')\]])\s+|(?<=[.!?])\s+/); + const lead = new RegExp(`^(?:${TAG}\\s*)+`); + const out: string[] = []; + for (const raw of pieces) { + let p = raw.trim(); + if (!p) continue; + const m = lead.exec(p); + if (m && out.length) { + out[out.length - 1] += ` ${m[0].trim()}`; + p = p.slice(m[0].length).trim(); + if (!p) continue; + } + if (out.length && /^[a-z]/.test(p)) out[out.length - 1] += ` ${p}`; + else out.push(p); + } + return out; +} + +/** One over-long sentence cut at clause boundaries, never mid-phrase. */ +export function splitLong(s: string, limit = CHUNK_MAX_CHARS): string[] { + if (s.length <= limit) return [s]; + const mid = s.length / 2; + for (const pat of [/[;:]\s+/g, new RegExp(`,\\s+(?=${CONJ}\\b)`, "g"), /,\s+/g]) { + const cuts = [...s.matchAll(pat)] + .filter((m) => m.index! >= 40 && m.index! <= s.length - 40) + .map((m) => m.index! + m[0].length); + if (cuts.length) { + const c = cuts.reduce((a, b) => (Math.abs(b - mid) < Math.abs(a - mid) ? b : a)); + return [...splitLong(s.slice(0, c).trim(), limit), ...splitLong(s.slice(c).trim(), limit)]; + } + } + let c = s.lastIndexOf(" ", Math.floor(mid)); + if (c <= 0) c = Math.floor(mid); + return [...splitLong(s.slice(0, c).trim(), limit), ...splitLong(s.slice(c).trim(), limit)]; +} + +// Balanced packing (DP): fewest chunks, then the least sum of squared lengths. +function pack(units: string[]): string[] { + const n = units.length; + const wt = units.map((u) => (wordsIn(u) < 6 ? 0.5 : 1)); + const best: [number, number, number][] = [[0, 0, -1]]; + for (let i = 1; i <= n; i++) best.push([Infinity, Infinity, -1]); + for (let i = 1; i <= n; i++) { + let w = 0; + for (let j = i - 1; j >= 0; j--) { + w += wt[j]; + const L = units.slice(j, i).join(" ").length; + if (i - j > 1 && (L > CHUNK_MAX_CHARS || w > CHUNK_MAX_SENTENCES)) break; + const c: [number, number, number] = [best[j][0] + 1, best[j][1] + L * L, j]; + if (c[0] < best[i][0] || (c[0] === best[i][0] && c[1] < best[i][1])) best[i] = c; + } + } + const out: string[] = []; + for (let i = n; i > 0; i = best[i][2]) out.push(units.slice(best[i][2], i).join(" ")); + return out.reverse(); +} + +function ending(text: string): ChunkEnding { + const core = text.replace(TAG_G, "").replace(/[ "')\]]+$/, ""); + return /[.!?]$/.test(core) ? "sentence" : "clause"; +} + +/** Normalized text (paragraphs as "\n\n") → chunks, each with the pause after it. */ +export function chunkTtsText(normalized: string): TtsChunk[] { + const paras = normalized.split("\n\n").filter((p) => p.trim()); + const chunks: TtsChunk[] = []; + paras.forEach((par, pi) => { + const units = splitSentences(par).flatMap((s) => splitLong(s)); + const packed = pack(units); + packed.forEach((text, ci) => { + const lastInPar = ci === packed.length - 1; + const ends: ChunkEnding = + lastInPar && pi === paras.length - 1 ? "end" : lastInPar ? "paragraph" : ending(text); + chunks.push({ text, ends, pauseAfter: CHUNK_PAUSE[ends] }); + }); + }); + return chunks; +} + +// SNAC 24 kHz: 7 tokens per frame of 2048 samples — 82.03 tokens a second of audio. +export const ORPHEUS_TOKENS_PER_AUDIO_S = (7 * 24000) / 2048; + +/** + * The token budget for one chunk: its expected seconds × 82.03 tokens/s × 1.6, + * rounded up to a whole 7-token frame, so a runaway take is cut (and flagged, + * never kept). Expected seconds = words ÷ 2.5 + 0.9 a tag + 0.3 an "..." + 0.6. + */ +export function nPredictFor(text: string): number { + const tags = (text.match(TAG_G) ?? []).length; + const ellipses = text.split("...").length - 1; + const expS = wordsIn(text) / 2.5 + 0.9 * tags + 0.3 * ellipses + 0.6; + return Math.ceil((expS * ORPHEUS_TOKENS_PER_AUDIO_S * 1.6) / 7) * 7; +} diff --git a/common/lib/ttsInstall.ts b/common/lib/ttsInstall.ts @@ -11,6 +11,7 @@ import fs from "node:fs"; import path from "node:path"; import type { Paths } from "./paths"; import { ttsInstallDir, ttsVenvPython, type TtsEngine } from "./ttsApps"; +import type { TtsSettings } from "./ttsSettings"; export type TtsInstallState = { engine: string; @@ -44,7 +45,7 @@ export function findOnPath(bin: string, envPath: string | undefined = process.en export function ttsInstallState( engine: TtsEngine, - opts: { home: string; paths: Pick<Paths, "espeakNgBin">; envPath?: string }, + opts: { home: string; paths: Pick<Paths, "espeakNgBin">; envPath?: string; tts?: TtsSettings }, ): TtsInstallState { const setup = engine.setup; if (setup.kind === "system") { @@ -72,5 +73,11 @@ export function ttsInstallState( if (size === null) missing.push(`${f.name}`); else if (size !== f.bytes) missing.push(`${f.name} (${size} bytes, expected ${f.bytes})`); } + // Binaries outside the install dir (Orpheus's llama-server, from settings). + if (engine.requires && opts.tts) { + for (const r of engine.requires(opts.tts)) { + if (!findOnPath(r.path, opts.envPath ?? process.env.PATH)) missing.push(`${r.what}: ${r.path}`); + } + } return { engine: engine.id, dir, installed: missing.length === 0, missing }; } diff --git a/common/lib/ttsSettings.test.ts b/common/lib/ttsSettings.test.ts @@ -2,14 +2,21 @@ import { test } from "node:test"; import assert from "node:assert/strict"; import os from "node:os"; import path from "node:path"; -import { DEFAULT_TTS_SETTINGS, resolveTtsCacheDir, resolveTtsHome, sanitizeTts } from "./ttsSettings"; +import { DEFAULT_ORPHEUS_TTS_SETTINGS, DEFAULT_TTS_SETTINGS, resolveTtsCacheDir, resolveTtsHome, sanitizeTts } from "./ttsSettings"; import { defaults } from "./settingsSchema"; // Run with: // pnpm --filter yt-dlp-transcript-common exec tsx --test lib/ttsSettings.test.ts test("the default block: kokoro, af_heart, natural pace, blank dirs", () => { - assert.deepEqual(defaults().tts, { engine: "kokoro", voice: "af_heart", speed: 1, home: "", dir: "" }); + assert.deepEqual(defaults().tts, { + engine: "kokoro", + voice: "af_heart", + speed: 1, + home: "", + dir: "", + orpheus: DEFAULT_ORPHEUS_TTS_SETTINGS, + }); assert.deepEqual(sanitizeTts(undefined), DEFAULT_TTS_SETTINGS); assert.deepEqual(sanitizeTts("nonsense"), DEFAULT_TTS_SETTINGS); }); @@ -35,3 +42,32 @@ test("home and dir: blank is the Paths default, ~/ expands, a relative path is d assert.equal(sanitizeTts({ dir: "relative/cache" }).dir, ""); assert.equal(sanitizeTts({ home: 7 }).home, ""); }); + +test("orpheus: leah by default, speed held at 1, its server block sanitized", () => { + const o = sanitizeTts({ engine: "orpheus", speed: 0.8 }); + assert.equal(o.voice, "leah"); + assert.equal(o.speed, 1); + assert.equal(sanitizeTts({ engine: "orpheus", voice: "zac" }).voice, "zac"); + assert.deepEqual(DEFAULT_ORPHEUS_TTS_SETTINGS, { + serverBin: "/usr/lib/ollama/llama-server", + libraryPath: "/usr/lib/ollama", + ggmlBackendPath: "/usr/lib/ollama/vulkan/libggml-vulkan.so", + port: 8799, + gpuLayers: 99, + contextSize: 8192, + startTimeoutSeconds: 150, + idleStopSeconds: 5, + heavyEstimateMB: 4000, + takes: 3, + tagCheck: false, + }); + const s = sanitizeTts({ + orpheus: { serverBin: "relative/llama", libraryPath: "", port: 80, takes: 99, tagCheck: "yes", gpuLayers: 12.4 }, + }).orpheus; + assert.equal(s.serverBin, "/usr/lib/ollama/llama-server"); + assert.equal(s.libraryPath, ""); + assert.equal(s.port, 1024); + assert.equal(s.takes, 6); + assert.equal(s.tagCheck, false); + assert.equal(s.gpuLayers, 12); +}); diff --git a/common/lib/ttsSettings.ts b/common/lib/ttsSettings.ts @@ -11,12 +11,72 @@ import type { FieldDocs } from "./fieldDocs"; import type { Paths } from "./paths"; import { DEFAULT_TTS_ENGINE_ID, DEFAULT_TTS_VOICE, getTtsEngine } from "./ttsApps"; +// Orpheus 3B (release 25 T1b): the local llama-server it runs on and how many +// takes a chunk gets. The server's binary and its two library paths default to +// Ollama's bundled build on Vulkan — settings, never hard-coded. +export type OrpheusTtsSettings = { + serverBin: string; + libraryPath: string; + ggmlBackendPath: string; + port: number; + gpuLayers: number; + contextSize: number; + startTimeoutSeconds: number; + idleStopSeconds: number; + heavyEstimateMB: number; + takes: number; + tagCheck: boolean; +}; + export type TtsSettings = { engine: string; voice: string; speed: number; home: string; dir: string; + orpheus: OrpheusTtsSettings; +}; + +export const DEFAULT_ORPHEUS_TTS_SETTINGS: OrpheusTtsSettings = { + serverBin: "/usr/lib/ollama/llama-server", + libraryPath: "/usr/lib/ollama", + ggmlBackendPath: "/usr/lib/ollama/vulkan/libggml-vulkan.so", + port: 8799, + gpuLayers: 99, + contextSize: 8192, + startTimeoutSeconds: 150, + idleStopSeconds: 5, + heavyEstimateMB: 4000, + takes: 3, + tagCheck: false, +}; + +export const ORPHEUS_TTS_SETTINGS_FIELD_DOCS: FieldDocs<OrpheusTtsSettings> = { + serverBin: + "The llama.cpp server Orpheus runs on (`llama-server`). Default: Ollama's bundled build. " + + "Started for a batch of syntheses on the `tts` queue and stopped (SIGTERM, then SIGKILL " + + "after 15 s) once the queue has been idle `idleStopSeconds`, so its VRAM is freed.", + libraryPath: "`LD_LIBRARY_PATH` for the server (Ollama's bundled libraries). Blank = not set.", + ggmlBackendPath: + "`GGML_BACKEND_PATH` for the server: the ggml backend it loads — Vulkan by default. Blank = not set.", + port: "The port the server listens on, on 127.0.0.1. A port something else already answers on is refused, never shared.", + gpuLayers: "`-ngl`: layers on the GPU. 99 = all of them; 0 runs on the CPU (about 9× slower).", + contextSize: "`-c`, the context in tokens; also the whole window the repeat penalty could see.", + startTimeoutSeconds: + "How long the server may take to answer `/health` once it is running (it took 2.5–14 s in the " + + "tuning round). The wait for the machine's heavy slot before it starts is not counted.", + idleStopSeconds: "How long the server is kept after the last synthesis before it is stopped, so the next one in the queue reuses it.", + heavyEstimateMB: + "The memory the server is admitted to the heavy slot with (`queue-lock --heavy --estimate`): it " + + "starts only when that much is free above the floor, beside other estimated jobs, never beside a build.", + takes: + "Takes per chunk, at most: the first that passes the checks (end token reached, no malformed frame, " + + "not truncated, words a second in band, no long silence) is kept. 1–6.", + tagCheck: + "The tag-length check: a chunk with expressive tags must run at least 0.4 s a tag longer than the " + + "same voice reading it without them (one extra take of the stripped text per tagged chunk), else the " + + "take is taken to have skipped its tag. OFF by default. (The tuning round's UTMOS scorer is not " + + "offered: it needs torch.)", }; export const DEFAULT_TTS_SETTINGS: TtsSettings = { @@ -25,21 +85,26 @@ export const DEFAULT_TTS_SETTINGS: TtsSettings = { speed: 1, home: "", dir: "", + orpheus: DEFAULT_ORPHEUS_TTS_SETTINGS, }; export const TTS_SETTINGS_FIELD_DOCS: FieldDocs<TtsSettings> = { engine: "The engine a synthesis uses when the request names none: `kokoro` (Kokoro-82M, " + - "Apache-2.0, CPU; installed by `archilyzer tts setup`) or `espeak-ng` (the " + - "zero-install fallback). An unknown id falls back to `kokoro`.", + "Apache-2.0, CPU; installed by `archilyzer tts setup`), `orpheus` (Orpheus 3B, " + + "Llama 3.2 Community License + Apache-2.0, \"Built with Llama\"; GPU, on a local " + + "llama-server — `tts.orpheus`; `archilyzer tts setup --engine orpheus`) or " + + "`espeak-ng` (the zero-install fallback). An unknown id falls back to `kokoro`.", voice: "The engine's stock voice when the request names none (stock voices only: no " + "cloning, no reference audio). For Kokoro, `a*` voices are American English and " + - "`b*` British; `af_heart` was picked by ear in the release 25 bake-off. A voice the " + + "`b*` British; `af_heart` was picked by ear in the release 25 bake-off. Orpheus: " + + "tara leah jess leo dan mia zac zoe — `leah` its default, `zac` the male option. A voice the " + "engine does not have falls back to the engine's default.", speed: "Speaking pace, 1 = the engine's natural pace (Kokoro speaks briskly; 0.9 slows it). " + - "Clamped to [0.5, 2]. In the cache key: a new speed is a new synthesis.", + "Clamped to the engine's range: [0.5, 2] for Kokoro and espeak-ng; Orpheus has none (1). " + + "In the cache key: a new speed is a new synthesis.", home: "Where `archilyzer tts setup` installs engines, one directory per engine " + "(`<home>/kokoro`: its python venv and model files). Blank = " + @@ -49,6 +114,7 @@ export const TTS_SETTINGS_FIELD_DOCS: FieldDocs<TtsSettings> = { "sidecar (engine, model, licence, voice, seconds, disclosure) per distinct (engine, " + "model, voice, speed, normalized text) — a re-ask is free. Never inside the corpus " + "(refused). Blank = `<repo>/.tts/cache` (gitignored). Absolute, or `~/`-relative.", + orpheus: "Orpheus 3B's server and takes. See OrpheusTtsSettings (`tts.orpheus` below).", }; // "" (the default), an absolute path, or a `~/` one; anything else is "". @@ -68,11 +134,51 @@ export function sanitizeTts(value: unknown): TtsSettings { typeof r.voice === "string" && engine.voices.includes(r.voice.trim()) ? r.voice.trim() : engine.defaultVoice; - const speed = - typeof r.speed === "number" && Number.isFinite(r.speed) - ? Math.min(2, Math.max(0.5, Math.round(r.speed * 100) / 100)) - : d.speed; - return { engine: engine.id, voice, speed, home: dirSetting(r.home), dir: dirSetting(r.dir) }; + // Within the engine's range (Orpheus has no speed control: always 1). + const [lo, hi] = engine.speedRange; + const speed = Math.min( + hi, + Math.max(lo, typeof r.speed === "number" && Number.isFinite(r.speed) ? Math.round(r.speed * 100) / 100 : d.speed), + ); + return { + engine: engine.id, + voice, + speed, + home: dirSetting(r.home), + dir: dirSetting(r.dir), + orpheus: sanitizeOrpheus(r.orpheus), + }; +} + +function int(value: unknown, fallback: number, min: number, max: number): number { + const n = typeof value === "number" && Number.isFinite(value) ? Math.round(value) : fallback; + return Math.min(max, Math.max(min, n)); +} + +// An absolute path, or "" where blank is allowed; anything else is the default. +function absPath(value: unknown, fallback: string, blankOk: boolean): string { + if (typeof value !== "string") return fallback; + const s = value.trim(); + if (s === "") return blankOk ? "" : fallback; + return path.isAbsolute(s) ? s : fallback; +} + +export function sanitizeOrpheus(value: unknown): OrpheusTtsSettings { + const d = DEFAULT_ORPHEUS_TTS_SETTINGS; + const r = value && typeof value === "object" ? (value as Record<string, unknown>) : {}; + return { + serverBin: absPath(r.serverBin, d.serverBin, false), + libraryPath: absPath(r.libraryPath, d.libraryPath, true), + ggmlBackendPath: absPath(r.ggmlBackendPath, d.ggmlBackendPath, true), + port: int(r.port, d.port, 1024, 65535), + gpuLayers: int(r.gpuLayers, d.gpuLayers, 0, 999), + contextSize: int(r.contextSize, d.contextSize, 2048, 131072), + startTimeoutSeconds: int(r.startTimeoutSeconds, d.startTimeoutSeconds, 5, 3600), + idleStopSeconds: int(r.idleStopSeconds, d.idleStopSeconds, 0, 3600), + heavyEstimateMB: int(r.heavyEstimateMB, d.heavyEstimateMB, 0, 65536), + takes: int(r.takes, d.takes, 1, 6), + tagCheck: r.tagCheck === true, + }; } function expand(p: string): string { diff --git a/common/lib/ttsText.test.ts b/common/lib/ttsText.test.ts @@ -4,6 +4,9 @@ import { TTS_EXPRESSIVE_TAGS, collapseTtsWhitespace, normalizeTtsText, + sayDecimal, + sayInt, + sayOrdinal, speakYears, stripTtsTags, twoDigitWords, @@ -117,16 +120,64 @@ test("whitespace collapses, so a re-wrapped paragraph is the same text", () => { assert.equal(collapseTtsWhitespace(" a\n\n b\t c "), "a b c"); assert.equal(collapseTtsWhitespace("a , b ."), "a, b."); assert.equal( - normalizeTtsText("In 2024,\n the <laugh> show\nended .", { tags: "strip", years: true }), + normalizeTtsText("In 2024,\n the <laugh> show\nended .", { tags: "strip", years: "plain", paragraphs: "join" }), "In twenty twenty-four, the show ended.", ); assert.equal( - normalizeTtsText("In 2024 <laugh> it ended.", { tags: "keep", years: false }), - "In 2024 <laugh> it ended.", + normalizeTtsText("In 2024 <laugh> it ended.", { tags: "keep", years: "guarded", paragraphs: "keep" }), + "In twenty twenty-four <laugh> it ended.", ); // NFC: a decomposed accent is the same text as a composed one. assert.equal( - normalizeTtsText("café", { tags: "strip", years: true }), - normalizeTtsText("café", { tags: "strip", years: true }), + normalizeTtsText("café", { tags: "strip", years: "plain", paragraphs: "join" }), + normalizeTtsText("café", { tags: "strip", years: "plain", paragraphs: "join" }), ); }); + +// The tuned Orpheus round's 17 self-tests (run_orpheus2.py selftest), ported +// as they stand: tags kept, the guarded year rule, paragraphs kept. +const ORPHEUS = { tags: "keep", years: "guarded", paragraphs: "keep" } as const; +const SELFTEST: [string, string][] = [ + ["On March 14th, 2024, he said", "On March fourteenth, twenty twenty-four, he said"], + ["the counter showed 3,812.", "the counter showed three thousand eight hundred twelve."], + ["in 2005 and 1999 and 1905 and 1900 and 2010", "in two thousand five and nineteen ninety-nine and nineteen oh five and nineteen hundred and twenty ten"], + ["1950 people", "one thousand nine hundred fifty people"], + ["the 1990s and the \u201990s", "the nineteen nineties and the nineties"], + ["21st, 22nd, 103rd, 12th, 40th", "twenty-first, twenty-second, one hundred third, twelfth, fortieth"], + ["up 45% or 3.5%", "up forty-five percent or three point five percent"], + ["$12.50, $1, $3.5 million, $1,200", "twelve dollars and fifty cents, one dollar, three point five million dollars, one thousand two hundred dollars"], + ["Dr. Smith vs. Mr. Jones, e.g. today", "Doctor Smith versus Mister Jones, for example, today"], + ["the claim \u2014 and the video", "the claim, and the video"], + ["from 2019\u20132021", "from twenty nineteen to twenty twenty-one"], + ["see https://example.pages.dev/c/x?y=1 now", "see example dot pages dot dev now"], + ["ask @some_handle about #TrueCrime", "ask at some handle about hashtag TrueCrime"], + ["at 3:45 and 10:00 and 7:05", "at three forty-five and ten o'clock and seven oh five"], + ["He laughed. <laugh> 2024 was <sigh> long.", "He laughed. <laugh> twenty twenty-four was <sigh> long."], + ["It\u2019s 3.14 and 0.5", "It's three point one four and zero point five"], + ["No. 5 & #1", "number five and number one"], +]; + +test("the spoken-form normalizer passes the tuned round's 17 self-tests", () => { + assert.equal(SELFTEST.length, 17); + for (const [src, want] of SELFTEST) assert.equal(normalizeTtsText(src, ORPHEUS), want, src); +}); + +test("numbers: cardinals, ordinals, decimals", () => { + assert.equal(sayInt(0), "zero"); + assert.equal(sayInt(115), "one hundred fifteen"); + assert.equal(sayInt(1_000_001), "one million one"); + assert.equal(sayInt(-3), "minus three"); + assert.equal(sayOrdinal(1), "first"); + assert.equal(sayOrdinal(30), "thirtieth"); + assert.equal(sayOrdinal(1002), "one thousand second"); + assert.equal(sayDecimal("1,200.75"), "one thousand two hundred point seven five"); +}); + +test("Kokoro keeps T1's year rule; Orpheus guards counts; paragraphs kept or joined", () => { + const kokoro = { tags: "strip", years: "plain", paragraphs: "join" } as const; + assert.equal(normalizeTtsText("1950 people came.", kokoro), "nineteen fifty people came."); + assert.equal(normalizeTtsText("1950 people came.", ORPHEUS), "one thousand nine hundred fifty people came."); + assert.equal(normalizeTtsText("It was 42 <sigh> episodes.", kokoro), "It was forty-two episodes."); + assert.equal(normalizeTtsText("One.\n\n\nTwo <gasp> three.\nFour.", ORPHEUS), "One.\n\nTwo <gasp> three. Four."); + assert.equal(normalizeTtsText("One.\n\nTwo <gasp> three.", kokoro), "One. Two three."); +}); diff --git a/common/lib/ttsText.ts b/common/lib/ttsText.ts @@ -1,24 +1,30 @@ -// THE TEXT PRE-PASS EVERY SPEECH ENGINE'S INPUT GOES THROUGH (release 25 T1). +// THE TEXT PRE-PASS EVERY SPEECH ENGINE'S INPUT GOES THROUGH (release 25 T1, +// widened by T1b to the tuned Orpheus round's spoken-form normalizer). // // One shared normalizer; each engine in lib/ttsApps.ts picks its options with -// its own `normalize` hook. What it does, in order: +// its own `normalize` hook. What it does: // // 1. Expressive tags. Narration may carry the tag set below (`<laugh>`, -// `<sigh>`, ...) for an engine that performs them. An engine that cannot -// (Kokoro, espeak-ng) has them STRIPPED here, so nothing reads "less-than -// laugh" aloud. Any OTHER `<...>` is refused before a job exists -// (`unknownTtsTags`, called by controller/ttsFile.ts): a typo must never -// be spoken. -// 2. Years. A four-digit year 1900-2099 is written out the way it is said -// ("twenty twenty-four", "nineteen ninety-nine", "two thousand five", the -// decade plural "the nineteen nineties") — Kokoro reads "2024" as "two -// thousand twenty-four". Every other number is left to the engine. A count -// that happens to be 1900-2099 ("2024 people") is read as a year too: the -// price of a pre-pass that has no grammar. -// 3. Whitespace. Every run of whitespace, line breaks included, becomes one -// space, a space left before punctuation by a stripped tag goes, and the -// ends are trimmed — so the cache key (controller/ttsFile.ts) does not -// change with a re-wrapped paragraph. +// `<sigh>`, ...). An engine that performs them (Orpheus) gets them as +// written; one that cannot (Kokoro, espeak-ng) has them STRIPPED, so +// nothing reads "less-than laugh" aloud. Any OTHER `<...>` is refused +// before a job exists (`unknownTtsTags`, called by controller/ttsFile.ts): +// a typo must never be spoken. +// 2. Spoken form, on the text between the tags, in this order (URLs and +// handles hold dots and digits, so they go first): typography, URLs (the +// spoken host only), @handles and #hashtags, abbreviations (Dr. Mr. vs. +// e.g. i.e. etc. No.), an em dash as a comma pause and a dash between +// numbers as "to", money ($ £ € with cents and "million"), percentages, +// ordinals, clock times, decades, years, grouped numbers, decimals, plain +// integers. Years 1900-2099 are said as years ("twenty twenty-four", +// "two thousand five", "nineteen oh five"); with `years: "guarded"` a year +// followed by a count noun is a number ("1950 people"), with `"plain"` +// (Kokoro's rule since T1) it is a year either way. +// 3. Whitespace. Inside a paragraph every whitespace run is one space, no +// space before punctuation, ends trimmed. Paragraphs (blank lines) are kept +// as "\n\n" for an engine that chunks by them (Orpheus) or joined — so the +// cache key (controller/ttsFile.ts) does not change with a re-wrapped +// paragraph. // // Pure, no imports: umtool's validator may import or mirror TTS_EXPRESSIVE_TAGS. @@ -144,20 +150,217 @@ export function speakYears(text: string): string { }); } +// --- numbers (the tuned Orpheus round's readers, ported) ---------------------- + +const SCALES: [number, string][] = [ + [1e12, "trillion"], + [1e9, "billion"], + [1e6, "million"], + [1e3, "thousand"], +]; +const ORD_IRREG: Record<string, string> = { + one: "first", two: "second", three: "third", five: "fifth", eight: "eighth", nine: "ninth", twelve: "twelfth", +}; + +/** 3812 → "three thousand eight hundred twelve" (US style, no "and"). */ +export function sayInt(n: number): string { + if (n < 0) return `minus ${sayInt(-n)}`; + if (n < 100) return twoDigitWords(n); + if (n < 1000) { + const h = Math.floor(n / 100); + const r = n % 100; + return `${ONES[h]} hundred${r ? ` ${sayInt(r)}` : ""}`; + } + for (const [v, name] of SCALES) { + if (n >= v) { + const q = Math.floor(n / v); + const r = n - q * v; + return `${sayInt(q)} ${name}${r ? ` ${sayInt(r)}` : ""}`; + } + } + return String(n); +} + +/** 21 → "twenty-first", 103 → "one hundred third", 40 → "fortieth". */ +export function sayOrdinal(n: number): string { + const words = sayInt(n); + const sp = words.lastIndexOf(" "); + const head = words.slice(0, sp + 1); + const last = words.slice(sp + 1); + const hy = last.lastIndexOf("-"); + const pre = last.slice(0, hy + 1); + let tail = last.slice(hy + 1); + if (ORD_IRREG[tail]) tail = ORD_IRREG[tail]; + else if (tail.endsWith("y")) tail = `${tail.slice(0, -1)}ieth`; + else tail += "th"; + return head + pre + tail; +} + +/** "3.5" → "three point five", "1,200.75" → "one thousand two hundred point seven five". */ +export function sayDecimal(s: string): string { + const [whole, frac] = s.replace(/,/g, "").split("."); + const out = sayInt(Number(whole || "0")); + return frac ? `${out} point ${[...frac].map((d) => ONES[Number(d)]).join(" ")}` : out; +} + +function pluralDecade(words: string): string { + const sp = words.lastIndexOf(" "); + const last = words.slice(sp + 1); + return words.slice(0, sp + 1) + (last.endsWith("y") ? `${last.slice(0, -1)}ies` : `${last}s`); +} + +const CURRENCY: Record<string, [string, string, string, string]> = { + $: ["dollar", "dollars", "cent", "cents"], + "£": ["pound", "pounds", "penny", "pence"], + "€": ["euro", "euros", "cent", "cents"], +}; + +function money(sym: string, num: string, scale: string | undefined): string { + const [one, many, sub1, subn] = CURRENCY[sym]; + if (scale) return `${sayDecimal(num)} ${scale.toLowerCase()} ${many}`; + const [whole, cents] = num.replace(/,/g, "").split("."); + const w = Number(whole || "0"); + let out = `${sayInt(w)} ${w === 1 ? one : many}`; + if (cents) { + const c = Number(cents.padEnd(2, "0").slice(0, 2)); + if (c) out += ` and ${sayInt(c)} ${c === 1 ? sub1 : subn}`; + } + return out; +} + +function speakDomain(host: string): string { + return host + .toLowerCase() + .replace(/^www\./, "") + .split(".") + .filter(Boolean) + .map((p) => p.replace(/-/g, " ")) + .join(" dot "); +} + +function clock(h: number, mm: number): string { + if (mm === 0) return `${sayInt(h)} o'clock`; + return `${sayInt(h)} ${mm < 10 ? `oh ${ONES[mm]}` : sayInt(mm)}`; +} + +// A four-digit number followed by one of these is a count, not a year ("1950 people"). +const COUNT_NOUNS = [ + "people", "viewers", "views", "subscribers", "followers", "videos", "streams", "clips", "comments", "times", + "dollars", "users", "members", "posts", "hours", "minutes", "seconds", "words", "messages", "likes", "votes", + "copies", "files", "miles", "pounds", "units", "donations", "watchers", +]; +const GUARDED_YEAR = new RegExp( + String.raw`(?<![\d,.])\b(19\d\d|20\d\d)\b(?!\d|,\d|\.\d)(?!\s+(?:${COUNT_NOUNS.join("|")})\b)`, + "g", +); + +type Rep = string | ((...m: string[]) => string); +const ABBREV: [RegExp, Rep][] = [ + [/\bDr\.(?=\s+[A-Z])/g, "Doctor"], + [/\bMr\./g, "Mister"], + [/\bMrs\./g, "Missus"], + [/\bMs\./g, "Miz"], + [/\bJr\./g, "Junior"], + [/\bSr\./g, "Senior"], + [/\bSt\.(?=\s+[A-Z])/g, "Saint"], + [/\bProf\./g, "Professor"], + [/\b[Vv]s\.?(?=\s)/g, "versus"], + [/\be\.g\.,?/g, "for example,"], + [/\bi\.e\.,?/g, "that is,"], + [/\betc\.(?=\s+[a-z])/g, "et cetera"], + [/\betc\./g, "et cetera."], + [/\bapprox\./g, "approximately"], + [/\b[Nn]o\.\s*(?=\d)/g, "number "], + [/#(?=\d)/g, "number "], + [/\b([ap])\.m\./g, (_m, a) => `${a.toUpperCase()} M`], + [/\b([AP])M\b/g, "$1 M"], + [/\bU\.S\.A?\.?/g, (m) => [...m].filter((c) => /[A-Za-z]/.test(c)).join(" ")], + [/\bU\.K\./g, "U K"], +]; + +function sub(t: string, re: RegExp, rep: Rep): string { + return typeof rep === "string" ? t.replace(re, rep) : t.replace(re, rep as (...a: string[]) => string); +} + +// One run of text holding no expressive tag, to its spoken form. +function spokenPlain(input: string, years: "plain" | "guarded"): string { + let t = input + .replace(/[’‘]/g, "'") + .replace(/[“”]/g, '"') + .replace(/…/g, "...") + .replace(/[  ]/g, " "); + // URLs → the spoken host only ("example dot com"); paths and queries dropped. + t = t.replace(/\bhttps?:\/\/([^\s/]+)\S*/g, (_m, host: string) => speakDomain(host)); + t = t.replace(/\bwww\.([a-z0-9-]+(?:\.[a-z0-9-]+)+)\S*/gi, (_m, host: string) => speakDomain(host)); + t = t.replace( + /\b([a-z0-9-]+(?:\.[a-z0-9-]+)*\.(?:com|org|net|dev|io|tv|gg|co|uk|me|app))\b(\/\S*)?/gi, + (_m, host: string) => speakDomain(host), + ); + // @handles and #hashtags (underscores read as spaces). + t = t.replace(/(?<![\w@])@([A-Za-z0-9_]+)/g, (_m, h: string) => `at ${h.replace(/_/g, " ")}`); + t = t.replace(/(?<![\w#])#([A-Za-z][A-Za-z0-9_]*)/g, (_m, h: string) => `hashtag ${h.replace(/_/g, " ")}`); + for (const [re, rep] of ABBREV) t = sub(t, re, rep); + t = t.replace(/\s&\s/g, " and "); + // A range between numbers is "to"; an em dash (or --, or a spaced en dash) is a pause. + t = t.replace(/(?<=\d)\s*[–—-]\s*(?=\d)/g, " to "); + t = t.replace(/\s*(?:—|--|\s–\s)\s*/g, ", "); + // Money, percent, ordinals, clock times. + t = t.replace( + /([$£€])((?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d+)?)(?:\s*(million|billion|trillion|thousand)\b)?/gi, + (_m, sym: string, num: string, scale?: string) => money(sym, num, scale), + ); + t = t.replace(/((?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d+)?)\s?%/g, (_m, n: string) => `${sayDecimal(n)} percent`); + t = t.replace(/\b(\d+)(?:st|nd|rd|th)\b/g, (_m, n: string) => sayOrdinal(Number(n))); + t = t.replace(/\b(\d{1,2}):(\d{2})\b/g, (_m, h: string, mm: string) => clock(Number(h), Number(mm))); + // Decades: 1990s → nineteen nineties, '90s → nineties. + t = t.replace(/\b(19|20)(\d)0s\b/g, (_m, c: string, d: string) => pluralDecade(yearWords(Number(`${c}${d}0`)))); + t = t.replace(/'(\d)0s\b/g, (_m, d: string) => pluralDecade(sayInt(Number(d) * 10))); + // Years 1900-2099. + t = + years === "guarded" + ? t.replace(GUARDED_YEAR, (_m, y: string) => yearWords(Number(y))) + : speakYears(t); + // Grouped numbers (3,812), decimals (3.5), plain integers. + t = t.replace(/\b\d{1,3}(?:,\d{3})+(?:\.\d+)?\b/g, (m) => sayDecimal(m)); + t = t.replace(/\b\d+\.\d+\b/g, (m) => sayDecimal(m)); + t = t.replace(/\b\d{1,15}\b/g, (m) => sayInt(Number(m))); + // Tidy. + t = t.replace(/\s+([,.;:!?])/g, "$1"); + t = t.replace(/,\s*,/g, ","); + t = t.replace(/[ \t]+/g, " "); + return t; +} + // --- the normalizer ---------------------------------------------------------- export type TtsNormalizeOptions = { // "strip" for an engine that cannot perform the expressive tags; "keep" for // one that does (passed through as written). tags: "strip" | "keep"; - // Write years out as they are said. - years: boolean; + // "guarded": a year followed by a count noun is a number (Orpheus, the + // tuned round's rule). "plain": every 1900-2099 is a year (Kokoro's, T1). + years: "plain" | "guarded"; + // "keep": paragraphs (blank lines) stay "\n\n" for a chunking engine; + // "join": one line. + paragraphs: "keep" | "join"; }; -/** The pre-pass: tags, then years, then whitespace (see the header). */ +const EXPRESSIVE = new RegExp(`(<(?:${TTS_EXPRESSIVE_TAGS.join("|")})>)`); + +/** The pre-pass: per paragraph, the spoken form of the text between the tags, then the tags (see the header). */ export function normalizeTtsText(text: string, opts: TtsNormalizeOptions): string { - let out = text.normalize("NFC"); - if (opts.tags === "strip") out = stripTtsTags(out); - if (opts.years) out = speakYears(out); - return collapseTtsWhitespace(out); + const paras = text + .normalize("NFC") + .trim() + .split(/\n\s*\n/) + .filter((p) => p.trim()); + const out: string[] = []; + for (const p of paras) { + const parts = p.replace(/\n/g, " ").split(EXPRESSIVE); + let s = parts.map((x) => (EXPRESSIVE.test(x) && /^<[^<>]*>$/.test(x) ? x : spokenPlain(x, opts.years))).join(""); + s = s.replace(/\s+/g, " ").trim(); + if (opts.tags === "strip") s = stripTtsTags(s); + if (s) out.push(collapseTtsWhitespace(s)); + } + return out.join(opts.paragraphs === "keep" ? "\n\n" : " "); } diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,8 @@ # Changelog ## [Unreleased] +- **Orpheus 3B narrates too, on the GPU.** `pnpm ops tts` takes `"engine": "orpheus"` — Orpheus 3B with one of its eight stock speakers (`leah` by default, `zac` the male option, then tara, jess, leo, dan, mia, zoe), which performs the expressive tags (`<laugh>`, `<sigh>`, …) instead of dropping them. It runs on a local llama-server the editor starts for a batch of syntheses — after waiting for the machine's heavy slot and for any transcription on the GPU to finish — and stops once nothing more is queued, so its 4–5 GB of video memory is freed; the server's binary, libraries, port and GPU layers are `settings.tts.orpheus` (Ollama's bundled Vulkan build by default). Each chunk of 1–3 sentences gets up to three takes and the first that passes the checks is kept (it ended, no broken frames, a sane pace, no dead air); a chunk where none passes is kept anyway and flagged in the job's log and the sidecar. Its disclosure line ends "Built with Llama", as its licence (Llama 3.2 Community License + Apache-2.0) asks. About 1.8× slower than real time. `archilyzer tts setup --engine orpheus [--from <dir>]` installs it (3.5 GB of model). Needs a restart of the editor. +- **Narration reads numbers, money, dates and links the way they are said, with Kokoro too.** "3,812" is "three thousand eight hundred twelve", "$12.50" "twelve dollars and fifty cents", "March 14th" "March fourteenth", "3:45" "three forty-five", "45%" "forty-five percent", a link its spoken host ("example dot com"), "Dr." "Doctor", "@name" "at name"; years are read as before. A synthesis made before this is made again the next time it is asked for. - **Narration in a local synthetic voice, as a job.** `pnpm ops tts` (`POST /api/ops/tts`) speaks a line — `{"text"}`, or `{"file"}` an absolute path to a UTF-8 text file, at most 20,000 characters — with a local text-to-speech engine and one of its stock voices, as a `tts-file` job on its own `tts` queue, one synthesis at a time. The default is Kokoro-82M with the voice `af_heart` (`settings.tts`: `engine`, `voice`, `speed`, `home`, `dir`; SETTINGS.md); `"engine": "espeak-ng"` needs no install. Years are read as they are said ("twenty twenty-four"); the expressive tags `<laugh>` `<chuckle>` `<sigh>` `<cough>` `<sniffle>` `<groan>` `<yawn>` `<gasp>` are dropped for an engine that cannot perform them, and any other `<…>` is refused, named, so a typo is never read aloud. The result — `{wav, seconds, engine, voice, cached, durationMs, waitedMs, sha, sampleRate, speed, disclosure}`, printed by `--wait` — names a 48 kHz mono WAV in the synthesis cache (`<repo>/.tts/cache` by default, never inside the corpus), or the `"out"` path it was copied to, with a sidecar beside it that marks it a synthetic voice; `disclosure` is the line a narrated export carries ("Narration: synthetic voice (Kokoro-82M · af_heart)"). The same words with the same voice and speed again are answered from the cache at once, with no engine run. There is no voice cloning and no reference audio: a voice is a name from the engine's list. Needs a restart of the editor. - **`archilyzer tts setup` installs the voice.** It builds `~/.local/share/archilyzer/tts/kokoro` (`settings.tts.home`): a python venv with kokoro-onnx 0.6.1 (made with `uv` when it is installed) and the model's two files, downloaded once from the kokoro-onnx project's release and checked by size and sha256 before they are kept. `--from <dir>` takes files already downloaded instead; `--check` says what is missing and installs nothing. `archilyzer doctor` reports the configured engine and voice as installed or not. - **`pnpm ops site-config` sets a site's cited-only channels and publish policy.** `{"siteId", "citedChannels"?: [slug…], "publishAuto"?: "off" | "build" | "preview" | "production"}` (`POST /api/ops/site-config`) writes through the site form's own validation: a slug the pool holds is dropped, a deploying policy without a Pages project is refused, and a private site is clamped to `build`. An unknown site, channel or key is refused before anything is written. The answer is the saved values. diff --git a/editor/app/api/ops/tts/route.ts b/editor/app/api/ops/tts/route.ts @@ -13,11 +13,14 @@ export const dynamic = "force-dynamic"; // /jobs (`tts-file`, the `tts` queue, one synthesis at a time) — narration is // never synthesized by hand. `text` is the words, or `file` an absolute path to // a UTF-8 text file holding them (at most 20,000 characters); `engine` -// (`kokoro` | `espeak-ng`), `voice` (one of the engine's stock voices) and -// `speed` (0.5-2) default to settings.tts (kokoro · af_heart · 1); `out` is an -// absolute .wav path the result is copied to. The expressive tags (`<laugh>`, -// `<sigh>`, ... lib/ttsText.ts TTS_EXPRESSIVE_TAGS) are stripped for an engine -// that cannot perform them; any other `<...>` is refused. +// (`kokoro` | `orpheus` | `espeak-ng`), `voice` (one of the engine's stock +// voices; Orpheus: leah by default, zac the male option) and `speed` (0.5-2; +// Orpheus has none) default to settings.tts (kokoro · af_heart · 1); `out` is +// an absolute .wav path the result is copied to. The expressive tags +// (`<laugh>`, `<sigh>`, ... lib/ttsText.ts TTS_EXPRESSIVE_TAGS) are performed by +// Orpheus and stripped for the others; any other `<...>` is refused. Orpheus +// runs on the GPU, on a llama-server the editor starts for the batch and stops +// once the `tts` queue is idle, and waits while a transcription holds the GPU. // // The job's log ends with the result as ONE line, `@@tts-result {json}`: // `{wav, seconds, engine, voice, cached, durationMs (the engine's time), waitedMs diff --git a/plans/release-25.md b/plans/release-25.md @@ -276,3 +276,65 @@ The review surface first, then the writing guide from the Orpheus tuning round's | `pnpm run test:scripts` | 833: 830 pass, 3 skip | | mcp unit | 306/306 (+1: a sweep plan carries the hard rule verbatim and each of the five writing rules) | | umtool e2e `narration-review.spec.ts` (new) + `report-narration.spec.ts` (start mode) | 5 passed (20.1 s): approve; reject refused without a note, then with one; edit saved through the manifest and un-rejected; play asked the stub once for that card's words and the audio route served the WAV; a build refused with "timeline k02: its narration is not reviewed" and wrote no mp4 | + +### T1b, as shipped — Orpheus 3B as a second engine (`r25/orpheus`) + +The operator's ask after the tuning round (job tmp `tts-orpheus2-report.md`; the pipeline `run_orpheus2.py`): Orpheus as +a second engine, its tuned pipeline ported, Kokoro (af_heart) still the default. + +- **The engine** (`common/lib/ttsApps.ts` `orpheus`): Orpheus 3B 0.1-ft Q8_0 GGUF on llama.cpp's server + the SNAC + 24 kHz ONNX decoder on the CPU (onnxruntime; no torch). `device: "gpu"`, `runtime: "server"`, voices `tara leah jess + leo dan mia zac zoe` (default `leah`, `zac` the male option), speed range [1, 1], licence "Llama 3.2 Community + License + Apache-2.0", attribution "Built with Llama" — the disclosure reads "Narration: synthetic voice (Orpheus 3B · + leah). Built with Llama". The sampler is the round's choice (t 0.7, top_p 0.9, top_k 50, min_p 0, repeat_penalty + 1.1, repeat_last_n 64), seeds 1234 + 101·take + chunk. Files pinned by size and sha256: the GGUF from + `unsloth/orpheus-3b-0.1-ft-GGUF`, `snac_decoder.onnx` and `snac_config.json` from `onnx-community/snac_24khz-ONNX` + (each identical to the bake-off's copy). +- **`settings.tts.orpheus`** (SETTINGS.md): `serverBin` `/usr/lib/ollama/llama-server`, `libraryPath` + `/usr/lib/ollama` (LD_LIBRARY_PATH), `ggmlBackendPath` `/usr/lib/ollama/vulkan/libggml-vulkan.so`, `port` 8799, + `gpuLayers` 99, `contextSize` 8192, `startTimeoutSeconds` 150, `idleStopSeconds` 5, `heavyEstimateMB` 4000, `takes` + 3, `tagCheck` false. Nothing about the server is hard-coded. +- **The normalizer** (`lib/ttsText.ts`): the round's `normalize()` ported, its 17 self-tests as unit tests (all pass + unchanged). Options per engine: tags kept (Orpheus) or stripped; years `guarded` (Orpheus: "1950 people" is a count) + or `plain` (Kokoro keeps T1's rule); paragraphs kept for the chunker or joined. Kokoro now gets the whole spoken form + too (numbers, money, ordinals, times, URLs, handles, abbreviations), so its cache keys change once. +- **The chunker** (`lib/ttsChunk.ts`): the round's `chunk()` and the token budget, held byte-equal to the pipeline's own + output on all nine bake-off lines. The editor chunks; the helper renders. +- **The helper** (`scripts/tts_orpheus.py`, behind `scripts/tts.mjs --engine-kind orpheus`): per chunk up to `takes` + takes, the FIRST that passes kept (end token reached, no malformed frame, not truncated, words/s in band, no long + silence); the rate floor is lowered 0.25 words/s per sentence past the first (min 1.5), so slow multi-sentence and + story reads pass. When none passes: the fewest failures (never a truncated or malformed take) are kept and the chunk + is FLAGGED (job log, sidecar `flagged`); all truncated or malformed fails the job. Joins: trim, loudness match ±6 dB, + 15 ms fades, pauses 0.30 / 0.15 / 0.60 s. **UTMOS is left out**: it needs torch, which the default install does not + carry. The tag-length check (a plain-twin take per tagged chunk) is behind `tagCheck`, off. +- **The server** (`controller/ttsServer.ts`): one holder per engine; started through `queue-lock --heavy --estimate` + for the first synthesis of a batch, `/health` polled, reused by the next, stopped (SIGTERM to its process group, + SIGKILL after 15 s) once `idleStopSeconds` pass with nothing taking it, on a failed or cancelled start, and on the + editor's exit. A port something else answers on is refused. Server output goes to `<install dir>/server.log`, the + gate's lines to the job log. +- **The GPU wait** (`ttsFile.ts` `waitForGpu`): a GPU engine waits to start while a transcription runs on a local + worker whose device is not `cpu`; a synthesis running is not interrupted. +- **Setup and doctor**: `archilyzer tts setup --engine orpheus [--from <dir>]` (venv with onnxruntime 1.31.0 and numpy + 2.5.4; the three files); setup, `--check` and the doctor's `tts` row also check the configured `serverBin`. +- **For Lane B / umtool**: the engine id is `orpheus`, its label `Orpheus 3B` (umtool's fallback label map says + `Orpheus`; the editor's `disclosure` is used verbatim when present, and it carries "Built with Llama"). `speed` must be + 1 for Orpheus (absent is fine). + +| commit | what | +|---|---| +| `edbabe51` | the spoken-form normalizer (17 self-tests) and the chunker, Kokoro on the new normalizer | +| `3be65c04` | the `orpheus` engine, `settings.tts.orpheus`, the server holder, the GPU wait, the helper and the wrapper | +| `1fe6160f` | `tts setup --engine orpheus`, the doctor, the ops help, COMMANDS.md | +| `998a3450` | merge of `r25/integration` (T5) | + +#### Gates (T1b) + +| gate | result | +|---|---| +| tsc (`pnpm -r … exec tsc --noEmit`) | clean at each code commit | +| common unit | 3772 pass, 0 fail (new: ttsChunk 5, ttsServer 6 — a fake llama-server: reuse, idle stop, restart on new settings, port refusal, early death, start timeout, cancel, SIGKILL; ttsFile +5, ttsApps +3, ttsText +3, ttsSettings +1, tts-setup +1) | +| editor unit | 260 pass | +| test:scripts | 827: 824 pass, 3 skip (new: `tts_orpheus.test.mjs` 2 — the helper's selftest of 22 checks; `tts.test.mjs` refusals) | +| `docs env\|files\|cli --check`, `settings example --check` | clean | +| `archilyzer tts setup --engine orpheus --from <bake-off models>` | real: uv venv py3.12 + onnxruntime 1.31.0 + numpy 2.5.4, the three files hard-linked and verified; `--check` 0 | +| one real Orpheus synthesis through the route, voice leah | in-process route handler, isolated temp corpus and cache, under `pnpm heavy` (10 GB free, VRAM idle 115 MB, nothing else on the GPU): 372 characters, 3 paragraphs with a `<sigh>`, numbers and a date → 3 chunks, each passing on its FIRST take → 24.8 s of audio in 44.9 s engine time — **RTF 1.81** (2.09 wall, the 6.8 s server start included); VRAM peak 4442 MB, back to 112 MB after the idle stop; no llama-server left running; the sidecar disclosed "Built with Llama" | diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -1044,18 +1044,21 @@ export function usage() { "", 'tts speaks a line with a local text-to-speech engine and a STOCK voice, as a', ' job on the `tts` queue: {"text": "..."} or {"file": "/abs/script.txt"} (UTF-8,', - ' at most 20,000 characters), "engine" (kokoro | espeak-ng), "voice" (one of', - ' the engine\'s stock voices; kokoro: af_heart, bm_george, ...), "speed"', - ' (0.5-2) — defaults from settings.tts (kokoro, af_heart, 1) — and "out" (an', - ' absolute .wav path the result is copied to, never inside the corpus). The', - " expressive tags <laugh> <chuckle> <sigh> <cough> <sniffle> <groan> <yawn>", - " <gasp> are stripped for an engine that cannot perform them; any other <...>", - " is refused. Years are spoken (2024: \"twenty twenty-four\"). The result is", + ' at most 20,000 characters), "engine" (kokoro | orpheus | espeak-ng), "voice"', + " (one of the engine's stock voices; kokoro: af_heart, bm_george, ...; orpheus:", + ' leah, zac, ...), "speed" (0.5-2; orpheus has none) — defaults from', + ' settings.tts (kokoro, af_heart, 1) — and "out" (an absolute .wav path the', + " result is copied to, never inside the corpus). The expressive tags <laugh>", + " <chuckle> <sigh> <cough> <sniffle> <groan> <yawn> <gasp> are performed by", + " orpheus and stripped for the others; any other <...> is refused. Numbers,", + ' years, money and times are spoken (2024: "twenty twenty-four"). The result is', " {wav, seconds, engine, voice, cached, durationMs, waitedMs, sha, sampleRate,", " speed, disclosure}: wav is the 48 kHz mono WAV the editor wrote (out, or its", " cache), disclosure the line a narrated export carries. The same ask again is", - " answered from the cache (cached: true, no engine run). Kokoro needs", - " `archilyzer tts setup` first. With --wait the result is printed on stdout.", + " answered from the cache (cached: true, no engine run). Kokoro and orpheus", + " need `archilyzer tts setup [--engine orpheus]` first; orpheus runs on the GPU", + " (a local llama-server the editor starts and stops) and waits while a", + " transcription holds it. With --wait the result is printed on stdout.", "", "Env: ARCHILYZER_EDITOR_URL (default http://localhost:3001), WORKER_TOKEN,", " ARCHILYZER_AGENT (provenance of a tag write; default \"cli\").", diff --git a/scripts/archilyzer-ops.test.mjs b/scripts/archilyzer-ops.test.mjs @@ -670,7 +670,7 @@ test("tts posts its body and carries its own result marker", () => { assert.equal(TTS_RESULT_MARKER, "@@tts-result "); assert.equal(p.resultMarker, TTS_RESULT_MARKER); assert.match(usage(), /tts speaks a line with a local text-to-speech engine and a STOCK voice/); - assert.match(usage(), /<laugh> <chuckle> <sigh> <cough> <sniffle> <groan> <yawn>/); + assert.match(usage(), /The expressive tags <laugh>\n\s+<chuckle> <sigh> <cough> <sniffle> <groan> <yawn> <gasp> are performed by\n\s+orpheus and stripped for the others/); assert.match(usage(), /\{wav, seconds, engine, voice, cached, durationMs, waitedMs, sha, sampleRate,/); // The result line comes out of the log as transcribe's does. const result = { wav: "/c/x.wav", seconds: 2.5, cached: true }; diff --git a/scripts/tts.mjs b/scripts/tts.mjs @@ -6,12 +6,17 @@ // engine registry (common/lib/ttsApps.ts) builds, so an engine can be added or // swapped without touching a caller, and the e2e suite can swap in a fake. // -// TWO ENGINES, PICKED BY --engine-kind: +// THREE ENGINES, PICKED BY --engine-kind: // kokoro Kokoro-82M through scripts/tts_kokoro.py (kokoro-onnx on the // CPU) in the venv `archilyzer tts setup` built. Its native rate // is 24 kHz. // espeak-ng The formant synthesizer every Linux has: the zero-install // fallback, and what the tests run. +// orpheus Orpheus 3B through scripts/tts_orpheus.py (onnxruntime for the +// SNAC decoder) against a llama-server the editor started +// (--server). Its input is not text but the editor's JSON of +// chunks, sampler and takes (common/lib/ttsApps.ts +// prepareInput); the voice is in it. 24 kHz native. // // WHAT IT WRITES is always the same shape whatever the engine: a 48 kHz mono // 16-bit PCM WAV with a bare 44-byte header (ffmpeg, bit-exact, no metadata), @@ -30,7 +35,7 @@ // // Options (env fallback in parens): // --output <f> the WAV to write [required] -// --engine-kind <k> kokoro | espeak-ng (default kokoro) +// --engine-kind <k> kokoro | espeak-ng | orpheus (default kokoro) // --voice <v> a stock voice of the engine (default: the engine's) // --speed <x> 0.5-2, 1 = the engine's natural pace (default 1) // --text <t> the text itself, in place of <textFile> @@ -38,6 +43,9 @@ // --model <p> kokoro-v1.0.onnx [kokoro] // --voices <p> voices-v1.0.bin [kokoro] // --espeak <bin> espeak-ng binary (ESPEAK_NG_BIN, espeak-ng) [espeak-ng] +// --python <p> the venv's python [orpheus] +// --snac <p> snac_decoder.onnx [orpheus] +// --server <url> the running llama-server [orpheus] // --ffmpeg <bin> ffmpeg binary (FFMPEG_BIN, ffmpeg) // -h, --help @@ -48,7 +56,8 @@ import path from "node:path"; const HELP = `tts.mjs [options] <textFile> (or --text "<text>") Synthesizes speech with a stock voice and writes a 48 kHz mono WAV to --output. -Engines: kokoro (default; needs \`archilyzer tts setup\`), espeak-ng. +Engines: kokoro (default; needs \`archilyzer tts setup\`), espeak-ng, orpheus +(needs \`archilyzer tts setup --engine orpheus\` and a running llama-server). See the header of this file for the full option list.`; const SAMPLE_RATE = 48_000; @@ -82,10 +91,10 @@ for (let i = 0; i < argv.length; i++) { const output = arg("--output", undefined); if (!output) fail("missing --output <file.wav>"); const engineKind = arg("--engine-kind", "kokoro"); -if (engineKind !== "kokoro" && engineKind !== "espeak-ng") { - fail(`--engine-kind must be 'kokoro' or 'espeak-ng' (got '${engineKind}')`); +if (engineKind !== "kokoro" && engineKind !== "espeak-ng" && engineKind !== "orpheus") { + fail(`--engine-kind must be 'kokoro', 'espeak-ng' or 'orpheus' (got '${engineKind}')`); } -const voice = arg("--voice", DEFAULT_VOICE[engineKind]); +let voice = arg("--voice", DEFAULT_VOICE[engineKind]); const speed = Number(arg("--speed", "1")); if (!Number.isFinite(speed) || speed < 0.5 || speed > 2) fail("--speed must be between 0.5 and 2"); const ffmpeg = arg("--ffmpeg", process.env.FFMPEG_BIN ?? "ffmpeg"); @@ -188,6 +197,32 @@ try { } catch { extra = {}; } + } else if (engineKind === "orpheus") { + const python = arg("--python", ""); + const snac = arg("--snac", ""); + const server = arg("--server", ""); + if (!python) throw new Error("missing --python (the venv `archilyzer tts setup --engine orpheus` built)"); + if (!snac) throw new Error("missing --snac (snac_decoder.onnx)"); + if (!server) throw new Error("missing --server (the llama-server the editor started)"); + let spec; + try { + spec = JSON.parse(text); + } catch { + throw new Error("orpheus reads the editor's JSON of chunks, not plain text"); + } + voice = spec.voice; + const stdout = await run(python, [ + path.join(import.meta.dirname, "tts_orpheus.py"), + "--server", server, + "--snac", snac, + "--output", raw, + textFile, + ]); + try { + extra = JSON.parse(stdout.trim().split("\n").pop() ?? "{}"); + } catch { + extra = {}; + } } else { const espeak = arg("--espeak", process.env.ESPEAK_NG_BIN ?? "espeak-ng"); // espeak-ng's pace is words per minute; 175 is its default. diff --git a/scripts/tts.test.mjs b/scripts/tts.test.mjs @@ -72,10 +72,15 @@ test("refusals: no output, an unknown engine, a speed out of range, empty text", writeFileSync(empty, " \n"); const out = path.join(dir, "o.wav"); assert.match(run([text]).stderr, /missing --output/); - assert.match(run(["--engine-kind", "piper", "--output", out, text]).stderr, /must be 'kokoro' or 'espeak-ng'/); + assert.match(run(["--engine-kind", "piper", "--output", out, text]).stderr, /must be 'kokoro', 'espeak-ng' or 'orpheus'/); assert.match(run(["--engine-kind", "espeak-ng", "--speed", "3", "--output", out, text]).stderr, /between 0\.5 and 2/); assert.match(run(["--engine-kind", "espeak-ng", "--output", out, empty]).stderr, /the text is empty/); assert.match(run(["--engine-kind", "kokoro", "--output", out, text]).stderr, /missing --python/); + assert.match(run(["--engine-kind", "orpheus", "--python", "/x/python", "--snac", "/x/s.onnx", "--output", out, text]).stderr, /missing --server/); + assert.match( + run(["--engine-kind", "orpheus", "--python", "/x/python", "--snac", "/x/s.onnx", "--server", "http://127.0.0.1:1", "--output", out, text]).stderr, + /orpheus reads the editor's JSON of chunks, not plain text/, + ); assert.deepEqual(readdirSync(dir).sort(), ["empty.txt", "in.txt"]); }); diff --git a/scripts/tts_orpheus.py b/scripts/tts_orpheus.py @@ -0,0 +1,460 @@ +#!/usr/bin/env python3 +"""Orpheus 3B: chunks in, one 16-bit mono WAV at 24 kHz out (release 25 T1b). + +Run by scripts/tts.mjs (the wrapper every TTS engine runs behind) with the +python of the venv `archilyzer tts setup --engine orpheus` built (onnxruntime +and numpy; no torch). The editor has already started llama-server with the +Orpheus GGUF (controller/ttsServer.ts) and chunked the normalized text +(common/lib/ttsChunk.ts); this renders the chunks. Ported from the tuned +round's pipeline of 2026-10-11 (its report, "Engine contract"). + + input.json ─► per chunk: up to `takes` takes (seeded) on llama-server + ─► SNAC decode (onnxruntime, CPU) ─► checks ─► the FIRST take + that passes is kept (early stop) + ─► trim, loudness-match, 15 ms fades, the chunk's pause ─► WAV + +STOCK VOICES ONLY: tara leah jess leo dan mia zac zoe. There is no +reference-audio path here and there must never be one. No ASR is run. + +The checks (no model): the end-of-speech token was reached (a take cut at its +token budget is never kept); no malformed frame; words a second in band — +2.0–3.6, the floor lowered 0.25 a second for each sentence past the first, so a +slow, dramatic multi-sentence read passes; no internal silence over 1.0 s in a +sentence, 1.3 s between sentences, plus 0.4 s a tag or "...". With +`tagCheck`, a chunk with tags must also run 0.4 s a tag longer than the same +voice reading it without them, else the take is taken to have skipped its tag. +When no take passes, the one with the fewest failures (then the shortest +longest silence) is kept and the chunk is FLAGGED on stderr and in the result; +when every take is truncated or malformed, the synthesis fails. + +input.json: {"version": 1, "voice", "sampler": {...}, "seedBase", "takes", +"tagCheck", "chunks": [{"text", "ends", "pauseAfter", "nPredict"}]}. +On stdout, one JSON line: {sampleRate, seconds, chunks, takes, flagged, +genSeconds, takeSeconds, rtfPerTake, loadSeconds}. `selftest` checks the audio +checks, the frame mapping, the take selection and the joins on synthetic data +(numpy only). +""" + +import argparse +import json +import re +import sys +import time +import urllib.request +import wave + +import numpy as np + +VOICES = ("tara", "leah", "jess", "leo", "dan", "mia", "zac", "zoe") +TAGS = ("laugh", "chuckle", "sigh", "cough", "sniffle", "groan", "yawn", "gasp") +TAG_RE = re.compile(r"<(?:%s)>" % "|".join(TAGS)) +SR = 24000 +FRAME = SR // 100 # 10 ms + +# Orpheus special tokens (Llama-3.2 vocabulary 128256 + custom tokens). +START_OF_HUMAN, BOS, EOT, END_OF_HUMAN = 128259, 128000, 128009, 128260 +START_OF_AI, START_OF_SPEECH, END_OF_SPEECH = 128261, 128257, 128258 +AUDIO_BASE = 128266 # frame slot k uses [AUDIO_BASE + k*4096, +4096) + +WPS_BAND = (2.0, 3.6) +WPS_FLOOR_PER_EXTRA_SENTENCE = 0.25 +WPS_FLOOR_MIN = 1.5 +TAG_EXCESS_S = 0.4 + + +def log(msg): + print(f"orpheus: {msg}", file=sys.stderr, flush=True) + + +# ── text ────────────────────────────────────────────────────────────────────── +def words_in(text): + return len(re.findall(r"[A-Za-z0-9]+(?:'[A-Za-z]+)?", TAG_RE.sub(" ", text))) + + +def sentences_in(text): + return len(re.findall(r"(?<!\.)[.!?][\"')]?(?=\s|$)", TAG_RE.sub("", text))) + + +def strip_tags(text): + return re.sub(r"\s+", " ", TAG_RE.sub(" ", text)).strip() + + +def wps_floor(n_sent): + return max(WPS_FLOOR_MIN, WPS_BAND[0] - WPS_FLOOR_PER_EXTRA_SENTENCE * max(0, n_sent - 1)) + + +# ── frames ──────────────────────────────────────────────────────────────────── +def codes_from_tokens(ids): + """The audio codes of a completion's tokens, de-offset by slot → (codes, bad_frames).""" + if END_OF_SPEECH in ids: + ids = ids[: ids.index(END_OF_SPEECH)] + if START_OF_SPEECH in ids: + ids = ids[len(ids) - ids[::-1].index(START_OF_SPEECH):] + raw = [t for t in ids if t >= AUDIO_BASE] + raw = raw[: len(raw) // 7 * 7] + codes, bad = [], 0 + for i in range(0, len(raw), 7): # slot k must sit in its own 4096-code band + fr = [raw[i + k] - AUDIO_BASE - k * 4096 for k in range(7)] + if all(0 <= c < 4096 for c in fr): + codes += fr + else: + bad += 1 + return codes, bad + + +def snac_inputs(codes): + """7-code frames → SNAC 24 kHz's three levels: c0 | c1, c4 | c2, c3, c5, c6.""" + l0, l1, l2 = [], [], [] + for i in range(len(codes) // 7): + c = codes[7 * i: 7 * i + 7] + l0.append(c[0]) + l1 += [c[1], c[4]] + l2 += [c[2], c[3], c[5], c[6]] + return [np.array([l], dtype=np.int64) for l in (l0, l1, l2)] + + +class Decoder: + def __init__(self, path): + import onnxruntime as ort + + self.sess = ort.InferenceSession(path, providers=["CPUExecutionProvider"]) + + def __call__(self, codes): + if not codes: + return np.zeros(0, np.float32) + a0, a1, a2 = snac_inputs(codes) + out = self.sess.run(None, {"audio_codes.0": a0, "audio_codes.1": a1, "audio_codes.2": a2})[0] + return out.squeeze().astype(np.float32) + + +# ── the server ──────────────────────────────────────────────────────────────── +def post(url, body, timeout=600): + req = urllib.request.Request(url, data=json.dumps(body).encode(), headers={"content-type": "application/json"}) + with urllib.request.urlopen(req, timeout=timeout) as r: + return json.loads(r.read()) + + +def generate(server, decode, voice, text, seed, sampler, n_predict): + """One take → dict(audio, end_reached, bad_frames, stop_type, n_tokens, gen_s).""" + assert voice in VOICES, voice # stock voices only + toks = post(f"{server}/tokenize", {"content": f"{voice}: {text}", "add_special": False})["tokens"] + prompt = [START_OF_HUMAN, BOS] + toks + [EOT, END_OF_HUMAN, START_OF_AI, START_OF_SPEECH] + t0 = time.perf_counter() + r = post( + f"{server}/completion", + dict(prompt=prompt, n_predict=n_predict, seed=seed, return_tokens=True, cache_prompt=False, + stop=["<custom_token_2>"], **sampler), + ) + if "error" in r: + raise RuntimeError(f"llama-server: {r['error']}") + gen_s = time.perf_counter() - t0 + ids = r.get("tokens", []) + end_reached = r.get("stop_type") in ("word", "eos") or END_OF_SPEECH in ids + codes, bad = codes_from_tokens(ids) + return dict(audio=decode(codes), end_reached=bool(end_reached), bad_frames=bad, + stop_type=r.get("stop_type"), n_tokens=len(ids), gen_s=gen_s) + + +# ── audio ───────────────────────────────────────────────────────────────────── +def frame_db(a): + n = len(a) // FRAME + if not n: + return np.zeros(0) + f = a[: n * FRAME].reshape(n, FRAME) + return 10 * np.log10(np.mean(f * f, axis=1) + 1e-12) + + +def trim(a, lead=0.04, tail=0.08): + """Leading/trailing silence cut by an energy gate 40 dB under the loudest 10 ms (floor −60 dBFS).""" + db = frame_db(a) + if not len(db): + return a + act = np.where(db > max(db.max() - 40, -60))[0] + if not len(act): + return a[:0] + s = max(0, act[0] * FRAME - int(lead * SR)) + e = min(len(a), (act[-1] + 1) * FRAME + int(tail * SR)) + return a[s:e] + + +def longest_gap(a): + """The longest internal pause (s): consecutive frames 35 dB under the peak.""" + db = frame_db(a) + if not len(db): + return 0.0 + quiet = db < db.max() - 35 + best = run = 0 + for q in quiet: + run = run + 1 if q else 0 + best = max(best, run) + return best * FRAME / SR + + +def active_db(a): + db = frame_db(a) + if not len(db): + return -99.0 + act = db[db > db.max() - 30] + return float(10 * np.log10(np.mean(10 ** (act / 10)))) + + +def check_take(text, take): + """The non-ASR checks → (passed, metrics).""" + a = trim(take["audio"]) + dur = len(a) / SR + n_tags, n_ell = len(TAG_RE.findall(text)), text.count("...") + speech_s = max(0.1, dur - 0.9 * n_tags - 0.3 * n_ell) + wps = words_in(text) / speech_s + gap = longest_gap(a) + n_sent = sentences_in(text) + lo = wps_floor(n_sent) + max_gap = min(2.2, (1.3 if n_sent > 1 else 1.0) + 0.4 * (n_tags + n_ell)) + fails = [] + if not take["end_reached"]: + fails.append("truncated (token budget hit, no end of speech)") + if take["bad_frames"]: + fails.append(f"{take['bad_frames']} malformed frames") + if not (lo <= wps <= WPS_BAND[1]): + fails.append(f"{wps:.2f} words/s outside ({lo:.2f}, {WPS_BAND[1]})") + if gap > max_gap: + fails.append(f"internal silence {gap:.2f}s > {max_gap:.1f}s") + return not fails, dict(dur=round(dur, 3), wps=round(wps, 3), longest_gap=round(gap, 3), fails=fails) + + +def fade(a, ms=15): + n = min(len(a) // 2, int(SR * ms / 1000)) + if n: + w = 0.5 - 0.5 * np.cos(np.linspace(0, np.pi, n, dtype=np.float32)) + a = a.copy() + a[:n] *= w + a[-n:] *= w[::-1] + return a + + +def assemble(pieces): + """[(trimmed audio, pause after)] → one line: chunk loudness matched (±6 dB), 15 ms fades, the + pauses; speech at about −20 dBFS active, peaks at or under −1 dBFS.""" + lev = [active_db(a) for a, _ in pieces] + target = float(np.median(lev)) if lev else -20.0 + out = [] + for (a, pause), l in zip(pieces, lev): + g = 10 ** (np.clip(target - l, -6, 6) / 20) + out += [fade(a * g), np.zeros(int(pause * SR), np.float32)] + y = np.concatenate(out).astype(np.float32) if out else np.zeros(0, np.float32) + y *= 10 ** ((-20 - target) / 20) + pk = float(np.abs(y).max()) if len(y) else 0.0 + if pk > 0.891: + y *= 0.891 / pk + return y + + +# ── takes ───────────────────────────────────────────────────────────────────── +def choose(cands): + """The kept take of a chunk: the first that passed; else, of those that reached their end with no + malformed frame, the one only its tag check failed (the longest), else the fewest failures then the + shortest silence. None when every take was truncated or malformed.""" + for c in cands: + if c["passed"]: + return c + pool = [c for c in cands if c["end_reached"] and not c["bad_frames"]] + if not pool: + return None + only_tag = [c for c in pool if c["fails"] and all(f.startswith("tag ") for f in c["fails"])] + if only_tag: + return max(only_tag, key=lambda c: c.get("tag_excess") or 0) + return min(pool, key=lambda c: (len(c["fails"]), c["longest_gap"])) + + +def render_chunk(gen, chunk, ci, n_chunks, voice, sampler, seed_base, takes, tag_check): + """Up to `takes` takes of one chunk; the first that passes ends it. gen(text, seed, n_predict) → take.""" + text, n_pred = chunk["text"], chunk["nPredict"] + n_tags = len(TAG_RE.findall(text)) + twin = None + if tag_check and n_tags: + plain = strip_tags(text) + for k in range(3): + g = gen(plain, seed_base + 7 + k, n_pred) + ok, m = check_take(plain, g) + if ok: + break + twin = m["dur"] + log(f"chunk {ci + 1}/{n_chunks}: read without its tags {twin:.2f}s") + cands = [] + for t in range(takes): + seed = seed_base + 101 * t + ci + g = gen(text, seed, n_pred) + ok, m = check_take(text, g) + excess = None + if twin is not None: + excess = round(m["dur"] - twin, 3) + if excess < TAG_EXCESS_S * n_tags: + m["fails"].append(f"tag likely skipped (excess {excess:.2f}s < {TAG_EXCESS_S * n_tags:.1f}s)") + ok = False + cands.append(dict(take=t, seed=seed, passed=ok, end_reached=g["end_reached"], bad_frames=g["bad_frames"], + gen_s=g["gen_s"], tag_excess=excess, audio=g["audio"], **m)) + log(f"chunk {ci + 1}/{n_chunks} take {t + 1} seed {seed}: {'PASS' if ok else 'fail'} {m['dur']:.2f}s " + f"{m['wps']:.2f} words/s, longest silence {m['longest_gap']:.2f}s" + + (f" — {'; '.join(m['fails'])}" if m["fails"] else "")) + if ok: + break # the first take that passes is kept + best = choose(cands) + return best, cands + + +def render(spec, server, decode): + voice = spec["voice"] + if voice not in VOICES: + raise SystemExit(f"not a stock voice: {voice!r} (stock: {' '.join(VOICES)})") + sampler, seed_base = spec["sampler"], int(spec.get("seedBase", 1234)) + takes, tag_check = max(1, int(spec.get("takes", 3))), bool(spec.get("tagCheck", False)) + chunks = spec["chunks"] + gen = lambda text, seed, n_pred: generate(server, decode, voice, text, seed, sampler, n_pred) + pieces, flagged, n_takes, gen_s, take_s = [], [], 0, 0.0, 0.0 + for ci, c in enumerate(chunks): + best, cands = render_chunk(gen, c, ci, len(chunks), voice, sampler, seed_base, takes, tag_check) + n_takes += len(cands) + gen_s += sum(x["gen_s"] for x in cands) + take_s += sum(x["dur"] for x in cands) + if best is None: + raise SystemExit(f"chunk {ci + 1}: every take was truncated or malformed — {cands[-1]['fails']}") + if not best["passed"]: + flagged.append(dict(chunk=ci + 1, take=best["take"] + 1, why="; ".join(best["fails"]))) + log(f"chunk {ci + 1}/{len(chunks)}: FLAGGED — no take passed; kept take {best['take'] + 1}: {'; '.join(best['fails'])}") + pieces.append((trim(best["audio"]), float(c["pauseAfter"]))) + return assemble(pieces), dict(chunks=len(chunks), takes=n_takes, flagged=flagged, genSeconds=round(gen_s, 2), + takeSeconds=round(take_s, 2), rtfPerTake=round(gen_s / max(take_s, 1e-6), 3)) + + +def write_wav(path, y): + pcm = (np.clip(y, -1.0, 1.0) * 32767.0).astype("<i2") + with wave.open(path, "wb") as w: + w.setnchannels(1) + w.setsampwidth(2) + w.setframerate(SR) + w.writeframes(pcm.tobytes()) + return len(pcm) / SR + + +# ── selftest (numpy only: no model, no server) ──────────────────────────────── +def _tone(seconds, freq=220.0, amp=0.3): + t = np.arange(int(seconds * SR)) / SR + return (amp * np.sin(2 * np.pi * freq * t)).astype(np.float32) + + +def _silence(seconds): + return np.zeros(int(seconds * SR), np.float32) + + +def selftest(): + fails = [] + + def ok(cond, what): + print(("ok " if cond else "FAIL ") + what) + if not cond: + fails.append(what) + + # trim and silences + a = np.concatenate([_silence(0.5), _tone(1.0), _silence(0.4), _tone(0.5), _silence(0.7)]) + tr = trim(a) + ok(abs(len(tr) / SR - (1.9 + 0.04 + 0.08)) < 0.02, f"trim keeps 40 ms before and 80 ms after ({len(tr) / SR:.3f}s)") + ok(abs(longest_gap(tr) - 0.4) < 0.02, f"the longest internal silence is found ({longest_gap(tr):.2f}s)") + ok(len(trim(_silence(1.0))) == 0, "an all-silent take trims to nothing") + + # the rate floor drops for multi-sentence chunks + ok(wps_floor(1) == 2.0 and wps_floor(2) == 1.75 and wps_floor(3) == 1.5 and wps_floor(6) == 1.5, + "the words/s floor: 2.0, 1.75 for two sentences, 1.5 at three and more") + ok(sentences_in("One file. No title. Just a date.") == 3 and sentences_in("And then... there it was.") == 1, + "sentences are counted; an ellipsis does not end one") + + def take(seconds, end=True, bad=0, gap=None): + audio = _tone(seconds) if gap is None else np.concatenate([_tone(seconds / 2), _silence(gap), _tone(seconds / 2)]) + return dict(audio=audio, end_reached=end, bad_frames=bad, gen_s=seconds * 1.5) + + one = "This sentence has exactly eight words in it." # 8 words + ok(check_take(one, take(3.0))[0], "8 words in 3.0 s (2.7/s) pass") + ok(not check_take(one, take(4.5))[0], "8 words in 4.5 s (1.8/s) fail as one sentence") + three = "This has four words. This has four words. And this has five." # 13 words, 3 sentences + ok(check_take(three, take(13 / 1.8))[0], "a slow three-sentence read (1.8 words/s) passes: the floor is 1.5") + ok(not check_take(one, take(1.5))[0], "8 words in 1.5 s (5.3/s) fail as too fast") + p, m = check_take(one, take(3.0, end=False)) + ok(not p and m["fails"][0].startswith("truncated"), "a take with no end of speech fails as truncated") + ok(not check_take(one, take(3.0, bad=2))[0], "malformed frames fail") + p, m = check_take(one, take(2.4, gap=1.5)) + ok(not p and any("internal silence" in f for f in m["fails"]), "1.5 s of dead air inside a sentence fails") + + # frames: the slot bands, the end token, the SNAC levels + frame = [AUDIO_BASE + k * 4096 + (k + 1) for k in range(7)] + bad_frame = [AUDIO_BASE + 5] * 7 # slot 1+ outside its band + ids = [START_OF_SPEECH] + frame + bad_frame + frame + [END_OF_SPEECH] + frame + codes, bad = codes_from_tokens(ids) + ok(codes == [1, 2, 3, 4, 5, 6, 7] * 2 and bad == 1, "frames: two good, one malformed, nothing after the end token") + l0, l1, l2 = snac_inputs([1, 2, 3, 4, 5, 6, 7]) + ok(l0.tolist() == [[1]] and l1.tolist() == [[2, 5]] and l2.tolist() == [[3, 4, 6, 7]], "SNAC levels: c0 | c1 c4 | c2 c3 c5 c6") + + # takes: the first passing take ends the chunk + calls = [] + script = [take(4.6), take(3.0), take(3.0)] + + def gen(text, seed, n_pred): + calls.append(seed) + return script[len(calls) - 1] + + best, cands = render_chunk(gen, dict(text=one, nPredict=700), 2, 5, "leah", {}, 1234, 3, False) + ok(best["take"] == 1 and calls == [1236, 1337], f"early stop: take 2 passes, take 3 is never asked (seeds {calls})") + + # nothing passes: the fewest failures are kept; all truncated → None + c = [dict(passed=False, end_reached=True, bad_frames=0, fails=["a", "b"], longest_gap=0.2, take=0), + dict(passed=False, end_reached=True, bad_frames=0, fails=["a"], longest_gap=0.9, take=1), + dict(passed=False, end_reached=False, bad_frames=0, fails=["truncated"], longest_gap=0.0, take=2)] + ok(choose(c)["take"] == 1, "no take passes: the fewest failures are kept, never a truncated one") + ok(choose([dict(c[2]), dict(c[2], bad_frames=1, end_reached=True)]) is None, "every take truncated or malformed: none") + tag = [dict(passed=False, end_reached=True, bad_frames=0, fails=["tag likely skipped"], tag_excess=0.1, longest_gap=0, take=0), + dict(passed=False, end_reached=True, bad_frames=0, fails=["tag likely skipped"], tag_excess=0.3, longest_gap=0, take=1)] + ok(choose(tag)["take"] == 1, "only the tag check failed: the take likeliest to hold the tag") + + # tag check: a take no longer than the plain read fails + calls.clear() + tagged = "This sentence has exactly eight words in it. <sigh>" + script = [take(3.5), take(3.6), take(3.6), take(3.6)] # the plain twin, then three takes + best, cands = render_chunk(gen, dict(text=tagged, nPredict=700), 0, 1, "leah", {}, 1234, 3, True) + ok(not best["passed"] and len(calls) == 4 and [f[:18] for f in best["fails"]] == ["tag likely skipped"], + "with the tag check, takes barely longer than the plain read fail as having skipped the tag") + calls.clear() + script = [take(3.5), take(4.4)] + best, cands = render_chunk(gen, dict(text=tagged, nPredict=700), 0, 1, "leah", {}, 1234, 3, True) + ok(best["passed"] and len(calls) == 2, "a take 0.9 s longer than the plain read holds its tag, and passes") + + # joins: the pause after each chunk, peaks at or under −1 dBFS + y = assemble([(_tone(1.0, amp=0.9), 0.3), (_tone(1.0, amp=0.1), 0.6), (_tone(0.5), 0.0)]) + ok(abs(len(y) / SR - 3.4) < 0.01, f"joined: 2.5 s of speech + 0.9 s of pauses ({len(y) / SR:.2f}s)") + ok(float(np.abs(y).max()) <= 0.8911, "peaks at or under −1 dBFS") + + print("SELFTEST", "PASS" if not fails else f"FAIL ({len(fails)})") + return not fails + + +def main(): + if sys.argv[1:2] == ["selftest"]: + return 0 if selftest() else 1 + p = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + p.add_argument("--server", required=True, help="llama-server base URL") + p.add_argument("--snac", required=True, help="snac_decoder.onnx") + p.add_argument("--output", required=True, help="the WAV to write (24 kHz)") + p.add_argument("input", help="input.json (see the docstring)") + args = p.parse_args() + with open(args.input, encoding="utf-8") as f: + spec = json.load(f) + if not spec.get("chunks"): + print("tts_orpheus: no chunks to speak", file=sys.stderr) + return 2 + t0 = time.perf_counter() + decode = Decoder(args.snac) + load = time.perf_counter() - t0 + y, stats = render(spec, args.server.rstrip("/"), decode) + seconds = write_wav(args.output, y) + print(json.dumps(dict(sampleRate=SR, seconds=round(seconds, 3), loadSeconds=round(load, 3), **stats))) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/tts_orpheus.test.mjs b/scripts/tts_orpheus.test.mjs @@ -0,0 +1,49 @@ +// scripts/tts_orpheus.py — the Orpheus helper's own checks, run through its +// `selftest` (numpy only: the take checks, the rate floor for multi-sentence +// chunks, the frame bands and SNAC levels, the first-pass early stop, the +// fallback when nothing passes, the tag-length check, the joins). +// +// Run with: node --test scripts/tts_orpheus.test.mjs (part of `pnpm run test:scripts`) +// +// Needs a python with numpy: `python3` when it has one. Skipped otherwise — the +// real model is never run here. + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import path from "node:path"; + +const HELPER = path.join(import.meta.dirname, "tts_orpheus.py"); +const probe = spawnSync("python3", ["-c", "import numpy"], { encoding: "utf8" }); +const skip = probe.status !== 0 && "python3 with numpy absent"; + +test("the Orpheus helper's selftest passes", { skip }, () => { + const r = spawnSync("python3", [HELPER, "selftest"], { encoding: "utf8" }); + assert.equal(r.status, 0, r.stdout + r.stderr); + assert.match(r.stdout, /SELFTEST PASS/); + assert.doesNotMatch(r.stdout, /^FAIL/m); + // The cases it holds, by name: a missing one is a dropped check. + for (const name of [ + "a slow three-sentence read (1.8 words/s) passes", + "a take with no end of speech fails as truncated", + "early stop: take 2 passes, take 3 is never asked", + "every take truncated or malformed: none", + "with the tag check, takes barely longer than the plain read fail", + "SNAC levels: c0 | c1 c4 | c2 c3 c5 c6", + ]) { + assert.ok(r.stdout.includes(`ok ${name}`), name); + } +}); + +test("the helper refuses a voice that is not a stock one, before anything runs", { skip }, () => { + const r = spawnSync( + "python3", + ["-B", "-c", `import sys; sys.path.insert(0, ${JSON.stringify(path.dirname(HELPER))}); import tts_orpheus as t +try: + t.render({"voice": "someone", "sampler": {}, "chunks": [{"text": "x", "nPredict": 7, "pauseAfter": 0}]}, "http://127.0.0.1:1", None) +except SystemExit as e: + print(e)`], + { encoding: "utf8" }, + ); + assert.match(r.stdout, /not a stock voice: 'someone'/); +}); diff --git a/settings.json.example b/settings.json.example @@ -222,6 +222,19 @@ "voice": "af_heart", "speed": 1, "home": "", - "dir": "" + "dir": "", + "orpheus": { + "serverBin": "/usr/lib/ollama/llama-server", + "libraryPath": "/usr/lib/ollama", + "ggmlBackendPath": "/usr/lib/ollama/vulkan/libggml-vulkan.so", + "port": 8799, + "gpuLayers": 99, + "contextSize": 8192, + "startTimeoutSeconds": 150, + "idleStopSeconds": 5, + "heavyEstimateMB": 4000, + "takes": 3, + "tagCheck": false + } } }