commit f889ac4c1ae93a0139eef397b74222994d720a2c
parent 3c6cde68c815c116269799dc472a332c3918d64c
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Sun, 11 Oct 2026 00:33:01 -0400
tts: the engine registry, the text pre-pass and the text-in, WAV-out wrapper
common/lib/ttsApps.ts registers Kokoro-82M (default voice af_heart, its 28
English stock voices, the pinned model files) and espeak-ng (the zero-install
fallback). Each engine names its model, licence, device, runtime, voices,
speed range, setup and its own pre-pass, and builds the argv for
scripts/tts.mjs, which runs the engine (scripts/tts_kokoro.py for Kokoro) and
leaves a 48 kHz mono 16-bit WAV in place atomically.
common/lib/ttsText.ts is the shared pre-pass: the expressive tag set
(TTS_EXPRESSIVE_TAGS, stripped for engines that cannot perform them, any
other <...> refused), years 1900-2099 spoken, whitespace collapsed.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
| A | common/lib/ttsApps.test.ts | | | 108 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| A | common/lib/ttsApps.ts | | | 246 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| A | common/lib/ttsText.test.ts | | | 132 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| A | common/lib/ttsText.ts | | | 163 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| A | scripts/tts.mjs | | | 223 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| A | scripts/tts.test.mjs | | | 94 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| A | scripts/tts_kokoro.py | | | 89 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
7 files changed, 1055 insertions(+), 0 deletions(-)
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/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/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())