// 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?, tuning?, reading?}`: 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. // `tuning` (`{temperature?, top_p?, top_k?, min_p?, repeat_penalty?, takes?}`) // and `reading` (a whole number, 0 = the first) read the same words again // differently (lib/ttsTuning.mjs: the ranges); an engine without a sampler // (kokoro, espeak-ng) ignores them and its result says so in `note`. // Every refusal comes back before a job exists — an unknown engine or voice, a // tag no engine knows (`` 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 — and, for Orpheus, its takes and tag // check plus any tuning or reading that is not the default) names // `/.wav` (48 kHz mono 16-bit) and `.json`, the sidecar that // discloses it (engine, model, licence, voice, seconds, `synthetic: true`, the // disclosure line; Orpheus: the tuning, reading and seed base). 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}`, plus for Orpheus `{tuning, reading, seedBase}` (the // effective values, defaults included) and, when a tuning was ignored, `note`. // `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 TtsAsk, type TtsEngine, type TtsTunedReport, } from "../lib/ttsApps"; import { unknownTtsTagsError } from "../lib/ttsText"; import { parseTtsTuning, ttsReadingError, type TtsTuning } from "../lib/ttsTuning.mjs"; import { ttsInstallState } from "../lib/ttsInstall"; import { DEFAULT_TTS_SETTINGS, resolveTtsCacheDir, resolveTtsHome, type TtsSettings, } from "../lib/ttsSettings"; import { gpuBusyFor, holdGpu, transcriptionOnGpu, waitForGpu } from "./gpuArbiter"; import { getTtsServerHolder, type TtsServerHolder } from "./ttsServer"; 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"; import "../lib/childKillGuard"; 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", "tuning", "reading"] 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 = { ok: true; value: T } | { ok: false; error: string }; // --- body -------------------------------------------------------------------- export type TtsFileBody = { text?: string; file?: string; voice?: string; engine?: string; speed?: number; out?: string; tuning?: TtsTuning; reading?: number; }; // The body's shape, judged without touching the disk. Every sentence here is // the refusal an ops caller reads. export function parseTtsFileBody(body: Record): Check { const { text, file, voice, engine, speed, out, tuning, reading } = 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}")` }; } } let tuned: TtsTuning | undefined; if (tuning !== undefined && tuning !== null) { const t = parseTtsTuning(tuning); if (!t.ok) return t; tuned = t.value; } if (reading !== undefined && reading !== null) { const err = ttsReadingError(reading); if (err) return { ok: false, error: err }; } 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) } : {}), ...(tuned ? { tuning: tuned } : {}), ...(typeof reading === "number" ? { reading } : {}), }, }; } // --- 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; // An engine with `tuned` (Orpheus): the tuning and reading as asked (in // range; the defaults are filled in by the engine). Never set for the rest. tuning?: TtsTuning; reading?: number; // Why a tuning or reading was not used (an engine without a sampler). note?: string; }; /** The tuning and reading a request hands its engine. */ export function ttsAskOf(req: Pick): TtsAsk { return { ...(req.tuning ? { tuning: req.tuning } : {}), ...(req.reading !== undefined ? { reading: req.reading } : {}), }; } // The body plus its text and settings.tts, resolved against the registry. Pure. export function resolveTtsRequest( body: TtsFileBody, text: string, tts: Pick, ): Check { 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(", ")}`, }; } // settings.tts.speed, like its voice, belongs to settings.tts.engine. const speed = body.speed ?? (engine.id === tts.engine ? tts.speed : 1); const [lo, hi] = engine.speedRange; if (speed < lo || speed > hi) { return { ok: false, error: `"speed" must be between ${lo} and ${hi} for ${engine.id} (got ${speed})` }; } 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" }; // A tuning or reading is an Orpheus knob: another engine reads as it always does, and says so. const asked = (body.tuning && Object.keys(body.tuning).length > 0) || (body.reading ?? 0) > 0; const tunable = Boolean(engine.tuned); return { ok: true, value: { engine, voice, speed, text, spoken, ...(body.file ? { file: body.file } : {}), ...(body.out ? { out: body.out } : {}), ...(tunable && body.tuning ? { tuning: body.tuning } : {}), ...(tunable && body.reading !== undefined ? { reading: body.reading } : {}), ...(!tunable && asked ? { note: `${engine.label} has no sampler or seed: the tuning and reading were ignored (it reads the same every time)` } : {}), }, }; } /** * The cache key: sha256 of (format version, engine, model, voice, speed, spoken * text) — plus, for an engine with `keyExtra` (Orpheus: its takes and tag * check, and a tuning or reading only when it is not the default), what else * changes its output. No tuning and no reading: the key it always had. */ export function ttsCacheKey( req: Pick, tts: TtsSettings = DEFAULT_TTS_SETTINGS, ): string { const key: unknown[] = [CACHE_KEY_VERSION, req.engine.id, req.engine.model, req.voice, req.speed, req.spoken]; if (req.engine.keyExtra) key.push(req.engine.keyExtra(tts, ttsAskOf(req))); return createHash("sha256").update(JSON.stringify(key)).digest("hex"); } // --- the disk checks ----------------------------------------------------------- export type TtsFileContext = { paths: Paths; cacheDir: string; home: string; tts?: TtsSettings; locations?: readonly Pick[]; }; // The text a body names: `text` as given, or the file read. Refusals as sentences. export async function readTtsBodyText(body: TtsFileBody): Promise> { 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> { 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, tts: ctx.tts ?? DEFAULT_TTS_SETTINGS, }); 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; // Orpheus: the chunks no take passed the checks for (the kept take named). flagged?: Flagged[]; // Orpheus: the tuning it was made with (every value), its reading and seed base. tuning?: TtsTunedReport["tuning"]; reading?: number; seedBase?: 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; // Orpheus: the EFFECTIVE tuning (defaults included), the reading and the seed // base it gave -- always, a cache hit too -- so a reading can be made again. tuning?: TtsTunedReport["tuning"]; reading?: number; seedBase?: number; // Why an asked tuning or reading was not used (kokoro, espeak-ng). note?: string; }; /** What a request's engine makes of its tuning and reading, or nothing (an engine without a sampler). */ export function ttsTunedOf(req: Pick, tts: TtsSettings = DEFAULT_TTS_SETTINGS): TtsTunedReport | null { return req.engine.tuned ? req.engine.tuned(tts, ttsAskOf(req)) : null; } 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 { 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 Flagged = { chunk: number; take: number; why: string }; type WrapperResult = { seconds?: number; sampleRate?: number; engineMs?: number; engineStats?: { flagged?: Flagged[]; takes?: number; chunks?: number }; }; export type RunTtsOpts = { paths: Paths; req: TtsRequest; sha: string; cacheDir: string; home: string; tts?: TtsSettings; onLog: (line: string) => void; signal?: AbortSignal; // Injected by tests: the server holder, and whether a transcription is // running on a GPU worker. servers?: TtsServerHolder; gpuBusy?: () => boolean; gpuPollMs?: number; }; // The GPU checks are the arbiter's (gpuArbiter.ts, release 27): TTS waits for // a transcription on a GPU worker AND for a running local-model draft call. export { transcriptionOnGpu, waitForGpu }; // 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 { 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`); const tts = opts.tts ?? DEFAULT_TTS_SETTINGS; const installDir = ttsInstallDir(opts.home, req.engine); await writeFile( textFile, req.engine.prepareInput ? req.engine.prepareInput(req.spoken, req.voice, tts, ttsAskOf(req)) : req.spoken, "utf8", ); let started = Date.now(); let server: { url: string; release: () => void } | null = null; let releaseGpu: (() => void) | null = null; try { // A GPU engine waits while a transcription holds the GPU; a server engine // takes its server (started for the batch behind the heavy slot, stopped // once the `tts` queue has been idle) and hands its URL to the wrapper. // The engine's time starts once both are in hand. if (req.engine.device === "gpu") { await waitForGpu({ busy: opts.gpuBusy ?? (() => gpuBusyFor("tts")), onLog, signal: opts.signal, pollMs: opts.gpuPollMs }); // Held while the engine runs: a draft call waits for it. releaseGpu = holdGpu("tts"); } if (req.engine.runtime === "server" && req.engine.serverCommand) { const holder = opts.servers ?? getTtsServerHolder(paths.monorepoRoot); server = await holder.acquire(req.engine.id, req.engine.serverCommand(installDir, tts), { onLog, signal: opts.signal, logFile: path.join(installDir, "server.log"), }); } started = Date.now(); const build = req.engine.build({ textFile, outWav: target.wav, voice: req.voice, speed: req.speed, installDir, bins: { ffmpegBin: paths.ffmpegBin, espeakNgBin: paths.espeakNgBin }, ...(server ? { server: server.url } : {}), }); 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 tuned = ttsTunedOf(req, tts); 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, ...(res.engineStats?.flagged?.length ? { flagged: res.engineStats.flagged } : {}), ...(tuned ?? {}), }; if (sidecar.flagged) { onLog( `${sidecar.flagged.length} chunk(s) FLAGGED — no take passed the checks: ` + sidecar.flagged.map((f) => `chunk ${f.chunk} (${f.why})`).join("; "), ); } await writeJsonAtomic(target.json, sidecar, { indent: 2 }); return sidecar; } finally { releaseGpu?.(); server?.release(); await rm(textFile, { force: true }).catch(() => {}); } } function describe(req: TtsRequest): string { const chars = req.spoken.length; const tuned = Object.entries(req.tuning ?? {}).map(([k, v]) => `${k} ${v}`); if (req.reading) tuned.push(`reading ${req.reading}`); return `${chars} character${chars === 1 ? "" : "s"} with ${req.engine.id} · ${req.voice} at ${req.speed}x` + (tuned.length ? ` (${tuned.join(", ")})` : ""); } // --- 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, opts: { paths: Paths }, ): Promise { 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, tts: settings.tts, locations: settings.storage?.locations ?? [], }); if (!checked.ok) return checked; const req = checked.value; const sha = ttsCacheKey(req, settings.tts); 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}` : ""}`); if (req.note) onLog(`Note: ${req.note}`); // 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, tts: settings.tts, onLog, signal }); onLog( `Synthesized ${side.seconds}s of audio in ${(side.durationMs / 1000).toFixed(1)}s` + ` (RTF ${side.seconds > 0 ? (side.durationMs / 1000 / side.seconds).toFixed(2) : "n/a"})`, ); } 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, ...(ttsTunedOf(req, settings.tts) ?? {}), ...(req.note ? { note: req.note } : {}), }; onLog(`${TTS_RESULT_MARKER}${JSON.stringify(result)}`); }, }); }