commit 31fcfff17c3c32fbc1840deb23cb28047a89a19c
parent 4e33b2f59622dec5e7c4ff912091dd900034a982
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Sun, 11 Oct 2026 00:43:23 -0400
tts: the tts-file job — one synthesis on the tts queue, content-addressed cache
controller/ttsFile.ts takes {text | file, voice?, engine?, speed?, out?},
refuses before any job (an unknown engine or stock voice, a speed out of the
engine's range, a tag no engine knows, an engine not installed, an `out` or a
cache dir inside the corpus), and runs the engine through scripts/tts.mjs on
the `tts` queue, one at a time. The cache is sha256 of (engine, model, voice,
speed, normalized text) -> <dir>/<sha>.wav + <sha>.json, the sidecar that
discloses the synthetic voice; a hit is a done job with cached: true that runs
no engine and waits on no queue. The log ends with
`@@tts-result {wav, seconds, engine, voice, cached, durationMs, waitedMs,
sha, sampleRate, speed, disclosure}`.
lib/ttsInstall.ts says whether an engine is installed (the venv and the
pinned model files, or the system binary).
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
6 files changed, 920 insertions(+), 0 deletions(-)
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/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/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 };
+}