commit 9d02a1bbd5cb1285e35f15bf6db692f2b78d37bc
parent ac147eda95f61ed777f1fced4f16591bb9ad0d4a
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Sun, 11 Oct 2026 12:23:10 -0400
tts: Orpheus 3B as a second engine — GPU, on a llama-server the editor starts and stops
The registry gains `orpheus`: Orpheus 3B 0.1-ft (Q8_0 GGUF) on llama.cpp's
server, its SNAC 24 kHz codes decoded by the ONNX decoder on the CPU; the
eight stock speakers, leah by default and zac the male option; tags
performed; no speed control; "Llama 3.2 Community License + Apache-2.0",
disclosed with "Built with Llama". settings.tts.orpheus holds the server
(llama-server, LD_LIBRARY_PATH, GGML_BACKEND_PATH — Ollama's bundled Vulkan
build by default — port, -ngl, -c), its idle stop, its heavy-slot estimate,
the takes per chunk and the tag-length check (off).
controller/ttsServer.ts starts the server for a batch behind the heavy slot,
reuses it, and stops its process group (SIGTERM, SIGKILL after 15 s) once
the tts queue has been idle, on a failed or cancelled start, and when the
editor exits; a port something else answers on is refused. A GPU engine
waits while a transcription runs on a non-CPU worker.
scripts/tts_orpheus.py renders the editor's chunks: up to three seeded
takes each, the first that passes the non-ASR checks kept (end token, no
malformed frame, words/s in band with the floor lowered 0.25 for each
sentence past the first, no long silence), the joins trimmed, matched,
faded and paused by punctuation; a chunk no take passes is flagged in the
log and the sidecar. The tuning round's UTMOS scorer is not ported: it
needs torch.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
19 files changed, 1750 insertions(+), 73 deletions(-)
diff --git a/ENVIRONMENT.md b/ENVIRONMENT.md
@@ -151,6 +151,7 @@ The publish pipeline sets these for a process it spawns. Listed so a reader know
| `BUILD_ARCHIVES` | on | `0` skips archive-zip generation for one build (`--skip-archives`). | common/bin/compose-site.ts, common/bin/build-archives.ts |
| `REPORTS_ALLOW_MISSING_MEDIA` | off | `1` lets a report citation whose evidence media was not prepared through compose (`--allow-missing-media`): its moment page renders without a clip. Off, compose fails with the list. | common/bin/compose-site.ts |
| `ARCHIVES_READONLY` | off | `1` inside a docker-mode build container: materialize archives, never write the shared cache. | common/bin/compose-site.ts |
+| `GGML_BACKEND_PATH` | settings.tts.orpheus.ggmlBackendPath | The ggml backend llama-server loads (Vulkan by default), set for the Orpheus server the editor starts — from `settings.tts.orpheus.ggmlBackendPath`, never the environment. | common/lib/ttsApps.ts |
| `HOMEPAGE_PUBLIC_DIR` | `<repo>/homepage/public` | Where `compose homepage` and `source publish` write. | common/bin/compose-homepage.ts, common/publish/source.ts |
## Docker
diff --git a/SETTINGS.md b/SETTINGS.md
@@ -897,11 +897,28 @@ Local text-to-speech (release 25): narration for report videos and podcasts, syn
| Key | Default | Description |
|---|---|---|
-| `engine` | `"kokoro"` | The engine a synthesis uses when the request names none: `kokoro` (Kokoro-82M, Apache-2.0, CPU; installed by `archilyzer tts setup`) or `espeak-ng` (the zero-install fallback). An unknown id falls back to `kokoro`. |
-| `voice` | `"af_heart"` | The engine's stock voice when the request names none (stock voices only: no cloning, no reference audio). For Kokoro, `a*` voices are American English and `b*` British; `af_heart` was picked by ear in the release 25 bake-off. A voice the engine does not have falls back to the engine's default. |
-| `speed` | `1` | Speaking pace, 1 = the engine's natural pace (Kokoro speaks briskly; 0.9 slows it). Clamped to [0.5, 2]. In the cache key: a new speed is a new synthesis. |
+| `engine` | `"kokoro"` | The engine a synthesis uses when the request names none: `kokoro` (Kokoro-82M, Apache-2.0, CPU; installed by `archilyzer tts setup`), `orpheus` (Orpheus 3B, Llama 3.2 Community License + Apache-2.0, "Built with Llama"; GPU, on a local llama-server — `tts.orpheus`; `archilyzer tts setup --engine orpheus`) or `espeak-ng` (the zero-install fallback). An unknown id falls back to `kokoro`. |
+| `voice` | `"af_heart"` | The engine's stock voice when the request names none (stock voices only: no cloning, no reference audio). For Kokoro, `a*` voices are American English and `b*` British; `af_heart` was picked by ear in the release 25 bake-off. Orpheus: tara leah jess leo dan mia zac zoe — `leah` its default, `zac` the male option. A voice the engine does not have falls back to the engine's default. |
+| `speed` | `1` | Speaking pace, 1 = the engine's natural pace (Kokoro speaks briskly; 0.9 slows it). Clamped to the engine's range: [0.5, 2] for Kokoro and espeak-ng; Orpheus has none (1). In the cache key: a new speed is a new synthesis. |
| `home` | `""` | Where `archilyzer tts setup` installs engines, one directory per engine (`<home>/kokoro`: its python venv and model files). Blank = `~/.local/share/archilyzer/tts`. Absolute, or `~/`-relative. |
| `dir` | `""` | The synthesis cache: `<sha256>.wav` (48 kHz mono 16-bit) and a `<sha256>.json` sidecar (engine, model, licence, voice, seconds, disclosure) per distinct (engine, model, voice, speed, normalized text) — a re-ask is free. Never inside the corpus (refused). Blank = `<repo>/.tts/cache` (gitignored). Absolute, or `~/`-relative. |
+| `orpheus` | object — see below | Orpheus 3B's server and takes. See OrpheusTtsSettings (`tts.orpheus` below). |
+
+#### `tts.orpheus`
+
+| Key | Default | Description |
+|---|---|---|
+| `serverBin` | `"/usr/lib/ollama/llama-server"` | The llama.cpp server Orpheus runs on (`llama-server`). Default: Ollama's bundled build. Started for a batch of syntheses on the `tts` queue and stopped (SIGTERM, then SIGKILL after 15 s) once the queue has been idle `idleStopSeconds`, so its VRAM is freed. |
+| `libraryPath` | `"/usr/lib/ollama"` | `LD_LIBRARY_PATH` for the server (Ollama's bundled libraries). Blank = not set. |
+| `ggmlBackendPath` | `"/usr/lib/ollama/vulkan/libggml-vulkan.so"` | `GGML_BACKEND_PATH` for the server: the ggml backend it loads — Vulkan by default. Blank = not set. |
+| `port` | `8799` | The port the server listens on, on 127.0.0.1. A port something else already answers on is refused, never shared. |
+| `gpuLayers` | `99` | `-ngl`: layers on the GPU. 99 = all of them; 0 runs on the CPU (about 9× slower). |
+| `contextSize` | `8192` | `-c`, the context in tokens; also the whole window the repeat penalty could see. |
+| `startTimeoutSeconds` | `150` | How long the server may take to answer `/health` once it is running (it took 2.5–14 s in the tuning round). The wait for the machine's heavy slot before it starts is not counted. |
+| `idleStopSeconds` | `5` | How long the server is kept after the last synthesis before it is stopped, so the next one in the queue reuses it. |
+| `heavyEstimateMB` | `4000` | The memory the server is admitted to the heavy slot with (`queue-lock --heavy --estimate`): it starts only when that much is free above the floor, beside other estimated jobs, never beside a build. |
+| `takes` | `3` | Takes per chunk, at most: the first that passes the checks (end token reached, no malformed frame, not truncated, words a second in band, no long silence) is kept. 1–6. |
+| `tagCheck` | `false` | The tag-length check: a chunk with expressive tags must run at least 0.4 s a tag longer than the same voice reading it without them (one extra take of the stripped text per tagged chunk), else the take is taken to have skipped its tag. OFF by default. (The tuning round's UTMOS scorer is not offered: it needs torch.) |
Default:
@@ -911,6 +928,19 @@ Default:
"voice": "af_heart",
"speed": 1,
"home": "",
- "dir": ""
+ "dir": "",
+ "orpheus": {
+ "serverBin": "/usr/lib/ollama/llama-server",
+ "libraryPath": "/usr/lib/ollama",
+ "ggmlBackendPath": "/usr/lib/ollama/vulkan/libggml-vulkan.so",
+ "port": 8799,
+ "gpuLayers": 99,
+ "contextSize": 8192,
+ "startTimeoutSeconds": 150,
+ "idleStopSeconds": 5,
+ "heavyEstimateMB": 4000,
+ "takes": 3,
+ "tagCheck": false
+ }
}
```
diff --git a/common/controller/ttsFile.test.ts b/common/controller/ttsFile.test.ts
@@ -39,6 +39,21 @@ 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 argv = process.argv.slice(2);
+if (argv.includes("orpheus")) {
+ // Orpheus stand-in: keep its input, write a 1 s 48 kHz WAV, report one flagged chunk.
+ fs.writeFileSync(${JSON.stringify(path.join(ROOT, "orpheus-input.json"))}, text);
+ const out = argv[argv.indexOf("--output") + 1];
+ const data = Buffer.alloc(96000);
+ const h = Buffer.alloc(44);
+ h.write("RIFF", 0); h.writeUInt32LE(36 + data.length, 4); h.write("WAVE", 8); h.write("fmt ", 12);
+ h.writeUInt32LE(16, 16); h.writeUInt16LE(1, 20); h.writeUInt16LE(1, 22); h.writeUInt32LE(48000, 24);
+ h.writeUInt32LE(96000, 28); h.writeUInt16LE(2, 32); h.writeUInt16LE(16, 34); h.write("data", 36); h.writeUInt32LE(data.length, 40);
+ fs.writeFileSync(out, Buffer.concat([h, data]));
+ console.error("orpheus: chunk 1/2 take 1 seed 1234: PASS");
+ console.log(JSON.stringify({ engine: "orpheus", voice: "zac", sampleRate: 48000, seconds: 1, engineStats: { flagged: [{ chunk: 2, take: 3, why: "internal silence 1.40s > 1.3s" }] } }));
+ process.exit(0);
+}
const r = spawnSync(process.execPath, [${JSON.stringify(WRAPPER)}, ...process.argv.slice(2)], { stdio: "inherit" });
process.exit(r.status ?? 1);
`,
@@ -57,6 +72,8 @@ process.env.SETTINGS_FILE = SETTINGS_FILE;
process.env.TTS_BIN = shim;
const {
+ runTtsSynthesis,
+ waitForGpu,
TTS_FILE_BODY_KEYS,
TTS_MAX_CHARS,
TTS_RESULT_MARKER,
@@ -69,6 +86,7 @@ const {
} = await import("./ttsFile");
const { getPaths } = await import("../lib/paths");
const { getTtsEngine } = await import("../lib/ttsApps");
+const { DEFAULT_TTS_SETTINGS, sanitizeTts } = await import("../lib/ttsSettings");
const paths = getPaths();
function has(bin: string, flag: string): boolean {
@@ -283,3 +301,122 @@ test("a failing engine fails the job with its words, and leaves no cache entry",
assert.equal(await engineRuns(), runs + 1);
assert.deepEqual((await readdir(CACHE).catch(() => [] as string[])).sort(), before);
});
+
+// --- Orpheus (T1b): the refusals, the GPU wait, the server, the input ------------
+
+test("Orpheus requests: leah by default, a stock voice, no speed but 1", () => {
+ const tts = { engine: "orpheus", voice: "leah", speed: 1 };
+ const r = resolveTtsRequest({}, "Back in 2024 <chuckle> it ended.", tts);
+ assert.ok(r.ok);
+ if (r.ok) {
+ assert.equal(r.value.voice, "leah");
+ assert.equal(r.value.spoken, "Back in twenty twenty-four <chuckle> it ended.");
+ }
+ const k = resolveTtsRequest({ engine: "orpheus" }, "x", { engine: "kokoro", voice: "af_heart", speed: 0.9 });
+ assert.ok(k.ok && k.value.voice === "leah" && k.value.speed === 1, "Kokoro's speed setting is not Orpheus's");
+ const cases: [Parameters<typeof resolveTtsRequest>[0], string, RegExp][] = [
+ [{ engine: "orpheus", voice: "af_heart" }, "x", /orpheus has no stock voice "af_heart" — its voices: tara, leah, jess, leo, dan, mia, zac, zoe/],
+ [{ engine: "orpheus", voice: "/home/someone/reference.wav" }, "x", /orpheus has no stock voice/],
+ [{ engine: "orpheus", speed: 0.9 }, "x", /"speed" must be between 1 and 1 for orpheus/],
+ [{ engine: "orpheus" }, "a <smirk>", /a tag no engine knows: <smirk>/],
+ ];
+ for (const [body, text, re] of cases) {
+ const x = resolveTtsRequest(body, text, tts);
+ assert.equal(x.ok, false);
+ if (!x.ok) assert.match(x.error, re);
+ }
+});
+
+test("Orpheus not installed: the venv, the model files and the server binary are named", async () => {
+ const r = resolveTtsRequest({ engine: "orpheus" }, "x", { engine: "kokoro", voice: "af_heart", speed: 1 });
+ assert.ok(r.ok);
+ if (!r.ok) return;
+ const tts = sanitizeTts({ orpheus: { serverBin: path.join(ROOT, "no-llama-server") } });
+ const c = await checkTtsRequest(r.value, { paths, cacheDir: CACHE, home: HOME, tts });
+ assert.ok(!c.ok);
+ if (!c.ok) {
+ assert.match(c.error, /Orpheus 3B is not installed \(.*tts-home\/orpheus\): missing the python venv/);
+ assert.match(c.error, /orpheus-3b-0\.1-ft-Q8_0\.gguf; snac_decoder\.onnx; snac_config\.json/);
+ assert.match(c.error, /llama-server \(settings\.tts\.orpheus\.serverBin\): .*no-llama-server/);
+ assert.match(c.error, /run `archilyzer tts setup --engine orpheus`/);
+ }
+});
+
+test("a GPU engine waits while a transcription holds the GPU, and can be cancelled while it waits", async () => {
+ const lines: string[] = [];
+ assert.equal(await waitForGpu({ busy: () => false, onLog: (l) => lines.push(l) }), 0);
+ assert.equal(lines.length, 0);
+ let polls = 0;
+ const waited = await waitForGpu({ busy: () => polls++ < 3, onLog: (l) => lines.push(l), pollMs: 10 });
+ assert.ok(waited >= 20);
+ assert.match(lines[0], /Waiting for the GPU: a transcription is running/);
+ assert.match(lines[1], /The GPU is free/);
+ const ac = new AbortController();
+ setTimeout(() => ac.abort(), 30);
+ await assert.rejects(waitForGpu({ busy: () => true, onLog: () => {}, signal: ac.signal, pollMs: 10 }), /cancelled while waiting for the GPU/);
+});
+
+test("an Orpheus synthesis: GPU wait, then its server, then the wrapper with the server's URL; released after", async () => {
+ const r = resolveTtsRequest({ engine: "orpheus", voice: "zac" }, "One file. No title. <sigh>\n\nThen in 2024, it came back.", {
+ engine: "kokoro", voice: "af_heart", speed: 1,
+ });
+ assert.ok(r.ok);
+ if (!r.ok) return;
+ const events: string[] = [];
+ let gpuPolls = 0;
+ const servers = {
+ acquire: async (key: string, cmd: { port: number }) => {
+ events.push(`acquire ${key} ${cmd.port}`);
+ return { url: "http://127.0.0.1:8799", release: () => events.push("release") };
+ },
+ };
+ const lines: string[] = [];
+ const sha = ttsCacheKey(r.value, DEFAULT_TTS_SETTINGS);
+ const side = await runTtsSynthesis({
+ paths,
+ req: r.value,
+ sha,
+ cacheDir: CACHE,
+ home: HOME,
+ tts: DEFAULT_TTS_SETTINGS,
+ onLog: (l) => lines.push(l),
+ servers: servers as never,
+ gpuBusy: () => (events.push("gpu?"), gpuPolls++ < 1),
+ gpuPollMs: 5,
+ });
+ assert.deepEqual(events, ["gpu?", "gpu?", "acquire orpheus 8799", "release"]);
+ const runs = (await readFile(RUNS, "utf8")).trim().split("\n").map((l) => JSON.parse(l) as string[]);
+ const argv = runs[runs.length - 1];
+ assert.equal(argv[argv.indexOf("--server") + 1], "http://127.0.0.1:8799");
+ assert.ok(argv[argv.indexOf("--python") + 1].endsWith("tts-home/orpheus/venv/bin/python"));
+ // The wrapper read the chunks, not the text.
+ const input = JSON.parse(await readFile(path.join(ROOT, "orpheus-input.json"), "utf8"));
+ assert.equal(input.voice, "zac");
+ assert.deepEqual(input.chunks.map((c: { text: string }) => c.text), ["One file. No title. <sigh>", "Then in twenty twenty-four, it came back."]);
+ // Disclosed with its attribution; the flagged chunk recorded and logged.
+ assert.equal(side.disclosure, "Narration: synthetic voice (Orpheus 3B · zac). Built with Llama");
+ assert.equal(side.attribution, "Built with Llama");
+ assert.equal(side.license, "Llama 3.2 Community License + Apache-2.0");
+ assert.deepEqual(side.flagged, [{ chunk: 2, take: 3, why: "internal silence 1.40s > 1.3s" }]);
+ assert.ok(lines.some((l) => /1 chunk\(s\) FLAGGED — no take passed the checks: chunk 2/.test(l)), lines.join("\n"));
+ assert.ok(lines.some((l) => /Waiting for the GPU/.test(l)));
+ // The takes and tag check are in the key: another setting is another synthesis.
+ assert.notEqual(ttsCacheKey(r.value, sanitizeTts({ orpheus: { takes: 1 } })), sha);
+ assert.equal(ttsCacheKey(r.value, sanitizeTts({ orpheus: { port: 9000 } })), sha);
+});
+
+test("a failing Orpheus wrapper still releases the server", async () => {
+ const r = resolveTtsRequest({ engine: "orpheus" }, "Please explode now.", { engine: "orpheus", voice: "leah", speed: 1 });
+ assert.ok(r.ok);
+ if (!r.ok) return;
+ const events: string[] = [];
+ const servers = { acquire: async () => ({ url: "http://127.0.0.1:1", release: () => events.push("release") }) };
+ await assert.rejects(
+ runTtsSynthesis({
+ paths, req: r.value, sha: ttsCacheKey(r.value), cacheDir: CACHE, home: HOME, onLog: () => {},
+ servers: servers as never, gpuBusy: () => false,
+ }),
+ /the orpheus synthesis failed/,
+ );
+ assert.deepEqual(events, ["release"]);
+});
diff --git a/common/controller/ttsFile.ts b/common/controller/ttsFile.ts
@@ -49,10 +49,13 @@ import {
import { unknownTtsTagsError } from "../lib/ttsText";
import { ttsInstallState } from "../lib/ttsInstall";
import {
+ DEFAULT_TTS_SETTINGS,
resolveTtsCacheDir,
resolveTtsHome,
type TtsSettings,
} from "../lib/ttsSettings";
+import { getWorkerPool } from "../jobs/workerPool";
+import { getTtsServerHolder, type TtsServerHolder } from "./ttsServer";
import { TTS_QUEUE } from "../lib/queueKeys";
import { copyFileAtomic, writeJsonAtomic } from "../lib/jsonFile-server";
import { getSettings } from "../lib/settings";
@@ -177,7 +180,8 @@ export function resolveTtsRequest(
error: `${engine.id} has no stock voice "${voice}" — its voices: ${engine.voices.join(", ")}`,
};
}
- const speed = body.speed ?? tts.speed;
+ // 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})` };
@@ -206,20 +210,18 @@ export function resolveTtsRequest(
};
}
-/** 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 cache key: sha256 of (format version, engine, model, voice, speed, spoken
+ * text) — plus, for an engine with `keyExtra` (Orpheus: its takes and tag
+ * check), the settings that change its output.
+ */
+export function ttsCacheKey(
+ req: Pick<TtsRequest, "engine" | "voice" | "speed" | "spoken">,
+ 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));
+ return createHash("sha256").update(JSON.stringify(key)).digest("hex");
}
// --- the disk checks -----------------------------------------------------------
@@ -228,6 +230,7 @@ export type TtsFileContext = {
paths: Paths;
cacheDir: string;
home: string;
+ tts?: TtsSettings;
locations?: readonly Pick<StorageLocation, "root">[];
};
@@ -288,7 +291,11 @@ export async function checkTtsRequest(
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 });
+ const install = ttsInstallState(req.engine, {
+ home: ctx.home,
+ paths: ctx.paths,
+ tts: ctx.tts ?? DEFAULT_TTS_SETTINGS,
+ });
if (!install.installed) {
return {
ok: false,
@@ -324,6 +331,8 @@ export type TtsSidecar = {
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[];
};
export type TtsResult = {
@@ -361,7 +370,13 @@ export async function readTtsCacheHit(cacheDir: string, sha: string): Promise<Tt
// --- the work ------------------------------------------------------------------
-type WrapperResult = { seconds?: number; sampleRate?: number; engineMs?: number };
+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;
@@ -369,10 +384,45 @@ export type RunTtsOpts = {
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;
};
+// A transcription running on a local worker that is not explicitly on the CPU
+// (an unknown device may be the GPU: parakeet-cli's default can be).
+export function transcriptionOnGpu(): boolean {
+ return getWorkerPool()
+ .summary()
+ .some((w) => w.busy && w.kind === "local" && (w.device ?? "").toLowerCase() !== "cpu");
+}
+
+// A GPU engine waits while a transcription holds the GPU — the `tts` queue
+// yields to transcription. It only waits to START; a synthesis running is
+// never interrupted.
+export async function waitForGpu(opts: {
+ busy: () => boolean;
+ onLog: (line: string) => void;
+ signal?: AbortSignal;
+ pollMs?: number;
+}): Promise<number> {
+ const t0 = Date.now();
+ if (!opts.busy()) return 0;
+ opts.onLog("Waiting for the GPU: a transcription is running…");
+ while (opts.busy()) {
+ if (opts.signal?.aborted) throw new Error("cancelled while waiting for the GPU");
+ await new Promise((r) => setTimeout(r, opts.pollMs ?? 5000));
+ }
+ const waited = Date.now() - t0;
+ opts.onLog(`The GPU is free (waited ${(waited / 1000).toFixed(1)}s)`);
+ return waited;
+}
+
// 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> {
@@ -380,20 +430,40 @@ export async function runTtsSynthesis(opts: RunTtsOpts): Promise<TtsSidecar> {
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();
+ 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) : req.spoken,
+ "utf8",
+ );
+ let started = Date.now();
+ let server: { url: string; release: () => void } | null = null;
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.
+ // 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 ?? transcriptionOnGpu, onLog, signal: opts.signal, pollMs: opts.gpuPollMs });
+ }
+ 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: ttsInstallDir(opts.home, req.engine),
+ installDir,
bins: { ffmpegBin: paths.ffmpegBin, espeakNgBin: paths.espeakNgBin },
+ ...(server ? { server: server.url } : {}),
});
const child = execa(paths.ttsBin, build.argv, {
cancelSignal: opts.signal,
@@ -449,10 +519,18 @@ export async function runTtsSynthesis(opts: RunTtsOpts): Promise<TtsSidecar> {
text: req.spoken,
createdAt: new Date().toISOString(),
durationMs: Date.now() - started,
+ ...(res.engineStats?.flagged?.length ? { flagged: res.engineStats.flagged } : {}),
};
+ 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 {
+ server?.release();
await rm(textFile, { force: true }).catch(() => {});
}
}
@@ -483,11 +561,12 @@ export async function enqueueTtsFile(
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);
+ const sha = ttsCacheKey(req, settings.tts);
const hitAtEnqueue = await readTtsCacheHit(cacheDir, sha);
const asked = Date.now();
return runManagedFunction({
@@ -504,7 +583,7 @@ export async function enqueueTtsFile(
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 });
+ 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"})`,
diff --git a/common/controller/ttsServer.test.ts b/common/controller/ttsServer.test.ts
@@ -0,0 +1,172 @@
+import { test, after } from "node:test";
+import assert from "node:assert/strict";
+import { chmod, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import http from "node:http";
+import net from "node:net";
+import os from "node:os";
+import path from "node:path";
+import { TtsServerHolder, portAnswers } from "./ttsServer";
+import type { TtsServerCommand } from "../lib/ttsApps";
+
+// Run with:
+// pnpm --filter yt-dlp-transcript-common exec tsx --test controller/ttsServer.test.ts
+//
+// The server lifecycle against a FAKE llama-server (a node script that answers
+// /health): started once for a batch, reused, stopped after the idle window
+// (SIGTERM to its group), stopped at once when the start fails or is
+// cancelled, SIGKILLed when it ignores SIGTERM, and never started beside
+// something already answering on its port. No GPU, no model.
+
+const ROOT = await mkdtemp(path.join(os.tmpdir(), "tts-server-"));
+after(() => rm(ROOT, { recursive: true, force: true }));
+
+// The fake: `--port <p>`; answers /health 200 after DELAY_MS (503 before);
+// writes "started"/"term" lines to EVENTS; IGNORE_TERM ignores SIGTERM;
+// EXIT_AT_ONCE exits 3 before listening.
+const fake = path.join(ROOT, "fake-llama-server");
+await writeFile(
+ fake,
+ `#!/usr/bin/env node
+const http = require("node:http");
+const fs = require("node:fs");
+const args = process.argv.slice(2);
+const port = Number(args[args.indexOf("--port") + 1]);
+const ev = (l) => fs.appendFileSync(process.env.EVENTS, l + " " + process.pid + "\\n");
+console.error("fake llama-server: loading model " + args[args.indexOf("-m") + 1]);
+if (process.env.EXIT_AT_ONCE) { console.error("fake: cannot load the model"); process.exit(3); }
+ev("started");
+const t0 = Date.now();
+http.createServer((q, r) => {
+ const ready = Date.now() - t0 >= Number(process.env.DELAY_MS || 0);
+ r.statusCode = q.url === "/health" && ready ? 200 : 503;
+ r.end("{}");
+}).listen(port, "127.0.0.1");
+process.on("SIGTERM", () => { ev("term"); if (!process.env.IGNORE_TERM) process.exit(0); });
+`,
+);
+await chmod(fake, 0o755);
+
+async function freePort(): Promise<number> {
+ return new Promise((resolve) => {
+ const s = net.createServer().listen(0, "127.0.0.1", () => {
+ const p = (s.address() as net.AddressInfo).port;
+ s.close(() => resolve(p));
+ });
+ });
+}
+
+let n = 0;
+async function cmd(env: Record<string, string> = {}, over: Partial<TtsServerCommand> = {}) {
+ const port = await freePort();
+ const events = path.join(ROOT, `events-${n++}.log`);
+ const c: TtsServerCommand = {
+ bin: fake,
+ args: ["-m", "/models/x.gguf", "--host", "127.0.0.1", "--port", String(port)],
+ env: { EVENTS: events, ...env },
+ host: "127.0.0.1",
+ port,
+ estimateMB: 0,
+ startTimeoutMs: 10_000,
+ idleStopMs: 150,
+ ...over,
+ };
+ return { c, events, port };
+}
+const events = async (f: string) => (await readFile(f, "utf8").catch(() => "")).split("\n").filter(Boolean);
+const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
+async function until(pred: () => Promise<boolean>, ms = 5000) {
+ const t0 = Date.now();
+ while (!(await pred())) {
+ if (Date.now() - t0 > ms) throw new Error("timed out");
+ await sleep(25);
+ }
+}
+
+test("one server for a batch: started once, reused, stopped once the queue is idle", async () => {
+ const holder = new TtsServerHolder({ gate: null, pollMs: 25 });
+ const { c, events: ev, port } = await cmd({ DELAY_MS: "200" });
+ const lines: string[] = [];
+ const logFile = path.join(ROOT, "server-a.log");
+ const a = await holder.acquire("orpheus", c, { onLog: (l) => lines.push(l), logFile });
+ assert.equal(a.url, `http://127.0.0.1:${port}`);
+ assert.equal((await fetch(`${a.url}/health`)).status, 200);
+ assert.match(lines[0], /Starting the orpheus server on 127\.0\.0\.1:\d+…/);
+ assert.match(lines[lines.length - 1], /The orpheus server is up/);
+ // The server's own lines go to its log, not the job's.
+ assert.match(await readFile(logFile, "utf8"), /fake llama-server: loading model \/models\/x\.gguf/);
+ a.release();
+ // The next synthesis arrives inside the idle window: the same server.
+ await sleep(50);
+ const b = await holder.acquire("orpheus", c, { onLog: () => {} });
+ assert.equal((await events(ev)).filter((l) => l.startsWith("started")).length, 1);
+ b.release();
+ b.release(); // a second release is a no-op
+ assert.equal(holder.running("orpheus"), true);
+ await until(async () => !holder.running("orpheus"));
+ await until(async () => !(await portAnswers("127.0.0.1", port)));
+ assert.deepEqual((await events(ev)).map((l) => l.split(" ")[0]), ["started", "term"]);
+});
+
+test("changed settings restart it; idleStopMs 0 stops it at once", async () => {
+ const holder = new TtsServerHolder({ gate: null, pollMs: 25 });
+ const one = await cmd();
+ const a = await holder.acquire("orpheus", one.c, { onLog: () => {} });
+ a.release();
+ const two = await cmd({}, { idleStopMs: 0 });
+ const b = await holder.acquire("orpheus", two.c, { onLog: () => {} });
+ assert.deepEqual((await events(one.events)).map((l) => l.split(" ")[0]), ["started", "term"]);
+ b.release();
+ await until(async () => (await events(two.events)).length === 2);
+ assert.equal(holder.running("orpheus"), false);
+ assert.deepEqual((await events(two.events)).map((l) => l.split(" ")[0]), ["started", "term"]);
+});
+
+test("a port something else answers on is refused, never shared", async () => {
+ const { c, port } = await cmd();
+ const other = http.createServer((_q, r) => r.end("ok")).listen(port, "127.0.0.1");
+ await new Promise((r) => other.once("listening", r));
+ try {
+ const holder = new TtsServerHolder({ gate: null });
+ await assert.rejects(
+ holder.acquire("orpheus", c, { onLog: () => {} }),
+ /something already answers on 127\.0\.0\.1:\d+ — refusing to start a second orpheus server/,
+ );
+ assert.equal(holder.running("orpheus"), false);
+ } finally {
+ other.close();
+ }
+});
+
+test("a server that dies before it answers fails with its last words", async () => {
+ const holder = new TtsServerHolder({ gate: null, pollMs: 25 });
+ const { c } = await cmd({ EXIT_AT_ONCE: "1" });
+ await assert.rejects(
+ holder.acquire("orpheus", c, { onLog: () => {}, logFile: path.join(ROOT, "dead.log") }),
+ /the orpheus server exited \(3\) before it answered — see .*dead\.log: .*cannot load the model/,
+ );
+ assert.equal(holder.running("orpheus"), false);
+});
+
+test("a start that times out, or is cancelled, stops the server", async () => {
+ const holder = new TtsServerHolder({ gate: null, pollMs: 25 });
+ const slow = await cmd({ DELAY_MS: "60000" }, { startTimeoutMs: 300 });
+ await assert.rejects(holder.acquire("orpheus", slow.c, { onLog: () => {} }), /did not answer .*\/health within 0s/);
+ await until(async () => (await events(slow.events)).some((l) => l.startsWith("term")));
+ const ac = new AbortController();
+ const late = await cmd({ DELAY_MS: "60000" });
+ setTimeout(() => ac.abort(), 200);
+ await assert.rejects(holder.acquire("orpheus", late.c, { onLog: () => {}, signal: ac.signal }), /start was cancelled/);
+ await until(async () => (await events(late.events)).some((l) => l.startsWith("term")));
+ assert.equal(holder.running("orpheus"), false);
+});
+
+test("a server that ignores SIGTERM is SIGKILLed after the grace", async () => {
+ const holder = new TtsServerHolder({ gate: null, pollMs: 25, killGraceMs: 300 });
+ const { c, port } = await cmd({ IGNORE_TERM: "1" });
+ const a = await holder.acquire("orpheus", c, { onLog: () => {} });
+ a.release();
+ const t0 = Date.now();
+ await holder.stop("orpheus");
+ assert.ok(Date.now() - t0 >= 250, "it waited for the grace");
+ await until(async () => !(await portAnswers("127.0.0.1", port)));
+});
diff --git a/common/controller/ttsServer.ts b/common/controller/ttsServer.ts
@@ -0,0 +1,310 @@
+// THE SERVER A `runtime: "server"` SPEECH ENGINE RUNS ON (release 25 T1b:
+// Orpheus 3B on llama.cpp's server, on the GPU).
+//
+// One holder per engine, process-wide. The first synthesis on the `tts` queue
+// starts the server and waits for `GET /health`; the next ones reuse it; once
+// the last one has released it and `idleStopMs` passes with no other taking it
+// — the queue has gone idle — it is stopped: SIGTERM to its process group,
+// SIGKILL after 15 s. That is what frees its VRAM (4–5 GB for Orpheus), so it
+// is also done on every way out: a failed start, a cancelled job, the editor
+// exiting.
+//
+// BEHIND THE HEAVY SLOT. The server is started through scripts/queue-lock.mjs
+// --heavy --estimate <MB> (the gate `pnpm heavy`, e2e and the publish builds
+// share), so it waits for the machine's memory floor and never starts beside a
+// build; the gate's own lines ("waiting for the heavy slot — held by …") go to
+// the job's log, the server's to `<install dir>/server.log`. The start timeout
+// counts from the server's first line of output, not from the wait. A checkout
+// without the gate (a test's temp root) starts the server directly; HEAVY=0
+// bypasses the gate.
+//
+// NEVER SHARED: a port something else already answers on is refused, not
+// used — a server this holder did not start may be another session's, with
+// another model.
+
+import { spawn, type ChildProcess } from "node:child_process";
+import { createWriteStream, existsSync, type WriteStream } from "node:fs";
+import net from "node:net";
+import path from "node:path";
+import type { TtsServerCommand } from "../lib/ttsApps";
+
+export type TtsServerHandle = { url: string; release: () => void };
+
+export type TtsServerDeps = {
+ // scripts/queue-lock.mjs, or null to start the server directly.
+ gate?: string | null;
+ killGraceMs?: number;
+ pollMs?: number;
+};
+
+type Entry = {
+ sig: string;
+ child: ChildProcess;
+ url: string;
+ users: number;
+ timer: ReturnType<typeof setTimeout> | null;
+ ready: Promise<void>;
+ exited: Promise<void>;
+ isExited: () => boolean;
+ log: WriteStream | null;
+};
+
+const GATE_LINE = /^(queue-lock:|heavy:|\s+\(heavy jobs)/;
+
+/** True when something accepts a TCP connection on host:port. */
+export function portAnswers(host: string, port: number, timeoutMs = 1000): Promise<boolean> {
+ return new Promise((resolve) => {
+ const sock = net.connect({ host, port });
+ const done = (v: boolean) => {
+ sock.destroy();
+ resolve(v);
+ };
+ sock.setTimeout(timeoutMs, () => done(false));
+ sock.once("connect", () => done(true));
+ sock.once("error", () => done(false));
+ });
+}
+
+async function healthy(url: string): Promise<boolean> {
+ try {
+ const res = await fetch(`${url}/health`, { signal: AbortSignal.timeout(1000) });
+ return res.status === 200;
+ } catch {
+ return false;
+ }
+}
+
+const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
+
+function killGroup(child: ChildProcess, sig: NodeJS.Signals): void {
+ if (child.pid === undefined) return;
+ try {
+ process.kill(-child.pid, sig);
+ } catch {
+ try {
+ child.kill(sig);
+ } catch {
+ /* gone */
+ }
+ }
+}
+
+export class TtsServerHolder {
+ private entries = new Map<string, Entry>();
+ private exitHooked = false;
+ constructor(private deps: TtsServerDeps = {}) {}
+
+ /** Whether the server for `key` is running (started, not yet stopped). */
+ running(key: string): boolean {
+ const e = this.entries.get(key);
+ return e !== undefined && !e.isExited();
+ }
+
+ /** The server for `key`: the running one, or a new one started from `cmd`. */
+ async acquire(
+ key: string,
+ cmd: TtsServerCommand,
+ opts: { onLog: (line: string) => void; signal?: AbortSignal; logFile?: string },
+ ): Promise<TtsServerHandle> {
+ const sig = JSON.stringify(cmd);
+ let e = this.entries.get(key);
+ if (e && (e.sig !== sig || e.isExited())) {
+ // Its settings changed, or it died between syntheses: start afresh.
+ if (e.users === 0) await this.stop(key);
+ else throw new Error(`the ${key} server is in use with other settings`);
+ e = undefined;
+ }
+ if (e) {
+ if (e.timer) clearTimeout(e.timer);
+ e.timer = null;
+ e.users++;
+ try {
+ await e.ready;
+ } catch (err) {
+ e.users--;
+ throw err;
+ }
+ return this.handle(key, e, cmd);
+ }
+ e = await this.start(key, cmd, sig, opts);
+ e.users = 1;
+ try {
+ await e.ready;
+ } catch (err) {
+ await this.stop(key);
+ throw err;
+ }
+ return this.handle(key, e, cmd);
+ }
+
+ private handle(key: string, e: Entry, cmd: TtsServerCommand): TtsServerHandle {
+ let released = false;
+ return {
+ url: e.url,
+ release: () => {
+ if (released) return;
+ released = true;
+ e.users = Math.max(0, e.users - 1);
+ if (e.users > 0 || this.entries.get(key) !== e) return;
+ if (cmd.idleStopMs <= 0) {
+ void this.stop(key);
+ return;
+ }
+ e.timer = setTimeout(() => void this.stop(key), cmd.idleStopMs);
+ e.timer.unref?.();
+ },
+ };
+ }
+
+ private async start(
+ key: string,
+ cmd: TtsServerCommand,
+ sig: string,
+ opts: { onLog: (line: string) => void; signal?: AbortSignal; logFile?: string },
+ ): Promise<Entry> {
+ const url = `http://${cmd.host}:${cmd.port}`;
+ if (await portAnswers(cmd.host, cmd.port)) {
+ throw new Error(
+ `something already answers on ${cmd.host}:${cmd.port} — refusing to start a second ${key} server ` +
+ `beside it; stop it, or set another port (settings.tts.${key}.port)`,
+ );
+ }
+ const gate = this.deps.gate ?? null;
+ const gated = gate !== null && existsSync(gate);
+ const [bin, args] = gated
+ ? [
+ process.execPath,
+ [gate, "--heavy", ...(cmd.estimateMB > 0 ? ["--estimate", String(cmd.estimateMB)] : []), "--", cmd.bin, ...cmd.args],
+ ]
+ : [cmd.bin, cmd.args];
+ opts.onLog(`Starting the ${key} server on ${cmd.host}:${cmd.port}${gated ? " (behind the heavy slot)" : ""}…`);
+ const child = spawn(bin, args, {
+ env: { ...process.env, ...cmd.env },
+ // Its own process group: the gate, the server and anything they start
+ // are stopped together.
+ detached: true,
+ stdio: ["ignore", "pipe", "pipe"],
+ });
+ const log = opts.logFile ? createWriteStream(opts.logFile, { flags: "a" }) : null;
+ log?.on("error", () => {});
+ let serverSince: number | null = null;
+ let tail: string[] = [];
+ let exitedFlag = false;
+ let exitCode: string | null = null;
+ const exited = new Promise<void>((resolve) => {
+ child.once("exit", (code, signal) => {
+ exitedFlag = true;
+ exitCode = code === null ? String(signal) : String(code);
+ resolve();
+ });
+ child.once("error", (err) => {
+ exitedFlag = true;
+ exitCode = err.message;
+ resolve();
+ });
+ });
+ const onData = (buf: Buffer) => {
+ for (const line of buf.toString("utf8").split("\n")) {
+ if (!line.trim()) continue;
+ if (GATE_LINE.test(line)) {
+ opts.onLog(line.trimEnd());
+ continue;
+ }
+ serverSince ??= Date.now();
+ tail = [...tail.slice(-4), line.trimEnd()];
+ log?.write(`${line}\n`);
+ }
+ };
+ child.stdout?.on("data", onData);
+ child.stderr?.on("data", onData);
+ this.hookExit();
+
+ const pollMs = this.deps.pollMs ?? 250;
+ const started = Date.now();
+ const ready = (async () => {
+ for (;;) {
+ if (exitedFlag) {
+ throw new Error(
+ `the ${key} server exited (${exitCode}) before it answered${opts.logFile ? ` — see ${opts.logFile}` : ""}` +
+ (tail.length ? `: ${tail.slice(-2).join(" | ")}` : ""),
+ );
+ }
+ if (opts.signal?.aborted) throw new Error(`the ${key} server's start was cancelled`);
+ if (serverSince !== null && Date.now() - serverSince > cmd.startTimeoutMs) {
+ throw new Error(`the ${key} server did not answer ${url}/health within ${Math.round(cmd.startTimeoutMs / 1000)}s`);
+ }
+ if (await healthy(url)) {
+ opts.onLog(`The ${key} server is up (${((Date.now() - started) / 1000).toFixed(1)}s)`);
+ return;
+ }
+ await sleep(pollMs);
+ }
+ })();
+ ready.catch(() => {});
+ const entry: Entry = {
+ sig,
+ child,
+ url,
+ users: 0,
+ timer: null,
+ ready,
+ exited,
+ isExited: () => exitedFlag,
+ log,
+ };
+ this.entries.set(key, entry);
+ return entry;
+ }
+
+ /** Stop the server for `key`: SIGTERM to its group, SIGKILL after the grace. */
+ async stop(key: string): Promise<void> {
+ const e = this.entries.get(key);
+ if (!e) return;
+ this.entries.delete(key);
+ if (e.timer) clearTimeout(e.timer);
+ if (!e.isExited()) {
+ killGroup(e.child, "SIGTERM");
+ const grace = this.deps.killGraceMs ?? 15_000;
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const t = new Promise<"timeout">((r) => {
+ timer = setTimeout(() => r("timeout"), grace);
+ });
+ const won = await Promise.race([e.exited.then(() => "exited" as const), t]);
+ clearTimeout(timer);
+ if (won === "timeout") {
+ killGroup(e.child, "SIGKILL");
+ await e.exited;
+ }
+ }
+ e.log?.end();
+ }
+
+ async stopAll(): Promise<void> {
+ await Promise.all([...this.entries.keys()].map((k) => this.stop(k)));
+ }
+
+ // The editor exiting stops every server it started (synchronously: an exit
+ // handler cannot wait), so no VRAM is left held by an orphan.
+ private hookExit(): void {
+ if (this.exitHooked) return;
+ this.exitHooked = true;
+ process.once("exit", () => {
+ for (const e of this.entries.values()) if (!e.isExited()) killGroup(e.child, "SIGTERM");
+ });
+ }
+}
+
+declare global {
+ // eslint-disable-next-line no-var
+ var __yttTtsServers__: TtsServerHolder | undefined;
+}
+
+/** The process-wide holder; its gate is `<repo>/scripts/queue-lock.mjs`. */
+export function getTtsServerHolder(monorepoRoot: string): TtsServerHolder {
+ if (!globalThis.__yttTtsServers__) {
+ globalThis.__yttTtsServers__ = new TtsServerHolder({
+ gate: path.join(monorepoRoot, "scripts", "queue-lock.mjs"),
+ });
+ }
+ return globalThis.__yttTtsServers__;
+}
diff --git a/common/lib/envVars.ts b/common/lib/envVars.ts
@@ -159,6 +159,7 @@ const DECLARED: EnvVarDecl[] = [
{ name: "BUILD_ARCHIVES", audience: "internal", default: "on", readBy: "common/bin/compose-site.ts, common/bin/build-archives.ts", doc: "`0` skips archive-zip generation for one build (`--skip-archives`)." },
{ name: "REPORTS_ALLOW_MISSING_MEDIA", audience: "internal", default: "off", readBy: "common/bin/compose-site.ts", doc: "`1` lets a report citation whose evidence media was not prepared through compose (`--allow-missing-media`): its moment page renders without a clip. Off, compose fails with the list." },
{ name: "ARCHIVES_READONLY", audience: "internal", default: "off", readBy: "common/bin/compose-site.ts", doc: "`1` inside a docker-mode build container: materialize archives, never write the shared cache." },
+ { name: "GGML_BACKEND_PATH", audience: "internal", default: "settings.tts.orpheus.ggmlBackendPath", readBy: "common/lib/ttsApps.ts", doc: "The ggml backend llama-server loads (Vulkan by default), set for the Orpheus server the editor starts — from `settings.tts.orpheus.ggmlBackendPath`, never the environment." },
{ name: "HOMEPAGE_PUBLIC_DIR", audience: "internal", default: "`<repo>/homepage/public`", readBy: "common/bin/compose-homepage.ts, common/publish/source.ts", doc: "Where `compose homepage` and `source publish` write." },
// ── docker: the container's set ────────────────────────────────────────
diff --git a/common/lib/settingsDocs.ts b/common/lib/settingsDocs.ts
@@ -23,6 +23,7 @@ import {
SAVED_VIDEO_BACKUP_SETTINGS_FIELD_DOCS,
SEEDER_SETTINGS_FIELD_DOCS,
TTS_SETTINGS_FIELD_DOCS,
+ ORPHEUS_TTS_SETTINGS_FIELD_DOCS,
SOCIAL_LINK_FIELD_DOCS,
SOCIAL_SETTINGS_FIELD_DOCS,
X_SOCIAL_SETTINGS_FIELD_DOCS,
@@ -267,6 +268,11 @@ export function blockTables(d: SiteSettings): Partial<Record<keyof SiteSettings,
docs: TTS_SETTINGS_FIELD_DOCS,
defaults: fromObject(d.tts),
},
+ {
+ path: "tts.orpheus",
+ docs: ORPHEUS_TTS_SETTINGS_FIELD_DOCS,
+ defaults: fromObject(d.tts.orpheus),
+ },
],
};
}
diff --git a/common/lib/settingsSchema.ts b/common/lib/settingsSchema.ts
@@ -79,7 +79,7 @@ import {
import { sanitizeSeeder, type SeederSettings } from "./seederSettings";
export { SEEDER_SETTINGS_FIELD_DOCS, type SeederSettings } from "./seederSettings";
import { sanitizeTts, type TtsSettings } from "./ttsSettings";
-export { TTS_SETTINGS_FIELD_DOCS, type TtsSettings } from "./ttsSettings";
+export { ORPHEUS_TTS_SETTINGS_FIELD_DOCS, TTS_SETTINGS_FIELD_DOCS, type TtsSettings } from "./ttsSettings";
import {
DEFAULT_COOKIE_MODE,
isCookieMode,
diff --git a/common/lib/ttsApps.test.ts b/common/lib/ttsApps.test.ts
@@ -11,15 +11,18 @@ import {
ttsEngineIds,
ttsInstallDir,
ttsVenvPython,
+ ORPHEUS_FILES,
+ ORPHEUS_SAMPLER,
} from "./ttsApps";
+import { DEFAULT_TTS_SETTINGS, sanitizeTts } from "./ttsSettings";
// 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"]);
+test("the registry: kokoro (af_heart) is the default, espeak-ng the zero-install fallback, orpheus the GPU one", () => {
+ assert.deepEqual(ttsEngineIds(), ["kokoro", "espeak-ng", "orpheus"]);
assert.equal(DEFAULT_TTS_ENGINE_ID, "kokoro");
assert.equal(DEFAULT_TTS_VOICE, "af_heart");
assert.equal(getTtsEngine("kokoro")!.defaultVoice, "af_heart");
@@ -30,13 +33,13 @@ test("the registry: kokoro (af_heart) is the default, espeak-ng the zero-install
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.equal(e.device, e.id === "orpheus" ? "gpu" : "cpu", e.id);
+ assert.equal(e.runtime, e.id === "orpheus" ? "server" : "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"]],
+ [["kokoro", "af_heart"], ["espeak-ng", "en-us"], ["orpheus", "leah"]],
);
});
@@ -86,8 +89,8 @@ test("each engine builds the wrapper's command line from its install dir", () =>
]);
});
-test("both engines strip the expressive tags and speak years", () => {
- for (const id of ttsEngineIds()) {
+test("Kokoro and espeak-ng strip the expressive tags and speak years", () => {
+ for (const id of ["kokoro", "espeak-ng"]) {
assert.equal(
getTtsEngine(id)!.normalize("Back in 1999 <laugh> we said\nso."),
"Back in nineteen ninety-nine we said so.",
@@ -106,3 +109,84 @@ test("the disclosure names the engine and voice, plus any attribution its licenc
"Narration: synthetic voice (Some Engine · v1). Built with Something.",
);
});
+
+test("Orpheus: eight stock voices, leah by default, no speed control, the Llama licence and attribution", () => {
+ const o = getTtsEngine("orpheus")!;
+ assert.deepEqual([...o.voices], ["tara", "leah", "jess", "leo", "dan", "mia", "zac", "zoe"]);
+ assert.equal(o.defaultVoice, "leah");
+ assert.ok(o.voices.includes("zac"));
+ assert.deepEqual([...o.speedRange], [1, 1]);
+ assert.equal(o.license, "Llama 3.2 Community License + Apache-2.0");
+ assert.equal(ttsDisclosure(o, "leah"), "Narration: synthetic voice (Orpheus 3B · leah). Built with Llama");
+ assert.equal(o.setup.kind, "python-venv");
+ if (o.setup.kind === "python-venv") {
+ assert.deepEqual(o.setup.packages, ["onnxruntime==1.31.0", "numpy==2.5.4"]);
+ assert.deepEqual(o.setup.files.map((f) => f.name), ["orpheus-3b-0.1-ft-Q8_0.gguf", "snac_decoder.onnx", "snac_config.json"]);
+ }
+ for (const f of ORPHEUS_FILES) assert.match(f.sha256, /^[0-9a-f]{64}$/);
+ // Tags are performed, so kept; the guarded year rule; paragraphs kept for the chunker.
+ assert.equal(
+ o.normalize("Back in 1999 <laugh> 1950 people\n\nsaid so."),
+ "Back in nineteen ninety-nine <laugh> one thousand nine hundred fifty people\n\nsaid so.",
+ );
+});
+
+test("Orpheus's server command comes from settings.tts.orpheus, never hard-coded", () => {
+ const o = getTtsEngine("orpheus")!;
+ const cmd = o.serverCommand!("/h/tts/orpheus", DEFAULT_TTS_SETTINGS);
+ assert.equal(cmd.bin, "/usr/lib/ollama/llama-server");
+ assert.deepEqual(cmd.env, {
+ LD_LIBRARY_PATH: "/usr/lib/ollama",
+ GGML_BACKEND_PATH: "/usr/lib/ollama/vulkan/libggml-vulkan.so",
+ });
+ assert.deepEqual(cmd.args, [
+ "-m", "/h/tts/orpheus/orpheus-3b-0.1-ft-Q8_0.gguf",
+ "--host", "127.0.0.1", "--port", "8799", "-ngl", "99", "-c", "8192", "-np", "1", "--no-webui",
+ ]);
+ assert.equal(cmd.estimateMB, 4000);
+ const mine = sanitizeTts({
+ engine: "orpheus",
+ orpheus: { serverBin: "/opt/llama/llama-server", libraryPath: "", ggmlBackendPath: "", port: 9001, gpuLayers: 0, idleStopSeconds: 30 },
+ });
+ const c2 = o.serverCommand!("/h/tts/orpheus", mine);
+ assert.equal(c2.bin, "/opt/llama/llama-server");
+ assert.deepEqual(c2.env, {});
+ assert.equal(c2.port, 9001);
+ assert.ok(c2.args.includes("0"));
+ assert.equal(c2.idleStopMs, 30_000);
+ assert.deepEqual(o.requires!(mine), [{ what: "llama-server (settings.tts.orpheus.serverBin)", path: "/opt/llama/llama-server" }]);
+});
+
+test("Orpheus's input is the editor's chunks, budgets, sampler and takes; the wrapper gets the server", () => {
+ const o = getTtsEngine("orpheus")!;
+ const spoken = o.normalize("One file. No title. Just a date.\n\nAnd then... there it was. <gasp>");
+ const input = JSON.parse(o.prepareInput!(spoken, "zac", DEFAULT_TTS_SETTINGS));
+ assert.equal(input.voice, "zac");
+ assert.deepEqual(input.sampler, { ...ORPHEUS_SAMPLER });
+ assert.equal(input.sampler.repeat_last_n, 64);
+ assert.equal(input.seedBase, 1234);
+ assert.equal(input.takes, 3);
+ assert.equal(input.tagCheck, false);
+ assert.deepEqual(
+ input.chunks.map((c: { text: string; ends: string; pauseAfter: number }) => [c.text, c.ends, c.pauseAfter]),
+ [
+ ["One file. No title. Just a date.", "paragraph", 0.6],
+ ["And then... there it was. <gasp>", "end", 0],
+ ],
+ );
+ assert.ok(input.chunks.every((c: { nPredict: number }) => c.nPredict > 0 && c.nPredict % 7 === 0));
+ assert.deepEqual(o.keyExtra!(DEFAULT_TTS_SETTINGS), { takes: 3, tagCheck: false });
+ const b = o.build({
+ textFile: "/c/x.json", outWav: "/c/x.wav", voice: "zac", speed: 1, installDir: "/h/tts/orpheus",
+ bins: BINS, server: "http://127.0.0.1:8799",
+ });
+ assert.deepEqual(b.argv, [
+ "--engine-kind", "orpheus",
+ "--python", "/h/tts/orpheus/venv/bin/python",
+ "--snac", "/h/tts/orpheus/snac_decoder.onnx",
+ "--server", "http://127.0.0.1:8799",
+ "--ffmpeg", "/bin/ffmpeg",
+ "--output", "/c/x.wav",
+ "/c/x.json",
+ ]);
+});
diff --git a/common/lib/ttsApps.ts b/common/lib/ttsApps.ts
@@ -13,23 +13,29 @@
// 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
+// THE THREE ENGINES: Kokoro-82M (the default; CPU), espeak-ng (zero-install)
+// and Orpheus 3B (release 25 T1b; GPU). What Orpheus added, and any engine like
+// it uses:
+// - `device: "gpu"`: ttsFile.ts's runTtsSynthesis waits while a
+// transcription runs on a non-CPU worker before it starts one.
+// - `runtime: "server"` + `serverCommand`: a local server
+// (controller/ttsServer.ts) started for a batch of syntheses behind the
+// heavy slot and stopped (SIGTERM, SIGKILL after 15 s) once the `tts`
+// queue has been idle, so its VRAM is freed; `build` gets its URL.
+// - `prepareInput`: what the wrapper's text file holds when it is not the
+// spoken text (Orpheus: the chunks of lib/ttsChunk.ts, each with its token
+// budget, the sampler, the takes), and `keyExtra`: the settings that change
+// the output, in the cache key.
+// - `normalize`: one shared normalizer (lib/ttsText.ts), options per engine.
+// - `attribution`: a sentence its licence requires beside the disclosure
// (Llama 3.2: "Built with Llama"); ttsDisclosure appends it.
+// - `requires`: binaries outside the install dir (the server), checked with
+// the install.
import path from "node:path";
import { normalizeTtsText } from "./ttsText";
+import { chunkTtsText, nPredictFor } from "./ttsChunk";
+import type { TtsSettings } from "./ttsSettings";
export type TtsDevice = "cpu" | "gpu";
@@ -64,10 +70,26 @@ export type TtsBuildInput = {
// 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.
+ // A `runtime: "server"` engine's base URL. Undefined for the rest.
server?: string;
};
+// A `runtime: "server"` engine's server: how to start it, from settings.
+export type TtsServerCommand = {
+ bin: string;
+ args: string[];
+ env: Record<string, string>;
+ host: string;
+ port: number;
+ // The memory it is admitted to the heavy slot with (scripts/queue-lock.mjs).
+ estimateMB: number;
+ startTimeoutMs: number;
+ idleStopMs: number;
+};
+
+// A binary the engine needs that is not in its install dir (the server).
+export type TtsRequirement = { what: string; path: string };
+
export type TtsBuild = {
// Args to paths.ttsBin (scripts/tts.mjs).
argv: string[];
@@ -91,6 +113,15 @@ export type TtsEngine = {
normalize: (text: string) => string;
setup: TtsSetup;
build: (input: TtsBuildInput) => TtsBuild;
+ // What the text file the wrapper reads holds, when it is not the spoken text
+ // itself (Orpheus: its chunks, budgets, sampler and takes, as JSON).
+ prepareInput?: (spoken: string, voice: string, tts: TtsSettings) => string;
+ // Settings that change the output, beside the model: in the cache key.
+ keyExtra?: (tts: TtsSettings) => unknown;
+ // A `runtime: "server"` engine's server.
+ serverCommand?: (installDir: string, tts: TtsSettings) => TtsServerCommand;
+ // Binaries outside the install dir it needs (checked with the install).
+ requires?: (tts: TtsSettings) => TtsRequirement[];
};
// The wrapper always writes this.
@@ -166,6 +197,120 @@ const kokoro: TtsEngine = {
}),
};
+// --- orpheus ------------------------------------------------------------------
+
+// Orpheus 3B 0.1-ft (Q8_0 GGUF) on llama.cpp's server, its SNAC 24 kHz codes
+// decoded by the ONNX decoder on the CPU — the tuned round of 2026-10-11. GPU
+// (Vulkan) by default, behind the machine's heavy slot. Its eight stock
+// speakers; leah the default, zac the male option. Tags are performed, so they
+// are kept; numbers, years and the rest are spoken by the shared normalizer
+// with the guarded year rule ("1950 people" is a count). No speed control.
+export const ORPHEUS_VOICES = ["tara", "leah", "jess", "leo", "dan", "mia", "zac", "zoe"] as const;
+
+// The tuned round's sampler (its report, "Sampler choice"): the repeat penalty
+// on with a 64-token window — `repeat_last_n` 0 would DISABLE it in llama.cpp,
+// and -1 is refused by the bundled build.
+export const ORPHEUS_SAMPLER = {
+ temperature: 0.7,
+ top_p: 0.9,
+ top_k: 50,
+ min_p: 0,
+ repeat_penalty: 1.1,
+ repeat_last_n: 64,
+ presence_penalty: 0,
+ frequency_penalty: 0,
+} as const;
+export const ORPHEUS_SEED_BASE = 1234;
+
+export const ORPHEUS_FILES: readonly TtsModelFile[] = [
+ {
+ name: "orpheus-3b-0.1-ft-Q8_0.gguf",
+ url: "https://huggingface.co/unsloth/orpheus-3b-0.1-ft-GGUF/resolve/main/orpheus-3b-0.1-ft-Q8_0.gguf",
+ bytes: 3_516_431_616,
+ sha256: "9a01ea76b66dd66d08a0952ed72932f0ecce59db3d5c9b1a33621ff7200ba531",
+ },
+ {
+ name: "snac_decoder.onnx",
+ url: "https://huggingface.co/onnx-community/snac_24khz-ONNX/resolve/main/onnx/decoder_model.onnx",
+ bytes: 52_600_822,
+ sha256: "9e2991fce96c3b49c508304e656052f4f6b860fe8432164fcd976eee195fd4f0",
+ },
+ {
+ name: "snac_config.json",
+ url: "https://huggingface.co/onnx-community/snac_24khz-ONNX/resolve/main/config.json",
+ bytes: 301,
+ sha256: "47a469c3b6ac9a9c940338d82f7a1ad05b92254d9aa05249cb6b81b7938f69bb",
+ },
+];
+
+const orpheus: TtsEngine = {
+ id: "orpheus",
+ label: "Orpheus 3B",
+ model: "orpheus-3b-0.1-ft Q8_0 + snac_24khz decoder (tuned 2026-10-11)",
+ license: "Llama 3.2 Community License + Apache-2.0",
+ attribution: "Built with Llama",
+ device: "gpu",
+ runtime: "server",
+ voices: ORPHEUS_VOICES,
+ defaultVoice: "leah",
+ speedRange: [1, 1],
+ normalize: (text) => normalizeTtsText(text, { tags: "keep", years: "guarded", paragraphs: "keep" }),
+ setup: {
+ kind: "python-venv",
+ python: "3.12",
+ packages: ["onnxruntime==1.31.0", "numpy==2.5.4"],
+ importName: "onnxruntime",
+ files: ORPHEUS_FILES,
+ },
+ prepareInput: (spoken, voice, tts) =>
+ JSON.stringify({
+ version: 1,
+ voice,
+ sampler: ORPHEUS_SAMPLER,
+ seedBase: ORPHEUS_SEED_BASE,
+ takes: tts.orpheus.takes,
+ tagCheck: tts.orpheus.tagCheck,
+ chunks: chunkTtsText(spoken).map((c) => ({ ...c, nPredict: nPredictFor(c.text) })),
+ }),
+ keyExtra: (tts) => ({ takes: tts.orpheus.takes, tagCheck: tts.orpheus.tagCheck }),
+ serverCommand: (installDir, tts) => {
+ const o = tts.orpheus;
+ const env: Record<string, string> = {};
+ if (o.libraryPath) env.LD_LIBRARY_PATH = o.libraryPath;
+ if (o.ggmlBackendPath) env.GGML_BACKEND_PATH = o.ggmlBackendPath;
+ return {
+ bin: o.serverBin,
+ args: [
+ "-m", path.join(installDir, ORPHEUS_FILES[0].name),
+ "--host", "127.0.0.1",
+ "--port", String(o.port),
+ "-ngl", String(o.gpuLayers),
+ "-c", String(o.contextSize),
+ "-np", "1",
+ "--no-webui",
+ ],
+ env,
+ host: "127.0.0.1",
+ port: o.port,
+ estimateMB: o.heavyEstimateMB,
+ startTimeoutMs: o.startTimeoutSeconds * 1000,
+ idleStopMs: o.idleStopSeconds * 1000,
+ };
+ },
+ requires: (tts) => [{ what: "llama-server (settings.tts.orpheus.serverBin)", path: tts.orpheus.serverBin }],
+ build: ({ textFile, outWav, installDir, bins, server }) => ({
+ argv: [
+ "--engine-kind", "orpheus",
+ "--python", ttsVenvPython(installDir),
+ "--snac", path.join(installDir, ORPHEUS_FILES[1].name),
+ "--server", server ?? "",
+ "--ffmpeg", bins.ffmpegBin,
+ "--output", outWav,
+ textFile,
+ ],
+ }),
+};
+
// --- espeak-ng ---------------------------------------------------------------
// The zero-install fallback: a formant synthesizer every Linux has, robotic
@@ -199,6 +344,7 @@ const espeakNg: TtsEngine = {
export const TTS_ENGINES: Record<string, TtsEngine> = {
[kokoro.id]: kokoro,
[espeakNg.id]: espeakNg,
+ [orpheus.id]: orpheus,
};
export const DEFAULT_TTS_ENGINE_ID = "kokoro";
diff --git a/common/lib/ttsInstall.ts b/common/lib/ttsInstall.ts
@@ -11,6 +11,7 @@ import fs from "node:fs";
import path from "node:path";
import type { Paths } from "./paths";
import { ttsInstallDir, ttsVenvPython, type TtsEngine } from "./ttsApps";
+import type { TtsSettings } from "./ttsSettings";
export type TtsInstallState = {
engine: string;
@@ -44,7 +45,7 @@ export function findOnPath(bin: string, envPath: string | undefined = process.en
export function ttsInstallState(
engine: TtsEngine,
- opts: { home: string; paths: Pick<Paths, "espeakNgBin">; envPath?: string },
+ opts: { home: string; paths: Pick<Paths, "espeakNgBin">; envPath?: string; tts?: TtsSettings },
): TtsInstallState {
const setup = engine.setup;
if (setup.kind === "system") {
@@ -72,5 +73,11 @@ export function ttsInstallState(
if (size === null) missing.push(`${f.name}`);
else if (size !== f.bytes) missing.push(`${f.name} (${size} bytes, expected ${f.bytes})`);
}
+ // Binaries outside the install dir (Orpheus's llama-server, from settings).
+ if (engine.requires && opts.tts) {
+ for (const r of engine.requires(opts.tts)) {
+ if (!findOnPath(r.path, opts.envPath ?? process.env.PATH)) missing.push(`${r.what}: ${r.path}`);
+ }
+ }
return { engine: engine.id, dir, installed: missing.length === 0, missing };
}
diff --git a/common/lib/ttsSettings.test.ts b/common/lib/ttsSettings.test.ts
@@ -2,14 +2,21 @@ import { test } from "node:test";
import assert from "node:assert/strict";
import os from "node:os";
import path from "node:path";
-import { DEFAULT_TTS_SETTINGS, resolveTtsCacheDir, resolveTtsHome, sanitizeTts } from "./ttsSettings";
+import { DEFAULT_ORPHEUS_TTS_SETTINGS, DEFAULT_TTS_SETTINGS, resolveTtsCacheDir, resolveTtsHome, sanitizeTts } from "./ttsSettings";
import { defaults } from "./settingsSchema";
// Run with:
// pnpm --filter yt-dlp-transcript-common exec tsx --test lib/ttsSettings.test.ts
test("the default block: kokoro, af_heart, natural pace, blank dirs", () => {
- assert.deepEqual(defaults().tts, { engine: "kokoro", voice: "af_heart", speed: 1, home: "", dir: "" });
+ assert.deepEqual(defaults().tts, {
+ engine: "kokoro",
+ voice: "af_heart",
+ speed: 1,
+ home: "",
+ dir: "",
+ orpheus: DEFAULT_ORPHEUS_TTS_SETTINGS,
+ });
assert.deepEqual(sanitizeTts(undefined), DEFAULT_TTS_SETTINGS);
assert.deepEqual(sanitizeTts("nonsense"), DEFAULT_TTS_SETTINGS);
});
@@ -35,3 +42,32 @@ test("home and dir: blank is the Paths default, ~/ expands, a relative path is d
assert.equal(sanitizeTts({ dir: "relative/cache" }).dir, "");
assert.equal(sanitizeTts({ home: 7 }).home, "");
});
+
+test("orpheus: leah by default, speed held at 1, its server block sanitized", () => {
+ const o = sanitizeTts({ engine: "orpheus", speed: 0.8 });
+ assert.equal(o.voice, "leah");
+ assert.equal(o.speed, 1);
+ assert.equal(sanitizeTts({ engine: "orpheus", voice: "zac" }).voice, "zac");
+ assert.deepEqual(DEFAULT_ORPHEUS_TTS_SETTINGS, {
+ serverBin: "/usr/lib/ollama/llama-server",
+ libraryPath: "/usr/lib/ollama",
+ ggmlBackendPath: "/usr/lib/ollama/vulkan/libggml-vulkan.so",
+ port: 8799,
+ gpuLayers: 99,
+ contextSize: 8192,
+ startTimeoutSeconds: 150,
+ idleStopSeconds: 5,
+ heavyEstimateMB: 4000,
+ takes: 3,
+ tagCheck: false,
+ });
+ const s = sanitizeTts({
+ orpheus: { serverBin: "relative/llama", libraryPath: "", port: 80, takes: 99, tagCheck: "yes", gpuLayers: 12.4 },
+ }).orpheus;
+ assert.equal(s.serverBin, "/usr/lib/ollama/llama-server");
+ assert.equal(s.libraryPath, "");
+ assert.equal(s.port, 1024);
+ assert.equal(s.takes, 6);
+ assert.equal(s.tagCheck, false);
+ assert.equal(s.gpuLayers, 12);
+});
diff --git a/common/lib/ttsSettings.ts b/common/lib/ttsSettings.ts
@@ -11,12 +11,72 @@ import type { FieldDocs } from "./fieldDocs";
import type { Paths } from "./paths";
import { DEFAULT_TTS_ENGINE_ID, DEFAULT_TTS_VOICE, getTtsEngine } from "./ttsApps";
+// Orpheus 3B (release 25 T1b): the local llama-server it runs on and how many
+// takes a chunk gets. The server's binary and its two library paths default to
+// Ollama's bundled build on Vulkan — settings, never hard-coded.
+export type OrpheusTtsSettings = {
+ serverBin: string;
+ libraryPath: string;
+ ggmlBackendPath: string;
+ port: number;
+ gpuLayers: number;
+ contextSize: number;
+ startTimeoutSeconds: number;
+ idleStopSeconds: number;
+ heavyEstimateMB: number;
+ takes: number;
+ tagCheck: boolean;
+};
+
export type TtsSettings = {
engine: string;
voice: string;
speed: number;
home: string;
dir: string;
+ orpheus: OrpheusTtsSettings;
+};
+
+export const DEFAULT_ORPHEUS_TTS_SETTINGS: OrpheusTtsSettings = {
+ serverBin: "/usr/lib/ollama/llama-server",
+ libraryPath: "/usr/lib/ollama",
+ ggmlBackendPath: "/usr/lib/ollama/vulkan/libggml-vulkan.so",
+ port: 8799,
+ gpuLayers: 99,
+ contextSize: 8192,
+ startTimeoutSeconds: 150,
+ idleStopSeconds: 5,
+ heavyEstimateMB: 4000,
+ takes: 3,
+ tagCheck: false,
+};
+
+export const ORPHEUS_TTS_SETTINGS_FIELD_DOCS: FieldDocs<OrpheusTtsSettings> = {
+ serverBin:
+ "The llama.cpp server Orpheus runs on (`llama-server`). Default: Ollama's bundled build. " +
+ "Started for a batch of syntheses on the `tts` queue and stopped (SIGTERM, then SIGKILL " +
+ "after 15 s) once the queue has been idle `idleStopSeconds`, so its VRAM is freed.",
+ libraryPath: "`LD_LIBRARY_PATH` for the server (Ollama's bundled libraries). Blank = not set.",
+ ggmlBackendPath:
+ "`GGML_BACKEND_PATH` for the server: the ggml backend it loads — Vulkan by default. Blank = not set.",
+ port: "The port the server listens on, on 127.0.0.1. A port something else already answers on is refused, never shared.",
+ gpuLayers: "`-ngl`: layers on the GPU. 99 = all of them; 0 runs on the CPU (about 9× slower).",
+ contextSize: "`-c`, the context in tokens; also the whole window the repeat penalty could see.",
+ startTimeoutSeconds:
+ "How long the server may take to answer `/health` once it is running (it took 2.5–14 s in the " +
+ "tuning round). The wait for the machine's heavy slot before it starts is not counted.",
+ idleStopSeconds: "How long the server is kept after the last synthesis before it is stopped, so the next one in the queue reuses it.",
+ heavyEstimateMB:
+ "The memory the server is admitted to the heavy slot with (`queue-lock --heavy --estimate`): it " +
+ "starts only when that much is free above the floor, beside other estimated jobs, never beside a build.",
+ takes:
+ "Takes per chunk, at most: the first that passes the checks (end token reached, no malformed frame, " +
+ "not truncated, words a second in band, no long silence) is kept. 1–6.",
+ tagCheck:
+ "The tag-length check: a chunk with expressive tags must run at least 0.4 s a tag longer than the " +
+ "same voice reading it without them (one extra take of the stripped text per tagged chunk), else the " +
+ "take is taken to have skipped its tag. OFF by default. (The tuning round's UTMOS scorer is not " +
+ "offered: it needs torch.)",
};
export const DEFAULT_TTS_SETTINGS: TtsSettings = {
@@ -25,21 +85,26 @@ export const DEFAULT_TTS_SETTINGS: TtsSettings = {
speed: 1,
home: "",
dir: "",
+ orpheus: DEFAULT_ORPHEUS_TTS_SETTINGS,
};
export const TTS_SETTINGS_FIELD_DOCS: FieldDocs<TtsSettings> = {
engine:
"The engine a synthesis uses when the request names none: `kokoro` (Kokoro-82M, " +
- "Apache-2.0, CPU; installed by `archilyzer tts setup`) or `espeak-ng` (the " +
- "zero-install fallback). An unknown id falls back to `kokoro`.",
+ "Apache-2.0, CPU; installed by `archilyzer tts setup`), `orpheus` (Orpheus 3B, " +
+ "Llama 3.2 Community License + Apache-2.0, \"Built with Llama\"; GPU, on a local " +
+ "llama-server — `tts.orpheus`; `archilyzer tts setup --engine orpheus`) or " +
+ "`espeak-ng` (the zero-install fallback). An unknown id falls back to `kokoro`.",
voice:
"The engine's stock voice when the request names none (stock voices only: no " +
"cloning, no reference audio). For Kokoro, `a*` voices are American English and " +
- "`b*` British; `af_heart` was picked by ear in the release 25 bake-off. A voice the " +
+ "`b*` British; `af_heart` was picked by ear in the release 25 bake-off. Orpheus: " +
+ "tara leah jess leo dan mia zac zoe — `leah` its default, `zac` the male option. A voice the " +
"engine does not have falls back to the engine's default.",
speed:
"Speaking pace, 1 = the engine's natural pace (Kokoro speaks briskly; 0.9 slows it). " +
- "Clamped to [0.5, 2]. In the cache key: a new speed is a new synthesis.",
+ "Clamped to the engine's range: [0.5, 2] for Kokoro and espeak-ng; Orpheus has none (1). " +
+ "In the cache key: a new speed is a new synthesis.",
home:
"Where `archilyzer tts setup` installs engines, one directory per engine " +
"(`<home>/kokoro`: its python venv and model files). Blank = " +
@@ -49,6 +114,7 @@ export const TTS_SETTINGS_FIELD_DOCS: FieldDocs<TtsSettings> = {
"sidecar (engine, model, licence, voice, seconds, disclosure) per distinct (engine, " +
"model, voice, speed, normalized text) — a re-ask is free. Never inside the corpus " +
"(refused). Blank = `<repo>/.tts/cache` (gitignored). Absolute, or `~/`-relative.",
+ orpheus: "Orpheus 3B's server and takes. See OrpheusTtsSettings (`tts.orpheus` below).",
};
// "" (the default), an absolute path, or a `~/` one; anything else is "".
@@ -68,11 +134,51 @@ export function sanitizeTts(value: unknown): TtsSettings {
typeof r.voice === "string" && engine.voices.includes(r.voice.trim())
? r.voice.trim()
: engine.defaultVoice;
- const speed =
- typeof r.speed === "number" && Number.isFinite(r.speed)
- ? Math.min(2, Math.max(0.5, Math.round(r.speed * 100) / 100))
- : d.speed;
- return { engine: engine.id, voice, speed, home: dirSetting(r.home), dir: dirSetting(r.dir) };
+ // Within the engine's range (Orpheus has no speed control: always 1).
+ const [lo, hi] = engine.speedRange;
+ const speed = Math.min(
+ hi,
+ Math.max(lo, typeof r.speed === "number" && Number.isFinite(r.speed) ? Math.round(r.speed * 100) / 100 : d.speed),
+ );
+ return {
+ engine: engine.id,
+ voice,
+ speed,
+ home: dirSetting(r.home),
+ dir: dirSetting(r.dir),
+ orpheus: sanitizeOrpheus(r.orpheus),
+ };
+}
+
+function int(value: unknown, fallback: number, min: number, max: number): number {
+ const n = typeof value === "number" && Number.isFinite(value) ? Math.round(value) : fallback;
+ return Math.min(max, Math.max(min, n));
+}
+
+// An absolute path, or "" where blank is allowed; anything else is the default.
+function absPath(value: unknown, fallback: string, blankOk: boolean): string {
+ if (typeof value !== "string") return fallback;
+ const s = value.trim();
+ if (s === "") return blankOk ? "" : fallback;
+ return path.isAbsolute(s) ? s : fallback;
+}
+
+export function sanitizeOrpheus(value: unknown): OrpheusTtsSettings {
+ const d = DEFAULT_ORPHEUS_TTS_SETTINGS;
+ const r = value && typeof value === "object" ? (value as Record<string, unknown>) : {};
+ return {
+ serverBin: absPath(r.serverBin, d.serverBin, false),
+ libraryPath: absPath(r.libraryPath, d.libraryPath, true),
+ ggmlBackendPath: absPath(r.ggmlBackendPath, d.ggmlBackendPath, true),
+ port: int(r.port, d.port, 1024, 65535),
+ gpuLayers: int(r.gpuLayers, d.gpuLayers, 0, 999),
+ contextSize: int(r.contextSize, d.contextSize, 2048, 131072),
+ startTimeoutSeconds: int(r.startTimeoutSeconds, d.startTimeoutSeconds, 5, 3600),
+ idleStopSeconds: int(r.idleStopSeconds, d.idleStopSeconds, 0, 3600),
+ heavyEstimateMB: int(r.heavyEstimateMB, d.heavyEstimateMB, 0, 65536),
+ takes: int(r.takes, d.takes, 1, 6),
+ tagCheck: r.tagCheck === true,
+ };
}
function expand(p: string): string {
diff --git a/scripts/tts.mjs b/scripts/tts.mjs
@@ -6,12 +6,17 @@
// 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:
+// 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 and takes (common/lib/ttsApps.ts
+// prepareInput); 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),
@@ -30,7 +35,7 @@
//
// Options (env fallback in parens):
// --output <f> the WAV to write [required]
-// --engine-kind <k> kokoro | espeak-ng (default kokoro)
+// --engine-kind <k> kokoro | espeak-ng | orpheus (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>
@@ -38,6 +43,9 @@
// --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]
+// --python <p> the venv's python [orpheus]
+// --snac <p> snac_decoder.onnx [orpheus]
+// --server <url> the running llama-server [orpheus]
// --ffmpeg <bin> ffmpeg binary (FFMPEG_BIN, ffmpeg)
// -h, --help
@@ -48,7 +56,8 @@ 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.
+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;
@@ -82,10 +91,10 @@ for (let i = 0; i < argv.length; 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}')`);
+if (engineKind !== "kokoro" && engineKind !== "espeak-ng" && engineKind !== "orpheus") {
+ fail(`--engine-kind must be 'kokoro', 'espeak-ng' or 'orpheus' (got '${engineKind}')`);
}
-const voice = arg("--voice", DEFAULT_VOICE[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");
@@ -188,6 +197,32 @@ try {
} 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.
diff --git a/scripts/tts.test.mjs b/scripts/tts.test.mjs
@@ -72,10 +72,15 @@ test("refusals: no output, an unknown engine, a speed out of range, empty text",
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", "piper", "--output", out, text]).stderr, /must be 'kokoro', 'espeak-ng' or 'orpheus'/);
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.match(run(["--engine-kind", "orpheus", "--python", "/x/python", "--snac", "/x/s.onnx", "--output", out, text]).stderr, /missing --server/);
+ assert.match(
+ run(["--engine-kind", "orpheus", "--python", "/x/python", "--snac", "/x/s.onnx", "--server", "http://127.0.0.1:1", "--output", out, text]).stderr,
+ /orpheus reads the editor's JSON of chunks, not plain text/,
+ );
assert.deepEqual(readdirSync(dir).sort(), ["empty.txt", "in.txt"]);
});
diff --git a/scripts/tts_orpheus.py b/scripts/tts_orpheus.py
@@ -0,0 +1,460 @@
+#!/usr/bin/env python3
+"""Orpheus 3B: chunks in, one 16-bit mono WAV at 24 kHz out (release 25 T1b).
+
+Run by scripts/tts.mjs (the wrapper every TTS engine runs behind) with the
+python of the venv `archilyzer tts setup --engine orpheus` built (onnxruntime
+and numpy; no torch). The editor has already started llama-server with the
+Orpheus GGUF (controller/ttsServer.ts) and chunked the normalized text
+(common/lib/ttsChunk.ts); this renders the chunks. Ported from the tuned
+round's pipeline of 2026-10-11 (its report, "Engine contract").
+
+ input.json ─► per chunk: up to `takes` takes (seeded) on llama-server
+ ─► SNAC decode (onnxruntime, CPU) ─► checks ─► the FIRST take
+ that passes is kept (early stop)
+ ─► trim, loudness-match, 15 ms fades, the chunk's pause ─► WAV
+
+STOCK VOICES ONLY: tara leah jess leo dan mia zac zoe. There is no
+reference-audio path here and there must never be one. No ASR is run.
+
+The checks (no model): the end-of-speech token was reached (a take cut at its
+token budget is never kept); no malformed frame; words a second in band —
+2.0–3.6, the floor lowered 0.25 a second for each sentence past the first, so a
+slow, dramatic multi-sentence read passes; no internal silence over 1.0 s in a
+sentence, 1.3 s between sentences, plus 0.4 s a tag or "...". With
+`tagCheck`, a chunk with tags must also run 0.4 s a tag longer than the same
+voice reading it without them, else the take is taken to have skipped its tag.
+When no take passes, the one with the fewest failures (then the shortest
+longest silence) is kept and the chunk is FLAGGED on stderr and in the result;
+when every take is truncated or malformed, the synthesis fails.
+
+input.json: {"version": 1, "voice", "sampler": {...}, "seedBase", "takes",
+"tagCheck", "chunks": [{"text", "ends", "pauseAfter", "nPredict"}]}.
+On stdout, one JSON line: {sampleRate, seconds, chunks, takes, flagged,
+genSeconds, takeSeconds, rtfPerTake, loadSeconds}. `selftest` checks the audio
+checks, the frame mapping, the take selection and the joins on synthetic data
+(numpy only).
+"""
+
+import argparse
+import json
+import re
+import sys
+import time
+import urllib.request
+import wave
+
+import numpy as np
+
+VOICES = ("tara", "leah", "jess", "leo", "dan", "mia", "zac", "zoe")
+TAGS = ("laugh", "chuckle", "sigh", "cough", "sniffle", "groan", "yawn", "gasp")
+TAG_RE = re.compile(r"<(?:%s)>" % "|".join(TAGS))
+SR = 24000
+FRAME = SR // 100 # 10 ms
+
+# Orpheus special tokens (Llama-3.2 vocabulary 128256 + custom tokens).
+START_OF_HUMAN, BOS, EOT, END_OF_HUMAN = 128259, 128000, 128009, 128260
+START_OF_AI, START_OF_SPEECH, END_OF_SPEECH = 128261, 128257, 128258
+AUDIO_BASE = 128266 # frame slot k uses [AUDIO_BASE + k*4096, +4096)
+
+WPS_BAND = (2.0, 3.6)
+WPS_FLOOR_PER_EXTRA_SENTENCE = 0.25
+WPS_FLOOR_MIN = 1.5
+TAG_EXCESS_S = 0.4
+
+
+def log(msg):
+ print(f"orpheus: {msg}", file=sys.stderr, flush=True)
+
+
+# ── text ──────────────────────────────────────────────────────────────────────
+def words_in(text):
+ return len(re.findall(r"[A-Za-z0-9]+(?:'[A-Za-z]+)?", TAG_RE.sub(" ", text)))
+
+
+def sentences_in(text):
+ return len(re.findall(r"(?<!\.)[.!?][\"')]?(?=\s|$)", TAG_RE.sub("", text)))
+
+
+def strip_tags(text):
+ return re.sub(r"\s+", " ", TAG_RE.sub(" ", text)).strip()
+
+
+def wps_floor(n_sent):
+ return max(WPS_FLOOR_MIN, WPS_BAND[0] - WPS_FLOOR_PER_EXTRA_SENTENCE * max(0, n_sent - 1))
+
+
+# ── frames ────────────────────────────────────────────────────────────────────
+def codes_from_tokens(ids):
+ """The audio codes of a completion's tokens, de-offset by slot → (codes, bad_frames)."""
+ if END_OF_SPEECH in ids:
+ ids = ids[: ids.index(END_OF_SPEECH)]
+ if START_OF_SPEECH in ids:
+ ids = ids[len(ids) - ids[::-1].index(START_OF_SPEECH):]
+ raw = [t for t in ids if t >= AUDIO_BASE]
+ raw = raw[: len(raw) // 7 * 7]
+ codes, bad = [], 0
+ for i in range(0, len(raw), 7): # slot k must sit in its own 4096-code band
+ fr = [raw[i + k] - AUDIO_BASE - k * 4096 for k in range(7)]
+ if all(0 <= c < 4096 for c in fr):
+ codes += fr
+ else:
+ bad += 1
+ return codes, bad
+
+
+def snac_inputs(codes):
+ """7-code frames → SNAC 24 kHz's three levels: c0 | c1, c4 | c2, c3, c5, c6."""
+ l0, l1, l2 = [], [], []
+ for i in range(len(codes) // 7):
+ c = codes[7 * i: 7 * i + 7]
+ l0.append(c[0])
+ l1 += [c[1], c[4]]
+ l2 += [c[2], c[3], c[5], c[6]]
+ return [np.array([l], dtype=np.int64) for l in (l0, l1, l2)]
+
+
+class Decoder:
+ def __init__(self, path):
+ import onnxruntime as ort
+
+ self.sess = ort.InferenceSession(path, providers=["CPUExecutionProvider"])
+
+ def __call__(self, codes):
+ if not codes:
+ return np.zeros(0, np.float32)
+ a0, a1, a2 = snac_inputs(codes)
+ out = self.sess.run(None, {"audio_codes.0": a0, "audio_codes.1": a1, "audio_codes.2": a2})[0]
+ return out.squeeze().astype(np.float32)
+
+
+# ── the server ────────────────────────────────────────────────────────────────
+def post(url, body, timeout=600):
+ req = urllib.request.Request(url, data=json.dumps(body).encode(), headers={"content-type": "application/json"})
+ with urllib.request.urlopen(req, timeout=timeout) as r:
+ return json.loads(r.read())
+
+
+def generate(server, decode, voice, text, seed, sampler, n_predict):
+ """One take → dict(audio, end_reached, bad_frames, stop_type, n_tokens, gen_s)."""
+ assert voice in VOICES, voice # stock voices only
+ toks = post(f"{server}/tokenize", {"content": f"{voice}: {text}", "add_special": False})["tokens"]
+ prompt = [START_OF_HUMAN, BOS] + toks + [EOT, END_OF_HUMAN, START_OF_AI, START_OF_SPEECH]
+ t0 = time.perf_counter()
+ r = post(
+ f"{server}/completion",
+ dict(prompt=prompt, n_predict=n_predict, seed=seed, return_tokens=True, cache_prompt=False,
+ stop=["<custom_token_2>"], **sampler),
+ )
+ if "error" in r:
+ raise RuntimeError(f"llama-server: {r['error']}")
+ gen_s = time.perf_counter() - t0
+ ids = r.get("tokens", [])
+ end_reached = r.get("stop_type") in ("word", "eos") or END_OF_SPEECH in ids
+ codes, bad = codes_from_tokens(ids)
+ return dict(audio=decode(codes), end_reached=bool(end_reached), bad_frames=bad,
+ stop_type=r.get("stop_type"), n_tokens=len(ids), gen_s=gen_s)
+
+
+# ── audio ─────────────────────────────────────────────────────────────────────
+def frame_db(a):
+ n = len(a) // FRAME
+ if not n:
+ return np.zeros(0)
+ f = a[: n * FRAME].reshape(n, FRAME)
+ return 10 * np.log10(np.mean(f * f, axis=1) + 1e-12)
+
+
+def trim(a, lead=0.04, tail=0.08):
+ """Leading/trailing silence cut by an energy gate 40 dB under the loudest 10 ms (floor −60 dBFS)."""
+ db = frame_db(a)
+ if not len(db):
+ return a
+ act = np.where(db > max(db.max() - 40, -60))[0]
+ if not len(act):
+ return a[:0]
+ s = max(0, act[0] * FRAME - int(lead * SR))
+ e = min(len(a), (act[-1] + 1) * FRAME + int(tail * SR))
+ return a[s:e]
+
+
+def longest_gap(a):
+ """The longest internal pause (s): consecutive frames 35 dB under the peak."""
+ db = frame_db(a)
+ if not len(db):
+ return 0.0
+ quiet = db < db.max() - 35
+ best = run = 0
+ for q in quiet:
+ run = run + 1 if q else 0
+ best = max(best, run)
+ return best * FRAME / SR
+
+
+def active_db(a):
+ db = frame_db(a)
+ if not len(db):
+ return -99.0
+ act = db[db > db.max() - 30]
+ return float(10 * np.log10(np.mean(10 ** (act / 10))))
+
+
+def check_take(text, take):
+ """The non-ASR checks → (passed, metrics)."""
+ a = trim(take["audio"])
+ dur = len(a) / SR
+ n_tags, n_ell = len(TAG_RE.findall(text)), text.count("...")
+ speech_s = max(0.1, dur - 0.9 * n_tags - 0.3 * n_ell)
+ wps = words_in(text) / speech_s
+ gap = longest_gap(a)
+ n_sent = sentences_in(text)
+ lo = wps_floor(n_sent)
+ max_gap = min(2.2, (1.3 if n_sent > 1 else 1.0) + 0.4 * (n_tags + n_ell))
+ fails = []
+ if not take["end_reached"]:
+ fails.append("truncated (token budget hit, no end of speech)")
+ if take["bad_frames"]:
+ fails.append(f"{take['bad_frames']} malformed frames")
+ if not (lo <= wps <= WPS_BAND[1]):
+ fails.append(f"{wps:.2f} words/s outside ({lo:.2f}, {WPS_BAND[1]})")
+ if gap > max_gap:
+ fails.append(f"internal silence {gap:.2f}s > {max_gap:.1f}s")
+ return not fails, dict(dur=round(dur, 3), wps=round(wps, 3), longest_gap=round(gap, 3), fails=fails)
+
+
+def fade(a, ms=15):
+ n = min(len(a) // 2, int(SR * ms / 1000))
+ if n:
+ w = 0.5 - 0.5 * np.cos(np.linspace(0, np.pi, n, dtype=np.float32))
+ a = a.copy()
+ a[:n] *= w
+ a[-n:] *= w[::-1]
+ return a
+
+
+def assemble(pieces):
+ """[(trimmed audio, pause after)] → one line: chunk loudness matched (±6 dB), 15 ms fades, the
+ pauses; speech at about −20 dBFS active, peaks at or under −1 dBFS."""
+ lev = [active_db(a) for a, _ in pieces]
+ target = float(np.median(lev)) if lev else -20.0
+ out = []
+ for (a, pause), l in zip(pieces, lev):
+ g = 10 ** (np.clip(target - l, -6, 6) / 20)
+ out += [fade(a * g), np.zeros(int(pause * SR), np.float32)]
+ y = np.concatenate(out).astype(np.float32) if out else np.zeros(0, np.float32)
+ y *= 10 ** ((-20 - target) / 20)
+ pk = float(np.abs(y).max()) if len(y) else 0.0
+ if pk > 0.891:
+ y *= 0.891 / pk
+ return y
+
+
+# ── takes ─────────────────────────────────────────────────────────────────────
+def choose(cands):
+ """The kept take of a chunk: the first that passed; else, of those that reached their end with no
+ malformed frame, the one only its tag check failed (the longest), else the fewest failures then the
+ shortest silence. None when every take was truncated or malformed."""
+ for c in cands:
+ if c["passed"]:
+ return c
+ pool = [c for c in cands if c["end_reached"] and not c["bad_frames"]]
+ if not pool:
+ return None
+ only_tag = [c for c in pool if c["fails"] and all(f.startswith("tag ") for f in c["fails"])]
+ if only_tag:
+ return max(only_tag, key=lambda c: c.get("tag_excess") or 0)
+ return min(pool, key=lambda c: (len(c["fails"]), c["longest_gap"]))
+
+
+def render_chunk(gen, chunk, ci, n_chunks, voice, sampler, seed_base, takes, tag_check):
+ """Up to `takes` takes of one chunk; the first that passes ends it. gen(text, seed, n_predict) → take."""
+ text, n_pred = chunk["text"], chunk["nPredict"]
+ n_tags = len(TAG_RE.findall(text))
+ twin = None
+ if tag_check and n_tags:
+ plain = strip_tags(text)
+ for k in range(3):
+ g = gen(plain, seed_base + 7 + k, n_pred)
+ ok, m = check_take(plain, g)
+ if ok:
+ break
+ twin = m["dur"]
+ log(f"chunk {ci + 1}/{n_chunks}: read without its tags {twin:.2f}s")
+ cands = []
+ for t in range(takes):
+ seed = seed_base + 101 * t + ci
+ g = gen(text, seed, n_pred)
+ ok, m = check_take(text, g)
+ excess = None
+ if twin is not None:
+ excess = round(m["dur"] - twin, 3)
+ if excess < TAG_EXCESS_S * n_tags:
+ m["fails"].append(f"tag likely skipped (excess {excess:.2f}s < {TAG_EXCESS_S * n_tags:.1f}s)")
+ ok = False
+ cands.append(dict(take=t, seed=seed, passed=ok, end_reached=g["end_reached"], bad_frames=g["bad_frames"],
+ gen_s=g["gen_s"], tag_excess=excess, audio=g["audio"], **m))
+ log(f"chunk {ci + 1}/{n_chunks} take {t + 1} seed {seed}: {'PASS' if ok else 'fail'} {m['dur']:.2f}s "
+ f"{m['wps']:.2f} words/s, longest silence {m['longest_gap']:.2f}s"
+ + (f" — {'; '.join(m['fails'])}" if m["fails"] else ""))
+ if ok:
+ break # the first take that passes is kept
+ best = choose(cands)
+ return best, cands
+
+
+def render(spec, server, decode):
+ voice = spec["voice"]
+ if voice not in VOICES:
+ raise SystemExit(f"not a stock voice: {voice!r} (stock: {' '.join(VOICES)})")
+ sampler, seed_base = spec["sampler"], int(spec.get("seedBase", 1234))
+ takes, tag_check = max(1, int(spec.get("takes", 3))), bool(spec.get("tagCheck", False))
+ chunks = spec["chunks"]
+ gen = lambda text, seed, n_pred: generate(server, decode, voice, text, seed, sampler, n_pred)
+ pieces, flagged, n_takes, gen_s, take_s = [], [], 0, 0.0, 0.0
+ for ci, c in enumerate(chunks):
+ best, cands = render_chunk(gen, c, ci, len(chunks), voice, sampler, seed_base, takes, tag_check)
+ n_takes += len(cands)
+ gen_s += sum(x["gen_s"] for x in cands)
+ take_s += sum(x["dur"] for x in cands)
+ if best is None:
+ raise SystemExit(f"chunk {ci + 1}: every take was truncated or malformed — {cands[-1]['fails']}")
+ if not best["passed"]:
+ flagged.append(dict(chunk=ci + 1, take=best["take"] + 1, why="; ".join(best["fails"])))
+ log(f"chunk {ci + 1}/{len(chunks)}: FLAGGED — no take passed; kept take {best['take'] + 1}: {'; '.join(best['fails'])}")
+ pieces.append((trim(best["audio"]), float(c["pauseAfter"])))
+ return assemble(pieces), dict(chunks=len(chunks), takes=n_takes, flagged=flagged, genSeconds=round(gen_s, 2),
+ takeSeconds=round(take_s, 2), rtfPerTake=round(gen_s / max(take_s, 1e-6), 3))
+
+
+def write_wav(path, y):
+ pcm = (np.clip(y, -1.0, 1.0) * 32767.0).astype("<i2")
+ with wave.open(path, "wb") as w:
+ w.setnchannels(1)
+ w.setsampwidth(2)
+ w.setframerate(SR)
+ w.writeframes(pcm.tobytes())
+ return len(pcm) / SR
+
+
+# ── selftest (numpy only: no model, no server) ────────────────────────────────
+def _tone(seconds, freq=220.0, amp=0.3):
+ t = np.arange(int(seconds * SR)) / SR
+ return (amp * np.sin(2 * np.pi * freq * t)).astype(np.float32)
+
+
+def _silence(seconds):
+ return np.zeros(int(seconds * SR), np.float32)
+
+
+def selftest():
+ fails = []
+
+ def ok(cond, what):
+ print(("ok " if cond else "FAIL ") + what)
+ if not cond:
+ fails.append(what)
+
+ # trim and silences
+ a = np.concatenate([_silence(0.5), _tone(1.0), _silence(0.4), _tone(0.5), _silence(0.7)])
+ tr = trim(a)
+ ok(abs(len(tr) / SR - (1.9 + 0.04 + 0.08)) < 0.02, f"trim keeps 40 ms before and 80 ms after ({len(tr) / SR:.3f}s)")
+ ok(abs(longest_gap(tr) - 0.4) < 0.02, f"the longest internal silence is found ({longest_gap(tr):.2f}s)")
+ ok(len(trim(_silence(1.0))) == 0, "an all-silent take trims to nothing")
+
+ # the rate floor drops for multi-sentence chunks
+ ok(wps_floor(1) == 2.0 and wps_floor(2) == 1.75 and wps_floor(3) == 1.5 and wps_floor(6) == 1.5,
+ "the words/s floor: 2.0, 1.75 for two sentences, 1.5 at three and more")
+ ok(sentences_in("One file. No title. Just a date.") == 3 and sentences_in("And then... there it was.") == 1,
+ "sentences are counted; an ellipsis does not end one")
+
+ def take(seconds, end=True, bad=0, gap=None):
+ audio = _tone(seconds) if gap is None else np.concatenate([_tone(seconds / 2), _silence(gap), _tone(seconds / 2)])
+ return dict(audio=audio, end_reached=end, bad_frames=bad, gen_s=seconds * 1.5)
+
+ one = "This sentence has exactly eight words in it." # 8 words
+ ok(check_take(one, take(3.0))[0], "8 words in 3.0 s (2.7/s) pass")
+ ok(not check_take(one, take(4.5))[0], "8 words in 4.5 s (1.8/s) fail as one sentence")
+ three = "This has four words. This has four words. And this has five." # 13 words, 3 sentences
+ ok(check_take(three, take(13 / 1.8))[0], "a slow three-sentence read (1.8 words/s) passes: the floor is 1.5")
+ ok(not check_take(one, take(1.5))[0], "8 words in 1.5 s (5.3/s) fail as too fast")
+ p, m = check_take(one, take(3.0, end=False))
+ ok(not p and m["fails"][0].startswith("truncated"), "a take with no end of speech fails as truncated")
+ ok(not check_take(one, take(3.0, bad=2))[0], "malformed frames fail")
+ p, m = check_take(one, take(2.4, gap=1.5))
+ ok(not p and any("internal silence" in f for f in m["fails"]), "1.5 s of dead air inside a sentence fails")
+
+ # frames: the slot bands, the end token, the SNAC levels
+ frame = [AUDIO_BASE + k * 4096 + (k + 1) for k in range(7)]
+ bad_frame = [AUDIO_BASE + 5] * 7 # slot 1+ outside its band
+ ids = [START_OF_SPEECH] + frame + bad_frame + frame + [END_OF_SPEECH] + frame
+ codes, bad = codes_from_tokens(ids)
+ ok(codes == [1, 2, 3, 4, 5, 6, 7] * 2 and bad == 1, "frames: two good, one malformed, nothing after the end token")
+ l0, l1, l2 = snac_inputs([1, 2, 3, 4, 5, 6, 7])
+ ok(l0.tolist() == [[1]] and l1.tolist() == [[2, 5]] and l2.tolist() == [[3, 4, 6, 7]], "SNAC levels: c0 | c1 c4 | c2 c3 c5 c6")
+
+ # takes: the first passing take ends the chunk
+ calls = []
+ script = [take(4.6), take(3.0), take(3.0)]
+
+ def gen(text, seed, n_pred):
+ calls.append(seed)
+ return script[len(calls) - 1]
+
+ best, cands = render_chunk(gen, dict(text=one, nPredict=700), 2, 5, "leah", {}, 1234, 3, False)
+ ok(best["take"] == 1 and calls == [1236, 1337], f"early stop: take 2 passes, take 3 is never asked (seeds {calls})")
+
+ # nothing passes: the fewest failures are kept; all truncated → None
+ c = [dict(passed=False, end_reached=True, bad_frames=0, fails=["a", "b"], longest_gap=0.2, take=0),
+ dict(passed=False, end_reached=True, bad_frames=0, fails=["a"], longest_gap=0.9, take=1),
+ dict(passed=False, end_reached=False, bad_frames=0, fails=["truncated"], longest_gap=0.0, take=2)]
+ ok(choose(c)["take"] == 1, "no take passes: the fewest failures are kept, never a truncated one")
+ ok(choose([dict(c[2]), dict(c[2], bad_frames=1, end_reached=True)]) is None, "every take truncated or malformed: none")
+ tag = [dict(passed=False, end_reached=True, bad_frames=0, fails=["tag likely skipped"], tag_excess=0.1, longest_gap=0, take=0),
+ dict(passed=False, end_reached=True, bad_frames=0, fails=["tag likely skipped"], tag_excess=0.3, longest_gap=0, take=1)]
+ ok(choose(tag)["take"] == 1, "only the tag check failed: the take likeliest to hold the tag")
+
+ # tag check: a take no longer than the plain read fails
+ calls.clear()
+ tagged = "This sentence has exactly eight words in it. <sigh>"
+ script = [take(3.5), take(3.6), take(3.6), take(3.6)] # the plain twin, then three takes
+ best, cands = render_chunk(gen, dict(text=tagged, nPredict=700), 0, 1, "leah", {}, 1234, 3, True)
+ ok(not best["passed"] and len(calls) == 4 and [f[:18] for f in best["fails"]] == ["tag likely skipped"],
+ "with the tag check, takes barely longer than the plain read fail as having skipped the tag")
+ calls.clear()
+ script = [take(3.5), take(4.4)]
+ best, cands = render_chunk(gen, dict(text=tagged, nPredict=700), 0, 1, "leah", {}, 1234, 3, True)
+ ok(best["passed"] and len(calls) == 2, "a take 0.9 s longer than the plain read holds its tag, and passes")
+
+ # joins: the pause after each chunk, peaks at or under −1 dBFS
+ y = assemble([(_tone(1.0, amp=0.9), 0.3), (_tone(1.0, amp=0.1), 0.6), (_tone(0.5), 0.0)])
+ ok(abs(len(y) / SR - 3.4) < 0.01, f"joined: 2.5 s of speech + 0.9 s of pauses ({len(y) / SR:.2f}s)")
+ ok(float(np.abs(y).max()) <= 0.8911, "peaks at or under −1 dBFS")
+
+ print("SELFTEST", "PASS" if not fails else f"FAIL ({len(fails)})")
+ return not fails
+
+
+def main():
+ if sys.argv[1:2] == ["selftest"]:
+ return 0 if selftest() else 1
+ p = argparse.ArgumentParser(description=__doc__.splitlines()[0])
+ p.add_argument("--server", required=True, help="llama-server base URL")
+ p.add_argument("--snac", required=True, help="snac_decoder.onnx")
+ p.add_argument("--output", required=True, help="the WAV to write (24 kHz)")
+ p.add_argument("input", help="input.json (see the docstring)")
+ args = p.parse_args()
+ with open(args.input, encoding="utf-8") as f:
+ spec = json.load(f)
+ if not spec.get("chunks"):
+ print("tts_orpheus: no chunks to speak", file=sys.stderr)
+ return 2
+ t0 = time.perf_counter()
+ decode = Decoder(args.snac)
+ load = time.perf_counter() - t0
+ y, stats = render(spec, args.server.rstrip("/"), decode)
+ seconds = write_wav(args.output, y)
+ print(json.dumps(dict(sampleRate=SR, seconds=round(seconds, 3), loadSeconds=round(load, 3), **stats)))
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/scripts/tts_orpheus.test.mjs b/scripts/tts_orpheus.test.mjs
@@ -0,0 +1,49 @@
+// scripts/tts_orpheus.py — the Orpheus helper's own checks, run through its
+// `selftest` (numpy only: the take checks, the rate floor for multi-sentence
+// chunks, the frame bands and SNAC levels, the first-pass early stop, the
+// fallback when nothing passes, the tag-length check, the joins).
+//
+// Run with: node --test scripts/tts_orpheus.test.mjs (part of `pnpm run test:scripts`)
+//
+// Needs a python with numpy: `python3` when it has one. Skipped otherwise — the
+// real model is never run here.
+
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { spawnSync } from "node:child_process";
+import path from "node:path";
+
+const HELPER = path.join(import.meta.dirname, "tts_orpheus.py");
+const probe = spawnSync("python3", ["-c", "import numpy"], { encoding: "utf8" });
+const skip = probe.status !== 0 && "python3 with numpy absent";
+
+test("the Orpheus helper's selftest passes", { skip }, () => {
+ const r = spawnSync("python3", [HELPER, "selftest"], { encoding: "utf8" });
+ assert.equal(r.status, 0, r.stdout + r.stderr);
+ assert.match(r.stdout, /SELFTEST PASS/);
+ assert.doesNotMatch(r.stdout, /^FAIL/m);
+ // The cases it holds, by name: a missing one is a dropped check.
+ for (const name of [
+ "a slow three-sentence read (1.8 words/s) passes",
+ "a take with no end of speech fails as truncated",
+ "early stop: take 2 passes, take 3 is never asked",
+ "every take truncated or malformed: none",
+ "with the tag check, takes barely longer than the plain read fail",
+ "SNAC levels: c0 | c1 c4 | c2 c3 c5 c6",
+ ]) {
+ assert.ok(r.stdout.includes(`ok ${name}`), name);
+ }
+});
+
+test("the helper refuses a voice that is not a stock one, before anything runs", { skip }, () => {
+ const r = spawnSync(
+ "python3",
+ ["-B", "-c", `import sys; sys.path.insert(0, ${JSON.stringify(path.dirname(HELPER))}); import tts_orpheus as t
+try:
+ t.render({"voice": "someone", "sampler": {}, "chunks": [{"text": "x", "nPredict": 7, "pauseAfter": 0}]}, "http://127.0.0.1:1", None)
+except SystemExit as e:
+ print(e)`],
+ { encoding: "utf8" },
+ );
+ assert.match(r.stdout, /not a stock voice: 'someone'/);
+});
diff --git a/settings.json.example b/settings.json.example
@@ -222,6 +222,19 @@
"voice": "af_heart",
"speed": 1,
"home": "",
- "dir": ""
+ "dir": "",
+ "orpheus": {
+ "serverBin": "/usr/lib/ollama/llama-server",
+ "libraryPath": "/usr/lib/ollama",
+ "ggmlBackendPath": "/usr/lib/ollama/vulkan/libggml-vulkan.so",
+ "port": 8799,
+ "gpuLayers": 99,
+ "contextSize": 8192,
+ "startTimeoutSeconds": 150,
+ "idleStopSeconds": 5,
+ "heavyEstimateMB": 4000,
+ "takes": 3,
+ "tagCheck": false
+ }
}
}