commit b62666fabe6dbad93b44cf395dff93b064a0a49f
parent 81640cab55064ea64dba39b9a4a6803de4d5be8d
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Sun, 11 Oct 2026 01:14:00 -0400
Merge branch 'r25/integration' into r25/tts-video
Diffstat:
36 files changed, 2933 insertions(+), 4 deletions(-)
diff --git a/.gitignore b/.gitignore
@@ -166,6 +166,10 @@ yarn-error.log*
/settings.json
/chart-templates.json
+# Text-to-speech synthesis cache (settings.tts.dir's default, release 25):
+# <sha256>.wav + .json per distinct synthesis. Rebuildable; never committed.
+/.tts/
+
# Diarization runtime: the uv-managed python 3.13 venv + the sherpa-onnx models.
# Machine-specific (~148 MB) and rebuildable from .diarize/README.md, which IS
# tracked. sherpa-onnx ships wheels only to cp313 and this box's system python is
diff --git a/COMMANDS.md b/COMMANDS.md
@@ -68,6 +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/<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 |
| `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\] -> a dated heading; all = both, one version, two commits |
@@ -118,6 +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 "## \[<version>\] - <date>": {"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 <workspace> <version>") — 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 <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 {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` |
| `settings` | settings patches settings.json through the editor's one writer: {"patch": {"<top-level key>": 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
@@ -33,6 +33,8 @@ The one override surface for where things live and which binary runs. Every one
| `PARAKEET_CLI` | `parakeet-cli` on PATH | The parakeet.cpp binary the wrapper drives (the wrapper reads it too). | common/lib/paths.ts (getPaths) |
| `PARAKEET_MODEL` | none | parakeet.cpp's `.gguf`, when a worker names none (the wrapper reads it too). | common/lib/paths.ts (getPaths) |
| `DIARIZE_BIN` | `<repo>/scripts/diarize.mjs` | The speaker-diarization wrapper. The e2e suite swaps in a fake here. | common/lib/paths.ts (getPaths) |
+| `TTS_BIN` | `<repo>/scripts/tts.mjs` | The text-to-speech wrapper (text in, 48 kHz WAV out) every engine runs behind. A test swaps in a fake here. | common/lib/paths.ts (getPaths) |
+| `ESPEAK_NG_BIN` | `espeak-ng` on PATH | eSpeak NG, the zero-install text-to-speech engine (the wrapper reads it too). | common/lib/paths.ts (getPaths) |
| `RSYNC_BIN` | `rsync` on PATH | Mirrors the saved-video store to a backup destination. | common/lib/paths.ts (getPaths) |
| `FINDMNT_BIN` | `findmnt` on PATH | The read-only volume-identity probe behind storage locations. Optional. | common/lib/paths.ts (getPaths) |
| `UDISKSCTL_BIN` | `udisksctl` on PATH | Mounts an attached volume from `/storage`. Optional. | common/lib/paths.ts (getPaths) |
diff --git a/SETTINGS.md b/SETTINGS.md
@@ -49,6 +49,7 @@ A copied example PINS every default it spells — including each lane's `autoQue
| [`archiveOrg`](#archiveorg) | object — see below |
| [`publish`](#publish) | object — see below |
| [`seeder`](#seeder) | object — see below |
+| [`tts`](#tts) | object — see below |
## `adminTitle`
@@ -887,3 +888,29 @@ Default:
"bindInterface": ""
}
```
+
+## `tts`
+
+Local text-to-speech (release 25): narration for report videos and podcasts, synthesized as an editor job (`pnpm ops tts`, the `tts` queue, one at a time) with a STOCK voice — never a cloned one — and cached by content. The default engine is Kokoro-82M with the voice `af_heart`, installed by `archilyzer tts setup`; espeak-ng needs no install. Every synthesis is disclosed as a synthetic voice (its sidecar and the result's `disclosure`). See TtsSettings and common/controller/ttsFile.ts.
+
+#### `tts`
+
+| 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. |
+| `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. |
+
+Default:
+
+```json
+{
+ "engine": "kokoro",
+ "voice": "af_heart",
+ "speed": 1,
+ "home": "",
+ "dir": ""
+}
+```
diff --git a/common/bin/archilyzer.ts b/common/bin/archilyzer.ts
@@ -710,6 +710,20 @@ export const COMMANDS: Command[] = [
run: async ({ flags }) =>
(await import("./settings-example")).main({ check: flags.check === true }),
},
+ // Text-to-speech (release 25): install an engine for `pnpm ops tts`.
+ {
+ 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",
+ flags: { engine: "string", from: "string", python: "string", check: "boolean" },
+ run: async ({ flags }) =>
+ (await import("./tts-setup")).main({
+ ...(typeof flags.engine === "string" ? { engine: flags.engine } : {}),
+ ...(typeof flags.from === "string" ? { from: flags.from } : {}),
+ ...(typeof flags.python === "string" ? { python: flags.python } : {}),
+ check: flags.check === true,
+ }),
+ },
{
path: ["doctor"],
usage:
diff --git a/common/bin/doctor.test.ts b/common/bin/doctor.test.ts
@@ -997,3 +997,26 @@ test("seeder: the same egress as the host fails; a different one is ok; an unans
assert.equal(find(down, "seeder", "egress")?.status, "warn");
assert.match(find(down, "seeder", "egress")!.detail, /No such container.*profile up/);
});
+
+// ── release 25: text-to-speech ──────────────────────────────────────────────
+
+test("tts: not installed is a note naming the setup; installed is ok; never a failure", async () => {
+ const c = checkout();
+ const home = path.join(c.root, "tts-home");
+ writeFileSync(c.paths.settingsFile, JSON.stringify({ tts: { home } }));
+ const before = tree(c.root);
+ const none = await run(c, {});
+ const row = find(none, "tts", "engine");
+ assert.equal(row?.status, "info");
+ assert.match(row!.detail, /kokoro · af_heart not installed \(.*tts-home\/kokoro: missing the python venv .*kokoro-v1\.0\.onnx; voices-v1\.0\.bin\) — `archilyzer tts setup` installs it/);
+ assert.deepEqual(tree(c.root), before, "the probe stats, never creates");
+ const ok = await run(c, {}, {
+ ttsState: async () => ({ engine: "kokoro", voice: "bm_george", voiceOk: true, dir: "/h/kokoro", installed: true, missing: [] }),
+ });
+ assert.equal(find(ok, "tts", "engine")?.status, "ok");
+ assert.match(find(ok, "tts", "engine")!.detail, /kokoro · bm_george installed \(\/h\/kokoro\)/);
+ const badVoice = await run(c, {}, {
+ ttsState: async () => ({ engine: "kokoro", voice: "x", voiceOk: false, dir: "/h/kokoro", installed: true, missing: [] }),
+ });
+ assert.equal(find(badVoice, "tts", "engine")?.status, "warn");
+});
diff --git a/common/bin/doctor.ts b/common/bin/doctor.ts
@@ -105,6 +105,18 @@ export type DoctorDeps = {
// The host's egress IP and the seeder container's, asked only when the
// seeder is configured. Default: probeSeederEgress.
seederEgress?: () => Promise<SeederEgressProbe>;
+ // The configured text-to-speech engine's install state. Default: settings.tts
+ // through lib/ttsInstall.ts (stats only).
+ ttsState?: () => Promise<TtsDoctorState>;
+};
+
+export type TtsDoctorState = {
+ engine: string;
+ voice: string;
+ voiceOk: boolean;
+ dir: string;
+ installed: boolean;
+ missing: string[];
};
// What `archilyzer doctor` learned of the seeder's way out: each egress IP, or
@@ -801,6 +813,44 @@ export async function collectDoctorReport(deps: DoctorDeps): Promise<DoctorRepor
}
}
+ // ── text-to-speech (release 25) ──────────────────────────────────────────
+ // The configured engine and voice (settings.tts): installed or not. Never a
+ // failure — narration is asked for, never run on its own, and a clone with no
+ // engine is a complete archive — so "not installed" is a note naming
+ // `archilyzer tts setup`. Presence only (lib/ttsInstall.ts): the venv and
+ // each model file at its pinned size; `tts setup --check` imports the package.
+ const TS = "tts";
+ if (settings) {
+ try {
+ const state = await (deps.ttsState ?? (async () => {
+ const { getTtsEngine } = await import("../lib/ttsApps");
+ const { ttsInstallState } = await import("../lib/ttsInstall");
+ const { resolveTtsHome } = await import("../lib/ttsSettings");
+ const engine = getTtsEngine(settings!.tts.engine)!;
+ const home = resolveTtsHome(settings!.tts, {
+ ttsHome: paths.ttsHome ?? path.join(os.homedir(), ".local", "share", "archilyzer", "tts"),
+ });
+ const voiceOk = engine.voices.includes(settings!.tts.voice);
+ return {
+ ...ttsInstallState(engine, { home, paths: { espeakNgBin: paths.espeakNgBin ?? "espeak-ng" }, envPath: env.PATH }),
+ voice: settings!.tts.voice,
+ voiceOk,
+ };
+ }))();
+ const what = `${state.engine} · ${state.voice}`;
+ if (!state.voiceOk) {
+ add(TS, "engine", "warn", `${what}: ${state.engine} has no such stock voice`);
+ } else if (state.installed) {
+ add(TS, "engine", "ok", `${what} installed (${state.dir})`);
+ } else {
+ add(TS, "engine", "info",
+ `${what} not installed (${state.dir}: missing ${state.missing.join("; ")}) — \`archilyzer tts setup\` installs it; narration only`);
+ }
+ } catch (e) {
+ add(TS, "engine", "info", `could not be checked: ${(e as Error).message}`);
+ }
+ }
+
// ── ports ────────────────────────────────────────────────────────────────
const P = "ports";
const block = await (deps.portBlock ?? (() => worktreePortBlock(root)))();
diff --git a/common/bin/tts-setup.test.ts b/common/bin/tts-setup.test.ts
@@ -0,0 +1,115 @@
+import { test, after } from "node:test";
+import assert from "node:assert/strict";
+import { createHash } from "node:crypto";
+import { mkdtemp, mkdir, readdir, rm, stat, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { adoptModelFile, downloadModelFile, main, verifyModelFile } from "./tts-setup";
+import type { TtsModelFile } from "../lib/ttsApps";
+
+// Run with:
+// pnpm --filter yt-dlp-transcript-common exec tsx --test bin/tts-setup.test.ts
+//
+// `archilyzer tts setup`'s pieces over a tiny synthetic "model": verification
+// by size and sha256, the one-stream download (a fake fetch — nothing here
+// touches the network), `--from` adoption, and `--check` over an empty home.
+// The real install (a venv, kokoro-onnx, 350 MB of model) is run by hand.
+
+const ROOT = await mkdtemp(path.join(os.tmpdir(), "tts-setup-"));
+after(() => rm(ROOT, { recursive: true, force: true }));
+
+const BYTES = Buffer.from("not a real model, ".repeat(64));
+const SPEC: TtsModelFile = {
+ name: "tiny.onnx",
+ url: "https://example.invalid/tiny.onnx",
+ bytes: BYTES.length,
+ sha256: createHash("sha256").update(BYTES).digest("hex"),
+};
+
+function fakeFetch(body: Buffer, status = 200): typeof fetch {
+ const calls: string[] = [];
+ const f = (async (url: string | URL | Request) => {
+ calls.push(String(url));
+ return new Response(status === 200 ? new Uint8Array(body) : null, { status });
+ }) as unknown as typeof fetch;
+ return Object.assign(f, { calls });
+}
+
+test("a file verifies by size, then sha256", async () => {
+ const dir = await mkdtemp(path.join(ROOT, "verify-"));
+ const f = path.join(dir, SPEC.name);
+ assert.equal(await verifyModelFile(f, SPEC), "absent");
+ await writeFile(f, BYTES.subarray(1));
+ assert.match(await verifyModelFile(f, SPEC), /bytes, expected/);
+ const bad = Buffer.from(BYTES);
+ bad[0] ^= 1;
+ await writeFile(f, bad);
+ assert.match(await verifyModelFile(f, SPEC), /^sha256 .* expected/);
+ await writeFile(f, BYTES);
+ assert.equal(await verifyModelFile(f, SPEC), "ok");
+});
+
+test("a download is one stream, verified before it is moved into place", async () => {
+ const dir = await mkdtemp(path.join(ROOT, "dl-"));
+ const target = path.join(dir, SPEC.name);
+ const lines: string[] = [];
+ const ok = fakeFetch(BYTES);
+ await downloadModelFile(SPEC, target, (l) => lines.push(l), ok);
+ assert.equal(await verifyModelFile(target, SPEC), "ok");
+ assert.deepEqual((ok as unknown as { calls: string[] }).calls, [SPEC.url]);
+ assert.deepEqual(await readdir(dir), [SPEC.name]);
+ assert.ok(lines.some((l) => /100%/.test(l)), lines.join("\n"));
+
+ // A body that does not verify is not kept, and is not retried.
+ const corrupt = Buffer.from(BYTES);
+ corrupt[3] ^= 1;
+ const other = path.join(dir, "other.onnx");
+ const bad = fakeFetch(corrupt);
+ await assert.rejects(downloadModelFile(SPEC, other, () => {}, bad), /does not verify/);
+ assert.equal((bad as unknown as { calls: string[] }).calls.length, 1);
+ assert.deepEqual(await readdir(dir), [SPEC.name]);
+ // A server error is an error, once.
+ await assert.rejects(downloadModelFile(SPEC, other, () => {}, fakeFetch(BYTES, 503)), /answered 503/);
+});
+
+test("--from adopts a verified file (a hard link), and refuses one that is not", async () => {
+ const src = await mkdtemp(path.join(ROOT, "from-"));
+ const dst = await mkdtemp(path.join(ROOT, "to-"));
+ await writeFile(path.join(src, SPEC.name), BYTES);
+ const lines: string[] = [];
+ assert.equal(await adoptModelFile(path.join(src, SPEC.name), path.join(dst, SPEC.name), SPEC, (l) => lines.push(l)), true);
+ const a = await stat(path.join(src, SPEC.name));
+ const b = await stat(path.join(dst, SPEC.name));
+ assert.equal(a.ino, b.ino, "a hard link on the same filesystem");
+ assert.match(lines.join("\n"), /linked tiny\.onnx/);
+ await writeFile(path.join(src, "short.onnx"), BYTES.subarray(2));
+ assert.equal(
+ await adoptModelFile(path.join(src, "short.onnx"), path.join(dst, "short.onnx"), SPEC, () => {}),
+ false,
+ );
+ assert.deepEqual(await readdir(dst), [SPEC.name]);
+});
+
+test("--check over an empty home lists what is missing, installs nothing, exits 1", async () => {
+ const home = path.join(ROOT, "empty-home");
+ await mkdir(home);
+ const lines: string[] = [];
+ const code = await main({ check: true, home, log: (l) => lines.push(l) });
+ assert.equal(code, 1);
+ const text = lines.join("\n");
+ assert.match(text, /Kokoro-82M at .*empty-home\/kokoro — missing:/);
+ assert.match(text, /- the python venv/);
+ assert.match(text, /- kokoro-v1\.0\.onnx/);
+ assert.match(text, /- voices-v1\.0\.bin/);
+ assert.match(text, /Run `archilyzer tts setup`/);
+ assert.deepEqual(await readdir(home), []);
+});
+
+test("an unknown engine is refused; espeak-ng has nothing to install", async () => {
+ const lines: string[] = [];
+ assert.equal(await main({ engine: "piper", log: (l) => lines.push(l) }), 2);
+ assert.match(lines[0], /no engine "piper" — known: kokoro, espeak-ng/);
+ const missing: string[] = [];
+ 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/);
+});
diff --git a/common/bin/tts-setup.ts b/common/bin/tts-setup.ts
@@ -0,0 +1,263 @@
+// `archilyzer tts setup` — install a text-to-speech engine (release 25 T1).
+//
+// For Kokoro (a `python-venv` engine, lib/ttsApps.ts) it builds, under
+// `<settings.tts.home>/kokoro` (default ~/.local/share/archilyzer/tts/kokoro):
+// venv/ a python venv with the pinned package
+// (kokoro-onnx==0.6.1) — made by `uv venv --python
+// 3.12` when uv is on PATH, else `<--python> -m venv`
+// kokoro-v1.0.onnx the model files, downloaded ONCE from the
+// voices-v1.0.bin kokoro-onnx project's `model-files-v1.0` release
+// install.json what was installed, and when
+//
+// POLITE: one download at a time, one stream each, no retry loop — a failed
+// download is reported and the next run resumes nothing (it starts the file
+// again). Every file is verified by size and sha256 before it is moved into
+// place; a file already there and verified is never fetched again. `--from
+// <dir>` takes the files from a directory that already holds them (hard
+// links where the filesystem allows, else copies), verified the same way —
+// for a machine that downloaded them once already.
+//
+// `--check` installs nothing: it lists what is missing (the venv, the package
+// at its pinned version — by importing it — each model file at its size) and
+// exits 1 when anything is.
+//
+// espeak-ng (a `system` engine) has nothing to install: setup says whether it
+// is on PATH.
+//
+// Scratch (pip's build dirs) goes to `<install dir>/.tmp`, never the OS temp
+// dir: it may be a small RAM tmpfs.
+
+import { createHash } from "node:crypto";
+import { createReadStream, createWriteStream } from "node:fs";
+import { copyFile, link, mkdir, rename, rm, stat } from "node:fs/promises";
+import path from "node:path";
+import { Readable } from "node:stream";
+import { pipeline } from "node:stream/promises";
+import { execa } from "execa";
+import { getPaths } from "../lib/paths";
+import { getSettings } from "../lib/settings";
+import {
+ DEFAULT_TTS_ENGINE_ID,
+ getTtsEngine,
+ ttsEngineIds,
+ ttsInstallDir,
+ ttsVenvPython,
+ type TtsModelFile,
+} from "../lib/ttsApps";
+import { findOnPath, ttsInstallState } from "../lib/ttsInstall";
+import { resolveTtsHome } from "../lib/ttsSettings";
+import { writeJsonAtomic } from "../lib/jsonFile-server";
+
+export type TtsSetupOptions = {
+ engine?: string;
+ from?: string;
+ python?: string;
+ check?: boolean;
+ // Injected by tests.
+ home?: string;
+ log?: (line: string) => void;
+ fetch?: typeof fetch;
+ envPath?: string;
+};
+
+async function sha256File(file: string): Promise<string> {
+ const h = createHash("sha256");
+ await pipeline(createReadStream(file), h);
+ return h.digest("hex");
+}
+
+// "ok" when `file` is the pinned file (size, then sha256), else why not.
+export async function verifyModelFile(file: string, spec: TtsModelFile): Promise<"ok" | string> {
+ const st = await stat(file).catch(() => null);
+ if (!st?.isFile()) return "absent";
+ if (st.size !== spec.bytes) return `${st.size} bytes, expected ${spec.bytes}`;
+ const sha = await sha256File(file);
+ return sha === spec.sha256 ? "ok" : `sha256 ${sha.slice(0, 12)}…, expected ${spec.sha256.slice(0, 12)}…`;
+}
+
+function mb(n: number): string {
+ return `${(n / 1_000_000).toFixed(1)} MB`;
+}
+
+// One stream to `<target>.part`, verified, then renamed. No retries.
+export async function downloadModelFile(
+ spec: TtsModelFile,
+ target: string,
+ log: (l: string) => void,
+ doFetch: typeof fetch,
+): Promise<void> {
+ const part = `${target}.part`;
+ log(` downloading ${spec.url} (${mb(spec.bytes)})…`);
+ const res = await doFetch(spec.url, { redirect: "follow" });
+ if (!res.ok || !res.body) throw new Error(`${spec.url} answered ${res.status}`);
+ let got = 0;
+ let nextReport = 0.25;
+ const counted = Readable.fromWeb(res.body as import("node:stream/web").ReadableStream).on("data", (c: Buffer) => {
+ got += c.length;
+ if (got / spec.bytes >= nextReport) {
+ log(` ${Math.round((got / spec.bytes) * 100)}%`);
+ nextReport += 0.25;
+ }
+ });
+ try {
+ await pipeline(counted, createWriteStream(part));
+ const v = await verifyModelFile(part, spec);
+ if (v !== "ok") throw new Error(`${spec.name} downloaded but does not verify (${v})`);
+ await rename(part, target);
+ } catch (e) {
+ await rm(part, { force: true }).catch(() => {});
+ throw e;
+ }
+}
+
+// From `--from`: a hard link when the filesystem allows, else a copy.
+export async function adoptModelFile(src: string, target: string, spec: TtsModelFile, log: (l: string) => void): Promise<boolean> {
+ const v = await verifyModelFile(src, spec);
+ if (v !== "ok") {
+ log(` ${src}: ${v} — not used`);
+ return false;
+ }
+ await rm(target, { force: true });
+ try {
+ await link(src, target);
+ log(` linked ${spec.name} from ${path.dirname(src)}`);
+ } catch {
+ const part = `${target}.part`;
+ await copyFile(src, part);
+ await rename(part, target);
+ log(` copied ${spec.name} from ${path.dirname(src)}`);
+ }
+ return true;
+}
+
+// The pinned package's installed version, or null when it does not import.
+async function installedVersion(python: string, importName: string, dist: string): Promise<string | null> {
+ try {
+ const { stdout } = await execa(python, [
+ "-c",
+ `import ${importName}, importlib.metadata as m; print(m.version(${JSON.stringify(dist)}))`,
+ ]);
+ return stdout.trim() || null;
+ } catch {
+ return null;
+ }
+}
+
+export async function main(opts: TtsSetupOptions = {}): Promise<number> {
+ const log = opts.log ?? ((l: string) => console.log(l));
+ const engineId = opts.engine ?? DEFAULT_TTS_ENGINE_ID;
+ const engine = getTtsEngine(engineId);
+ if (!engine) {
+ log(`tts setup: no engine "${engineId}" — known: ${ttsEngineIds().join(", ")}`);
+ return 2;
+ }
+ const paths = getPaths();
+ const envPath = opts.envPath ?? process.env.PATH;
+ const setup = engine.setup;
+
+ if (setup.kind === "system") {
+ const found = findOnPath(paths[setup.bin], envPath);
+ log(found ? `${engine.label}: ${found} — nothing to install` : `${engine.label}: ${paths[setup.bin]} is not on PATH — ${setup.hint}`);
+ return found ? 0 : 1;
+ }
+
+ const home = opts.home ?? resolveTtsHome(getSettings().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 missing = [...state.missing];
+ if (!missing.some((m) => m.startsWith("the python venv"))) {
+ const v = await installedVersion(python, setup.importName, dist);
+ if (v !== pinned) missing.push(v ? `${dist} ${v} (pinned ${pinned})` : `${dist} does not import in the venv`);
+ }
+ if (missing.length === 0) {
+ log(`${engine.label}: installed at ${dir} (${dist} ${pinned}, ${setup.files.map((f) => f.name).join(", ")})`);
+ return 0;
+ }
+ log(`${engine.label} at ${dir} — missing:`);
+ for (const m of missing) log(` - ${m}`);
+ log("Run `archilyzer tts setup` to install it.");
+ return 1;
+ }
+
+ log(`Installing ${engine.label} at ${dir}`);
+ const scratch = path.join(dir, ".tmp");
+ await mkdir(scratch, { recursive: true });
+ const env = { TMPDIR: scratch, PIP_DISABLE_PIP_VERSION_CHECK: "1", NO_COLOR: "1" };
+ const uv = findOnPath("uv", envPath);
+ const run = async (cmd: string, args: string[]) => {
+ log(` $ ${[cmd, ...args].join(" ")}`);
+ const child = execa(cmd, args, { env, all: true, buffer: false });
+ let pending = "";
+ child.all?.on("data", (c: Buffer) => {
+ pending += c.toString("utf8");
+ const lines = pending.split("\n");
+ pending = lines.pop() ?? "";
+ for (const l of lines) if (l.trim()) log(` ${l.trimEnd()}`);
+ });
+ await child;
+ if (pending.trim()) log(` ${pending.trimEnd()}`);
+ };
+
+ try {
+ // 1. The venv.
+ if ((await stat(python).catch(() => null)) === null) {
+ const venv = path.join(dir, "venv");
+ if (opts.python) await run(opts.python, ["-m", "venv", venv]);
+ else if (uv) await run(uv, ["venv", "--python", setup.python, venv]);
+ else await run("python3", ["-m", "venv", venv]);
+ } else {
+ log(` venv present (${python})`);
+ }
+
+ // 2. The pinned package.
+ const have = await installedVersion(python, setup.importName, dist);
+ if (have === pinned) {
+ log(` ${dist} ${pinned} present`);
+ } else if (uv && !opts.python) {
+ await run(uv, ["pip", "install", "--python", python, ...setup.packages]);
+ } else {
+ await run(python, ["-m", "pip", "install", ...setup.packages]);
+ }
+
+ // 3. The model files, one at a time.
+ for (const spec of setup.files) {
+ const target = path.join(dir, spec.name);
+ if ((await verifyModelFile(target, spec)) === "ok") {
+ log(` ${spec.name} present and verified`);
+ continue;
+ }
+ if (opts.from && (await adoptModelFile(path.join(path.resolve(opts.from), spec.name), target, spec, log))) continue;
+ await downloadModelFile(spec, target, log, opts.fetch ?? fetch);
+ log(` ${spec.name} downloaded and verified`);
+ }
+ } catch (e) {
+ log(`tts setup failed: ${(e as Error).message}`);
+ return 1;
+ } finally {
+ await rm(scratch, { recursive: true, force: true }).catch(() => {});
+ }
+
+ const version = await installedVersion(python, setup.importName, dist);
+ if (version !== pinned) {
+ log(`tts setup: ${dist} does not import at ${pinned} in ${python} (got ${version ?? "nothing"})`);
+ return 1;
+ }
+ await writeJsonAtomic(
+ path.join(dir, "install.json"),
+ {
+ engine: engine.id,
+ model: engine.model,
+ license: engine.license,
+ packages: setup.packages,
+ files: setup.files.map((f) => ({ name: f.name, bytes: f.bytes, sha256: f.sha256, url: f.url })),
+ installedAt: new Date().toISOString(),
+ },
+ { indent: 2 },
+ );
+ log(`${engine.label} installed: ${dir}`);
+ return 0;
+}
diff --git a/common/controller/ttsFile.test.ts b/common/controller/ttsFile.test.ts
@@ -0,0 +1,285 @@
+import { test, after } from "node:test";
+import assert from "node:assert/strict";
+import { execFileSync } from "node:child_process";
+import { chmod, mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+
+// Run with:
+// pnpm --filter yt-dlp-transcript-common exec tsx --test controller/ttsFile.test.ts
+//
+// One text-to-speech synthesis (`pnpm ops tts`): the body's shape, the
+// refusals that come before any job, the cache key — and whole jobs run
+// through the real registry, the real job queue and the REAL wrapper with
+// espeak-ng (the zero-install engine), behind a counting shim at TTS_BIN so a
+// cache hit can be shown to run no engine. In a temp corpus; nothing here
+// touches a real transcripts dir, and Kokoro is never run.
+
+const ROOT = await mkdtemp(path.join(os.tmpdir(), "tts-file-"));
+after(() => rm(ROOT, { recursive: true, force: true }));
+const CORPUS = path.join(ROOT, "transcripts");
+const OUTSIDE = path.join(ROOT, "outside");
+const CACHE = path.join(ROOT, "tts-cache");
+const HOME = path.join(ROOT, "tts-home");
+const BIN = path.join(ROOT, "bin");
+await mkdir(path.join(CORPUS, "channels", "chan", "data"), { recursive: true });
+await mkdir(OUTSIDE, { recursive: true });
+await mkdir(HOME, { recursive: true });
+await mkdir(BIN, { recursive: true });
+
+// The shim: one line per engine run, then the real wrapper with the same argv.
+const RUNS = path.join(ROOT, "runs.log");
+const WRAPPER = path.resolve(import.meta.dirname, "..", "..", "scripts", "tts.mjs");
+const shim = path.join(BIN, "tts-shim");
+await writeFile(
+ shim,
+ `#!/usr/bin/env node
+const fs = require("node:fs");
+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 r = spawnSync(process.execPath, [${JSON.stringify(WRAPPER)}, ...process.argv.slice(2)], { stdio: "inherit" });
+process.exit(r.status ?? 1);
+`,
+);
+await chmod(shim, 0o755);
+
+const SETTINGS_FILE = path.join(ROOT, "settings.json");
+async function setTts(tts: Record<string, unknown>) {
+ await writeFile(SETTINGS_FILE, JSON.stringify({ workers: [], tts }, null, 2));
+}
+await setTts({ engine: "espeak-ng", voice: "en-us", dir: CACHE, home: HOME });
+
+// Set before getPaths (which caches) is first reached through the imports.
+process.env.TRANSCRIPTS_DIR = CORPUS;
+process.env.SETTINGS_FILE = SETTINGS_FILE;
+process.env.TTS_BIN = shim;
+
+const {
+ TTS_FILE_BODY_KEYS,
+ TTS_MAX_CHARS,
+ TTS_RESULT_MARKER,
+ checkTtsRequest,
+ enqueueTtsFile,
+ parseTtsFileBody,
+ readTtsCacheHit,
+ resolveTtsRequest,
+ ttsCacheKey,
+} = await import("./ttsFile");
+const { getPaths } = await import("../lib/paths");
+const { getTtsEngine } = await import("../lib/ttsApps");
+const paths = getPaths();
+
+function has(bin: string, flag: string): boolean {
+ try {
+ execFileSync(bin, [flag], { stdio: "ignore" });
+ return true;
+ } catch {
+ return false;
+ }
+}
+const REAL = has("espeak-ng", "--version") && has("ffmpeg", "-version");
+const SKIP = !REAL && "espeak-ng or ffmpeg absent";
+
+async function engineRuns(): Promise<number> {
+ return (await readFile(RUNS, "utf8").catch(() => "")).split("\n").filter(Boolean).length;
+}
+
+// --- body ----------------------------------------------------------------------
+
+test("the body keys are the contract", () => {
+ assert.deepEqual([...TTS_FILE_BODY_KEYS], ["text", "file", "voice", "engine", "speed", "out"]);
+});
+
+test("the body's shape is judged before the disk", () => {
+ const bad: [Record<string, unknown>, RegExp][] = [
+ [{}, /"text" .* or "file" .* is required/],
+ [{ text: "a", file: "/x.txt" }, /not both/],
+ [{ text: " " }, /"text" must be a non-empty string/],
+ [{ text: 5 }, /"text" must be a non-empty string/],
+ [{ file: "rel.txt" }, /"file" must be an absolute path/],
+ [{ text: "a", voice: "" }, /"voice" must be a non-empty string/],
+ [{ text: "a", engine: 3 }, /"engine" must be a non-empty string/],
+ [{ text: "a", speed: "fast" }, /"speed" must be a number/],
+ [{ text: "a", out: "rel.wav" }, /"out" must be an absolute path/],
+ [{ text: "a", out: "/x/y.mp3" }, /"out" must name a \.wav file/],
+ ];
+ for (const [body, re] of bad) {
+ const r = parseTtsFileBody(body);
+ assert.equal(r.ok, false, JSON.stringify(body));
+ if (!r.ok) assert.match(r.error, re, JSON.stringify(body));
+ }
+ const ok = parseTtsFileBody({ text: "Hi.", voice: " bf_emma ", speed: 0.9, out: "/o/../o/a.WAV" });
+ assert.deepEqual(ok, { ok: true, value: { text: "Hi.", voice: "bf_emma", speed: 0.9, out: "/o/a.WAV" } });
+});
+
+test("the request resolves against settings.tts and the registry", () => {
+ const tts = { engine: "kokoro", voice: "af_heart", speed: 1 };
+ const r = resolveTtsRequest({}, "In 2024 <laugh> it ended.", tts);
+ assert.ok(r.ok);
+ if (r.ok) {
+ assert.equal(r.value.engine.id, "kokoro");
+ assert.equal(r.value.voice, "af_heart");
+ assert.equal(r.value.speed, 1);
+ assert.equal(r.value.spoken, "In twenty twenty-four it ended.");
+ }
+ // Another engine named in the body speaks with ITS default voice.
+ const e = resolveTtsRequest({ engine: "espeak-ng" }, "x", tts);
+ assert.ok(e.ok && e.value.voice === "en-us");
+ const refusals: [Parameters<typeof resolveTtsRequest>[0], string, RegExp][] = [
+ [{ engine: "piper" }, "x", /no text-to-speech engine "piper" — known: kokoro, espeak-ng/],
+ [{ voice: "someone" }, "x", /kokoro has no stock voice "someone" — its voices: af_alloy/],
+ [{ engine: "espeak-ng", voice: "af_heart" }, "x", /espeak-ng has no stock voice "af_heart"/],
+ [{ speed: 3 }, "x", /"speed" must be between 0.5 and 2 for kokoro \(got 3\)/],
+ [{}, "a".repeat(TTS_MAX_CHARS + 1), /at most 20000 — split it/],
+ [{}, "Well <lagh> then", /a tag no engine knows: <lagh>/],
+ [{}, "<sigh> <laugh>", /nothing to speak once its tags are removed/],
+ ];
+ for (const [body, text, re] of refusals) {
+ const x = resolveTtsRequest(body, text, tts);
+ assert.equal(x.ok, false);
+ if (!x.ok) assert.match(x.error, re);
+ }
+});
+
+test("the cache key follows engine, model, voice, speed and the spoken text", () => {
+ const k = getTtsEngine("kokoro")!;
+ const base = { engine: k, voice: "af_heart", speed: 1, spoken: "Hello." };
+ const sha = ttsCacheKey(base);
+ assert.match(sha, /^[0-9a-f]{64}$/);
+ assert.equal(ttsCacheKey({ ...base }), sha);
+ assert.notEqual(ttsCacheKey({ ...base, voice: "bf_emma" }), sha);
+ assert.notEqual(ttsCacheKey({ ...base, speed: 0.9 }), sha);
+ assert.notEqual(ttsCacheKey({ ...base, spoken: "Hello!" }), sha);
+ assert.notEqual(ttsCacheKey({ ...base, engine: { ...k, model: "kokoro-v1.1" } }), sha);
+ assert.notEqual(ttsCacheKey({ ...base, engine: getTtsEngine("espeak-ng")! }), sha);
+});
+
+test("the corpus fence and the install check answer before any job", async () => {
+ const k = resolveTtsRequest({ engine: "espeak-ng" }, "x", { engine: "kokoro", voice: "af_heart", speed: 1 });
+ assert.ok(k.ok);
+ if (!k.ok) return;
+ const ctx = { paths, cacheDir: CACHE, home: HOME };
+ const inCorpus = await checkTtsRequest({ ...k.value, out: path.join(CORPUS, "a.wav") }, ctx);
+ assert.ok(!inCorpus.ok && /"out" .* is inside the corpus/.test(inCorpus.error));
+ const cacheIn = await checkTtsRequest(k.value, { ...ctx, cacheDir: path.join(CORPUS, "tts") });
+ assert.ok(!cacheIn.ok && /synthesis cache .* is inside the corpus/.test(cacheIn.error));
+ const noDir = await checkTtsRequest({ ...k.value, out: path.join(ROOT, "nope", "a.wav") }, ctx);
+ assert.ok(!noDir.ok && /the directory .* does not exist/.test(noDir.error));
+ // Kokoro, with nothing installed under the home.
+ const kk = resolveTtsRequest({}, "x", { engine: "kokoro", voice: "af_heart", speed: 1 });
+ assert.ok(kk.ok);
+ if (!kk.ok) return;
+ const notInstalled = await checkTtsRequest(kk.value, ctx);
+ assert.ok(!notInstalled.ok);
+ if (!notInstalled.ok) {
+ assert.match(notInstalled.error, /Kokoro-82M is not installed \(.*tts-home\/kokoro\): missing the python venv/);
+ assert.match(notInstalled.error, /kokoro-v1\.0\.onnx; voices-v1\.0\.bin — run `archilyzer tts setup`/);
+ }
+});
+
+// --- whole jobs ----------------------------------------------------------------
+
+async function runJob(body: Record<string, unknown>) {
+ const res = await enqueueTtsFile(body, { paths });
+ if (!res.ok) return { error: res.error };
+ void res.stream.cancel();
+ const done = await res.done;
+ // `done` settles as the log stream is ENDED, not flushed: a job that runs
+ // no engine (a cache hit) can settle before its log reaches the disk.
+ const logFile = path.join(paths.jobsDir, `${res.jobId}.log`);
+ let log = "";
+ for (let i = 0; i < 100; i++) {
+ log = await readFile(logFile, "utf8").catch(() => "");
+ if (log.includes(TTS_RESULT_MARKER) || log.includes("[error]")) break;
+ await new Promise((r) => setTimeout(r, 20));
+ }
+ const line = log.split("\n").find((l) => l.startsWith(TTS_RESULT_MARKER));
+ return {
+ status: done.status,
+ log,
+ result: line ? JSON.parse(line.slice(TTS_RESULT_MARKER.length)) : null,
+ };
+}
+
+test("refusals through the job door start nothing", async () => {
+ assert.match((await runJob({ text: "x", engine: "kokoro" })).error!, /not installed/);
+ assert.match((await runJob({ text: "x", voice: "af_heart" })).error!, /espeak-ng has no stock voice/);
+ assert.match((await runJob({ file: path.join(ROOT, "missing.txt") })).error!, /does not exist/);
+ assert.match((await runJob({ text: "x", out: path.join(CORPUS, "x.wav") })).error!, /inside the corpus/);
+ assert.equal(await engineRuns(), 0);
+});
+
+test("a synthesis runs the engine once; the same ask again is a cached done job", { skip: SKIP }, async () => {
+ const first = await runJob({ text: "In 2024 <laugh> the archive spoke." });
+ assert.equal(first.status, "done", first.log);
+ const r = first.result;
+ assert.equal(r.engine, "espeak-ng");
+ assert.equal(r.voice, "en-us");
+ assert.equal(r.cached, false);
+ assert.equal(r.sampleRate, 48000);
+ assert.equal(r.speed, 1);
+ assert.match(r.sha, /^[0-9a-f]{64}$/);
+ assert.equal(r.wav, path.join(CACHE, `${r.sha}.wav`));
+ assert.ok(r.seconds > 0.5, String(r.seconds));
+ assert.ok(r.durationMs > 0);
+ assert.ok(r.waitedMs >= 0);
+ assert.equal(r.disclosure, "Narration: synthetic voice (eSpeak NG · en-us)");
+ assert.equal(await engineRuns(), 1);
+ // The engine got the spoken text: tags stripped, the year said.
+ const side = await readTtsCacheHit(CACHE, r.sha);
+ assert.ok(side);
+ assert.equal(side!.synthetic, true);
+ assert.equal(side!.text, "In twenty twenty-four the archive spoke.");
+ assert.equal(side!.license, "GPL-3.0-or-later");
+ assert.equal(side!.disclosure, r.disclosure);
+ const wav = await readFile(r.wav);
+ assert.equal(wav.readUInt32LE(24), 48000);
+ assert.equal(wav.readUInt16LE(22), 1);
+ // Nothing but the pair in the cache: the text file is gone.
+ assert.deepEqual((await readdir(CACHE)).sort(), [`${r.sha}.json`, `${r.sha}.wav`]);
+
+ // The same words re-wrapped, and the tag where it was: a hit, no engine run.
+ const again = await runJob({ text: "In 2024\n<laugh> the archive spoke." });
+ assert.equal(again.status, "done", again.log);
+ assert.equal(again.result.cached, true);
+ assert.equal(again.result.sha, r.sha);
+ assert.equal(again.result.wav, r.wav);
+ assert.equal(again.result.seconds, r.seconds);
+ assert.match(again.log!, /Cached: .* no engine run/);
+ assert.equal(await engineRuns(), 1);
+
+ // `out` gets a copy, and the result names it.
+ const out = path.join(OUTSIDE, "line.wav");
+ const copied = await runJob({ text: "In 2024 the archive spoke.", out });
+ assert.equal(copied.result.cached, true);
+ assert.equal(copied.result.wav, out);
+ assert.deepEqual(await readFile(out), wav);
+ assert.equal(await engineRuns(), 1);
+
+ // From a file, at another speed: a new synthesis.
+ const file = path.join(OUTSIDE, "script.txt");
+ await writeFile(file, "In 2024 the archive spoke.\n");
+ const slower = await runJob({ file, speed: 0.8 });
+ assert.equal(slower.status, "done", slower.log);
+ assert.equal(slower.result.cached, false);
+ assert.notEqual(slower.result.sha, r.sha);
+ assert.ok(slower.result.seconds > r.seconds, `${slower.result.seconds} vs ${r.seconds}`);
+ assert.equal(await engineRuns(), 2);
+
+ // Nothing landed in the corpus but the job logs.
+ assert.deepEqual((await readdir(CORPUS)).filter((n) => n !== ".jobs" && n !== "channels"), []);
+ assert.deepEqual(await readdir(path.join(CORPUS, "channels", "chan", "data")), []);
+});
+
+test("a failing engine fails the job with its words, and leaves no cache entry", async () => {
+ const before = (await readdir(CACHE).catch(() => [] as string[])).sort();
+ const runs = await engineRuns();
+ const run = await runJob({ text: "Please explode now." });
+ assert.equal(run.status, "failed");
+ assert.match(run.log!, /the espeak-ng synthesis failed: .*engine exploded/);
+ assert.equal(run.result, null);
+ assert.equal(await engineRuns(), runs + 1);
+ assert.deepEqual((await readdir(CACHE).catch(() => [] as string[])).sort(), before);
+});
diff --git a/common/controller/ttsFile.ts b/common/controller/ttsFile.ts
@@ -0,0 +1,535 @@
+// ONE TEXT-TO-SPEECH SYNTHESIS, AS AN EDITOR JOB — what `pnpm ops tts`
+// (`POST /api/ops/tts`) enqueues (release 25 T1). transcribeFile.ts's twin:
+// narration is never synthesized by hand, the way a quote check is never
+// transcribed by hand.
+//
+// THE BODY is `{text | file, voice?, engine?, speed?, out?}`: the text itself,
+// or an absolute path to a UTF-8 text file holding it; an engine and one of its
+// STOCK voices (ruled: no cloning, no reference audio — a voice is a name from
+// the registry, never a path), defaulting to settings.tts; a speed in the
+// engine's range; and `out`, an absolute `.wav` path the result is copied to.
+// Every refusal comes back before a job exists — an unknown engine or voice, a
+// tag no engine knows (`<lagh>` would be read aloud), an engine that is not
+// installed, an `out` or a cache dir inside the corpus.
+//
+// THE CACHE. sha256 of (engine, model, voice, speed, the NORMALIZED text — the
+// engine's own pre-pass, lib/ttsText.ts) names `<dir>/<sha>.wav` (48 kHz mono
+// 16-bit) and `<sha>.json`, the sidecar that discloses it (engine, model,
+// licence, voice, seconds, `synthetic: true`, the disclosure line). A request
+// whose pair is already there is a `done` job with `cached: true` that runs no
+// engine and waits on no queue. Anything else runs on the `tts` queue, one
+// synthesis at a time, and checks the cache again when its turn comes (a job
+// queued ahead of it may have made the same file).
+//
+// THE RESULT is logged as ONE line starting with TTS_RESULT_MARKER:
+// `{wav, seconds, engine, voice, cached, durationMs, waitedMs, sha, sampleRate,
+// speed, disclosure}`. `wav` is an absolute path this editor wrote: `out` when
+// given, else the cache file. `durationMs` is the engine's time (0-ish for a
+// hit); `waitedMs` the wait on the queue.
+//
+// WHAT IT TOUCHES: reads `file` (anywhere); writes the cache dir and `out`,
+// both refused inside the corpus (the transcripts dir, the saved-video store,
+// the sites dir, every storage location root — compared as written and through
+// symlinks, transcribeFile's fence). Never settings.json, never a channel.
+
+import { createHash, randomBytes } from "node:crypto";
+import path from "node:path";
+import { access, constants, mkdir, readFile, rm, stat, writeFile } from "node:fs/promises";
+import { execa } from "execa";
+import type { Paths } from "../lib/paths";
+import type { StorageLocation } from "../lib/storageLocations";
+import {
+ TTS_SAMPLE_RATE,
+ getTtsEngine,
+ ttsDisclosure,
+ ttsEngineIds,
+ ttsInstallDir,
+ type TtsEngine,
+} from "../lib/ttsApps";
+import { unknownTtsTagsError } from "../lib/ttsText";
+import { ttsInstallState } from "../lib/ttsInstall";
+import {
+ resolveTtsCacheDir,
+ resolveTtsHome,
+ type TtsSettings,
+} from "../lib/ttsSettings";
+import { TTS_QUEUE } from "../lib/queueKeys";
+import { copyFileAtomic, writeJsonAtomic } from "../lib/jsonFile-server";
+import { getSettings } from "../lib/settings";
+import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand";
+import { corpusRootContaining, corpusRoots, realpathDeep } from "./transcribeFile";
+
+export const TTS_FILE_JOB_KIND = "tts-file";
+
+// The log line carrying the result. One line, compact JSON after the marker.
+// scripts/archilyzer-ops.mjs matches the same string.
+export const TTS_RESULT_MARKER = "@@tts-result ";
+
+// The body `/api/ops/tts` accepts; anything else is a 400.
+export const TTS_FILE_BODY_KEYS = ["text", "file", "voice", "engine", "speed", "out"] as const;
+
+// The most text one synthesis takes, in characters (about 25 minutes of
+// speech). A longer script is several asks — which the cache then serves
+// piecewise when one paragraph changes.
+export const TTS_MAX_CHARS = 20_000;
+
+// The cache key's format version: a change to what goes into the key, or to
+// what the wrapper writes, bumps it.
+const CACHE_KEY_VERSION = "archilyzer-tts/1";
+
+type Check<T> = { ok: true; value: T } | { ok: false; error: string };
+
+// --- body --------------------------------------------------------------------
+
+export type TtsFileBody = {
+ text?: string;
+ file?: string;
+ voice?: string;
+ engine?: string;
+ speed?: number;
+ out?: string;
+};
+
+// The body's shape, judged without touching the disk. Every sentence here is
+// the refusal an ops caller reads.
+export function parseTtsFileBody(body: Record<string, unknown>): Check<TtsFileBody> {
+ const { text, file, voice, engine, speed, out } = body;
+ if (text !== undefined && file !== undefined) {
+ return { ok: false, error: 'give "text" or "file", not both' };
+ }
+ if (text === undefined && file === undefined) {
+ return { ok: false, error: '"text" (the words to speak) or "file" (an absolute path to a UTF-8 text file) is required' };
+ }
+ if (text !== undefined && (typeof text !== "string" || !text.trim())) {
+ return { ok: false, error: '"text" must be a non-empty string' };
+ }
+ if (file !== undefined) {
+ if (typeof file !== "string" || !file.trim()) {
+ return { ok: false, error: '"file" must be a non-empty string' };
+ }
+ if (!path.isAbsolute(file)) {
+ return { ok: false, error: `"file" must be an absolute path (got "${file}")` };
+ }
+ }
+ for (const [key, v] of [["voice", voice], ["engine", engine]] as const) {
+ if (v !== undefined && (typeof v !== "string" || !v.trim())) {
+ return { ok: false, error: `"${key}" must be a non-empty string` };
+ }
+ }
+ if (speed !== undefined && (typeof speed !== "number" || !Number.isFinite(speed))) {
+ return { ok: false, error: '"speed" must be a number (1 = the engine\'s natural pace)' };
+ }
+ if (out !== undefined) {
+ if (typeof out !== "string" || !out.trim()) {
+ return { ok: false, error: '"out" must be a non-empty string' };
+ }
+ if (!path.isAbsolute(out)) {
+ return { ok: false, error: `"out" must be an absolute path (got "${out}")` };
+ }
+ if (path.extname(out).toLowerCase() !== ".wav") {
+ return { ok: false, error: `"out" must name a .wav file (got "${out}")` };
+ }
+ }
+ return {
+ ok: true,
+ value: {
+ ...(typeof text === "string" ? { text } : {}),
+ ...(typeof file === "string" ? { file: path.resolve(file) } : {}),
+ ...(typeof voice === "string" ? { voice: voice.trim() } : {}),
+ ...(typeof engine === "string" ? { engine: engine.trim() } : {}),
+ ...(typeof speed === "number" ? { speed } : {}),
+ ...(typeof out === "string" ? { out: path.resolve(out) } : {}),
+ },
+ };
+}
+
+// --- the request, resolved -----------------------------------------------------
+
+export type TtsRequest = {
+ engine: TtsEngine;
+ voice: string;
+ speed: number;
+ // As given (from `text`, or read from `file`).
+ text: string;
+ // After the engine's pre-pass: what is spoken and what is keyed.
+ spoken: string;
+ file?: string;
+ out?: string;
+};
+
+// The body plus its text and settings.tts, resolved against the registry. Pure.
+export function resolveTtsRequest(
+ body: TtsFileBody,
+ text: string,
+ tts: Pick<TtsSettings, "engine" | "voice" | "speed">,
+): Check<TtsRequest> {
+ const engineId = body.engine ?? tts.engine;
+ const engine = getTtsEngine(engineId);
+ if (!engine) {
+ return { ok: false, error: `no text-to-speech engine "${engineId}" — known: ${ttsEngineIds().join(", ")}` };
+ }
+ // settings.tts.voice belongs to settings.tts.engine; another engine named in
+ // the body speaks with its own default.
+ const voice = body.voice ?? (engine.id === tts.engine ? tts.voice : engine.defaultVoice);
+ if (!engine.voices.includes(voice)) {
+ return {
+ ok: false,
+ error: `${engine.id} has no stock voice "${voice}" — its voices: ${engine.voices.join(", ")}`,
+ };
+ }
+ const speed = body.speed ?? tts.speed;
+ 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})` };
+ }
+ if (text.length > TTS_MAX_CHARS) {
+ return {
+ ok: false,
+ error: `the text is ${text.length} characters; one synthesis takes at most ${TTS_MAX_CHARS} — split it`,
+ };
+ }
+ const tagError = unknownTtsTagsError(text);
+ if (tagError) return { ok: false, error: tagError };
+ const spoken = engine.normalize(text);
+ if (!spoken) return { ok: false, error: "the text has nothing to speak once its tags are removed" };
+ return {
+ ok: true,
+ value: {
+ engine,
+ voice,
+ speed,
+ text,
+ spoken,
+ ...(body.file ? { file: body.file } : {}),
+ ...(body.out ? { out: body.out } : {}),
+ },
+ };
+}
+
+/** 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 disk checks -----------------------------------------------------------
+
+export type TtsFileContext = {
+ paths: Paths;
+ cacheDir: string;
+ home: string;
+ locations?: readonly Pick<StorageLocation, "root">[];
+};
+
+// The text a body names: `text` as given, or the file read. Refusals as sentences.
+export async function readTtsBodyText(body: TtsFileBody): Promise<Check<string>> {
+ if (body.text !== undefined) return { ok: true, value: body.text };
+ const file = body.file!;
+ let st;
+ try {
+ st = await stat(file);
+ } catch {
+ return { ok: false, error: `"file" ${file} does not exist` };
+ }
+ if (!st.isFile()) return { ok: false, error: `"file" ${file} is not a file` };
+ // Four bytes a character at most in UTF-8.
+ if (st.size > TTS_MAX_CHARS * 4) {
+ return { ok: false, error: `"file" ${file} is ${st.size} bytes; one synthesis takes at most ${TTS_MAX_CHARS} characters — split it` };
+ }
+ try {
+ await access(file, constants.R_OK);
+ const text = await readFile(file, "utf8");
+ if (!text.trim()) return { ok: false, error: `"file" ${file} is empty` };
+ return { ok: true, value: text };
+ } catch {
+ return { ok: false, error: `"file" ${file} is not readable` };
+ }
+}
+
+export async function checkTtsRequest(
+ req: TtsRequest,
+ ctx: TtsFileContext,
+): Promise<Check<TtsRequest>> {
+ const roots = corpusRoots(ctx.paths, ctx.locations ?? []);
+ const cacheRoot = await corpusRootContaining(ctx.cacheDir, roots);
+ if (cacheRoot) {
+ return {
+ ok: false,
+ error: `the synthesis cache ${ctx.cacheDir} (settings.tts.dir) is inside the corpus (${cacheRoot}) — set it outside`,
+ };
+ }
+ if (req.out !== undefined) {
+ const root = await corpusRootContaining(req.out, roots);
+ if (root) {
+ return {
+ ok: false,
+ error: `"out" ${req.out} is inside the corpus (${root}) — this command never writes there; pick a path outside it`,
+ };
+ }
+ if (req.file && (await realpathDeep(req.out)) === (await realpathDeep(req.file))) {
+ return { ok: false, error: '"out" is the input file itself' };
+ }
+ const outStat = await stat(req.out).catch(() => null);
+ if (outStat?.isDirectory()) {
+ return { ok: false, error: `"out" ${req.out} is a directory; name a file` };
+ }
+ const dirStat = await stat(path.dirname(req.out)).catch(() => null);
+ if (!dirStat?.isDirectory()) {
+ 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 });
+ if (!install.installed) {
+ return {
+ ok: false,
+ error:
+ `${req.engine.label} is not installed (${install.dir}): missing ${install.missing.join("; ")} — ` +
+ (req.engine.setup.kind === "system"
+ ? req.engine.setup.hint
+ : `run \`archilyzer tts setup${req.engine.id === "kokoro" ? "" : ` --engine ${req.engine.id}`}\``),
+ };
+ }
+ return { ok: true, value: req };
+}
+
+// --- the cache -----------------------------------------------------------------
+
+export type TtsSidecar = {
+ version: 1;
+ sha: string;
+ // Always true: the file is a synthetic voice, and says so.
+ synthetic: true;
+ disclosure: string;
+ engine: string;
+ engineLabel: string;
+ model: string;
+ license: string;
+ attribution?: string;
+ voice: string;
+ speed: number;
+ sampleRate: number;
+ seconds: number;
+ // The spoken (normalized) text.
+ text: string;
+ createdAt: string;
+ // The engine's time to make it.
+ durationMs: number;
+};
+
+export type TtsResult = {
+ wav: string;
+ seconds: number;
+ engine: string;
+ voice: string;
+ cached: boolean;
+ durationMs: number;
+ waitedMs: number;
+ sha: string;
+ sampleRate: number;
+ speed: number;
+ disclosure: string;
+};
+
+export function ttsCachePaths(cacheDir: string, sha: string): { wav: string; json: string } {
+ return { wav: path.join(cacheDir, `${sha}.wav`), json: path.join(cacheDir, `${sha}.json`) };
+}
+
+// The sidecar of a complete cache entry, or null: the WAV must be there with
+// audio in it, and the sidecar must parse and name the same sha.
+export async function readTtsCacheHit(cacheDir: string, sha: string): Promise<TtsSidecar | null> {
+ const p = ttsCachePaths(cacheDir, sha);
+ try {
+ const [wavStat, raw] = await Promise.all([stat(p.wav), readFile(p.json, "utf8")]);
+ if (!wavStat.isFile() || wavStat.size <= 44) return null;
+ const side = JSON.parse(raw) as TtsSidecar;
+ if (side?.sha !== sha || typeof side.seconds !== "number") return null;
+ return side;
+ } catch {
+ return null;
+ }
+}
+
+// --- the work ------------------------------------------------------------------
+
+type WrapperResult = { seconds?: number; sampleRate?: number; engineMs?: number };
+
+export type RunTtsOpts = {
+ paths: Paths;
+ req: TtsRequest;
+ sha: string;
+ cacheDir: string;
+ home: string;
+ onLog: (line: string) => void;
+ signal?: AbortSignal;
+};
+
+// 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> {
+ const { req, sha, cacheDir, paths, onLog } = opts;
+ 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();
+ 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.
+ const build = req.engine.build({
+ textFile,
+ outWav: target.wav,
+ voice: req.voice,
+ speed: req.speed,
+ installDir: ttsInstallDir(opts.home, req.engine),
+ bins: { ffmpegBin: paths.ffmpegBin, espeakNgBin: paths.espeakNgBin },
+ });
+ const child = execa(paths.ttsBin, build.argv, {
+ cancelSignal: opts.signal,
+ env: build.env,
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+ let pending = "";
+ child.stderr?.on("data", (c: Buffer) => {
+ pending += c.toString("utf8");
+ const lines = pending.split("\n");
+ pending = lines.pop() ?? "";
+ for (const l of lines) if (l.trim()) onLog(l.trimEnd());
+ });
+ let stdout: string;
+ try {
+ stdout = String((await child).stdout ?? "");
+ } catch (err) {
+ if (opts.signal?.aborted) throw err;
+ const e = err as { stderr?: string; shortMessage?: string; message: string };
+ const tail = String(e.stderr ?? "").trim().split("\n").slice(-2).join(" | ");
+ throw new Error(`the ${req.engine.id} synthesis failed: ${tail || e.shortMessage || e.message}`);
+ }
+ if (pending.trim()) onLog(pending.trimEnd());
+ let res: WrapperResult = {};
+ try {
+ res = JSON.parse(stdout.trim().split("\n").pop() ?? "{}") as WrapperResult;
+ } catch {
+ res = {};
+ }
+ const wavStat = await stat(target.wav).catch(() => null);
+ if (!wavStat || wavStat.size <= 44) {
+ throw new Error(`the ${req.engine.id} synthesis left no audio at ${target.wav}`);
+ }
+ const sampleRate = res.sampleRate ?? TTS_SAMPLE_RATE;
+ const sidecar: TtsSidecar = {
+ version: 1,
+ sha,
+ synthetic: true,
+ disclosure: ttsDisclosure(req.engine, req.voice),
+ engine: req.engine.id,
+ engineLabel: req.engine.label,
+ model: req.engine.model,
+ license: req.engine.license,
+ ...(req.engine.attribution ? { attribution: req.engine.attribution } : {}),
+ voice: req.voice,
+ speed: req.speed,
+ sampleRate,
+ seconds:
+ typeof res.seconds === "number"
+ ? res.seconds
+ : Math.round(((wavStat.size - 44) / (sampleRate * 2)) * 1000) / 1000,
+ text: req.spoken,
+ createdAt: new Date().toISOString(),
+ durationMs: Date.now() - started,
+ };
+ await writeJsonAtomic(target.json, sidecar, { indent: 2 });
+ return sidecar;
+ } finally {
+ await rm(textFile, { force: true }).catch(() => {});
+ }
+}
+
+function describe(req: TtsRequest): string {
+ const chars = req.spoken.length;
+ return `${chars} character${chars === 1 ? "" : "s"} with ${req.engine.id} · ${req.voice} at ${req.speed}x`;
+}
+
+// --- the job -------------------------------------------------------------------
+
+// Validate, then enqueue. Every refusal comes back as `{ ok: false, error }`
+// BEFORE a job exists, so the ops route answers it as a 400.
+export async function enqueueTtsFile(
+ body: Record<string, unknown>,
+ opts: { paths: Paths },
+): Promise<StreamActionResult> {
+ const parsed = parseTtsFileBody(body);
+ if (!parsed.ok) return parsed;
+ const text = await readTtsBodyText(parsed.value);
+ if (!text.ok) return text;
+ const settings = getSettings();
+ const resolved = resolveTtsRequest(parsed.value, text.value, settings.tts);
+ if (!resolved.ok) return resolved;
+ const home = resolveTtsHome(settings.tts, opts.paths);
+ const cacheDir = resolveTtsCacheDir(settings.tts, opts.paths);
+ const checked = await checkTtsRequest(resolved.value, {
+ paths: opts.paths,
+ cacheDir,
+ home,
+ locations: settings.storage?.locations ?? [],
+ });
+ if (!checked.ok) return checked;
+ const req = checked.value;
+ const sha = ttsCacheKey(req);
+ const hitAtEnqueue = await readTtsCacheHit(cacheDir, sha);
+ const asked = Date.now();
+ return runManagedFunction({
+ kind: TTS_FILE_JOB_KIND,
+ // A hit runs no engine: it does not wait behind one.
+ queueKey: hitAtEnqueue ? "" : TTS_QUEUE,
+ paths: opts.paths,
+ fn: async (onLog, signal) => {
+ const started = Date.now();
+ onLog(`Speak ${describe(req)}${req.file ? ` from ${req.file}` : ""}`);
+ // Again, at the job's turn: a job queued ahead may have made it.
+ let side = hitAtEnqueue ?? (await readTtsCacheHit(cacheDir, sha));
+ const cached = side !== null;
+ 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 });
+ 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"})`,
+ );
+ }
+ let wav = ttsCachePaths(cacheDir, sha).wav;
+ if (req.out) {
+ await copyFileAtomic(wav, req.out);
+ onLog(`Written to ${req.out}`);
+ wav = req.out;
+ }
+ const result: TtsResult = {
+ wav,
+ seconds: side.seconds,
+ engine: req.engine.id,
+ voice: req.voice,
+ cached,
+ durationMs: cached ? Date.now() - started : side.durationMs,
+ waitedMs: started - asked,
+ sha,
+ sampleRate: side.sampleRate,
+ speed: req.speed,
+ disclosure: side.disclosure,
+ };
+ onLog(`${TTS_RESULT_MARKER}${JSON.stringify(result)}`);
+ },
+ });
+}
diff --git a/common/jobs/jobKinds.test.ts b/common/jobs/jobKinds.test.ts
@@ -97,6 +97,8 @@ const ADDED_KINDS: Record<string, { label: string; drainable: boolean }> = {
"refresh-metadata": { label: "Refresh metadata", drainable: false },
// One file through a local worker (pnpm ops transcribe): one engine run.
"transcribe-file": { label: "Transcribe file", drainable: false },
+ // One synthesis (pnpm ops tts): one engine run, or a cache hit.
+ "tts-file": { label: "Text to speech", drainable: false },
};
test("added kinds carry their pinned label and drainability", () => {
diff --git a/common/jobs/jobKinds.ts b/common/jobs/jobKinds.ts
@@ -909,6 +909,21 @@ const JOB_KINDS: Record<string, JobKindMeta> = {
replayable: false,
queueKeyStrategy: "parallel",
},
+ // ONE TEXT-TO-SPEECH SYNTHESIS (release 25) — `pnpm ops tts`
+ // (controller/ttsFile.ts). No channel: it reads the text (or a text file)
+ // it was given and writes only to the synthesis cache and the caller's
+ // `out`, never into the corpus, so neither guard applies. On the `tts`
+ // queue (TTS_QUEUE), one at a time; a cache hit runs unqueued and starts no
+ // engine. Not an ingest kind: nothing the index reads changes. One engine
+ // run — cancelled, not drained; not replayable (the caller asks again, and
+ // the cache answers).
+ "tts-file": {
+ kind: "tts-file",
+ label: "Text to speech",
+ drainable: false,
+ replayable: false,
+ queueKeyStrategy: "custom",
+ },
"download-one-pipeline": {
kind: "download-one-pipeline",
drainable: false,
diff --git a/common/lib/envVars.ts b/common/lib/envVars.ts
@@ -74,6 +74,8 @@ const DECLARED: EnvVarDecl[] = [
paths("PARAKEET_CLI", "`parakeet-cli` on PATH", "The parakeet.cpp binary the wrapper drives (the wrapper reads it too)."),
paths("PARAKEET_MODEL", "none", "parakeet.cpp's `.gguf`, when a worker names none (the wrapper reads it too)."),
paths("DIARIZE_BIN", "`<repo>/scripts/diarize.mjs`", "The speaker-diarization wrapper. The e2e suite swaps in a fake here."),
+ paths("TTS_BIN", "`<repo>/scripts/tts.mjs`", "The text-to-speech wrapper (text in, 48 kHz WAV out) every engine runs behind. A test swaps in a fake here."),
+ paths("ESPEAK_NG_BIN", "`espeak-ng` on PATH", "eSpeak NG, the zero-install text-to-speech engine (the wrapper reads it too)."),
paths("RSYNC_BIN", "`rsync` on PATH", "Mirrors the saved-video store to a backup destination."),
paths("FINDMNT_BIN", "`findmnt` on PATH", "The read-only volume-identity probe behind storage locations. Optional."),
paths("UDISKSCTL_BIN", "`udisksctl` on PATH", "Mounts an attached volume from `/storage`. Optional."),
diff --git a/common/lib/paths.ts b/common/lib/paths.ts
@@ -152,6 +152,16 @@ export type Paths = {
// parakeetBin is. Overridable via DIARIZE_BIN — which is also how the e2e
// suite swaps in a fake diarizer.
diarizeBin: string;
+ // Text-to-speech (release 25): the wrapper every engine runs behind
+ // (scripts/tts.mjs, TTS_BIN — how a test swaps in a fake), espeak-ng (the
+ // zero-install engine), and the two defaults settings.tts falls back to when
+ // its `home`/`dir` are blank: where `archilyzer tts setup` installs engines
+ // (`<ttsHome>/<engine id>`, outside the checkout) and the synthesis cache
+ // (`<repo>/.tts/cache`, gitignored; never inside the corpus).
+ ttsBin: string;
+ espeakNgBin: string;
+ ttsHome: string;
+ ttsCacheDir: string;
// Base URL of the local ollama server, the local-GPU digest lane
// (common/lib/digestApps.ts posts to `${ollamaUrl}/api/chat`). The FIRST
// URL-valued entry in Paths, so it is normalized here the way
@@ -299,6 +309,10 @@ export function getPaths(): Paths {
diarizeBin:
process.env.DIARIZE_BIN ??
under(monorepoRoot, "scripts", "diarize.mjs"),
+ ttsBin: process.env.TTS_BIN ?? under(monorepoRoot, "scripts", "tts.mjs"),
+ espeakNgBin: process.env.ESPEAK_NG_BIN ?? "espeak-ng",
+ ttsHome: path.join(os.homedir(), ".local", "share", "archilyzer", "tts"),
+ ttsCacheDir: under(monorepoRoot, ".tts", "cache"),
ollamaUrl: (process.env.OLLAMA_URL ?? "http://127.0.0.1:11434").replace(
/\/+$/,
"",
diff --git a/common/lib/queueKeys.ts b/common/lib/queueKeys.ts
@@ -34,6 +34,13 @@ export const BACKFILL_QUEUE = "backfill";
// corpus-wide — jobs/snapshotScheduler.ts says why (release 17 slice D0).
export const REFRESH_REPORT_QUEUE = "refresh-report";
+// Every text-to-speech synthesis (`pnpm ops tts`, controller/ttsFile.ts), one
+// at a time machine-wide (release 25). Its own key, not TRANSCRIPTION_QUEUE: a
+// CPU engine contends with nothing the worker pool hands out, and a synthesis
+// must never wait behind a corpus transcription. One at a time because Kokoro
+// takes every core and ~1 GB; two at once only thrash.
+export const TTS_QUEUE = "tts";
+
// Per-channel queue for channel-local bookkeeping jobs (clean/clear/verify).
export function channelQueueKey(slug: string): string {
return `channel:${slug}`;
diff --git a/common/lib/settingsDocs.ts b/common/lib/settingsDocs.ts
@@ -22,6 +22,7 @@ import {
DIGEST_SETTINGS_FIELD_DOCS,
SAVED_VIDEO_BACKUP_SETTINGS_FIELD_DOCS,
SEEDER_SETTINGS_FIELD_DOCS,
+ TTS_SETTINGS_FIELD_DOCS,
SOCIAL_LINK_FIELD_DOCS,
SOCIAL_SETTINGS_FIELD_DOCS,
X_SOCIAL_SETTINGS_FIELD_DOCS,
@@ -260,6 +261,13 @@ export function blockTables(d: SiteSettings): Partial<Record<keyof SiteSettings,
defaults: fromObject(d.seeder),
},
],
+ tts: [
+ {
+ path: "tts",
+ docs: TTS_SETTINGS_FIELD_DOCS,
+ defaults: fromObject(d.tts),
+ },
+ ],
};
}
diff --git a/common/lib/settingsSchema.test.ts b/common/lib/settingsSchema.test.ts
@@ -31,6 +31,7 @@ import type {
import type { StorageSettings } from "./storageLocations";
import type { ArchiveOrgFetchSettings } from "./archiveOrgTorrent";
import type { SeederSettings } from "./seederSettings";
+import type { TtsSettings } from "./ttsSettings";
import type {
AttributionSettings,
BackfillSettings,
@@ -106,13 +107,15 @@ type PreSchemaSiteSettings = {
publish: PublishSettings;
// The home seeder of last resort (release 21 D4b).
seeder: SeederSettings;
+ // Local text-to-speech (release 25 T1).
+ tts: TtsSettings;
};
// Bracketed so the conditional does not distribute (see commit 8c43231).
type Same<A, B> = [A] extends [B] ? ([B] extends [A] ? true : false) : false;
const shapeUnchanged: Same<SiteSettings, PreSchemaSiteSettings> = true;
-test("SiteSettings keeps its 37 fields, in file order", () => {
+test("SiteSettings keeps its 38 fields, in file order", () => {
assert.equal(shapeUnchanged, true);
assert.deepEqual(Object.keys(siteSettingsSchema.shape), [
"adminTitle",
@@ -152,6 +155,7 @@ test("SiteSettings keeps its 37 fields, in file order", () => {
"archiveOrg",
"publish",
"seeder",
+ "tts",
]);
// A parsed object carries every key, in that order — writeSettings writes
// exactly this, so the order is the on-disk order.
diff --git a/common/lib/settingsSchema.ts b/common/lib/settingsSchema.ts
@@ -78,6 +78,8 @@ import {
} from "./archiveOrgTorrent";
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";
import {
DEFAULT_COOKIE_MODE,
isCookieMode,
@@ -1827,6 +1829,9 @@ export const siteSettingsSchema = z.object({
seeder: settingsField((v): SeederSettings => sanitizeSeeder(v)).describe(
"The home seeder of last resort (release 21): `archilyzer seed` seeds the sites' playable torrents (`archilyzer media playable`), each one only while no other seeder has it, and only behind a VPN (the docker profile `seeder`, docker-compose.seeder.yml). Not configured until `sites` names one. See SeederSettings and common/controller/seeder.ts.",
),
+ tts: settingsField((v): TtsSettings => sanitizeTts(v)).describe(
+ "Local text-to-speech (release 25): narration for report videos and podcasts, synthesized as an editor job (`pnpm ops tts`, the `tts` queue, one at a time) with a STOCK voice — never a cloned one — and cached by content. The default engine is Kokoro-82M with the voice `af_heart`, installed by `archilyzer tts setup`; espeak-ng needs no install. Every synthesis is disclosed as a synthetic voice (its sidecar and the result's `disclosure`). See TtsSettings and common/controller/ttsFile.ts.",
+ ),
});
export type SiteSettings = z.infer<typeof siteSettingsSchema>;
diff --git a/common/lib/ttsApps.test.ts b/common/lib/ttsApps.test.ts
@@ -0,0 +1,108 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import {
+ DEFAULT_TTS_ENGINE_ID,
+ DEFAULT_TTS_VOICE,
+ KOKORO_FILES,
+ TTS_ENGINES,
+ getTtsEngine,
+ listTtsEngines,
+ ttsDisclosure,
+ ttsEngineIds,
+ ttsInstallDir,
+ ttsVenvPython,
+} from "./ttsApps";
+
+// 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"]);
+ assert.equal(DEFAULT_TTS_ENGINE_ID, "kokoro");
+ assert.equal(DEFAULT_TTS_VOICE, "af_heart");
+ assert.equal(getTtsEngine("kokoro")!.defaultVoice, "af_heart");
+ // A typo is not silently the default.
+ assert.equal(getTtsEngine("kokoro2"), undefined);
+ assert.equal(getTtsEngine(undefined), undefined);
+ for (const e of Object.values(TTS_ENGINES)) {
+ 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.deepEqual(
+ listTtsEngines().map((e) => [e.id, e.defaultVoice]),
+ [["kokoro", "af_heart"], ["espeak-ng", "en-us"]],
+ );
+});
+
+test("Kokoro offers its English stock voices only, and pins its model files", () => {
+ const k = getTtsEngine("kokoro")!;
+ assert.equal(k.voices.length, 28);
+ assert.ok(k.voices.every((v) => /^[ab][fm]_[a-z]+$/.test(v)), k.voices.join(" "));
+ assert.deepEqual(KOKORO_FILES.map((f) => f.name), ["kokoro-v1.0.onnx", "voices-v1.0.bin"]);
+ for (const f of KOKORO_FILES) {
+ assert.match(f.sha256, /^[0-9a-f]{64}$/);
+ assert.ok(f.bytes > 1_000_000);
+ assert.ok(f.url.startsWith("https://github.com/thewh1teagle/kokoro-onnx/releases/download/model-files-v1.0/"));
+ assert.ok(f.url.endsWith(`/${f.name}`));
+ }
+ assert.equal(k.setup.kind, "python-venv");
+ if (k.setup.kind === "python-venv") assert.deepEqual(k.setup.packages, ["kokoro-onnx==0.6.1"]);
+});
+
+test("each engine builds the wrapper's command line from its install dir", () => {
+ const home = "/h/tts";
+ const k = getTtsEngine("kokoro")!;
+ const dir = ttsInstallDir(home, k);
+ assert.equal(dir, "/h/tts/kokoro");
+ assert.equal(ttsVenvPython(dir), "/h/tts/kokoro/venv/bin/python");
+ const kb = k.build({ textFile: "/c/x.txt", outWav: "/c/x.wav", voice: "bf_emma", speed: 0.9, installDir: dir, bins: BINS });
+ assert.deepEqual(kb.argv, [
+ "--engine-kind", "kokoro",
+ "--python", "/h/tts/kokoro/venv/bin/python",
+ "--model", "/h/tts/kokoro/kokoro-v1.0.onnx",
+ "--voices", "/h/tts/kokoro/voices-v1.0.bin",
+ "--voice", "bf_emma",
+ "--speed", "0.9",
+ "--ffmpeg", "/bin/ffmpeg",
+ "--output", "/c/x.wav",
+ "/c/x.txt",
+ ]);
+ const e = getTtsEngine("espeak-ng")!;
+ const eb = e.build({ textFile: "/c/y.txt", outWav: "/c/y.wav", voice: "en-gb", speed: 1, installDir: ttsInstallDir(home, e), bins: BINS });
+ assert.deepEqual(eb.argv, [
+ "--engine-kind", "espeak-ng",
+ "--espeak", "/bin/espeak-ng",
+ "--voice", "en-gb",
+ "--speed", "1",
+ "--ffmpeg", "/bin/ffmpeg",
+ "--output", "/c/y.wav",
+ "/c/y.txt",
+ ]);
+});
+
+test("both engines strip the expressive tags and speak years", () => {
+ for (const id of ttsEngineIds()) {
+ assert.equal(
+ getTtsEngine(id)!.normalize("Back in 1999 <laugh> we said\nso."),
+ "Back in nineteen ninety-nine we said so.",
+ id,
+ );
+ }
+});
+
+test("the disclosure names the engine and voice, plus any attribution its licence asks for", () => {
+ assert.equal(
+ ttsDisclosure(getTtsEngine("kokoro")!, "af_heart"),
+ "Narration: synthetic voice (Kokoro-82M · af_heart)",
+ );
+ assert.equal(
+ ttsDisclosure({ label: "Some Engine", attribution: "Built with Something." }, "v1"),
+ "Narration: synthetic voice (Some Engine · v1). Built with Something.",
+ );
+});
diff --git a/common/lib/ttsApps.ts b/common/lib/ttsApps.ts
@@ -0,0 +1,246 @@
+// THE TEXT-TO-SPEECH ENGINE REGISTRY (release 25 T1) — transcriptionApps.ts's
+// twin for the other direction.
+//
+// Each engine owns: what it is (label, the model identity that goes into the
+// cache key, its licence, any attribution line its licence asks for), which
+// voices it has (a fixed list of the engine's STOCK voices — ruled: no voice
+// cloning, no reference audio, so a voice is never a path), its text pre-pass
+// (`normalize`, built from the shared lib/ttsText.ts), how it is installed
+// (`setup`, read by `archilyzer tts setup` and the doctor), and the argv/env
+// it gives the dual-use wrapper `scripts/tts.mjs` (paths.ttsBin), which runs
+// the engine and leaves a 48 kHz mono 16-bit WAV at `--output`.
+//
+// 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
+// (Llama 3.2: "Built with Llama"); ttsDisclosure appends it.
+
+import path from "node:path";
+import { normalizeTtsText } from "./ttsText";
+
+export type TtsDevice = "cpu" | "gpu";
+
+// A file `archilyzer tts setup` downloads once, verified by size and sha256.
+export type TtsModelFile = {
+ name: string;
+ url: string;
+ bytes: number;
+ sha256: string;
+};
+
+export type TtsSetup =
+ // A python venv at `<home>/<engine>/venv` with pinned packages, plus model
+ // files beside it. `python` is the interpreter version the venv is made with
+ // when `uv` is available (else the `--python` given, else python3).
+ | {
+ kind: "python-venv";
+ python: string;
+ packages: readonly string[];
+ // The module whose import proves the install (`--check`).
+ importName: string;
+ files: readonly TtsModelFile[];
+ }
+ // A system binary (paths.<bin>), nothing to install.
+ | { kind: "system"; bin: "espeakNgBin"; hint: string };
+
+export type TtsBuildInput = {
+ textFile: string;
+ outWav: string;
+ voice: string;
+ speed: number;
+ // 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.
+ server?: string;
+};
+
+export type TtsBuild = {
+ // Args to paths.ttsBin (scripts/tts.mjs).
+ argv: string[];
+ env?: Record<string, string>;
+};
+
+export type TtsEngine = {
+ id: string;
+ label: string;
+ // The weights' identity, IN THE CACHE KEY: a new model is a new key.
+ model: string;
+ license: string;
+ // A sentence the engine's licence asks to be shown with the disclosure.
+ attribution?: string;
+ device: TtsDevice;
+ runtime: "process" | "server";
+ voices: readonly string[];
+ defaultVoice: string;
+ // Lowest/highest speed the engine accepts (1 = its natural pace).
+ speedRange: readonly [number, number];
+ normalize: (text: string) => string;
+ setup: TtsSetup;
+ build: (input: TtsBuildInput) => TtsBuild;
+};
+
+// The wrapper always writes this.
+export const TTS_SAMPLE_RATE = 48_000;
+
+// --- kokoro ------------------------------------------------------------------
+
+// Kokoro-82M v1.0's English stock voices: `a*` American (en-us), `b*` British
+// (en-gb). The voices file holds other languages too; the pre-pass and the
+// phonemizer here are English, so those are not offered.
+export const KOKORO_VOICES = [
+ "af_alloy", "af_aoede", "af_bella", "af_heart", "af_jessica", "af_kore",
+ "af_nicole", "af_nova", "af_river", "af_sarah", "af_sky",
+ "am_adam", "am_echo", "am_eric", "am_fenrir", "am_liam", "am_michael",
+ "am_onyx", "am_puck", "am_santa",
+ "bf_alice", "bf_emma", "bf_isabella", "bf_lily",
+ "bm_daniel", "bm_fable", "bm_george", "bm_lewis",
+] as const;
+
+const KOKORO_RELEASE =
+ "https://github.com/thewh1teagle/kokoro-onnx/releases/download/model-files-v1.0";
+
+export const KOKORO_FILES: readonly TtsModelFile[] = [
+ {
+ name: "kokoro-v1.0.onnx",
+ url: `${KOKORO_RELEASE}/kokoro-v1.0.onnx`,
+ bytes: 325_532_387,
+ sha256: "7d5df8ecf7d4b1878015a32686053fd0eebe2bc377234608764cc0ef3636a6c5",
+ },
+ {
+ name: "voices-v1.0.bin",
+ url: `${KOKORO_RELEASE}/voices-v1.0.bin`,
+ bytes: 28_214_398,
+ sha256: "bca610b8308e8d99f32e6fe4197e7ec01679264efed0cac9140fe9c29f1fbf7d",
+ },
+];
+
+/** The venv's interpreter under an engine's install dir. */
+export function ttsVenvPython(installDir: string): string {
+ return path.join(installDir, "venv", "bin", "python");
+}
+
+const kokoro: TtsEngine = {
+ id: "kokoro",
+ label: "Kokoro-82M",
+ model: "kokoro-v1.0 (fp32 onnx, kokoro-onnx 0.6.1)",
+ license: "Apache-2.0",
+ device: "cpu",
+ runtime: "process",
+ voices: KOKORO_VOICES,
+ defaultVoice: "af_heart",
+ speedRange: [0.5, 2],
+ normalize: (text) => normalizeTtsText(text, { tags: "strip", years: true }),
+ setup: {
+ kind: "python-venv",
+ python: "3.12",
+ packages: ["kokoro-onnx==0.6.1"],
+ importName: "kokoro_onnx",
+ files: KOKORO_FILES,
+ },
+ build: ({ textFile, outWav, voice, speed, installDir, bins }) => ({
+ argv: [
+ "--engine-kind", "kokoro",
+ "--python", ttsVenvPython(installDir),
+ "--model", path.join(installDir, KOKORO_FILES[0].name),
+ "--voices", path.join(installDir, KOKORO_FILES[1].name),
+ "--voice", voice,
+ "--speed", String(speed),
+ "--ffmpeg", bins.ffmpegBin,
+ "--output", outWav,
+ textFile,
+ ],
+ }),
+};
+
+// --- espeak-ng ---------------------------------------------------------------
+
+// The zero-install fallback: a formant synthesizer every Linux has, robotic
+// and unmistakably synthetic. What the tests run, and what a machine without
+// `tts setup` can still use.
+const espeakNg: TtsEngine = {
+ id: "espeak-ng",
+ label: "eSpeak NG",
+ model: "espeak-ng (formant)",
+ license: "GPL-3.0-or-later",
+ device: "cpu",
+ runtime: "process",
+ voices: ["en-us", "en-gb", "en"],
+ defaultVoice: "en-us",
+ speedRange: [0.5, 2],
+ normalize: (text) => normalizeTtsText(text, { tags: "strip", years: true }),
+ setup: { kind: "system", bin: "espeakNgBin", hint: "install espeak-ng from the system's packages" },
+ build: ({ textFile, outWav, voice, speed, bins }) => ({
+ argv: [
+ "--engine-kind", "espeak-ng",
+ "--espeak", bins.espeakNgBin,
+ "--voice", voice,
+ "--speed", String(speed),
+ "--ffmpeg", bins.ffmpegBin,
+ "--output", outWav,
+ textFile,
+ ],
+ }),
+};
+
+export const TTS_ENGINES: Record<string, TtsEngine> = {
+ [kokoro.id]: kokoro,
+ [espeakNg.id]: espeakNg,
+};
+
+export const DEFAULT_TTS_ENGINE_ID = "kokoro";
+export const DEFAULT_TTS_VOICE = "af_heart";
+
+export function ttsEngineIds(): string[] {
+ return Object.keys(TTS_ENGINES);
+}
+
+/** The engine with this id, or undefined (never a silent fallback: a typo is refused). */
+export function getTtsEngine(id: string | undefined): TtsEngine | undefined {
+ return id ? TTS_ENGINES[id] : undefined;
+}
+
+/** `<home>/<engine id>`: where an engine is installed. */
+export function ttsInstallDir(home: string, engine: Pick<TtsEngine, "id">): string {
+ return path.join(home, engine.id);
+}
+
+/** The disclosure line a narrated export carries for a synthesis. */
+export function ttsDisclosure(engine: Pick<TtsEngine, "label" | "attribution">, voice: string): string {
+ const line = `Narration: synthetic voice (${engine.label} · ${voice})`;
+ return engine.attribution ? `${line}. ${engine.attribution}` : line;
+}
+
+// A client-safe view (no functions).
+export type TtsEngineDescriptor = {
+ id: string;
+ label: string;
+ license: string;
+ device: TtsDevice;
+ voices: readonly string[];
+ defaultVoice: string;
+};
+
+export function listTtsEngines(): TtsEngineDescriptor[] {
+ return Object.values(TTS_ENGINES).map((e) => ({
+ id: e.id,
+ label: e.label,
+ license: e.license,
+ device: e.device,
+ voices: e.voices,
+ defaultVoice: e.defaultVoice,
+ }));
+}
diff --git a/common/lib/ttsInstall.ts b/common/lib/ttsInstall.ts
@@ -0,0 +1,76 @@
+// IS A TEXT-TO-SPEECH ENGINE INSTALLED? (release 25 T1)
+//
+// One answer, read by three callers: controller/ttsFile.ts refuses a synthesis
+// for an engine that is not (a 400 naming `archilyzer tts setup`, before any
+// job exists), `archilyzer doctor` reports it, and `archilyzer tts setup
+// --check` lists what is missing. Presence only — the venv's interpreter and
+// each model file at its pinned size; setup's `--check` goes further and
+// imports the package. Read-only: never creates anything.
+
+import fs from "node:fs";
+import path from "node:path";
+import type { Paths } from "./paths";
+import { ttsInstallDir, ttsVenvPython, type TtsEngine } from "./ttsApps";
+
+export type TtsInstallState = {
+ engine: string;
+ // `<home>/<engine id>`, or the system binary for a `system` engine.
+ dir: string;
+ installed: boolean;
+ // One line per missing piece, in words.
+ missing: string[];
+};
+
+// A binary named without a slash, looked up on PATH; with one, as a path.
+export function findOnPath(bin: string, envPath: string | undefined = process.env.PATH): string | null {
+ const isExec = (p: string) => {
+ try {
+ const st = fs.statSync(p);
+ if (!st.isFile()) return false;
+ fs.accessSync(p, fs.constants.X_OK);
+ return true;
+ } catch {
+ return false;
+ }
+ };
+ if (bin.includes("/")) return isExec(bin) ? bin : null;
+ for (const dir of (envPath ?? "").split(path.delimiter)) {
+ if (!dir) continue;
+ const p = path.join(dir, bin);
+ if (isExec(p)) return p;
+ }
+ return null;
+}
+
+export function ttsInstallState(
+ engine: TtsEngine,
+ opts: { home: string; paths: Pick<Paths, "espeakNgBin">; envPath?: string },
+): TtsInstallState {
+ const setup = engine.setup;
+ if (setup.kind === "system") {
+ const bin = opts.paths[setup.bin];
+ const found = findOnPath(bin, opts.envPath ?? process.env.PATH);
+ return {
+ engine: engine.id,
+ dir: found ?? bin,
+ installed: found !== null,
+ missing: found ? [] : [`${bin} is not on PATH — ${setup.hint}`],
+ };
+ }
+ const dir = ttsInstallDir(opts.home, engine);
+ const missing: string[] = [];
+ const python = ttsVenvPython(dir);
+ if (!fs.existsSync(python)) missing.push(`the python venv (${python})`);
+ for (const f of setup.files) {
+ const p = path.join(dir, f.name);
+ let size: number | null = null;
+ try {
+ size = fs.statSync(p).size;
+ } catch {
+ size = null;
+ }
+ if (size === null) missing.push(`${f.name}`);
+ else if (size !== f.bytes) missing.push(`${f.name} (${size} bytes, expected ${f.bytes})`);
+ }
+ return { engine: engine.id, dir, installed: missing.length === 0, missing };
+}
diff --git a/common/lib/ttsSettings.test.ts b/common/lib/ttsSettings.test.ts
@@ -0,0 +1,37 @@
+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 { 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(sanitizeTts(undefined), DEFAULT_TTS_SETTINGS);
+ assert.deepEqual(sanitizeTts("nonsense"), DEFAULT_TTS_SETTINGS);
+});
+
+test("an unknown engine or a voice the engine lacks falls back; speed is clamped", () => {
+ assert.equal(sanitizeTts({ engine: "piper" }).engine, "kokoro");
+ assert.deepEqual(sanitizeTts({ engine: "espeak-ng" }), { ...DEFAULT_TTS_SETTINGS, engine: "espeak-ng", voice: "en-us" });
+ assert.equal(sanitizeTts({ engine: "espeak-ng", voice: "en-gb" }).voice, "en-gb");
+ assert.equal(sanitizeTts({ voice: "bm_george" }).voice, "bm_george");
+ assert.equal(sanitizeTts({ voice: "someone_real" }).voice, "af_heart");
+ assert.equal(sanitizeTts({ speed: 0.1 }).speed, 0.5);
+ assert.equal(sanitizeTts({ speed: 9 }).speed, 2);
+ assert.equal(sanitizeTts({ speed: 0.904 }).speed, 0.9);
+ assert.equal(sanitizeTts({ speed: "fast" }).speed, 1);
+});
+
+test("home and dir: blank is the Paths default, ~/ expands, a relative path is dropped", () => {
+ const paths = { ttsHome: "/d/home", ttsCacheDir: "/d/cache" };
+ assert.equal(resolveTtsHome(sanitizeTts({}), paths), "/d/home");
+ assert.equal(resolveTtsCacheDir(sanitizeTts({}), paths), "/d/cache");
+ assert.equal(resolveTtsHome(sanitizeTts({ home: "/opt/tts" }), paths), "/opt/tts");
+ assert.equal(resolveTtsCacheDir(sanitizeTts({ dir: "~/tts-cache" }), paths), path.join(os.homedir(), "tts-cache"));
+ assert.equal(sanitizeTts({ dir: "relative/cache" }).dir, "");
+ assert.equal(sanitizeTts({ home: 7 }).home, "");
+});
diff --git a/common/lib/ttsSettings.ts b/common/lib/ttsSettings.ts
@@ -0,0 +1,90 @@
+// settings.tts — local text-to-speech (release 25 T1).
+//
+// Pure: the type, its defaults, the sanitizer settingsSchema.ts runs it
+// through, the per-field docs SETTINGS.md renders, and the two resolvers that
+// turn a blank `home`/`dir` into the defaults on Paths. The engines are
+// lib/ttsApps.ts; a synthesis is controller/ttsFile.ts (`pnpm ops tts`).
+
+import os from "node:os";
+import path from "node:path";
+import type { FieldDocs } from "./fieldDocs";
+import type { Paths } from "./paths";
+import { DEFAULT_TTS_ENGINE_ID, DEFAULT_TTS_VOICE, getTtsEngine } from "./ttsApps";
+
+export type TtsSettings = {
+ engine: string;
+ voice: string;
+ speed: number;
+ home: string;
+ dir: string;
+};
+
+export const DEFAULT_TTS_SETTINGS: TtsSettings = {
+ engine: DEFAULT_TTS_ENGINE_ID,
+ voice: DEFAULT_TTS_VOICE,
+ speed: 1,
+ home: "",
+ dir: "",
+};
+
+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`.",
+ 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 " +
+ "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.",
+ 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.",
+};
+
+// "" (the default), an absolute path, or a `~/` one; anything else is "".
+function dirSetting(value: unknown): string {
+ if (typeof value !== "string") return "";
+ const s = value.trim();
+ if (s === "" || path.isAbsolute(s) || s.startsWith("~/")) return s;
+ return "";
+}
+
+export function sanitizeTts(value: unknown): TtsSettings {
+ const d = DEFAULT_TTS_SETTINGS;
+ const r = value && typeof value === "object" ? (value as Record<string, unknown>) : {};
+ const engine = getTtsEngine(typeof r.engine === "string" ? r.engine.trim() : undefined)
+ ?? getTtsEngine(d.engine)!;
+ const voice =
+ 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) };
+}
+
+function expand(p: string): string {
+ return p.startsWith("~/") ? path.join(os.homedir(), p.slice(2)) : path.resolve(p);
+}
+
+/** Where engines are installed: settings.tts.home, else paths.ttsHome. */
+export function resolveTtsHome(tts: Pick<TtsSettings, "home">, paths: Pick<Paths, "ttsHome">): string {
+ return tts.home ? expand(tts.home) : paths.ttsHome;
+}
+
+/** The synthesis cache: settings.tts.dir, else paths.ttsCacheDir. */
+export function resolveTtsCacheDir(tts: Pick<TtsSettings, "dir">, paths: Pick<Paths, "ttsCacheDir">): string {
+ return tts.dir ? expand(tts.dir) : paths.ttsCacheDir;
+}
diff --git a/common/lib/ttsText.test.ts b/common/lib/ttsText.test.ts
@@ -0,0 +1,132 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import {
+ TTS_EXPRESSIVE_TAGS,
+ collapseTtsWhitespace,
+ normalizeTtsText,
+ speakYears,
+ stripTtsTags,
+ twoDigitWords,
+ unknownTtsTags,
+ unknownTtsTagsError,
+ yearWords,
+} from "./ttsText";
+
+// Run with:
+// pnpm --filter yt-dlp-transcript-common exec tsx --test lib/ttsText.test.ts
+
+test("years are written out the way they are said", () => {
+ const cases: [number, string][] = [
+ [1900, "nineteen hundred"],
+ [1901, "nineteen oh one"],
+ [1909, "nineteen oh nine"],
+ [1910, "nineteen ten"],
+ [1984, "nineteen eighty-four"],
+ [1999, "nineteen ninety-nine"],
+ [2000, "two thousand"],
+ [2001, "two thousand one"],
+ [2005, "two thousand five"],
+ [2009, "two thousand nine"],
+ [2010, "twenty ten"],
+ [2019, "twenty nineteen"],
+ [2024, "twenty twenty-four"],
+ [2099, "twenty ninety-nine"],
+ ];
+ for (const [y, words] of cases) assert.equal(yearWords(y), words, String(y));
+ assert.equal(yearWords(1990, true), "nineteen nineties");
+ assert.equal(yearWords(1900, true), "nineteen hundreds");
+ assert.equal(yearWords(2000, true), "two thousands");
+ assert.equal(yearWords(2010, true), "twenty tens");
+ assert.equal(yearWords(2020, true), "twenty twenties");
+ assert.throws(() => yearWords(1899));
+ assert.throws(() => yearWords(2100));
+ assert.throws(() => yearWords(2024, true));
+ assert.equal(twoDigitWords(0), "zero");
+ assert.equal(twoDigitWords(17), "seventeen");
+ assert.equal(twoDigitWords(40), "forty");
+ assert.equal(twoDigitWords(73), "seventy-three");
+});
+
+test("a year in running text is spoken; every other number is left to the engine", () => {
+ assert.equal(
+ speakYears("In 2024 he said so, and again in 1999."),
+ "In twenty twenty-four he said so, and again in nineteen ninety-nine.",
+ );
+ assert.equal(speakYears("From 2005 to 2010."), "From two thousand five to twenty ten.");
+ assert.equal(speakYears("the 1990s and the 2020s"), "the nineteen nineties and the twenty twenties");
+ assert.equal(speakYears("1999-2001"), "nineteen ninety-nine-two thousand one");
+ // Not years: outside the range, part of a longer number, an amount, a
+ // decimal, a percentage, a time, a slashed date, a code.
+ for (const s of [
+ "1899 and 2100",
+ "12024",
+ "20245",
+ "$2024",
+ "£1999",
+ "2,024 people",
+ "1,2024",
+ "2024.5",
+ "3.2024",
+ "2024%",
+ "20:24",
+ "10/11/2024",
+ "#2024",
+ "COVID2019",
+ "2024th",
+ "2024s",
+ ]) {
+ assert.equal(speakYears(s), s, s);
+ }
+ // A sentence's full stop after a year is not a decimal.
+ assert.equal(speakYears("It was 2024."), "It was twenty twenty-four.");
+});
+
+test("the expressive tag set is exported, and unknown tags are named", () => {
+ assert.deepEqual(
+ [...TTS_EXPRESSIVE_TAGS],
+ ["laugh", "chuckle", "sigh", "cough", "sniffle", "groan", "yawn", "gasp"],
+ );
+ assert.deepEqual(unknownTtsTags("Fine <laugh> and <sigh>."), []);
+ assert.deepEqual(unknownTtsTags("Oh <lagh> no <b>bold</b> <lagh>"), ["<lagh>", "<b>", "</b>"]);
+ assert.deepEqual(unknownTtsTags("a < b and c > d"), ["< b and c >"]);
+ assert.deepEqual(unknownTtsTags("x < y, z > w? no: 3 < 4"), ["< y, z >"]);
+ assert.deepEqual(unknownTtsTags("plain text, 3 < 4"), []);
+ assert.equal(unknownTtsTagsError("fine <laugh>"), null);
+ const err = unknownTtsTagsError("ha <Laugh> <smirk>")!;
+ assert.match(err, /tags no engine knows: <Laugh> \(did you mean <laugh>\?\), <smirk>/);
+ assert.match(err, /<laugh> <chuckle> <sigh> <cough> <sniffle> <groan> <yawn> <gasp>/);
+});
+
+test("stripping a tag leaves no stray or doubled space", () => {
+ assert.equal(stripTtsTags("That's rich <laugh>."), "That's rich.");
+ assert.equal(stripTtsTags("<sigh> Here we go."), "Here we go.");
+ assert.equal(stripTtsTags("Here <sigh> we go."), "Here we go.");
+ assert.equal(stripTtsTags("Here<sigh>we go."), "Here we go.");
+ assert.equal(stripTtsTags("Well, <chuckle>, fine."), "Well, fine.");
+ assert.equal(stripTtsTags("End <gasp>"), "End");
+ assert.equal(stripTtsTags("<cough><cough> Sorry <yawn> <groan>!"), "Sorry!");
+ assert.equal(stripTtsTags("a\n<sniffle>\nb"), "a b");
+ // Only the expressive tags go: anything else is the refusal's business.
+ assert.equal(stripTtsTags("keep <b> this"), "keep <b> this");
+ for (const t of TTS_EXPRESSIVE_TAGS) {
+ assert.equal(stripTtsTags(`one <${t}> two`), "one two", t);
+ }
+});
+
+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 }),
+ "In twenty twenty-four, the show ended.",
+ );
+ assert.equal(
+ normalizeTtsText("In 2024 <laugh> it ended.", { tags: "keep", years: false }),
+ "In 2024 <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 }),
+ );
+});
diff --git a/common/lib/ttsText.ts b/common/lib/ttsText.ts
@@ -0,0 +1,163 @@
+// THE TEXT PRE-PASS EVERY SPEECH ENGINE'S INPUT GOES THROUGH (release 25 T1).
+//
+// One shared normalizer; each engine in lib/ttsApps.ts picks its options with
+// its own `normalize` hook. What it does, in order:
+//
+// 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.
+//
+// Pure, no imports: umtool's validator may import or mirror TTS_EXPRESSIVE_TAGS.
+
+// The expressive tags a script may carry (Orpheus's set). Lowercase, exact.
+export const TTS_EXPRESSIVE_TAGS = [
+ "laugh",
+ "chuckle",
+ "sigh",
+ "cough",
+ "sniffle",
+ "groan",
+ "yawn",
+ "gasp",
+] as const;
+
+export type TtsExpressiveTag = (typeof TTS_EXPRESSIVE_TAGS)[number];
+
+const TAG_SET: ReadonlySet<string> = new Set(TTS_EXPRESSIVE_TAGS);
+
+// Anything that reads as a tag: `<`, no angle brackets, `>`.
+const ANY_TAG = /<[^<>]*>/g;
+
+/** Every `<...>` in `text` that is not one of TTS_EXPRESSIVE_TAGS, in order, de-duplicated. */
+export function unknownTtsTags(text: string): string[] {
+ const out: string[] = [];
+ for (const m of text.matchAll(ANY_TAG)) {
+ const inner = m[0].slice(1, -1);
+ if (TAG_SET.has(inner)) continue;
+ if (!out.includes(m[0])) out.push(m[0]);
+ }
+ return out;
+}
+
+/** The refusal for the tags `unknownTtsTags` found, or null when there are none. */
+export function unknownTtsTagsError(text: string): string | null {
+ const bad = unknownTtsTags(text);
+ if (bad.length === 0) return null;
+ const hints = bad
+ .map((t) => {
+ const inner = t.slice(1, -1).trim().toLowerCase();
+ return TAG_SET.has(inner) ? `${t} (did you mean <${inner}>?)` : t;
+ })
+ .join(", ");
+ return (
+ `the text holds ${bad.length === 1 ? "a tag" : "tags"} no engine knows: ${hints} — ` +
+ `the expressive tags are ${TTS_EXPRESSIVE_TAGS.map((t) => `<${t}>`).join(" ")}`
+ );
+}
+
+/** `text` with every expressive tag removed and the whitespace around it closed up. */
+export function stripTtsTags(text: string): string {
+ const stripped = text.replace(ANY_TAG, (tag) =>
+ TAG_SET.has(tag.slice(1, -1)) ? " " : tag,
+ );
+ // A tag between two commas ("Well, <chuckle>, fine.") leaves two.
+ return collapseTtsWhitespace(stripped).replace(/([.,!?;:]),/g, "$1");
+}
+
+/** One space for every whitespace run, none before punctuation, trimmed. */
+export function collapseTtsWhitespace(text: string): string {
+ return text
+ .replace(/\s+/g, " ")
+ .replace(/ +([.,!?;:])/g, "$1")
+ .trim();
+}
+
+// --- years -------------------------------------------------------------------
+
+const ONES = [
+ "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine",
+ "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen",
+ "seventeen", "eighteen", "nineteen",
+];
+const TENS = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"];
+const TENS_PLURAL = ["", "tens", "twenties", "thirties", "forties", "fifties", "sixties", "seventies", "eighties", "nineties"];
+
+/** 0-99 in words: "seven", "fourteen", "twenty-four". */
+export function twoDigitWords(n: number): string {
+ if (!Number.isInteger(n) || n < 0 || n > 99) throw new RangeError(`not 0-99: ${n}`);
+ if (n < 20) return ONES[n];
+ const t = Math.floor(n / 10);
+ const o = n % 10;
+ return o === 0 ? TENS[t] : `${TENS[t]}-${ONES[o]}`;
+}
+
+/**
+ * A year 1900-2099 as it is said: 1900 "nineteen hundred", 1905 "nineteen oh
+ * five", 1999 "nineteen ninety-nine", 2000 "two thousand", 2005 "two thousand
+ * five", 2010 "twenty ten", 2024 "twenty twenty-four". With `plural` (a decade,
+ * "the 1990s") the last word is pluralised: "nineteen nineties", "two
+ * thousands", "twenty twenties".
+ */
+export function yearWords(year: number, plural = false): string {
+ if (!Number.isInteger(year) || year < 1900 || year > 2099) {
+ throw new RangeError(`not a year 1900-2099: ${year}`);
+ }
+ const c = Math.floor(year / 100);
+ const r = year % 100;
+ if (plural) {
+ if (r % 10 !== 0) throw new RangeError(`not a decade: ${year}`);
+ if (year === 1900) return "nineteen hundreds";
+ if (year === 2000) return "two thousands";
+ return `${twoDigitWords(c)} ${TENS_PLURAL[r / 10]}`;
+ }
+ if (year === 2000) return "two thousand";
+ if (c === 20 && r < 10) return `two thousand ${ONES[r]}`;
+ if (r === 0) return `${twoDigitWords(c)} hundred`;
+ if (r < 10) return `${twoDigitWords(c)} oh ${ONES[r]}`;
+ return `${twoDigitWords(c)} ${twoDigitWords(r)}`;
+}
+
+// A standalone four-digit 19xx/20xx, optionally a decade's "s". Not part of a
+// longer number, an amount, a decimal, a time, a date written with slashes or
+// a percentage: those are left to the engine.
+const YEAR = /(?<![\d$£€.,:/#])\b(19\d\d|20\d\d)(s?)\b(?!%|\d|[.,:/]\d)/g;
+
+/** `text` with every year 1900-2099 written out as it is said. */
+export function speakYears(text: string): string {
+ return text.replace(YEAR, (whole, digits: string, s: string) => {
+ const year = Number(digits);
+ if (s) return year % 10 === 0 ? yearWords(year, true) : whole;
+ return yearWords(year);
+ });
+}
+
+// --- 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;
+};
+
+/** The pre-pass: tags, then years, then whitespace (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);
+}
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -1,6 +1,8 @@
# Changelog
## [Unreleased]
+- **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.
- **"Saved." on /sites comes at once.** Saving the hub config or a site, deleting a site and migrating settings into a first site sometimes waited up to ~6 s for the page's refresh before saying anything, the button stuck on "Saving…". They now save without making the page refresh wait, show what was saved straight away, and then refresh the page.
- **A channel taken off a site, or moved to its cited scope, is withdrawn at the edge.** The next build of the site replaces every `transcripts/`, `subs/`, `posts/` and `digests/` path its last build served for that channel with an empty file of the same shape, served no-store (the way withheld X posts already are), and keeps doing so while the channel stays out. The channel's cited moments and clips still publish. A site's deploy now reads its withdrawn paths back in its live check, as the hub's does.
diff --git a/editor/app/api/ops/tts/route.test.ts b/editor/app/api/ops/tts/route.test.ts
@@ -0,0 +1,121 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { execFileSync } from "node:child_process";
+import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+
+// Run with:
+// pnpm -C editor exec tsx --test "app/api/ops/tts/route.test.ts"
+//
+// The adapter's surface: the token, the body's keys, the controller's
+// refusals answered as 400s before any job exists — and one synthesis through
+// the route with espeak-ng (the zero-install engine), read back from the job's
+// log as `pnpm ops tts --wait` reads it. The job itself is covered by
+// common/controller/ttsFile.test.ts. In a temp corpus with its own cache.
+
+const ROOT = await mkdtemp(path.join(os.tmpdir(), "tts-route-"));
+const CORPUS = path.join(ROOT, "transcripts");
+const CACHE = path.join(ROOT, "cache");
+await mkdir(CORPUS, { recursive: true });
+const SETTINGS_FILE = path.join(ROOT, "settings.json");
+const SETTINGS_TEXT = JSON.stringify({
+ workers: [],
+ tts: { engine: "espeak-ng", voice: "en-us", dir: CACHE, home: path.join(ROOT, "home") },
+});
+await writeFile(SETTINGS_FILE, SETTINGS_TEXT);
+// Set before the route (and getPaths, which caches) is first imported.
+process.env.WORKER_TOKEN = "test-token";
+process.env.TRANSCRIPTS_DIR = CORPUS;
+process.env.SETTINGS_FILE = SETTINGS_FILE;
+const { POST } = await import("./route");
+const { TTS_RESULT_MARKER } = await import("yt-dlp-transcript-common/controller/ttsFile");
+test.after(() => rm(ROOT, { recursive: true, force: true }));
+
+async function post(
+ body: Record<string, unknown>,
+ token = "test-token",
+): Promise<{ status: number; json: { ok?: boolean; error?: string; jobId?: string } }> {
+ const res = await POST(
+ new Request("http://localhost/api/ops/tts", {
+ method: "POST",
+ headers: {
+ authorization: `Bearer ${token}`,
+ "content-type": "application/json",
+ },
+ body: JSON.stringify(body),
+ }),
+ );
+ return { status: res.status, json: await res.json() };
+}
+
+test("a wrong token is a 401", async () => {
+ const { status } = await post({ text: "hi" }, "wrong");
+ assert.equal(status, 401);
+});
+
+test("an unknown key is a 400 naming the accepted ones", async () => {
+ const { status, json } = await post({ text: "hi", reference: "/voice.wav" });
+ assert.equal(status, 400);
+ assert.match(json.error!, /unknown key\(s\): reference — this route accepts text, file, voice, engine, speed, out/);
+});
+
+test("the controller's refusals come back as 400s", async () => {
+ const cases: [Record<string, unknown>, RegExp][] = [
+ [{}, /"text" .* or "file" .* is required/],
+ [{ text: "a", file: "/a.txt" }, /not both/],
+ [{ file: "a.txt" }, /"file" must be an absolute path/],
+ [{ file: path.join(ROOT, "missing.txt") }, /does not exist/],
+ [{ text: "hi", engine: "piper" }, /no text-to-speech engine "piper"/],
+ [{ text: "hi", voice: "af_heart" }, /espeak-ng has no stock voice "af_heart"/],
+ [{ text: "hi", speed: 9 }, /"speed" must be between 0.5 and 2/],
+ [{ text: "oh <lagh> no" }, /a tag no engine knows: <lagh>/],
+ [{ text: "hi", engine: "kokoro" }, /Kokoro-82M is not installed .* run `archilyzer tts setup`/],
+ [{ text: "hi", out: path.join(CORPUS, "a.wav") }, /inside the corpus/],
+ [{ text: "hi", out: path.join(ROOT, "a.mp3") }, /must name a \.wav file/],
+ ];
+ for (const [body, re] of cases) {
+ const { status, json } = await post(body);
+ assert.equal(status, 400, JSON.stringify(body));
+ assert.equal(json.ok, false);
+ assert.match(json.error!, re);
+ assert.equal(json.jobId, undefined);
+ }
+ assert.equal(await readFile(SETTINGS_FILE, "utf8"), SETTINGS_TEXT);
+});
+
+let real = true;
+try {
+ execFileSync("espeak-ng", ["--version"], { stdio: "ignore" });
+ execFileSync("ffmpeg", ["-version"], { stdio: "ignore" });
+} catch {
+ real = false;
+}
+
+test("a synthesis through the route: a job whose log ends with the result", { skip: !real && "espeak-ng or ffmpeg absent" }, async () => {
+ const { status, json } = await post({ text: "Narrated <sigh> in 2025." });
+ assert.equal(status, 200);
+ assert.equal(json.ok, true);
+ assert.ok(json.jobId);
+ const logFile = path.join(CORPUS, ".jobs", `${json.jobId}.log`);
+ let line: string | undefined;
+ for (let i = 0; i < 300 && !line; i++) {
+ const log = await readFile(logFile, "utf8").catch(() => "");
+ line = log.split("\n").find((l) => l.startsWith(TTS_RESULT_MARKER));
+ if (!line) await new Promise((r) => setTimeout(r, 50));
+ }
+ assert.ok(line, "the result line");
+ const r = JSON.parse(line!.slice(TTS_RESULT_MARKER.length));
+ assert.deepEqual(Object.keys(r), [
+ "wav", "seconds", "engine", "voice", "cached", "durationMs", "waitedMs",
+ "sha", "sampleRate", "speed", "disclosure",
+ ]);
+ assert.equal(r.engine, "espeak-ng");
+ assert.equal(r.cached, false);
+ assert.equal(r.wav, path.join(CACHE, `${r.sha}.wav`));
+ assert.equal(r.sampleRate, 48000);
+ assert.match(r.disclosure, /^Narration: synthetic voice \(eSpeak NG · en-us\)$/);
+ const side = JSON.parse(await readFile(path.join(CACHE, `${r.sha}.json`), "utf8"));
+ assert.equal(side.text, "Narrated in twenty twenty-five.");
+ assert.equal(side.synthetic, true);
+});
diff --git a/editor/app/api/ops/tts/route.ts b/editor/app/api/ops/tts/route.ts
@@ -0,0 +1,38 @@
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import {
+ TTS_FILE_BODY_KEYS,
+ enqueueTtsFile,
+} from "yt-dlp-transcript-common/controller/ttsFile";
+import { jobResponse, ops } from "../_lib";
+
+export const dynamic = "force-dynamic";
+
+// POST { text | file, voice?, engine?, speed?, out? } -> { ok: true, jobId }
+//
+// Speak a line with a local text-to-speech engine and a STOCK voice, as a job on
+// /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.
+//
+// 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
+// (the wait on the queue), sha, sampleRate, speed, disclosure}`. `wav` is an
+// absolute path this editor wrote: `out` when given, else the cache file
+// (`<settings.tts.dir>/<sha>.wav`, 48 kHz mono 16-bit, a `<sha>.json` sidecar
+// beside it). The same ask again is a `done` job with `cached: true` that runs
+// no engine. `pnpm ops tts --wait` prints that JSON on stdout.
+//
+// AN ADAPTER: every refusal is the controller's (controller/ttsFile.ts) — both
+// or neither of text and file, an unknown engine or voice, a speed out of
+// range, an unknown tag, an engine not installed (`archilyzer tts setup`), an
+// `out` or a cache dir inside the corpus.
+export async function POST(request: Request) {
+ return ops(request, TTS_FILE_BODY_KEYS, async (body) =>
+ jobResponse(await enqueueTtsFile(body, { paths: getPaths() })),
+ );
+}
diff --git a/plans/release-25.md b/plans/release-25.md
@@ -35,9 +35,11 @@ thousand twenty-four" (a text pre-pass fixes it); it speaks briskly (speed is a
| **T1** | Engine + job + ops: **`archilyzer tts setup`** (creates a venv at `settings.tts.home` — default `~/.local/share/archilyzer/tts/kokoro` — installs `kokoro-onnx==0.6.1`, and downloads `kokoro-v1.0.onnx` + `voices-v1.0.bin` once from the kokoro-onnx project's `model-files-v1.0` release, verified by size/sha, polite: one stream, no retries in a loop; `--check` reports what is missing), a Python helper `scripts/tts_kokoro.py` (text file in, WAV out; lang from the voice prefix: `b*` → en-gb, else en-us), a **text pre-pass** in common (years 1900–2099 read as spoken — "twenty twenty-four", "nineteen ninety-nine", "two thousand five"; keep numbers otherwise to the engine; unit-tested), `common/lib/ttsApps.ts` (registry: id, label, license, `build({textFile, outWav, voice, speed}) → argv/env`, `voices()`), `scripts/tts.mjs` (dual-use wrapper: text in, WAV out; engine kinds: `kokoro` (default) and `espeak-ng` (the zero-install fallback the tests use)), `settings.tts` (`engine` = kokoro, `voice` = af_heart, `speed` = 1.0, `home` (the venv + models), `dir` (the cache); SETTINGS.md), `paths`/envVars rows (ENVIRONMENT.md), `common/controller/ttsFile.ts` (`enqueueTtsFile`: body `{text | file, voice?, engine?, speed?, out?}`, the corpus fence from transcribeFile, cache hit = a `done` job with `cached: true` and no engine run, result marker `@@tts-result ` `{wav, seconds, engine, voice, cached, durationMs, waitedMs}`), job kind `tts-file` on queue `tts` (not ingest), `editor/app/api/ops/tts/route.ts` + test, `pnpm ops tts` + usage + marker (COMMANDS.md), doctor check (engine + voice present) | common, scripts, editor | unit: registry, body refusals, fence, cache hit/miss, marker; route test; ops test; one real synthesis through the job with espeak-ng; `docs env|files|cli --check`, `settings example --check` |
| **T2** | Report-video narration: manifest `narration` on `card` entries (`{text, voice?}`; text explicit — never derived from the card: opt-in, the operator's "show, don't tell" stays the default), `render.narration` (`engine?`, `voice?`, `lufs` default −17.7 to sit with the clips (README "teaser level"), `lead`/`tail` ≥ the crossfade `D`), `validateNarration` in `build-video.mjs` AND `lint.mjs` (text non-empty, length cap), `narrate-via-editor.mjs` (one batch of `pnpm ops tts` asks, follows the jobs, NDJSON events; driver step + `busy.mjs` regex), `buildCardSegment` swaps `anullsrc` for the narration WAV (`apad`/`atrim`, leveled, at `render.audioRate`/`audioChannels`), card `seconds`: `"auto"` = narration + lead + tail, a number shorter than that is a lint ERROR; a narration record beside the segment (teaser-style) so rebuilds re-encode only on change; chapters/description export add the disclosure line | umtool/report-to-video, umtool/lib/report | unit: validator, seconds auto, record invalidation, the ffmpeg args; one fixture build with a narrated card through a fake editor (e2e fixture); `onscreen*.spec` untouched or updated |
| **T3** | Podcast: `build-video.mjs <manifest> --audio-only` (or `build-podcast.mjs`) renders the same entry list as sound only — clips' audio, narrated cards, a short silence for an unnarrated card (or skip it: `render.podcast.skipSilentCards`, default true) — loudness-normalized (−16 LUFS, podcast norm), chapters from the same ffmeta, to `out/<variant>/podcast.m4a` (+ `podcast.mp3`), and `show-notes.md` (chapters with timestamps, every cited source's link, the disclosure). umtool's report page offers it beside the video export | umtool | unit on the entry→audio plan and notes; one fixture render; the umtool spec for the export button |
+| **T1b** | **Orpheus 3B as a second engine** (operator, 2026-10-11: "I want Orpheus too, but it needs to be used better"), after T1, by Lane A, from the tuning round `~/reports/tts-bakeoff/orpheus2/` (chunker of 1–3 sentences, the shared normalizer with numbers/ordinals spelled out, the swept sampler settings, best-of-3 takes by a non-ASR check, punctuation-aware joins). llama-server (Vulkan) started per batch and stopped after, so VRAM is free for transcription; the engine declares the GPU, and the `tts` queue yields while a transcription runs; the disclosure adds "Built with Llama" (Llama 3.2 licence). Expressive tags pass through for Orpheus; Kokoro strips them | common, scripts | unit (chunker, normalizer, lifecycle with a fake server); one real Orpheus synthesis through a test editor |
+| **T5** | **Writing for the ear** (operator: "if the text is written with a little storytelling and pre-baked emotion, Orpheus can shine"): a narration-script step. A writing guide (rules from the tuning round's "written for the ear" takes) in `mcp/src/instructions.ts` (where corpus discipline lives) and the report-to-video docs; a umtool surface to review a video's narration script card by card (approve / edit; persisted), before synthesis. **Hard rule:** storytelling and emotion live in the delivery, never in the claims — every factual statement stays exactly as the cited evidence supports | mcp, umtool | unit; a umtool spec for the review page |
| **T4** (later) | Publishing a podcast: `reports attach-audio` + an RSS enclosure on the report feed; docker image TTS stage + `fetch_tts_voice()` | common/publish, export, docker | — deferred, not this release |
-**Order / lanes:** T1 ∥ T2 (T2 codes against T1's contract above and a fake editor in its tests), then T3 after T2.
+**Order / lanes:** T1 ∥ T2 (T2 codes against T1's contract above and a fake editor in its tests), then T1b after T1 and T3 after T2; T5 after the tuning round's writing rules.
Two Opus implementers. Gates as release 23/24 (tsc per commit; the four builds; `pnpm e2e:all`; privacy counts).
## Where it plugs in (from the map)
@@ -52,5 +54,78 @@ Two Opus implementers. Gates as release 23/24 (tsc per commit; the four builds;
## Not doing
-Voice cloning (ruled out); narration derived automatically from card text; narration under clips (the join graph —
+Voice cloning (ruled out); Orpheus as the default (Kokoro af_heart stays the default); narration derived automatically from card text; narration under clips (the join graph —
bigger, later if wanted); a cloud TTS.
+
+## Record
+
+### T1, as shipped — the TTS engine, the `tts-file` job and `pnpm ops tts` (`r25/tts-core`)
+
+Synthesis is an editor job, never by hand: `pnpm ops tts` (`POST /api/ops/tts`) enqueues a `tts-file` job that runs one
+engine through one wrapper into a content-addressed cache, and `archilyzer tts setup` installs the engine.
+
+- **The contract (Lane B codes against it).** Body `{text | file, voice?, engine?, speed?, out?}` — exactly one of
+ `text` / `file` (an absolute path to UTF-8 text), at most 20,000 characters; `engine` `kokoro` | `espeak-ng`;
+ `voice` one of the engine's stock voices; `speed` in the engine's range (0.5–2); `out` an absolute `.wav` path
+ outside the corpus. Unknown keys are a 400; every refusal comes before a job. The job's log ends with ONE line
+ `@@tts-result {json}`: `{wav, seconds, engine, voice, cached, durationMs, waitedMs, sha, sampleRate, speed,
+ disclosure}` — `wav` an absolute path the editor wrote (`out` when given, else `<cache>/<sha>.wav`), `sampleRate`
+ 48000, `disclosure` "Narration: synthetic voice (<engine label> · <voice>)" plus the engine's attribution sentence
+ when it has one. `durationMs` is the engine's time (≈0 on a hit), `waitedMs` the wait on the `tts` queue.
+- **Expressive tags.** `TTS_EXPRESSIVE_TAGS` (`common/lib/ttsText.ts`): `laugh chuckle sigh cough sniffle groan yawn
+ gasp`. Stripped, with no stray or doubled space and no doubled comma, for Kokoro and espeak-ng; any other `<…>` is a
+ 400 naming it (with "did you mean <laugh>?" for a case slip). Exported for umtool's validator.
+- **The pre-pass** (`normalizeTtsText`, each engine's `normalize` hook): tags, then years 1900–2099 spoken ("twenty
+ twenty-four", "nineteen oh five", "two thousand five", decades "the nineteen nineties"; amounts, decimals, times,
+ slashed dates, percentages and longer numbers left alone), then whitespace collapsed — the cache key is on the
+ result, so a re-wrapped paragraph is a hit.
+- **The registry** (`common/lib/ttsApps.ts`): id, label, model (in the key), licence, `attribution?`, `device`,
+ `runtime` (`process` | `server`), the stock voices, default voice, speed range, `normalize`, `setup`, and `build`
+ → the argv of `scripts/tts.mjs` (TTS_BIN), which runs the engine (`scripts/tts_kokoro.py` for Kokoro) and leaves a
+ 48 kHz mono 16-bit WAV, bare 44-byte header, atomically. Kokoro: its 28 English voices (`a*` en-us, `b*` en-gb),
+ `af_heart` default. A voice is a name from that list — never a path.
+- **The cache**: sha256 of (`archilyzer-tts/1`, engine, model, voice, speed, spoken text) → `<dir>/<sha>.wav` +
+ `<sha>.json` (`synthetic: true`, the disclosure, engine, model, licence, voice, speed, seconds, the spoken text). A
+ hit at enqueue is a `done` job on queue `""` that runs no engine; a miss runs on queue `tts` (`TTS_QUEUE`) and checks
+ the cache again at its turn.
+- **Settings**: `settings.tts` `{engine: "kokoro", voice: "af_heart", speed: 1, home: "", dir: ""}`. **`home` is the
+ ROOT of all engines** (`~/.local/share/archilyzer/tts` when blank), each engine in `<home>/<id>` — so Kokoro is at
+ `~/.local/share/archilyzer/tts/kokoro`, the plan's path, and Orpheus (T1b) gets its own dir beside it. `dir` blank =
+ `<repo>/.tts/cache` (gitignored `/.tts/`); a cache dir inside the corpus is refused. Paths: `ttsBin` (TTS_BIN),
+ `espeakNgBin` (ESPEAK_NG_BIN), `ttsHome`, `ttsCacheDir`.
+- **`archilyzer tts setup [--engine] [--from <dir>] [--python <py>] [--check]`**: a venv (`uv venv --python 3.12`
+ when uv is on PATH), `kokoro-onnx==0.6.1`, the two model files from the `model-files-v1.0` release pinned by size and
+ sha256 — one stream each, no retries, `.part` then rename; `--from` hard-links (else copies) verified files;
+ `--check` imports the package and lists what is missing. Scratch under the install dir, never the OS temp dir.
+ `archilyzer doctor`'s `tts` row: installed is ok, not installed is a note (never a failure).
+- **How T1b (Orpheus 3B) slots in**: a registry entry with `device: "gpu"`, `runtime: "server"`, `attribution: "Built
+ with Llama"`, `normalize` with `tags: "keep"` and a new numbers/ordinals option on `normalizeTtsText`, and a `setup`
+ of its own; in `runTtsSynthesis` (marked) a GPU engine waits for the transcription pool to be idle, and a server
+ engine takes a per-engine holder (llama-server started for the batch on the `tts` queue, stopped once the queue has
+ been idle) whose URL `build` receives as `server`; `scripts/tts.mjs` gains `--engine-kind orpheus`.
+
+| commit | what |
+|---|---|
+| `cebeaff9` | the registry, the pre-pass (tags, years, whitespace) and the wrapper + Kokoro helper |
+| `c44946b1` | `settings.tts`, the TTS paths and env vars; SETTINGS.md, settings.json.example, ENVIRONMENT.md |
+| `24ca5907` | `tts-file` on the `tts` queue, the cache and its sidecar, the install check |
+| `7d37f6b2` | `POST /api/ops/tts`, `pnpm ops tts`, COMMANDS.md |
+| `ee9c1cd8` | `archilyzer tts setup`, the doctor's `tts` row |
+
+#### Gates
+
+| gate | result |
+|---|---|
+| tsc (`pnpm -r … exec tsc --noEmit`) | clean at every commit |
+| common unit | 3748 pass, 0 fail (new: ttsText 5, ttsApps 5, ttsSettings 3, ttsFile 8, tts-setup 5, doctor +1, settingsSchema/jobKinds updated) |
+| editor unit | 260 pass (new: `api/ops/tts/route.test.ts` 4, one a real espeak-ng synthesis through the route) |
+| test:scripts | 798: 795 pass, 3 skip (new: `tts.test.mjs` 4, `archilyzer-ops.test.mjs` +1) |
+| one real synthesis through the job with espeak-ng | `ttsFile.test.ts`: engine run once, the same ask re-wrapped a cache hit with no engine run, `out` copied, a file at another speed a new synthesis |
+| `docs env\|files\|cli --check`, `settings example --check` | clean |
+| `archilyzer tts setup --from <bake-off models>` | real, into the default home: venv + kokoro-onnx 0.6.1 by uv, both files hard-linked and verified; `--check` 0; re-run idempotent |
+| one real Kokoro synthesis through the route | the route handler in-process (an isolated temp corpus and cache, the real default home; under `pnpm heavy`): 466 characters (years, numbers, a `<laugh>`) → 30.65 s of 48 kHz audio in 14.85 s engine time, model load included — **RTF 0.48** (the bake-off's 0.46 without load); the sidecar spoke "nineteen ninety-nine" / "twenty twenty-four", the tag gone; the same ask again a cached done job, `durationMs` 0, no engine run |
+
+Not done here: the four `next build`s and `pnpm e2e:all` (the orchestrator's); no e2e spec was added (the route test
+runs a real synthesis in-process). Found and left: a job's `done` settles when its log stream is ended, not flushed
+(`runManagedFunction`), so a near-instant job (a cache hit) can settle before its log is on disk — `pnpm ops --wait`
+polls over HTTP and does not see it; the unit tests poll for the marker.
diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs
@@ -90,6 +90,8 @@
// pnpm ops cut-release --json '{"workspace":"all","version":"next","commit":true}'
// pnpm ops transcribe --json '{"path":"/abs/clip.mp4","start":120,"end":150}' --wait
// pnpm ops transcribe --json '{"path":"/abs/a.wav","workerId":"parakeet-cpu","out":"/tmp/a.json"}' --wait
+// pnpm ops tts --json '{"text":"In 2024 the archive spoke."}' --wait
+// pnpm ops tts --json '{"file":"/abs/script.txt","voice":"bm_george","out":"/abs/line.wav"}' --wait
//
// --file reads the BODY from a JSON file, which is how a big one gets sent: a
// four-thousand-id tag-videos body is written by a script, not typed by a model
@@ -333,6 +335,11 @@ const ACTIONS = [
// ({path, start?, end?, workerId?, out?}) — the corpus's own engine and
// model, as a job. With --wait the result JSON is what stdout carries.
"transcribe",
+ // Speak a line with a local text-to-speech engine and a stock voice
+ // ({text | file, voice?, engine?, speed?, out?}), as a job on the `tts`
+ // queue; the same ask again is answered from the cache. With --wait the
+ // result JSON is what stdout carries.
+ "tts",
// ARCHIVAL WRITES (release 19, A4). settings.json through the editor's one
// writer ({patch}); a platform's rate-limit hold cleared ({platform});
// workers switched on, off or drained ({op, ids}); one video transcribed
@@ -352,6 +359,9 @@ const ACTIONS = [
// compact JSON. The same string is TRANSCRIBE_RESULT_MARKER in
// common/controller/transcribeFile.ts.
export const TRANSCRIBE_RESULT_MARKER = "@@transcribe-result ";
+// The same for a text-to-speech job (TTS_RESULT_MARKER in
+// common/controller/ttsFile.ts).
+export const TTS_RESULT_MARKER = "@@tts-result ";
// The same for a remote listing (REMOTE_LISTING_RESULT_MARKER in
// common/controller/remoteListing.ts).
export const REMOTE_LISTING_RESULT_MARKER = "@@remote-listing ";
@@ -576,6 +586,7 @@ export function parseArgs(argv) {
...(action === "tag-videos" ? { defaultSource: agentSource() } : {}),
// A job whose log carries a RESULT, which --wait prints on stdout.
...(action === "transcribe" ? { resultMarker: TRANSCRIBE_RESULT_MARKER } : {}),
+ ...(action === "tts" ? { resultMarker: TTS_RESULT_MARKER } : {}),
...(action === "remote-listing" ? { resultMarker: REMOTE_LISTING_RESULT_MARKER } : {}),
wait,
quiet,
@@ -1031,6 +1042,21 @@ export function usage() {
" With --wait it is printed on stdout (the response and the log go to",
" stderr), so `pnpm ops transcribe ... --wait | jq -r .text` works.",
"",
+ '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",
+ " {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.",
+ "",
"Env: ARCHILYZER_EDITOR_URL (default http://localhost:3001), WORKER_TOKEN,",
" ARCHILYZER_AGENT (provenance of a tag write; default \"cli\").",
" WORKER_TOKEN and ARCHILYZER_EDITOR_URL, when unset, are read from",
@@ -1321,7 +1347,7 @@ export async function followJob(jobId, quiet, opts = {}) {
// Follow every id to its end, one after another, and say how each ended.
// 0 only when every one finished `done`. A job still queued says where it waits
// (followJob), so a list of ids behind one long job reads as a queue, not a
-// hang. In result mode (transcribe) each job's RESULT goes to stdout.
+// hang. In result mode (transcribe, tts, remote-listing) each job's RESULT goes to stdout.
async function followAll(jobIds, parsed, resultMode = false) {
let worst = 0;
for (const jobId of jobIds) {
diff --git a/scripts/archilyzer-ops.test.mjs b/scripts/archilyzer-ops.test.mjs
@@ -8,6 +8,7 @@ import test from "node:test";
import {
REMOTE_LISTING_RESULT_MARKER,
TRANSCRIBE_RESULT_MARKER,
+ TTS_RESULT_MARKER,
editorEnvFiles,
followJob,
loadEditorEnv,
@@ -655,6 +656,30 @@ test("transcribe posts its body and carries the result marker", () => {
assert.match(usage(), /it is printed on stdout/);
});
+test("tts posts its body and carries its own result marker", () => {
+ const p = parseArgs([
+ "tts",
+ "--json",
+ '{"text":"In 2024 the archive spoke.","voice":"bm_george","out":"/abs/line.wav"}',
+ "--wait",
+ ]);
+ assert.equal(p.method, "POST");
+ assert.equal(p.path, "/api/ops/tts");
+ assert.deepEqual(p.body, { text: "In 2024 the archive spoke.", voice: "bm_george", out: "/abs/line.wav" });
+ assert.equal(p.wait, true);
+ 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(), /\{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 };
+ const cap = makeResultCapture(TTS_RESULT_MARKER);
+ const echoed = cap.feed(`Speak 12 characters\n${TTS_RESULT_MARKER}${JSON.stringify(result)}\n`);
+ assert.equal(echoed, "Speak 12 characters\n");
+ assert.deepEqual(cap.finish().result, result);
+});
+
test("the result line is taken out of the log, across chunk boundaries", () => {
const result = { cues: [{ start: 120.5, end: 121, text: "hi" }], text: "hi" };
const line = `${TRANSCRIBE_RESULT_MARKER}${JSON.stringify(result)}`;
diff --git a/scripts/tts.mjs b/scripts/tts.mjs
@@ -0,0 +1,223 @@
+#!/usr/bin/env node
+// Text in, WAV out: the one wrapper every text-to-speech engine runs behind
+// (release 25 T1) — scripts/diarize.mjs's shape, the other way round.
+//
+// The app only ever knows a PATH (paths.ttsBin / TTS_BIN) and the argv the
+// 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:
+// 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.
+//
+// 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),
+// moved into place atomically, so a half-written file is never what a cache
+// hit finds. On stdout, one JSON line: {engine, voice, speed, sampleRate,
+// seconds, engineMs, ...the engine's own figures}.
+//
+// Dual-use, by design:
+// * In the app: controller/ttsFile.ts runs it with a text file it wrote and
+// an --output in the cache.
+// * On the CLI: `scripts/tts.mjs --engine-kind espeak-ng --text "Hello."
+// --output hello.wav`. (An agent asks the editor instead: `pnpm ops tts`.)
+//
+// Usage:
+// tts.mjs [options] <textFile> (or --text "<text>" in place of the file)
+//
+// Options (env fallback in parens):
+// --output <f> the WAV to write [required]
+// --engine-kind <k> kokoro | espeak-ng (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>
+// --python <p> the venv's python [kokoro]
+// --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]
+// --ffmpeg <bin> ffmpeg binary (FFMPEG_BIN, ffmpeg)
+// -h, --help
+
+import { spawn } from "node:child_process";
+import { readFile, rename, rm, writeFile, open } from "node:fs/promises";
+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.
+See the header of this file for the full option list.`;
+
+const SAMPLE_RATE = 48_000;
+const DEFAULT_VOICE = { kokoro: "af_heart", "espeak-ng": "en-us" };
+
+function fail(msg, code = 2) {
+ process.stderr.write(`tts: ${msg}\n`);
+ process.exit(code);
+}
+
+const argv = process.argv.slice(2);
+if (argv.includes("-h") || argv.includes("--help")) {
+ process.stdout.write(HELP + "\n");
+ process.exit(0);
+}
+
+function arg(flag, fallback) {
+ const i = argv.indexOf(flag);
+ return i < 0 || i === argv.length - 1 ? fallback : argv[i + 1];
+}
+
+const positional = [];
+for (let i = 0; i < argv.length; i++) {
+ if (argv[i].startsWith("--")) {
+ i++; // every flag here takes a value
+ continue;
+ }
+ positional.push(argv[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}')`);
+}
+const 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");
+const inlineText = arg("--text", undefined);
+if (inlineText === undefined && !positional[0]) fail("missing <textFile> (or --text)");
+
+const out = path.resolve(output);
+const raw = `${out}.raw-${process.pid}.wav`;
+const tmp = `${out}.tmp-${process.pid}.wav`;
+const inlineFile = `${out}.text-${process.pid}.txt`;
+let child = null;
+
+async function cleanup() {
+ await Promise.all([raw, tmp, inlineFile].map((f) => rm(f, { force: true }).catch(() => {})));
+}
+
+for (const sig of ["SIGTERM", "SIGINT"]) {
+ process.on(sig, () => {
+ child?.kill("SIGTERM");
+ void cleanup().finally(() => process.exit(143));
+ });
+}
+
+// Run a command; resolve with its stdout, reject with its stderr's tail.
+function run(cmd, args) {
+ return new Promise((resolve, reject) => {
+ let stdout = "";
+ let stderr = "";
+ child = spawn(cmd, args, { stdio: ["ignore", "pipe", "pipe"] });
+ child.stdout.setEncoding("utf8");
+ child.stderr.setEncoding("utf8");
+ child.stdout.on("data", (d) => (stdout += d));
+ child.stderr.on("data", (d) => {
+ stderr += d;
+ process.stderr.write(d);
+ });
+ child.on("error", (err) => reject(new Error(`failed to run ${cmd}: ${err.message}`)));
+ child.on("close", (code, signal) => {
+ child = null;
+ if (code === 0) resolve(stdout);
+ else {
+ const tail = stderr.trim().split("\n").slice(-3).join(" | ");
+ reject(new Error(`${path.basename(cmd)} exited ${code ?? signal}${tail ? `: ${tail}` : ""}`));
+ }
+ });
+ });
+}
+
+// Seconds of audio in a PCM WAV, from its fmt and data chunks.
+async function wavSeconds(file) {
+ const fh = await open(file, "r");
+ try {
+ const head = Buffer.alloc(4096);
+ const { bytesRead } = await fh.read(head, 0, head.length, 0);
+ const buf = head.subarray(0, bytesRead);
+ if (buf.toString("ascii", 0, 4) !== "RIFF" || buf.toString("ascii", 8, 12) !== "WAVE") {
+ throw new Error("not a WAV");
+ }
+ let off = 12;
+ let byteRate = 0;
+ while (off + 8 <= buf.length) {
+ const id = buf.toString("ascii", off, off + 4);
+ const size = buf.readUInt32LE(off + 4);
+ if (id === "fmt ") byteRate = buf.readUInt32LE(off + 16);
+ if (id === "data") return byteRate ? size / byteRate : 0;
+ off += 8 + size + (size % 2);
+ }
+ throw new Error("no data chunk");
+ } finally {
+ await fh.close();
+ }
+}
+
+try {
+ const textFile = inlineText !== undefined ? inlineFile : path.resolve(positional[0]);
+ if (inlineText !== undefined) await writeFile(inlineFile, inlineText, "utf8");
+ const text = (await readFile(textFile, "utf8")).trim();
+ if (!text) throw new Error("the text is empty");
+
+ const started = Date.now();
+ let extra = {};
+ if (engineKind === "kokoro") {
+ const python = arg("--python", "");
+ const model = arg("--model", "");
+ const voices = arg("--voices", "");
+ if (!python) throw new Error("missing --python (the venv `archilyzer tts setup` built)");
+ if (!model) throw new Error("missing --model (kokoro-v1.0.onnx)");
+ if (!voices) throw new Error("missing --voices (voices-v1.0.bin)");
+ const stdout = await run(python, [
+ path.join(import.meta.dirname, "tts_kokoro.py"),
+ "--model", model,
+ "--voices", voices,
+ "--voice", voice,
+ "--speed", String(speed),
+ "--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.
+ await run(espeak, ["-v", voice, "-s", String(Math.round(175 * speed)), "-w", raw, "-f", textFile]);
+ }
+ const engineMs = Date.now() - started;
+
+ await run(ffmpeg, [
+ "-nostdin", "-hide_banner", "-v", "error", "-y",
+ "-i", raw,
+ "-ac", "1", "-ar", String(SAMPLE_RATE), "-c:a", "pcm_s16le",
+ "-map_metadata", "-1", "-fflags", "+bitexact", "-flags:a", "+bitexact",
+ "-f", "wav", tmp,
+ ]);
+ const seconds = await wavSeconds(tmp);
+ if (!(seconds > 0)) throw new Error("the engine produced no audio");
+ await rename(tmp, out);
+ await cleanup();
+ const result = {
+ engine: engineKind,
+ voice,
+ speed,
+ sampleRate: SAMPLE_RATE,
+ seconds: Math.round(seconds * 1000) / 1000,
+ engineMs,
+ ...(extra && typeof extra === "object" && Object.keys(extra).length ? { engineStats: extra } : {}),
+ };
+ process.stdout.write(JSON.stringify(result) + "\n");
+ process.stderr.write(`tts: ${engineKind}/${voice} ${result.seconds}s of audio in ${(engineMs / 1000).toFixed(2)}s -> ${out}\n`);
+} catch (err) {
+ await cleanup();
+ fail(err instanceof Error ? err.message : String(err), 1);
+}
diff --git a/scripts/tts.test.mjs b/scripts/tts.test.mjs
@@ -0,0 +1,94 @@
+// scripts/tts.mjs — the text-to-speech wrapper, run for real with espeak-ng
+// (the zero-install engine) and ffmpeg, and with a failing fake engine.
+//
+// Run with: node --test scripts/tts.test.mjs (part of `pnpm run test:scripts`)
+//
+// Kokoro is not run here: it needs `archilyzer tts setup`'s venv and ~350 MB
+// of model. Its command line is held by common/lib/ttsApps.test.ts.
+
+import { test, after } from "node:test";
+import assert from "node:assert/strict";
+import { execFileSync, spawnSync } from "node:child_process";
+import { chmodSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+
+const WRAPPER = path.join(import.meta.dirname, "tts.mjs");
+const TMP = mkdtempSync(path.join(os.tmpdir(), "tts-wrapper-"));
+after(() => rmSync(TMP, { recursive: true, force: true }));
+
+function has(bin, flag) {
+ try {
+ execFileSync(bin, [flag], { stdio: "ignore" });
+ return true;
+ } catch {
+ return false;
+ }
+}
+const real = has("espeak-ng", "--version") && has("ffmpeg", "-version");
+
+function run(args) {
+ const r = spawnSync(process.execPath, [WRAPPER, ...args], { encoding: "utf8" });
+ return { code: r.status, stdout: r.stdout, stderr: r.stderr };
+}
+
+test("espeak-ng: text in, a 48 kHz mono 16-bit WAV with a bare header out", { skip: !real && "espeak-ng or ffmpeg absent" }, () => {
+ const dir = mkdtempSync(path.join(TMP, "ok-"));
+ const text = path.join(dir, "in.txt");
+ writeFileSync(text, "Hello from the test suite.");
+ const out = path.join(dir, "out.wav");
+ const r = run(["--engine-kind", "espeak-ng", "--voice", "en-gb", "--speed", "1.2", "--output", out, text]);
+ assert.equal(r.code, 0, r.stderr);
+ const res = JSON.parse(r.stdout.trim());
+ assert.equal(res.engine, "espeak-ng");
+ assert.equal(res.voice, "en-gb");
+ assert.equal(res.speed, 1.2);
+ assert.equal(res.sampleRate, 48000);
+ assert.ok(res.seconds > 0.5 && res.seconds < 10, String(res.seconds));
+ const wav = readFileSync(out);
+ assert.equal(wav.toString("ascii", 0, 4), "RIFF");
+ assert.equal(wav.toString("ascii", 36, 40), "data", "a 44-byte header");
+ assert.equal(wav.readUInt16LE(22), 1, "mono");
+ assert.equal(wav.readUInt32LE(24), 48000);
+ assert.equal(wav.readUInt16LE(34), 16);
+ assert.equal(Math.round(((wav.length - 44) / 96000) * 1000) / 1000, res.seconds);
+ // Nothing left beside it but the input.
+ assert.deepEqual(readdirSync(dir).sort(), ["in.txt", "out.wav"]);
+});
+
+test("--text in place of a file leaves no text file behind", { skip: !real && "espeak-ng or ffmpeg absent" }, () => {
+ const dir = mkdtempSync(path.join(TMP, "inline-"));
+ const out = path.join(dir, "out.wav");
+ const r = run(["--engine-kind", "espeak-ng", "--text", "Inline.", "--output", out]);
+ assert.equal(r.code, 0, r.stderr);
+ assert.deepEqual(readdirSync(dir), ["out.wav"]);
+});
+
+test("refusals: no output, an unknown engine, a speed out of range, empty text", () => {
+ const dir = mkdtempSync(path.join(TMP, "bad-"));
+ const text = path.join(dir, "in.txt");
+ writeFileSync(text, "x");
+ const empty = path.join(dir, "empty.txt");
+ 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", "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.deepEqual(readdirSync(dir).sort(), ["empty.txt", "in.txt"]);
+});
+
+test("an engine that fails exits non-zero with its stderr, and leaves nothing", () => {
+ const dir = mkdtempSync(path.join(TMP, "fail-"));
+ const fake = path.join(dir, "fake-espeak");
+ writeFileSync(fake, "#!/bin/sh\necho 'voice not found' >&2\nexit 7\n");
+ chmodSync(fake, 0o755);
+ const text = path.join(dir, "in.txt");
+ writeFileSync(text, "x");
+ const out = path.join(dir, "o.wav");
+ const r = run(["--engine-kind", "espeak-ng", "--espeak", fake, "--output", out, text]);
+ assert.equal(r.code, 1);
+ assert.match(r.stderr, /fake-espeak exited 7: voice not found/);
+ assert.deepEqual(readdirSync(dir).sort(), ["fake-espeak", "in.txt"]);
+});
diff --git a/scripts/tts_kokoro.py b/scripts/tts_kokoro.py
@@ -0,0 +1,89 @@
+#!/usr/bin/env python3
+"""Kokoro-82M: a text file in, a 16-bit mono WAV at the model's native rate out.
+
+Run by scripts/tts.mjs (the wrapper every TTS engine runs behind), with the
+python of the venv `archilyzer tts setup` built (kokoro-onnx 0.6.1 on
+onnxruntime, CPU). The wrapper resamples to 48 kHz and moves the file into
+place; this script only synthesizes.
+
+Stock voices only: --voice names one of the voices in voices-v1.0.bin. The
+language follows the voice's prefix: `b*` is British English (en-gb), every
+other voice American (en-us).
+
+On stdout, one JSON line: {sampleRate, seconds, loadSeconds, synthSeconds,
+lang}. Errors go to stderr with a non-zero exit.
+"""
+
+import argparse
+import json
+import sys
+import time
+import wave
+
+
+def main() -> int:
+ p = argparse.ArgumentParser(description=__doc__.splitlines()[0])
+ p.add_argument("--model", required=True, help="kokoro-v1.0.onnx")
+ p.add_argument("--voices", required=True, help="voices-v1.0.bin")
+ p.add_argument("--voice", default="af_heart")
+ p.add_argument("--speed", type=float, default=1.0)
+ p.add_argument("--lang", default=None, help="default: en-gb for b* voices, else en-us")
+ p.add_argument("--output", required=False, help="the WAV to write")
+ p.add_argument("--list-voices", action="store_true", help="print the voices file's names and exit")
+ p.add_argument("text_file", nargs="?")
+ args = p.parse_args()
+
+ t0 = time.perf_counter()
+ import numpy as np
+ from kokoro_onnx import Kokoro
+
+ kokoro = Kokoro(args.model, args.voices)
+ load = time.perf_counter() - t0
+
+ if args.list_voices:
+ print(json.dumps(sorted(kokoro.get_voices())))
+ return 0
+ if not args.output or not args.text_file:
+ print("tts_kokoro: --output and a text file are required", file=sys.stderr)
+ return 2
+ if args.voice not in kokoro.get_voices():
+ print(f"tts_kokoro: no voice {args.voice!r} in {args.voices}", file=sys.stderr)
+ return 2
+
+ with open(args.text_file, encoding="utf-8") as f:
+ text = f.read().strip()
+ if not text:
+ print("tts_kokoro: the text is empty", file=sys.stderr)
+ return 2
+
+ lang = args.lang or ("en-gb" if args.voice.startswith("b") else "en-us")
+ t1 = time.perf_counter()
+ samples, rate = kokoro.create(text, voice=args.voice, speed=args.speed, lang=lang)
+ synth = time.perf_counter() - t1
+
+ audio = np.clip(np.asarray(samples, dtype=np.float32).squeeze(), -1.0, 1.0)
+ pcm = (audio * 32767.0).astype("<i2")
+ with wave.open(args.output, "wb") as w:
+ w.setnchannels(1)
+ w.setsampwidth(2)
+ w.setframerate(int(rate))
+ w.writeframes(pcm.tobytes())
+
+ seconds = len(pcm) / float(rate)
+ print(
+ json.dumps(
+ {
+ "sampleRate": int(rate),
+ "seconds": round(seconds, 3),
+ "loadSeconds": round(load, 3),
+ "synthSeconds": round(synth, 3),
+ "rtf": round(synth / seconds, 3) if seconds else None,
+ "lang": lang,
+ }
+ )
+ )
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/settings.json.example b/settings.json.example
@@ -216,5 +216,12 @@
"pollSeconds": 60,
"standbyAfterSeconds": 600,
"bindInterface": ""
+ },
+ "tts": {
+ "engine": "kokoro",
+ "voice": "af_heart",
+ "speed": 1,
+ "home": "",
+ "dir": ""
}
}