#!/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. // // THREE ENGINES, PICKED BY --engine-kind: // kokoro Kokoro-82M through scripts/tts_kokoro.py (kokoro-onnx on the // CPU) in the venv `archilyzer tts setup` built. Its native rate // is 24 kHz. // espeak-ng The formant synthesizer every Linux has: the zero-install // fallback, and what the tests run. // orpheus Orpheus 3B through scripts/tts_orpheus.py (onnxruntime for the // SNAC decoder) against a llama-server the editor started // (--server). Its input is not text but the editor's JSON of // chunks, sampler, seed base and takes (common/lib/ttsApps.ts // prepareInput: a synthesis's tuning and reading are already in // it, so this passes it through untouched); the voice is in it. // 24 kHz native. // // WHAT IT WRITES is always the same shape whatever the engine: a 48 kHz mono // 16-bit PCM WAV with a bare 44-byte header (ffmpeg, bit-exact, no metadata), // 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] (or --text "" in place of the file) // // Options (env fallback in parens): // --output the WAV to write [required] // --engine-kind kokoro | espeak-ng | orpheus (default kokoro) // --voice a stock voice of the engine (default: the engine's) // --speed 0.5-2, 1 = the engine's natural pace (default 1) // --text the text itself, in place of // --python

the venv's python [kokoro] // --model

kokoro-v1.0.onnx [kokoro] // --voices

voices-v1.0.bin [kokoro] // --espeak espeak-ng binary (ESPEAK_NG_BIN, espeak-ng) [espeak-ng] // --python

the venv's python [orpheus] // --snac

snac_decoder.onnx [orpheus] // --server the running llama-server [orpheus] // --ffmpeg 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] (or --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, orpheus (needs \`archilyzer tts setup --engine orpheus\` and a running llama-server). See the header of this file for the full option list.`; const SAMPLE_RATE = 48_000; 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 "); const engineKind = arg("--engine-kind", "kokoro"); if (engineKind !== "kokoro" && engineKind !== "espeak-ng" && engineKind !== "orpheus") { fail(`--engine-kind must be 'kokoro', 'espeak-ng' or 'orpheus' (got '${engineKind}')`); } let voice = arg("--voice", DEFAULT_VOICE[engineKind]); const speed = Number(arg("--speed", "1")); if (!Number.isFinite(speed) || speed < 0.5 || speed > 2) fail("--speed must be between 0.5 and 2"); const ffmpeg = arg("--ffmpeg", process.env.FFMPEG_BIN ?? "ffmpeg"); const inlineText = arg("--text", undefined); if (inlineText === undefined && !positional[0]) fail("missing (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, () => { // (A child with no pid never started: Node would signal this process's own group — common/lib/childKillGuard.ts.) if (child?.pid !== undefined) 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 if (engineKind === "orpheus") { const python = arg("--python", ""); const snac = arg("--snac", ""); const server = arg("--server", ""); if (!python) throw new Error("missing --python (the venv `archilyzer tts setup --engine orpheus` built)"); if (!snac) throw new Error("missing --snac (snac_decoder.onnx)"); if (!server) throw new Error("missing --server (the llama-server the editor started)"); let spec; try { spec = JSON.parse(text); } catch { throw new Error("orpheus reads the editor's JSON of chunks, not plain text"); } voice = spec.voice; const stdout = await run(python, [ path.join(import.meta.dirname, "tts_orpheus.py"), "--server", server, "--snac", snac, "--output", raw, textFile, ]); try { extra = JSON.parse(stdout.trim().split("\n").pop() ?? "{}"); } catch { extra = {}; } } else { const espeak = arg("--espeak", process.env.ESPEAK_NG_BIN ?? "espeak-ng"); // espeak-ng's pace is words per minute; 175 is its default. 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); }