import { test, after } from "node:test"; import assert from "node:assert/strict"; import { execFileSync } from "node:child_process"; import { chmod, mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; // Run with: // pnpm --filter yt-dlp-transcript-common exec tsx --test controller/ttsFile.test.ts // // One text-to-speech synthesis (`pnpm ops tts`): the body's shape, the // refusals that come before any job, the cache key — and whole jobs run // through the real registry, the real job queue and the REAL wrapper with // espeak-ng (the zero-install engine), behind a counting shim at TTS_BIN so a // cache hit can be shown to run no engine. In a temp corpus; nothing here // touches a real transcripts dir, and Kokoro is never run. const ROOT = await mkdtemp(path.join(os.tmpdir(), "tts-file-")); after(() => rm(ROOT, { recursive: true, force: true })); const CORPUS = path.join(ROOT, "transcripts"); const OUTSIDE = path.join(ROOT, "outside"); const CACHE = path.join(ROOT, "tts-cache"); const HOME = path.join(ROOT, "tts-home"); const BIN = path.join(ROOT, "bin"); await mkdir(path.join(CORPUS, "channels", "chan", "data"), { recursive: true }); await mkdir(OUTSIDE, { recursive: true }); await mkdir(HOME, { recursive: true }); await mkdir(BIN, { recursive: true }); // The shim: one line per engine run, then the real wrapper with the same argv. const RUNS = path.join(ROOT, "runs.log"); const WRAPPER = path.resolve(import.meta.dirname, "..", "..", "scripts", "tts.mjs"); const shim = path.join(BIN, "tts-shim"); await writeFile( shim, `#!/usr/bin/env node const fs = require("node:fs"); const { spawnSync } = require("node:child_process"); fs.appendFileSync(${JSON.stringify(RUNS)}, JSON.stringify(process.argv.slice(2)) + "\\n"); const text = fs.readFileSync(process.argv[process.argv.length - 1], "utf8"); if (text.includes("explode")) { console.error("tts: engine exploded"); process.exit(3); } const 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); `, ); await chmod(shim, 0o755); const SETTINGS_FILE = path.join(ROOT, "settings.json"); async function setTts(tts: Record) { await writeFile(SETTINGS_FILE, JSON.stringify({ workers: [], tts }, null, 2)); } await setTts({ engine: "espeak-ng", voice: "en-us", dir: CACHE, home: HOME }); // Set before getPaths (which caches) is first reached through the imports. process.env.TRANSCRIPTS_DIR = CORPUS; process.env.SETTINGS_FILE = SETTINGS_FILE; process.env.TTS_BIN = shim; const { runTtsSynthesis, waitForGpu, TTS_FILE_BODY_KEYS, TTS_MAX_CHARS, TTS_RESULT_MARKER, checkTtsRequest, enqueueTtsFile, parseTtsFileBody, readTtsCacheHit, resolveTtsRequest, ttsCacheKey, ttsTunedOf, } = 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(); // Orpheus's input.json for GOLDEN_TEXT in zac, captured on main 976efc77e before the tuning existed. const GOLDEN_INPUT_MAIN = "{\"version\":1,\"voice\":\"zac\",\"sampler\":{\"temperature\":0.55,\"top_p\":0.85,\"top_k\":50,\"min_p\":0,\"repeat_penalty\":1.2,\"repeat_last_n\":64,\"presence_penalty\":0,\"frequency_penalty\":0},\"seedBase\":1234,\"takes\":3,\"tagCheck\":false,\"chunks\":[{\"text\":\"One file. No title. \",\"ends\":\"paragraph\",\"pauseAfter\":0.4,\"nPredict\":525},{\"text\":\"Then in twenty twenty-four, it came back.\",\"ends\":\"end\",\"pauseAfter\":0,\"nPredict\":525}]}"; function has(bin: string, flag: string): boolean { try { execFileSync(bin, [flag], { stdio: "ignore" }); return true; } catch { return false; } } const REAL = has("espeak-ng", "--version") && has("ffmpeg", "-version"); const SKIP = !REAL && "espeak-ng or ffmpeg absent"; async function engineRuns(): Promise { return (await readFile(RUNS, "utf8").catch(() => "")).split("\n").filter(Boolean).length; } // --- body ---------------------------------------------------------------------- test("the body keys are the contract", () => { assert.deepEqual([...TTS_FILE_BODY_KEYS], ["text", "file", "voice", "engine", "speed", "out", "tuning", "reading"]); }); test("the body's shape is judged before the disk", () => { const bad: [Record, RegExp][] = [ [{}, /"text" .* or "file" .* is required/], [{ text: "a", file: "/x.txt" }, /not both/], [{ text: " " }, /"text" must be a non-empty string/], [{ text: 5 }, /"text" must be a non-empty string/], [{ file: "rel.txt" }, /"file" must be an absolute path/], [{ text: "a", voice: "" }, /"voice" must be a non-empty string/], [{ text: "a", engine: 3 }, /"engine" must be a non-empty string/], [{ text: "a", speed: "fast" }, /"speed" must be a number/], [{ text: "a", out: "rel.wav" }, /"out" must be an absolute path/], [{ text: "a", out: "/x/y.mp3" }, /"out" must name a \.wav file/], [{ text: "a", tuning: [] }, /"tuning" must be an object of temperature, top_p, top_k, min_p, repeat_penalty, takes/], [{ text: "a", tuning: { temperature: 3 } }, /^"tuning\.temperature" must be a number from 0\.1 to 1\.5 \(got 3\)$/], [{ text: "a", tuning: { takes: 0 } }, /^"tuning\.takes" must be a whole number from 1 to 6 \(got 0\)$/], [{ text: "a", tuning: { seed: 9 } }, /"tuning\.seed" is not a tuning field/], [{ text: "a", reading: -1 }, /^"reading" must be a whole number from 0 to 99999/], [{ text: "a", reading: 1.5 }, /^"reading" must be a whole number/], ]; for (const [body, re] of bad) { const r = parseTtsFileBody(body); assert.equal(r.ok, false, JSON.stringify(body)); if (!r.ok) assert.match(r.error, re, JSON.stringify(body)); } const ok = parseTtsFileBody({ text: "Hi.", voice: " bf_emma ", speed: 0.9, out: "/o/../o/a.WAV" }); assert.deepEqual(ok, { ok: true, value: { text: "Hi.", voice: "bf_emma", speed: 0.9, out: "/o/a.WAV" } }); const tuned = parseTtsFileBody({ text: "Hi.", tuning: { temperature: 0.7, top_k: null }, reading: 2 }); assert.deepEqual(tuned, { ok: true, value: { text: "Hi.", tuning: { temperature: 0.7 }, reading: 2 } }); }); test("the request resolves against settings.tts and the registry", () => { const tts = { engine: "kokoro", voice: "af_heart", speed: 1 }; const r = resolveTtsRequest({}, "In 2024 it ended.", tts); assert.ok(r.ok); if (r.ok) { assert.equal(r.value.engine.id, "kokoro"); assert.equal(r.value.voice, "af_heart"); assert.equal(r.value.speed, 1); assert.equal(r.value.spoken, "In twenty twenty-four it ended."); } // Another engine named in the body speaks with ITS default voice. const e = resolveTtsRequest({ engine: "espeak-ng" }, "x", tts); assert.ok(e.ok && e.value.voice === "en-us"); const refusals: [Parameters[0], string, RegExp][] = [ [{ engine: "piper" }, "x", /no text-to-speech engine "piper" — known: kokoro, espeak-ng/], [{ voice: "someone" }, "x", /kokoro has no stock voice "someone" — its voices: af_alloy/], [{ engine: "espeak-ng", voice: "af_heart" }, "x", /espeak-ng has no stock voice "af_heart"/], [{ speed: 3 }, "x", /"speed" must be between 0.5 and 2 for kokoro \(got 3\)/], [{}, "a".repeat(TTS_MAX_CHARS + 1), /at most 20000 — split it/], [{}, "Well then", /a tag no engine knows: /], [{}, " ", /nothing to speak once its tags are removed/], ]; for (const [body, text, re] of refusals) { const x = resolveTtsRequest(body, text, tts); assert.equal(x.ok, false); if (!x.ok) assert.match(x.error, re); } }); test("the cache key follows engine, model, voice, speed and the spoken text", () => { const k = getTtsEngine("kokoro")!; const base = { engine: k, voice: "af_heart", speed: 1, spoken: "Hello." }; const sha = ttsCacheKey(base); assert.match(sha, /^[0-9a-f]{64}$/); assert.equal(ttsCacheKey({ ...base }), sha); assert.notEqual(ttsCacheKey({ ...base, voice: "bf_emma" }), sha); assert.notEqual(ttsCacheKey({ ...base, speed: 0.9 }), sha); assert.notEqual(ttsCacheKey({ ...base, spoken: "Hello!" }), sha); assert.notEqual(ttsCacheKey({ ...base, engine: { ...k, model: "kokoro-v1.1" } }), sha); assert.notEqual(ttsCacheKey({ ...base, engine: getTtsEngine("espeak-ng")! }), sha); }); // The cache keys of "One file. No title. \n\nThen in 2024, it came back." captured on main 976efc77e, // BEFORE the tuning existed: an ask without one keys exactly as it did (the cache hits it always had). const GOLDEN_SHA_MAIN = { orpheus: "2fc839e21ec07b574ff047cf40b2f272044065065acad2469dcca470096cf2b4", kokoro: "82e95bff9c1a4b620d33539cd12128d6a38bf8316980960231093a256b1499cc", "espeak-ng": "83dea25c24c121ff91d1d32debf87d7573e78794081747fc2f3af0cf184c5a60", } as const; const GOLDEN_TEXT = "One file. No title. \n\nThen in 2024, it came back."; const GOLDEN_VOICE = { orpheus: "zac", kokoro: "af_heart", "espeak-ng": "en-us" } as const; const SETTINGS_TTS = { engine: "kokoro", voice: "af_heart", speed: 1 }; function goldenKey(engine: keyof typeof GOLDEN_SHA_MAIN, extra: Record = {}): string { const body = parseTtsFileBody({ text: GOLDEN_TEXT, engine, voice: GOLDEN_VOICE[engine], ...extra }); if (!body.ok) throw new Error(body.error); const r = resolveTtsRequest(body.value, GOLDEN_TEXT, SETTINGS_TTS); if (!r.ok) throw new Error(r.error); return ttsCacheKey(r.value, DEFAULT_TTS_SETTINGS); } test("no tuning and no reading key as main did -- and so do the defaults spelled out and reading 0", () => { const defaults = { tuning: { temperature: 0.55, top_p: 0.85, top_k: 50, min_p: 0, repeat_penalty: 1.2, takes: 3 }, reading: 0, }; for (const engine of ["orpheus", "kokoro", "espeak-ng"] as const) { assert.equal(goldenKey(engine), GOLDEN_SHA_MAIN[engine], engine); assert.equal(goldenKey(engine, defaults), GOLDEN_SHA_MAIN[engine], `${engine}, the defaults spelled out`); assert.equal(goldenKey(engine, { tuning: {}, reading: 0 }), GOLDEN_SHA_MAIN[engine], `${engine}, an empty tuning`); } }); test("floats are quantised before the key: a default within rounding is main's key, 0.7000000000000001 keys as 0.7, -0 as 0", () => { assert.equal(goldenKey("orpheus", { tuning: { temperature: 0.550000001, top_p: 0.8500000001, repeat_penalty: 1.2000004 } }), GOLDEN_SHA_MAIN.orpheus); assert.equal(goldenKey("orpheus", { tuning: { min_p: -0, top_k: -0 + 50 } }), GOLDEN_SHA_MAIN.orpheus); assert.equal(goldenKey("orpheus", { tuning: { temperature: 0.7000000000000001 } }), goldenKey("orpheus", { tuning: { temperature: 0.7 } })); assert.notEqual(goldenKey("orpheus", { tuning: { temperature: 0.7 } }), GOLDEN_SHA_MAIN.orpheus); }); test("a tuning or a reading is a new key for Orpheus; the same one again is the same key", () => { const seen = new Set([GOLDEN_SHA_MAIN.orpheus]); for (const extra of [ { reading: 1 }, { reading: 2 }, { tuning: { temperature: 0.7 } }, { tuning: { top_p: 0.9 } }, { tuning: { top_k: 40 } }, { tuning: { min_p: 0.05 } }, { tuning: { repeat_penalty: 1.1 } }, { tuning: { takes: 4 } }, { tuning: { temperature: 0.7 }, reading: 1 }, ]) { const k = goldenKey("orpheus", extra); assert.ok(!seen.has(k), JSON.stringify(extra)); seen.add(k); assert.equal(goldenKey("orpheus", extra), k, `${JSON.stringify(extra)} again`); } // A default value beside a changed one changes nothing more. assert.equal( goldenKey("orpheus", { tuning: { temperature: 0.7, top_p: 0.85 }, reading: 1 }), goldenKey("orpheus", { tuning: { temperature: 0.7 }, reading: 1 }), ); }); test("kokoro and espeak-ng ignore a tuning and a reading: the same key, and a note", () => { for (const engine of ["kokoro", "espeak-ng"] as const) { assert.equal(goldenKey(engine, { tuning: { temperature: 0.9 }, reading: 3 }), GOLDEN_SHA_MAIN[engine], engine); const r = resolveTtsRequest({ engine, tuning: { temperature: 0.9 }, reading: 3 }, "Hello.", SETTINGS_TTS); assert.ok(r.ok); if (!r.ok) continue; assert.equal(r.value.tuning, undefined); assert.equal(r.value.reading, undefined); assert.match(r.value.note ?? "", /has no sampler or seed: the tuning and reading were ignored/); // Nothing asked: no note. const plain = resolveTtsRequest({ engine, reading: 0 }, "Hello.", SETTINGS_TTS); assert.ok(plain.ok && plain.value.note === undefined); } }); test("the corpus fence and the install check answer before any job", async () => { const k = resolveTtsRequest({ engine: "espeak-ng" }, "x", { engine: "kokoro", voice: "af_heart", speed: 1 }); assert.ok(k.ok); if (!k.ok) return; const ctx = { paths, cacheDir: CACHE, home: HOME }; const inCorpus = await checkTtsRequest({ ...k.value, out: path.join(CORPUS, "a.wav") }, ctx); assert.ok(!inCorpus.ok && /"out" .* is inside the corpus/.test(inCorpus.error)); const cacheIn = await checkTtsRequest(k.value, { ...ctx, cacheDir: path.join(CORPUS, "tts") }); assert.ok(!cacheIn.ok && /synthesis cache .* is inside the corpus/.test(cacheIn.error)); const noDir = await checkTtsRequest({ ...k.value, out: path.join(ROOT, "nope", "a.wav") }, ctx); assert.ok(!noDir.ok && /the directory .* does not exist/.test(noDir.error)); // Kokoro, with nothing installed under the home. const kk = resolveTtsRequest({}, "x", { engine: "kokoro", voice: "af_heart", speed: 1 }); assert.ok(kk.ok); if (!kk.ok) return; const notInstalled = await checkTtsRequest(kk.value, ctx); assert.ok(!notInstalled.ok); if (!notInstalled.ok) { assert.match(notInstalled.error, /Kokoro-82M is not installed \(.*tts-home\/kokoro\): missing the python venv/); assert.match(notInstalled.error, /kokoro-v1\.0\.onnx; voices-v1\.0\.bin — run `archilyzer tts setup`/); } }); // --- whole jobs ---------------------------------------------------------------- async function runJob(body: Record) { const res = await enqueueTtsFile(body, { paths }); if (!res.ok) return { error: res.error }; void res.stream.cancel(); const done = await res.done; // `done` settles as the log stream is ENDED, not flushed: a job that runs // no engine (a cache hit) can settle before its log reaches the disk. const logFile = path.join(paths.jobsDir, `${res.jobId}.log`); let log = ""; for (let i = 0; i < 100; i++) { log = await readFile(logFile, "utf8").catch(() => ""); if (log.includes(TTS_RESULT_MARKER) || log.includes("[error]")) break; await new Promise((r) => setTimeout(r, 20)); } const line = log.split("\n").find((l) => l.startsWith(TTS_RESULT_MARKER)); return { status: done.status, log, result: line ? JSON.parse(line.slice(TTS_RESULT_MARKER.length)) : null, }; } test("refusals through the job door start nothing", async () => { assert.match((await runJob({ text: "x", engine: "kokoro" })).error!, /not installed/); assert.match((await runJob({ text: "x", voice: "af_heart" })).error!, /espeak-ng has no stock voice/); assert.match((await runJob({ file: path.join(ROOT, "missing.txt") })).error!, /does not exist/); assert.match((await runJob({ text: "x", out: path.join(CORPUS, "x.wav") })).error!, /inside the corpus/); assert.equal(await engineRuns(), 0); }); test("a synthesis runs the engine once; the same ask again is a cached done job", { skip: SKIP }, async () => { const first = await runJob({ text: "In 2024 the archive spoke." }); assert.equal(first.status, "done", first.log); const r = first.result; assert.equal(r.engine, "espeak-ng"); assert.equal(r.voice, "en-us"); assert.equal(r.cached, false); assert.equal(r.sampleRate, 48000); assert.equal(r.speed, 1); assert.match(r.sha, /^[0-9a-f]{64}$/); assert.equal(r.wav, path.join(CACHE, `${r.sha}.wav`)); assert.ok(r.seconds > 0.5, String(r.seconds)); assert.ok(r.durationMs > 0); assert.ok(r.waitedMs >= 0); assert.equal(r.disclosure, "Narration: synthetic voice (eSpeak NG · en-us)"); assert.equal(await engineRuns(), 1); // The engine got the spoken text: tags stripped, the year said. const side = await readTtsCacheHit(CACHE, r.sha); assert.ok(side); assert.equal(side!.synthetic, true); assert.equal(side!.text, "In twenty twenty-four the archive spoke."); assert.equal(side!.license, "GPL-3.0-or-later"); assert.equal(side!.disclosure, r.disclosure); const wav = await readFile(r.wav); assert.equal(wav.readUInt32LE(24), 48000); assert.equal(wav.readUInt16LE(22), 1); // Nothing but the pair in the cache: the text file is gone. assert.deepEqual((await readdir(CACHE)).sort(), [`${r.sha}.json`, `${r.sha}.wav`]); // The same words re-wrapped, and the tag where it was: a hit, no engine run. const again = await runJob({ text: "In 2024\n the archive spoke." }); assert.equal(again.status, "done", again.log); assert.equal(again.result.cached, true); assert.equal(again.result.sha, r.sha); assert.equal(again.result.wav, r.wav); assert.equal(again.result.seconds, r.seconds); assert.match(again.log!, /Cached: .* no engine run/); assert.equal(await engineRuns(), 1); // `out` gets a copy, and the result names it. const out = path.join(OUTSIDE, "line.wav"); const copied = await runJob({ text: "In 2024 the archive spoke.", out }); assert.equal(copied.result.cached, true); assert.equal(copied.result.wav, out); assert.deepEqual(await readFile(out), wav); assert.equal(await engineRuns(), 1); // From a file, at another speed: a new synthesis. const file = path.join(OUTSIDE, "script.txt"); await writeFile(file, "In 2024 the archive spoke.\n"); const slower = await runJob({ file, speed: 0.8 }); assert.equal(slower.status, "done", slower.log); assert.equal(slower.result.cached, false); assert.notEqual(slower.result.sha, r.sha); assert.ok(slower.result.seconds > r.seconds, `${slower.result.seconds} vs ${r.seconds}`); assert.equal(await engineRuns(), 2); // Nothing landed in the corpus but the job logs. assert.deepEqual((await readdir(CORPUS)).filter((n) => n !== ".jobs" && n !== "channels"), []); assert.deepEqual(await readdir(path.join(CORPUS, "channels", "chan", "data")), []); }); test("an engine without a sampler: a tuning and reading change nothing, the job is the same cache hit, and the result says why", { skip: SKIP }, async () => { const plain = await runJob({ text: "A tuned line for a formant voice." }); assert.equal(plain.status, "done", plain.log); const runs = await engineRuns(); const tuned = await runJob({ text: "A tuned line for a formant voice.", tuning: { temperature: 0.9 }, reading: 4 }); assert.equal(tuned.status, "done", tuned.log); assert.equal(tuned.result.cached, true); assert.equal(tuned.result.sha, plain.result.sha); assert.match(tuned.result.note, /^eSpeak NG has no sampler or seed: the tuning and reading were ignored/); assert.equal(tuned.result.tuning, undefined); assert.equal(tuned.result.reading, undefined); assert.equal(plain.result.note, undefined); assert.match(tuned.log!, /Note: eSpeak NG has no sampler/); assert.equal(await engineRuns(), runs); }); test("a failing engine fails the job with its words, and leaves no cache entry", async () => { const before = (await readdir(CACHE).catch(() => [] as string[])).sort(); const runs = await engineRuns(); const run = await runJob({ text: "Please explode now." }); assert.equal(run.status, "failed"); assert.match(run.log!, /the espeak-ng synthesis failed: .*engine exploded/); assert.equal(run.result, null); assert.equal(await engineRuns(), runs + 1); assert.deepEqual((await readdir(CACHE).catch(() => [] as string[])).sort(), before); }); // --- Orpheus (T1b): the refusals, the GPU wait, the server, the input ------------ test("Orpheus requests: zac by default, a stock voice, no speed but 1", () => { const tts = { engine: "orpheus", voice: "leah", speed: 1 }; const r = resolveTtsRequest({}, "Back in 2024 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 it ended."); } const k = resolveTtsRequest({ engine: "orpheus" }, "x", { engine: "kokoro", voice: "af_heart", speed: 0.9 }); assert.ok(k.ok && k.value.voice === "zac" && k.value.speed === 1, "Kokoro's speed setting is not Orpheus's"); const cases: [Parameters[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 ", /a tag no engine knows: /], ]; 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" }, GOLDEN_TEXT, SETTINGS_TTS); 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); assert.equal(sha, GOLDEN_SHA_MAIN.orpheus); 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 -- main's input.json, byte for byte. const raw = await readFile(path.join(ROOT, "orpheus-input.json"), "utf8"); assert.equal(raw, GOLDEN_INPUT_MAIN); const input = JSON.parse(raw); assert.equal(input.voice, "zac"); assert.deepEqual(input.chunks.map((c: { text: string }) => c.text), ["One file. No title. ", "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); // The sidecar says what it was made with: the defaults, reading 0. assert.deepEqual( { tuning: side.tuning, reading: side.reading, seedBase: side.seedBase }, { tuning: { temperature: 0.55, top_p: 0.85, top_k: 50, min_p: 0, repeat_penalty: 1.2, takes: 3 }, reading: 0, seedBase: 1234 }, ); }); test("a tuned Orpheus reading: the wrapper gets the tuning and the reading's seed base; the sidecar and the report say so", async () => { const body = parseTtsFileBody({ text: "One line, read warmer.", engine: "orpheus", voice: "leah", tuning: { temperature: 0.8, takes: 2 }, reading: 3 }); assert.ok(body.ok); if (!body.ok) return; const r = resolveTtsRequest(body.value, "One line, read warmer.", SETTINGS_TTS); assert.ok(r.ok); if (!r.ok) return; const servers = { acquire: async () => ({ url: "http://127.0.0.1:8799", release: () => {} }) }; const sha = ttsCacheKey(r.value, DEFAULT_TTS_SETTINGS); const lines: string[] = []; 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: () => false, }); const input = JSON.parse(await readFile(path.join(ROOT, "orpheus-input.json"), "utf8")); assert.equal(input.sampler.temperature, 0.8); assert.equal(input.sampler.top_p, 0.85); assert.equal(input.takes, 2); assert.equal(input.seedBase, 1234 + 3 * 9973); const made = { temperature: 0.8, top_p: 0.85, top_k: 50, min_p: 0, repeat_penalty: 1.2, takes: 2 }; assert.deepEqual({ tuning: side.tuning, reading: side.reading, seedBase: side.seedBase }, { tuning: made, reading: 3, seedBase: 31_153 }); assert.deepEqual(ttsTunedOf(r.value, DEFAULT_TTS_SETTINGS), { tuning: made, reading: 3, seedBase: 31_153 }); // A kokoro request reports nothing of the kind. const k = resolveTtsRequest({ engine: "kokoro", reading: 3 }, "x", SETTINGS_TTS); assert.ok(k.ok && ttsTunedOf(k.value) === null); }); 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"]); });