Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit f58a0826e2481751095a6321d4aa3c88a5cdfe4e
parent cef1b7e007b301f3a27a5f9ece83e5a2816ed2c5
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Mon, 16 Nov 2026 07:48:25 -0500

tts: an Orpheus synthesis takes a tuning and a reading

The tts op (`pnpm ops tts`, POST /api/ops/tts) takes `tuning` (temperature,
top_p, top_k, min_p, repeat_penalty, takes) and `reading` (0-99999; seed
base 1234 + 9973 x reading), range-checked in one shared table
(common/lib/ttsTuning.mjs) and refused in a sentence naming the field.

A tuning whose values all equal the defaults, and reading 0, normalise to
none: the cache key and the wrapper's input.json are main's byte for byte,
pinned against literals captured on main 8f6ac97eb. A non-default value or
reading > 0 is in the key. Every Orpheus result and sidecar gives the
effective tuning, the reading and the seed base. Kokoro and eSpeak NG
ignore both and say so in `note`; their keys are unchanged.

tts_orpheus.py is unchanged but for a selftest case (a reading's seed base
moves every take's seed). COMMANDS.md regenerated.

Co-Authored-By: Claude <noreply@anthropic.com>

Diffstat:
MCOMMANDS.md | 2+-
Mcommon/controller/ttsFile.test.ts | 145+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
Mcommon/controller/ttsFile.ts | 90++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------
Mcommon/lib/ttsApps.test.ts | 64++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/ttsApps.ts | 104++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------
Acommon/lib/ttsTuning.d.mts | 18++++++++++++++++++
Acommon/lib/ttsTuning.mjs | 84+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/ttsTuning.test.ts | 85+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/package.json | 1+
Meditor/CHANGELOG.md | 11+++++++++++
Meditor/app/api/ops/tts/route.ts | 15+++++++++++----
Mscripts/archilyzer-ops.mjs | 15+++++++++++----
Mscripts/tts.mjs | 6++++--
Mscripts/tts_orpheus.py | 11++++++++++-
Mscripts/tts_orpheus.test.mjs | 1+
15 files changed, 613 insertions(+), 39 deletions(-)

diff --git a/COMMANDS.md b/COMMANDS.md @@ -191,7 +191,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `cut-release` | cut-release turns a changelog's \[Unreleased\] into "## \[&lt;version&gt;\] - &lt;date&gt;": {"workspace": "editor" \| "export" \| "all", "version": "X.Y.Z" \| "next" \| "next-minor", "commit": boolean (default false), "date": "YYYY-MM-DD" (default today)}. "all" cuts both with ONE version and commits each ("Release &lt;workspace&gt; &lt;version&gt;") — or neither: every check runs before either file is written. Only an editor built from release 10 or later has the route (an older one answers 404); with no editor running, `archilyzer release cut` does the same locally. | `pnpm ops cut-release --json '{"workspace":"all","version":"next","commit":true}'` | | `amend-release` | amend-release rewrites the LATEST release of one changelog: {"workspace": "editor" \| "export", "release": "&lt;its version, as you saw it&gt;", "version": "patch" \| "minor" \| "major" (a bump of the release BEFORE it) \| "X.Y.Z", "date": "YYYY-MM-DD", "fold": true (the \[Unreleased\] bullets move into it), "commit": boolean (default false)} -- or {"uncut": true} to withdraw it, its bullets back under \[Unreleased\]. An older release is refused. A version change commits as that version's release ("Release editor 0.12.0") with the amend in the body; history is never rewritten. The same amend again changes nothing. With no editor running, `archilyzer release amend` does the same locally. | `pnpm ops amend-release --json '{"workspace":"editor","release":"0.11.1","version":"minor","commit":true}'` | | `transcribe` | transcribe runs ONE local file through a local transcription worker, as a job: {"path": "/abs/file"} (audio or video), "start"/"end" (seconds) for a window, "workerId" (a settings worker id; default: the one auto-transcribe would get), "out" (an absolute path for the result JSON, never inside the corpus). The result is {path, window, worker: {id, appId, model, device}, cues: \[{start, end, text}\], text, ...}, cue times on the file's own clock. "words": true adds words: \[{w, start, end, conf?}\] on the same clock -- from parakeet, which keeps its word timestamps; \[\] from an engine that does not. "whilePaused": true runs it during a pause-all on a worker the pause alone switched off (never one drained, degraded or disabled by hand); the pause stays on. With --wait it is printed on stdout (the response and the log go to stderr), so `pnpm ops transcribe ... --wait \| jq -r .text` works. | `pnpm ops transcribe --json '{"path":"/abs/clip.mp4","start":120,"end":150}' --wait`<br>`pnpm ops transcribe --json '{"path":"/abs/a.wav","workerId":"parakeet-cpu","out":"/tmp/a.json"}' --wait` | -| `tts` | tts speaks a line with a local text-to-speech engine and a STOCK voice, as a job on the `tts` queue: {"text": "..."} or {"file": "/abs/script.txt"} (UTF-8, at most 20,000 characters), "engine" (kokoro \| orpheus \| espeak-ng), "voice" (one of the engine's stock voices; kokoro: af\_heart, bm\_george, ...; orpheus: leah, zac, ...), "speed" (0.5-2; orpheus has none) — defaults from settings.tts (kokoro, af\_heart, 1) — and "out" (an absolute .wav path the result is copied to, never inside the corpus). The expressive tags &lt;laugh&gt; &lt;chuckle&gt; &lt;sigh&gt; &lt;cough&gt; &lt;sniffle&gt; &lt;groan&gt; &lt;yawn&gt; &lt;gasp&gt; are performed by orpheus and stripped for the others; any other &lt;...&gt; is refused. Numbers, years, money and times are spoken (2024: "twenty twenty-four"). The result is {wav, seconds, engine, voice, cached, durationMs, waitedMs, sha, sampleRate, speed, disclosure}: wav is the 48 kHz mono WAV the editor wrote (out, or its cache), disclosure the line a narrated export carries. The same ask again is answered from the cache (cached: true, no engine run). Kokoro and orpheus need `archilyzer tts setup [--engine orpheus]` first; orpheus runs on the GPU (a local llama-server the editor starts and stops) and waits while a transcription holds it. With --wait the result is printed on stdout. | `pnpm ops tts --json '{"text":"In 2024 the archive spoke."}' --wait`<br>`pnpm ops tts --json '{"file":"/abs/script.txt","voice":"bm_george","out":"/abs/line.wav"}' --wait` | +| `tts` | tts speaks a line with a local text-to-speech engine and a STOCK voice, as a job on the `tts` queue: {"text": "..."} or {"file": "/abs/script.txt"} (UTF-8, at most 20,000 characters), "engine" (kokoro \| orpheus \| espeak-ng), "voice" (one of the engine's stock voices; kokoro: af\_heart, bm\_george, ...; orpheus: leah, zac, ...), "speed" (0.5-2; orpheus has none) — defaults from settings.tts (kokoro, af\_heart, 1) — and "out" (an absolute .wav path the result is copied to, never inside the corpus). Orpheus also takes "tuning" ({"temperature": 0.1-1.5, "top\_p": 0.05-1, "top\_k": 0-200, "min\_p": 0-0.5, "repeat\_penalty": 1-2, "takes": 1-6}, any of them; the rest its defaults) and "reading" (0-99999; 0 = the first): the same words read again differently, a new cached file; kokoro and espeak-ng ignore both and say so in the result's "note". The expressive tags &lt;laugh&gt; &lt;chuckle&gt; &lt;sigh&gt; &lt;cough&gt; &lt;sniffle&gt; &lt;groan&gt; &lt;yawn&gt; &lt;gasp&gt; are performed by orpheus and stripped for the others; any other &lt;...&gt; is refused. Numbers, years, money and times are spoken (2024: "twenty twenty-four"). The result is {wav, seconds, engine, voice, cached, durationMs, waitedMs, sha, sampleRate, speed, disclosure} (orpheus: also tuning, reading and seedBase, every value it was made with): wav is the 48 kHz mono WAV the editor wrote (out, or its cache), disclosure the line a narrated export carries. The same ask again is answered from the cache (cached: true, no engine run). Kokoro and orpheus need `archilyzer tts setup [--engine orpheus]` first; orpheus runs on the GPU (a local llama-server the editor starts and stops) and waits while a transcription holds it. With --wait the result is printed on stdout. | `pnpm ops tts --json '{"text":"In 2024 the archive spoke."}' --wait`<br>`pnpm ops tts --json '{"file":"/abs/script.txt","voice":"bm_george","out":"/abs/line.wav"}' --wait`<br>`pnpm ops tts --json '{"text":"Read it again.","engine":"orpheus","reading":1,"tuning":{"temperature":0.7}}' --wait` | | `voice-enhance` | voice-enhance cleans a speech recording up (denoise, soften the room, level it) as a job on the `voice` queue, behind the heavy slot: {"file": "/abs/take.wav", "out": "/abs/clean.wav"} (never inside the corpus; 48 kHz mono, exactly as long as the input), "engine" (deepfilternet \| rnnoise; settings.voice), "params" (the engine's knobs: lufs, highpass, attenLimDb, postFilter, mix), "parts" (\[{file, out}\], a take recorded part by part). deepfilternet needs `archilyzer voice setup --engine deepfilternet`; rnnoise needs nothing. The result is {op, engine, wav, seconds, samples, sampleRate, engineMs, durationMs, waitedMs, gainDb, params, parts?, synthetic}; with --wait it is printed on stdout. | | | `voice-convert` | voice-convert keeps a recording's performance (timing, pitch contour) and swaps its timbre for a STOCK synthetic voice, as voice-enhance's job: the same body plus "voice" — "&lt;tts engine&gt;:&lt;stock voice&gt;" (orpheus:zac, orpheus:leah, kokoro:am\_michael, ...; settings.voice.convert.target); a file, a path or a recording is REFUSED as a target (no real person's voice) — and "engine" (openvoice \| seed-vc, each installed by `archilyzer voice setup --engine <id>`). "pitch" is where the result's pitch comes from (settings.voice.convert.pitch): "target" — the stock voice's own, the read's intonation flattened to it; "source" — the pitch the take was read at (raise your voice and it rises); "contour" — the read's rises and falls, moved as a whole to the stock voice's register. "semitones" (-12 to 12) then moves a followed pitch; left out, a followed pitch takes settings.voice.convert.semitones (0 unless set). source and contour are seed-vc's, on its optional f0 model (`archilyzer voice setup --engine seed-vc --with f0`; slower, 44.1 kHz); openvoice refuses them. The target's reference is synthesized once through the tts op and kept. The result adds target, voice, pitch (semitones and f0 — the medians heard and the move applied — when followed), synthetic: true and the disclosure line. | | | `settings` | settings patches settings.json through the editor's one writer: {"patch": {"&lt;top-level key&gt;": value, …}} (SETTINGS.md). A block's keys merge one level; an array, a scalar or an object nested in a block replaces. Refused before anything is written: an unknown key; a key another writer owns (channelPriority, autoQueue, workers, storage — the refusal names it); a value the schema would not keep as sent (clamped, dropped), named with what would be saved. Answers the saved values. | `pnpm ops settings --json '{"patch":{"diarization":{"cleanAfterCapture":true}}}'`<br>`pnpm ops settings --json '{"patch":{"minFreeDiskGB":20}}'` | diff --git a/common/controller/ttsFile.test.ts b/common/controller/ttsFile.test.ts @@ -83,12 +83,17 @@ const { 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. <sigh>\",\"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" }); @@ -107,7 +112,7 @@ async function engineRuns(): Promise<number> { // --- body ---------------------------------------------------------------------- test("the body keys are the contract", () => { - assert.deepEqual([...TTS_FILE_BODY_KEYS], ["text", "file", "voice", "engine", "speed", "out"]); + assert.deepEqual([...TTS_FILE_BODY_KEYS], ["text", "file", "voice", "engine", "speed", "out", "tuning", "reading"]); }); test("the body's shape is judged before the disk", () => { @@ -122,6 +127,12 @@ test("the body's shape is judged before the disk", () => { [{ 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); @@ -130,6 +141,8 @@ test("the body's shape is judged before the disk", () => { } 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", () => { @@ -174,6 +187,77 @@ test("the cache key follows engine, model, voice, speed and the spoken text", () assert.notEqual(ttsCacheKey({ ...base, engine: getTtsEngine("espeak-ng")! }), sha); }); +// The cache keys of "One file. No title. <sigh>\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. <sigh>\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, unknown> = {}): 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("a tuning or a reading is a new key for Orpheus; the same one again is the same key", () => { + const seen = new Set<string>([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); @@ -291,6 +375,22 @@ test("a synthesis runs the engine once; the same ask again is a cached done job" 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(); @@ -357,9 +457,7 @@ test("a GPU engine waits while a transcription holds the GPU, and can be cancell }); 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, - }); + const r = resolveTtsRequest({ engine: "orpheus", voice: "zac" }, GOLDEN_TEXT, SETTINGS_TTS); assert.ok(r.ok); if (!r.ok) return; const events: string[] = []; @@ -372,6 +470,7 @@ test("an Orpheus synthesis: GPU wait, then its server, then the wrapper with the }; 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, @@ -389,8 +488,10 @@ test("an Orpheus synthesis: GPU wait, then its server, then the wrapper with the 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")); + // 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. <sigh>", "Then in twenty twenty-four, it came back."]); // Disclosed with its attribution; the flagged chunk recorded and logged. @@ -403,6 +504,38 @@ test("an Orpheus synthesis: GPU wait, then its server, then the wrapper with the // 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 () => { diff --git a/common/controller/ttsFile.ts b/common/controller/ttsFile.ts @@ -3,17 +3,22 @@ // narration is never synthesized by hand, the way a quote check is never // transcribed by hand. // -// THE BODY is `{text | file, voice?, engine?, speed?, out?}`: the text itself, +// THE BODY is `{text | file, voice?, engine?, speed?, out?, tuning?, reading?}`: the text itself, // or an absolute path to a UTF-8 text file holding it; an engine and one of its // STOCK voices (ruled: no cloning, no reference audio — a voice is a name from // the registry, never a path), defaulting to settings.tts; a speed in the // engine's range; and `out`, an absolute `.wav` path the result is copied to. +// `tuning` (`{temperature?, top_p?, top_k?, min_p?, repeat_penalty?, takes?}`) +// and `reading` (a whole number, 0 = the first) read the same words again +// differently (lib/ttsTuning.mjs: the ranges); an engine without a sampler +// (kokoro, espeak-ng) ignores them and its result says so in `note`. // Every refusal comes back before a job exists — an unknown engine or voice, a // tag no engine knows (`<lagh>` would be read aloud), an engine that is not // installed, an `out` or a cache dir inside the corpus. // // THE CACHE. sha256 of (engine, model, voice, speed, the NORMALIZED text — the -// engine's own pre-pass, lib/ttsText.ts) names `<dir>/<sha>.wav` (48 kHz mono +// engine's own pre-pass, lib/ttsText.ts — and, for Orpheus, its takes and tag +// check plus any tuning or reading that is not the default) names `<dir>/<sha>.wav` (48 kHz mono // 16-bit) and `<sha>.json`, the sidecar that discloses it (engine, model, // licence, voice, seconds, `synthetic: true`, the disclosure line). A request // whose pair is already there is a `done` job with `cached: true` that runs no @@ -23,7 +28,8 @@ // // THE RESULT is logged as ONE line starting with TTS_RESULT_MARKER: // `{wav, seconds, engine, voice, cached, durationMs, waitedMs, sha, sampleRate, -// speed, disclosure}`. `wav` is an absolute path this editor wrote: `out` when +// speed, disclosure}`, plus for Orpheus `{tuning, reading, seedBase}` (the +// effective values, defaults included) and, when a tuning was ignored, `note`. `wav` is an absolute path this editor wrote: `out` when // given, else the cache file. `durationMs` is the engine's time (0-ish for a // hit); `waitedMs` the wait on the queue. // @@ -44,9 +50,12 @@ import { ttsDisclosure, ttsEngineIds, ttsInstallDir, + type TtsAsk, type TtsEngine, + type TtsTunedReport, } from "../lib/ttsApps"; import { unknownTtsTagsError } from "../lib/ttsText"; +import { parseTtsTuning, ttsReadingError, type TtsTuning } from "../lib/ttsTuning.mjs"; import { ttsInstallState } from "../lib/ttsInstall"; import { DEFAULT_TTS_SETTINGS, @@ -70,7 +79,7 @@ export const TTS_FILE_JOB_KIND = "tts-file"; export const TTS_RESULT_MARKER = "@@tts-result "; // The body `/api/ops/tts` accepts; anything else is a 400. -export const TTS_FILE_BODY_KEYS = ["text", "file", "voice", "engine", "speed", "out"] as const; +export const TTS_FILE_BODY_KEYS = ["text", "file", "voice", "engine", "speed", "out", "tuning", "reading"] as const; // The most text one synthesis takes, in characters (about 25 minutes of // speech). A longer script is several asks — which the cache then serves @@ -92,12 +101,14 @@ export type TtsFileBody = { engine?: string; speed?: number; out?: string; + tuning?: TtsTuning; + reading?: number; }; // The body's shape, judged without touching the disk. Every sentence here is // the refusal an ops caller reads. export function parseTtsFileBody(body: Record<string, unknown>): Check<TtsFileBody> { - const { text, file, voice, engine, speed, out } = body; + const { text, file, voice, engine, speed, out, tuning, reading } = body; if (text !== undefined && file !== undefined) { return { ok: false, error: 'give "text" or "file", not both' }; } @@ -134,6 +145,16 @@ export function parseTtsFileBody(body: Record<string, unknown>): Check<TtsFileBo return { ok: false, error: `"out" must name a .wav file (got "${out}")` }; } } + let tuned: TtsTuning | undefined; + if (tuning !== undefined && tuning !== null) { + const t = parseTtsTuning(tuning); + if (!t.ok) return t; + tuned = t.value; + } + if (reading !== undefined && reading !== null) { + const err = ttsReadingError(reading); + if (err) return { ok: false, error: err }; + } return { ok: true, value: { @@ -143,6 +164,8 @@ export function parseTtsFileBody(body: Record<string, unknown>): Check<TtsFileBo ...(typeof engine === "string" ? { engine: engine.trim() } : {}), ...(typeof speed === "number" ? { speed } : {}), ...(typeof out === "string" ? { out: path.resolve(out) } : {}), + ...(tuned ? { tuning: tuned } : {}), + ...(typeof reading === "number" ? { reading } : {}), }, }; } @@ -159,8 +182,22 @@ export type TtsRequest = { spoken: string; file?: string; out?: string; + // An engine with `tuned` (Orpheus): the tuning and reading as asked (in + // range; the defaults are filled in by the engine). Never set for the rest. + tuning?: TtsTuning; + reading?: number; + // Why a tuning or reading was not used (an engine without a sampler). + note?: string; }; +/** The tuning and reading a request hands its engine. */ +export function ttsAskOf(req: Pick<TtsRequest, "tuning" | "reading">): TtsAsk { + return { + ...(req.tuning ? { tuning: req.tuning } : {}), + ...(req.reading !== undefined ? { reading: req.reading } : {}), + }; +} + // The body plus its text and settings.tts, resolved against the registry. Pure. export function resolveTtsRequest( body: TtsFileBody, @@ -197,6 +234,9 @@ export function resolveTtsRequest( if (tagError) return { ok: false, error: tagError }; const spoken = engine.normalize(text); if (!spoken) return { ok: false, error: "the text has nothing to speak once its tags are removed" }; + // A tuning or reading is an Orpheus knob: another engine reads as it always does, and says so. + const asked = (body.tuning && Object.keys(body.tuning).length > 0) || (body.reading ?? 0) > 0; + const tunable = Boolean(engine.tuned); return { ok: true, value: { @@ -207,6 +247,11 @@ export function resolveTtsRequest( spoken, ...(body.file ? { file: body.file } : {}), ...(body.out ? { out: body.out } : {}), + ...(tunable && body.tuning ? { tuning: body.tuning } : {}), + ...(tunable && body.reading !== undefined ? { reading: body.reading } : {}), + ...(!tunable && asked + ? { note: `${engine.label} has no sampler or seed: the tuning and reading were ignored (it reads the same every time)` } + : {}), }, }; } @@ -214,14 +259,15 @@ export function resolveTtsRequest( /** * 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. + * check, and a tuning or reading only when it is not the default), what else + * changes its output. No tuning and no reading: the key it always had. */ export function ttsCacheKey( - req: Pick<TtsRequest, "engine" | "voice" | "speed" | "spoken">, + req: Pick<TtsRequest, "engine" | "voice" | "speed" | "spoken" | "tuning" | "reading">, 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)); + if (req.engine.keyExtra) key.push(req.engine.keyExtra(tts, ttsAskOf(req))); return createHash("sha256").update(JSON.stringify(key)).digest("hex"); } @@ -334,6 +380,10 @@ export type TtsSidecar = { durationMs: number; // Orpheus: the chunks no take passed the checks for (the kept take named). flagged?: Flagged[]; + // Orpheus: the tuning it was made with (every value), its reading and seed base. + tuning?: TtsTunedReport["tuning"]; + reading?: number; + seedBase?: number; }; export type TtsResult = { @@ -348,8 +398,20 @@ export type TtsResult = { sampleRate: number; speed: number; disclosure: string; + // Orpheus: the EFFECTIVE tuning (defaults included), the reading and the seed + // base it gave -- always, a cache hit too -- so a reading can be made again. + tuning?: TtsTunedReport["tuning"]; + reading?: number; + seedBase?: number; + // Why an asked tuning or reading was not used (kokoro, espeak-ng). + note?: string; }; +/** What a request's engine makes of its tuning and reading, or nothing (an engine without a sampler). */ +export function ttsTunedOf(req: Pick<TtsRequest, "engine" | "tuning" | "reading">, tts: TtsSettings = DEFAULT_TTS_SETTINGS): TtsTunedReport | null { + return req.engine.tuned ? req.engine.tuned(tts, ttsAskOf(req)) : null; +} + export function ttsCachePaths(cacheDir: string, sha: string): { wav: string; json: string } { return { wav: path.join(cacheDir, `${sha}.wav`), json: path.join(cacheDir, `${sha}.json`) }; } @@ -410,7 +472,7 @@ export async function runTtsSynthesis(opts: RunTtsOpts): Promise<TtsSidecar> { const installDir = ttsInstallDir(opts.home, req.engine); await writeFile( textFile, - req.engine.prepareInput ? req.engine.prepareInput(req.spoken, req.voice, tts) : req.spoken, + req.engine.prepareInput ? req.engine.prepareInput(req.spoken, req.voice, tts, ttsAskOf(req)) : req.spoken, "utf8", ); let started = Date.now(); @@ -478,6 +540,7 @@ export async function runTtsSynthesis(opts: RunTtsOpts): Promise<TtsSidecar> { throw new Error(`the ${req.engine.id} synthesis left no audio at ${target.wav}`); } const sampleRate = res.sampleRate ?? TTS_SAMPLE_RATE; + const tuned = ttsTunedOf(req, tts); const sidecar: TtsSidecar = { version: 1, sha, @@ -499,6 +562,7 @@ export async function runTtsSynthesis(opts: RunTtsOpts): Promise<TtsSidecar> { createdAt: new Date().toISOString(), durationMs: Date.now() - started, ...(res.engineStats?.flagged?.length ? { flagged: res.engineStats.flagged } : {}), + ...(tuned ?? {}), }; if (sidecar.flagged) { onLog( @@ -517,7 +581,10 @@ export async function runTtsSynthesis(opts: RunTtsOpts): Promise<TtsSidecar> { function describe(req: TtsRequest): string { const chars = req.spoken.length; - return `${chars} character${chars === 1 ? "" : "s"} with ${req.engine.id} · ${req.voice} at ${req.speed}x`; + const tuned = Object.entries(req.tuning ?? {}).map(([k, v]) => `${k} ${v}`); + if (req.reading) tuned.push(`reading ${req.reading}`); + return `${chars} character${chars === 1 ? "" : "s"} with ${req.engine.id} · ${req.voice} at ${req.speed}x` + + (tuned.length ? ` (${tuned.join(", ")})` : ""); } // --- the job ------------------------------------------------------------------- @@ -557,6 +624,7 @@ export async function enqueueTtsFile( fn: async (onLog, signal) => { const started = Date.now(); onLog(`Speak ${describe(req)}${req.file ? ` from ${req.file}` : ""}`); + if (req.note) onLog(`Note: ${req.note}`); // Again, at the job's turn: a job queued ahead may have made it. let side = hitAtEnqueue ?? (await readTtsCacheHit(cacheDir, sha)); const cached = side !== null; @@ -587,6 +655,8 @@ export async function enqueueTtsFile( sampleRate: side.sampleRate, speed: req.speed, disclosure: side.disclosure, + ...(ttsTunedOf(req, settings.tts) ?? {}), + ...(req.note ? { note: req.note } : {}), }; onLog(`${TTS_RESULT_MARKER}${JSON.stringify(result)}`); }, diff --git a/common/lib/ttsApps.test.ts b/common/lib/ttsApps.test.ts @@ -13,6 +13,8 @@ import { ttsVenvPython, ORPHEUS_FILES, ORPHEUS_SAMPLER, + ORPHEUS_SEED_BASE, + normalizeOrpheusAsk, } from "./ttsApps"; import { DEFAULT_TTS_SETTINGS, sanitizeTts } from "./ttsSettings"; @@ -190,3 +192,65 @@ test("Orpheus's input is the editor's chunks, budgets, sampler and takes; the wr "/c/x.json", ]); }); + +// --- a tuning and a reading (lane orpheus-tuning, S1) ----------------------------- + +// Orpheus's input.json for "One file. No title. <sigh>\n\nThen in 2024, it came back." in zac, captured +// on main 976efc77e BEFORE the tuning existed: an ask without one must give these bytes exactly. +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. <sigh>\",\"ends\":\"paragraph\",\"pauseAfter\":0.4,\"nPredict\":525},{\"text\":\"Then in twenty twenty-four, it came back.\",\"ends\":\"end\",\"pauseAfter\":0,\"nPredict\":525}]}"; + +test("no tuning and no reading: Orpheus's input.json and key are main's, byte for byte -- the defaults spelled out too", () => { + const o = getTtsEngine("orpheus")!; + const spoken = o.normalize("One file. No title. <sigh>\n\nThen in 2024, it came back."); + assert.equal(o.prepareInput!(spoken, "zac", DEFAULT_TTS_SETTINGS), GOLDEN_INPUT_MAIN); + assert.equal(o.prepareInput!(spoken, "zac", DEFAULT_TTS_SETTINGS, {}), GOLDEN_INPUT_MAIN); + const defaults = { + tuning: { temperature: 0.55, top_p: 0.85, top_k: 50, min_p: 0, repeat_penalty: 1.2, takes: 3 }, + reading: 0, + }; + assert.equal(o.prepareInput!(spoken, "zac", DEFAULT_TTS_SETTINGS, defaults), GOLDEN_INPUT_MAIN); + assert.deepEqual(normalizeOrpheusAsk(DEFAULT_TTS_SETTINGS, defaults), {}); + for (const ask of [undefined, {}, defaults]) { + assert.deepEqual(o.keyExtra!(DEFAULT_TTS_SETTINGS, ask), { takes: 3, tagCheck: false }, JSON.stringify(ask)); + } + // The report: every value, the defaults included. + assert.deepEqual(o.tuned!(DEFAULT_TTS_SETTINGS), { + 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 tuning changes only what it names; a reading moves the seed base by 9973", () => { + const o = getTtsEngine("orpheus")!; + const spoken = o.normalize("One line."); + const input = JSON.parse(o.prepareInput!(spoken, "leah", DEFAULT_TTS_SETTINGS, { tuning: { temperature: 0.7, top_k: 40, takes: 5 }, reading: 2 })); + assert.deepEqual(input.sampler, { ...ORPHEUS_SAMPLER, temperature: 0.7, top_k: 40 }); + // The sampler's keys keep the constant's order. + assert.deepEqual(Object.keys(input.sampler), Object.keys(ORPHEUS_SAMPLER)); + assert.equal(input.seedBase, ORPHEUS_SEED_BASE + 2 * 9973); + assert.equal(input.takes, 5); + assert.equal(input.tagCheck, false); + assert.deepEqual( + o.keyExtra!(DEFAULT_TTS_SETTINGS, { tuning: { temperature: 0.7, top_k: 40, takes: 5, min_p: 0 }, reading: 2 }), + { takes: 5, tagCheck: false, sampler: { temperature: 0.7, top_k: 40 }, reading: 2 }, + ); + assert.deepEqual(o.tuned!(DEFAULT_TTS_SETTINGS, { tuning: { repeat_penalty: 1.1 }, reading: 1 }), { + tuning: { temperature: 0.55, top_p: 0.85, top_k: 50, min_p: 0, repeat_penalty: 1.1, takes: 3 }, + reading: 1, + seedBase: 11_207, + }); + // A tuning's takes equal to the SETTINGS' (not the default's) is no tuning: the key it would have anyway. + const five = sanitizeTts({ engine: "orpheus", orpheus: { takes: 5 } }); + assert.deepEqual(normalizeOrpheusAsk(five, { tuning: { takes: 5 } }), {}); + assert.deepEqual(o.keyExtra!(five, { tuning: { takes: 3 } }), o.keyExtra!(DEFAULT_TTS_SETTINGS)); +}); + +test("kokoro and espeak-ng take no tuning: no key extra, no report", () => { + for (const id of ["kokoro", "espeak-ng"]) { + const e = getTtsEngine(id)!; + assert.equal(e.tuned, undefined, id); + assert.equal(e.keyExtra, undefined, id); + } +}); diff --git a/common/lib/ttsApps.ts b/common/lib/ttsApps.ts @@ -36,9 +36,20 @@ import path from "node:path"; import { normalizeTtsText } from "./ttsText"; import { chunkTtsText, nPredictFor } from "./ttsChunk"; import type { TtsSettings } from "./ttsSettings"; +import { ttsReadingSeedBase, type TtsTuning } from "./ttsTuning.mjs"; export type TtsDevice = "cpu" | "gpu"; +// What one synthesis asks beyond its words and voice (lib/ttsTuning.mjs): a +// tuning and a reading, both already range-checked. Only an engine with +// `tuned` takes them; for the rest they are ignored, and the result says so. +export type TtsAsk = { tuning?: TtsTuning; reading?: number }; + +// The tuning a synthesis was made with, EFFECTIVE (every field, defaults +// included), its reading and the seed base it gave: in the result and the +// sidecar, so a reading can be made again exactly. +export type TtsTunedReport = { tuning: Required<TtsTuning>; reading: number; seedBase: number }; + // A file `archilyzer tts setup` downloads once, verified by size and sha256. export type TtsModelFile = { name: string; @@ -114,10 +125,16 @@ export type TtsEngine = { 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; + // itself (Orpheus: its chunks, budgets, sampler and takes, as JSON). `ask`: + // the tuning and reading, for an engine with `tuned`. + prepareInput?: (spoken: string, voice: string, tts: TtsSettings, ask?: TtsAsk) => string; + // Settings that change the output, beside the model: in the cache key. A + // tuning or reading only when it is not the default, so an ask without one + // keys as it always did. + keyExtra?: (tts: TtsSettings, ask?: TtsAsk) => unknown; + // An engine that takes a tuning and a reading (Orpheus): what one ask comes + // to, every value filled in. Absent: the engine ignores them. + tuned?: (tts: TtsSettings, ask?: TtsAsk) => TtsTunedReport; // A `runtime: "server"` engine's server. serverCommand?: (installDir: string, tts: TtsSettings) => TtsServerCommand; // Binaries outside the install dir it needs (checked with the install). @@ -225,6 +242,44 @@ export const ORPHEUS_SAMPLER = { } as const; export const ORPHEUS_SEED_BASE = 1234; +// The sampler knobs a tuning may set (lib/ttsTuning.mjs); repeat_last_n and the +// presence / frequency penalties stay as above. +const ORPHEUS_TUNED_SAMPLER = ["temperature", "top_p", "top_k", "min_p", "repeat_penalty"] as const; + +/** + * An Orpheus ask with every value that EQUALS its default left out (the + * sampler's against ORPHEUS_SAMPLER, takes against settings.tts.orpheus.takes) + * and reading 0 dropped: `{}` is "no tuning". What the cache key holds. + */ +export function normalizeOrpheusAsk(tts: TtsSettings, ask: TtsAsk = {}): TtsAsk { + const tuning: TtsTuning = {}; + for (const k of ORPHEUS_TUNED_SAMPLER) { + const v = ask.tuning?.[k]; + if (v !== undefined && v !== ORPHEUS_SAMPLER[k]) tuning[k] = v; + } + const takes = ask.tuning?.takes; + if (takes !== undefined && takes !== tts.orpheus.takes) tuning.takes = takes; + return { + ...(Object.keys(tuning).length ? { tuning } : {}), + ...(ask.reading ? { reading: ask.reading } : {}), + }; +} + +/** What an Orpheus ask comes to: the sampler sent, the takes, the reading and its seed base. */ +export function orpheusEffective(tts: TtsSettings, ask: TtsAsk = {}) { + const n = normalizeOrpheusAsk(tts, ask); + const { takes, ...samplerDiff } = n.tuning ?? {}; + // Spread over the constant: its keys keep their order, so no ask serializes as it always did. + const sampler = { ...ORPHEUS_SAMPLER, ...samplerDiff }; + const reading = n.reading ?? 0; + return { + sampler, + takes: takes ?? tts.orpheus.takes, + reading, + seedBase: ttsReadingSeedBase(ORPHEUS_SEED_BASE, reading), + }; +} + export const ORPHEUS_FILES: readonly TtsModelFile[] = [ { name: "orpheus-3b-0.1-ft-Q8_0.gguf", @@ -265,17 +320,44 @@ const orpheus: TtsEngine = { importName: "onnxruntime", files: ORPHEUS_FILES, }, - prepareInput: (spoken, voice, tts) => - JSON.stringify({ + prepareInput: (spoken, voice, tts, ask) => { + const e = orpheusEffective(tts, ask); + return JSON.stringify({ version: 1, voice, - sampler: ORPHEUS_SAMPLER, - seedBase: ORPHEUS_SEED_BASE, - takes: tts.orpheus.takes, + sampler: e.sampler, + seedBase: e.seedBase, + takes: e.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 }), + }); + }, + // No tuning and no reading: `{takes, tagCheck}`, the key it always had. + keyExtra: (tts, ask) => { + const n = normalizeOrpheusAsk(tts, ask); + const { takes, ...sampler } = n.tuning ?? {}; + return { + takes: takes ?? tts.orpheus.takes, + tagCheck: tts.orpheus.tagCheck, + ...(Object.keys(sampler).length ? { sampler } : {}), + ...(n.reading ? { reading: n.reading } : {}), + }; + }, + tuned: (tts, ask) => { + const e = orpheusEffective(tts, ask); + return { + tuning: { + temperature: e.sampler.temperature, + top_p: e.sampler.top_p, + top_k: e.sampler.top_k, + min_p: e.sampler.min_p, + repeat_penalty: e.sampler.repeat_penalty, + takes: e.takes, + }, + reading: e.reading, + seedBase: e.seedBase, + }; + }, serverCommand: (installDir, tts) => { const o = tts.orpheus; const env: Record<string, string> = {}; diff --git a/common/lib/ttsTuning.d.mts b/common/lib/ttsTuning.d.mts @@ -0,0 +1,18 @@ +// Types for ./ttsTuning.mjs (lane orpheus-tuning): an Orpheus tuning, a reading, and their ranges. + +export type TtsTuningField = "temperature" | "top_p" | "top_k" | "min_p" | "repeat_penalty" | "takes"; +export type TtsTuning = Partial<Record<TtsTuningField, number>>; +export type TtsTuningRange = { min: number; max: number; integer: boolean }; + +export const TTS_TUNING_RANGES: Readonly<Record<TtsTuningField, TtsTuningRange>>; +export const TTS_TUNING_FIELDS: readonly TtsTuningField[]; +export const TTS_READING_MAX: number; +export const TTS_READING_SEED_STEP: number; +export function ttsTuningRangeText(field: TtsTuningField): string; +export function ttsTuningValueError(field: TtsTuningField, value: unknown, name?: string): string | null; +export function parseTtsTuning( + raw: unknown, + opts?: { name?: string }, +): { ok: true; value: TtsTuning } | { ok: false; error: string }; +export function ttsReadingError(value: unknown, name?: string): string | null; +export function ttsReadingSeedBase(base: number, reading?: number): number; diff --git a/common/lib/ttsTuning.mjs b/common/lib/ttsTuning.mjs @@ -0,0 +1,84 @@ +// AN ORPHEUS TUNING AND A READING (lane orpheus-tuning, S1 of the re-tune +// plan): the knobs a synthesis may carry so the same words are read again +// differently, and their ranges. Shared by the editor's tts op +// (controller/ttsFile.ts, lib/ttsApps.ts) and umtool (its post bench, its CLI, +// a card's narration), so a value is refused in the same words everywhere. +// +// tuning: { temperature?, top_p?, top_k?, min_p?, repeat_penalty?, takes? } +// -- the sampler's knobs (llama-server's names) and the takes a chunk +// gets; a missing one is the default (ttsApps.ts ORPHEUS_SAMPLER, the +// settings' tts.orpheus.takes). +// reading: a whole number, 0 = today's seeds; reading r reads with the seed +// base ORPHEUS_SEED_BASE + 9973 x r ("another reading" = r + 1). +// +// Pure: no I/O, no defaults (those are the engine's). + +/** Each field's range: [lowest, highest], and whether it is a whole number. */ +export const TTS_TUNING_RANGES = Object.freeze({ + // At or below 0 llama.cpp samples greedily, and the seed would mean nothing. + temperature: Object.freeze({ min: 0.1, max: 1.5, integer: false }), + top_p: Object.freeze({ min: 0.05, max: 1, integer: false }), + // 0 switches top-k off. + top_k: Object.freeze({ min: 0, max: 200, integer: true }), + // 0 switches min-p off. + min_p: Object.freeze({ min: 0, max: 0.5, integer: false }), + // Below 1 a repeat would be rewarded. + repeat_penalty: Object.freeze({ min: 1, max: 2, integer: false }), + // tts.orpheus.takes' own range (ttsSettings.ts). + takes: Object.freeze({ min: 1, max: 6, integer: true }), +}); + +export const TTS_TUNING_FIELDS = Object.freeze(Object.keys(TTS_TUNING_RANGES)); + +/** The highest reading (the seed base stays under 2^31). */ +export const TTS_READING_MAX = 99_999; + +/** The step between two readings' seed bases: a prime well past one reading's own seeds (101 x takes + chunks). */ +export const TTS_READING_SEED_STEP = 9973; + +const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v); +const shown = (v) => (typeof v === "number" ? String(v) : JSON.stringify(v) ?? String(v)); + +/** "a number from 0.1 to 1.5" / "a whole number from 1 to 6". */ +export function ttsTuningRangeText(field) { + const r = TTS_TUNING_RANGES[field]; + return `${r.integer ? "a whole number" : "a number"} from ${r.min} to ${r.max}`; +} + +/** The refusal for one field's value, or null. `name` is how the caller names it ("tuning.top_p", "--top-p"). */ +export function ttsTuningValueError(field, value, name = `"tuning.${field}"`) { + const r = TTS_TUNING_RANGES[field]; + const ok = typeof value === "number" && Number.isFinite(value) && value >= r.min && value <= r.max && (!r.integer || Number.isInteger(value)); + return ok ? null : `${name} must be ${ttsTuningRangeText(field)} (got ${shown(value)})`; +} + +/** + * A tuning as asked: an object of the known fields, each in range. Undefined + * and null fields are left out; an empty result is `{}`. + * @returns {{ ok: true, value: Record<string, number> } | { ok: false, error: string }} + */ +export function parseTtsTuning(raw, { name = "tuning" } = {}) { + if (!isObj(raw)) return { ok: false, error: `"${name}" must be an object of ${TTS_TUNING_FIELDS.join(", ")}` }; + const value = {}; + for (const [k, v] of Object.entries(raw)) { + if (!Object.hasOwn(TTS_TUNING_RANGES, k)) { + return { ok: false, error: `"${name}.${k}" is not a tuning field (${TTS_TUNING_FIELDS.join(", ")})` }; + } + if (v === undefined || v === null) continue; + const err = ttsTuningValueError(k, v, `"${name}.${k}"`); + if (err) return { ok: false, error: err }; + value[k] = v; + } + return { ok: true, value }; +} + +/** The refusal for a reading, or null. */ +export function ttsReadingError(value, name = '"reading"') { + const ok = typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= TTS_READING_MAX; + return ok ? null : `${name} must be a whole number from 0 to ${TTS_READING_MAX} (0 = the first reading; got ${shown(value)})`; +} + +/** A reading's seed base: `base + 9973 x reading`. */ +export function ttsReadingSeedBase(base, reading = 0) { + return base + TTS_READING_SEED_STEP * (reading || 0); +} diff --git a/common/lib/ttsTuning.test.ts b/common/lib/ttsTuning.test.ts @@ -0,0 +1,85 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; + +// Run with: +// pnpm --filter yt-dlp-transcript-common exec tsx --test lib/ttsTuning.test.ts +// +// An Orpheus tuning and a reading (lane orpheus-tuning, S1): every field's +// range, at its edges and past them, refused in a sentence naming the field. + +import { + TTS_READING_MAX, + TTS_TUNING_FIELDS, + TTS_TUNING_RANGES, + parseTtsTuning, + ttsReadingError, + ttsReadingSeedBase, + ttsTuningValueError, +} from "./ttsTuning.mjs"; + +test("the fields and their ranges", () => { + assert.deepEqual([...TTS_TUNING_FIELDS], ["temperature", "top_p", "top_k", "min_p", "repeat_penalty", "takes"]); + assert.deepEqual( + Object.fromEntries(Object.entries(TTS_TUNING_RANGES).map(([k, r]) => [k, [r.min, r.max, r.integer]])), + { + temperature: [0.1, 1.5, false], + top_p: [0.05, 1, false], + top_k: [0, 200, true], + min_p: [0, 0.5, false], + repeat_penalty: [1, 2, false], + takes: [1, 6, true], + }, + ); + assert.equal(TTS_READING_MAX, 99_999); +}); + +test("each field is taken at its edges and refused past them, naming the field and its range", () => { + for (const f of TTS_TUNING_FIELDS) { + const r = TTS_TUNING_RANGES[f]; + assert.equal(ttsTuningValueError(f, r.min), null, `${f} ${r.min}`); + assert.equal(ttsTuningValueError(f, r.max), null, `${f} ${r.max}`); + const low = parseTtsTuning({ [f]: r.min - (r.integer ? 1 : 0.01) }); + assert.ok(!low.ok, f); + if (!low.ok) { + assert.match(low.error, new RegExp(`^"tuning\\.${f}" must be a (whole )?number from ${r.min} to ${r.max} \\(got `), low.error); + } + const high = parseTtsTuning({ [f]: r.max + 1 }); + assert.ok(!high.ok, f); + } + assert.equal( + ttsTuningValueError("temperature", 3), + '"tuning.temperature" must be a number from 0.1 to 1.5 (got 3)', + ); + assert.equal(ttsTuningValueError("takes", 2.5), '"tuning.takes" must be a whole number from 1 to 6 (got 2.5)'); + assert.equal(ttsTuningValueError("top_k", "50"), '"tuning.top_k" must be a whole number from 0 to 200 (got "50")'); + assert.equal(ttsTuningValueError("top_p", Number.NaN, "--top-p"), "--top-p must be a number from 0.05 to 1 (got NaN)"); +}); + +test("a tuning: an object of the known fields; nulls left out; anything else refused", () => { + assert.deepEqual(parseTtsTuning({ temperature: 0.7, top_k: 40, min_p: null }), { ok: true, value: { temperature: 0.7, top_k: 40 } }); + assert.deepEqual(parseTtsTuning({}), { ok: true, value: {} }); + for (const [raw, re] of [ + [[], /"tuning" must be an object of temperature, top_p, top_k, min_p, repeat_penalty, takes/], + ["warm", /"tuning" must be an object/], + [{ seed: 4 }, /"tuning\.seed" is not a tuning field \(temperature, top_p/], + [{ repeat_last_n: 64 }, /"tuning\.repeat_last_n" is not a tuning field/], + ] as const) { + const r = parseTtsTuning(raw); + assert.ok(!r.ok, JSON.stringify(raw)); + if (!r.ok) assert.match(r.error, re); + } +}); + +test("a reading: a whole number from 0 to 99999; its seed base steps by 9973", () => { + for (const ok of [0, 1, 99_999]) assert.equal(ttsReadingError(ok), null, String(ok)); + for (const bad of [-1, 1.5, 100_000, "2", null]) { + assert.match(ttsReadingError(bad) ?? "", /^"reading" must be a whole number from 0 to 99999 \(0 = the first reading; got /, String(bad)); + } + assert.match(ttsReadingError(-1, "--reading") ?? "", /^--reading must be/); + assert.equal(ttsReadingSeedBase(1234), 1234); + assert.equal(ttsReadingSeedBase(1234, 0), 1234); + assert.equal(ttsReadingSeedBase(1234, 1), 11_207); + assert.equal(ttsReadingSeedBase(1234, 2), 21_180); + // The highest one's seeds stay a signed 32-bit integer (llama-server's seed). + assert.ok(ttsReadingSeedBase(1234, TTS_READING_MAX) + 101 * 6 + 5000 < 2 ** 31); +}); diff --git a/common/package.json b/common/package.json @@ -48,6 +48,7 @@ "./lib/recordingClock.mjs": "./lib/recordingClock.mjs", "./lib/recordingClock-read.mjs": "./lib/recordingClock-read.mjs", "./lib/jitter.mjs": "./lib/jitter.mjs", + "./lib/ttsTuning.mjs": "./lib/ttsTuning.mjs", "./lib/montage/cueTextCache.mjs": "./lib/montage/cueTextCache.mjs", "./lib/montage/phraseScan.mjs": "./lib/montage/phraseScan.mjs", "./lib/montage/phraseSource.mjs": "./lib/montage/phraseSource.mjs", diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,17 @@ # Changelog ## [Unreleased] +- **An Orpheus line can be read again differently: the tts op takes a `tuning` and a `reading`.** `pnpm ops tts` + (`POST /api/ops/tts`) takes `tuning` (any of temperature 0.1–1.5, top_p 0.05–1, top_k 0–200, min_p 0–0.5, + repeat_penalty 1–2, takes 1–6) and `reading` (0–99,999; reading r reads with seed base 1234 + 9973 × r). A value out + of range is refused, in a sentence naming the field and its range. + - Each new tuning or reading makes a new cached file. Asking for the same one again is still a cache hit. + - Without a tuning, the cache key, the engine's input and so the audio are exactly what they were. That also holds + when every value equals its default, or the reading is 0. Every existing cached line is still a hit. + - Every Orpheus result, cached or not, gives the `tuning` it was made with (every value, the defaults included), + the `reading` and the `seedBase`. The cache sidecar records them too, so a reading can be made again exactly. + - Kokoro and eSpeak NG ignore a tuning and a reading. Their result says so in `note`; their cached files are + unchanged. - **A tag can be offered under the site's More filters, per site or for the whole corpus.** A site's Tags tab (Sites → a site → Tags) replaces Visibility with **Placement**: Inherit, Main row, More filters, Hidden. Main row and More filters both override a tag the corpus hides, which "Shown here" said it did but never saved. On /tags, a definition's **More filters** box sets the corpus default. The CLI twin is a new `tags` op, `present`: `pnpm ops tags --json '{"op":"present","site":"<site>","tag":{"id":"<tag>","secondary":true}}'` changes one row of `sites/<site>/tags.json`, keeping its other rows and fields; `null` clears a field so the site inherits it again. It is refused, with nothing written, for an unknown site, a tag the corpus does not define, or a field a site cannot set (rules, sites). Needs a rebuild and deploy of the site. - **umtool: a `take --priority` or `render-mode on -- …` signalled while it turns render mode on lets it go before it exits.** The signal handlers used to go on only after the claim (the state file and the editor's lanes, held over HTTP), so a diff --git a/editor/app/api/ops/tts/route.ts b/editor/app/api/ops/tts/route.ts @@ -7,7 +7,7 @@ import { jobResponse, ops } from "../_lib"; export const dynamic = "force-dynamic"; -// POST { text | file, voice?, engine?, speed?, out? } -> { ok: true, jobId } +// POST { text | file, voice?, engine?, speed?, out?, tuning?, reading? } -> { ok: true, jobId } // // Speak a line with a local text-to-speech engine and a STOCK voice, as a job on // /jobs (`tts-file`, the `tts` queue, one synthesis at a time) — narration is @@ -16,7 +16,12 @@ export const dynamic = "force-dynamic"; // (`kokoro` | `orpheus` | `espeak-ng`), `voice` (one of the engine's stock // voices; Orpheus: zac by default, leah the female option) and `speed` (0.5-2; // Orpheus has none) default to settings.tts (kokoro · af_heart · 1); `out` is -// an absolute .wav path the result is copied to. The expressive tags +// an absolute .wav path the result is copied to. `tuning` ({temperature 0.1-1.5, +// top_p 0.05-1, top_k 0-200, min_p 0-0.5, repeat_penalty 1-2, takes 1-6}, any +// of them; the rest stay Orpheus's defaults) and `reading` (a whole number +// 0-99999; 0 = the first) read the same words again differently, as a new +// cached file; kokoro and espeak-ng ignore both and say so in the result's +// `note` (common/lib/ttsTuning.mjs). The expressive tags // (`<laugh>`, `<sigh>`, ... lib/ttsText.ts TTS_EXPRESSIVE_TAGS) are performed by // Orpheus and stripped for the others; any other `<...>` is refused. Orpheus // runs on the GPU, on a llama-server the editor starts for the batch and stops @@ -24,7 +29,9 @@ export const dynamic = "force-dynamic"; // // The job's log ends with the result as ONE line, `@@tts-result {json}`: // `{wav, seconds, engine, voice, cached, durationMs (the engine's time), waitedMs -// (the wait on the queue), sha, sampleRate, speed, disclosure}`. `wav` is an +// (the wait on the queue), sha, sampleRate, speed, disclosure}`, plus for +// Orpheus `{tuning, reading, seedBase}` -- every value it was made with, the +// defaults included -- and `note` when a tuning was ignored. `wav` is an // absolute path this editor wrote: `out` when given, else the cache file // (`<settings.tts.dir>/<sha>.wav`, 48 kHz mono 16-bit, a `<sha>.json` sidecar // beside it). The same ask again is a `done` job with `cached: true` that runs @@ -32,7 +39,7 @@ export const dynamic = "force-dynamic"; // // AN ADAPTER: every refusal is the controller's (controller/ttsFile.ts) — both // or neither of text and file, an unknown engine or voice, a speed out of -// range, an unknown tag, an engine not installed (`archilyzer tts setup`), an +// range, a tuning value or reading out of its range, an unknown tag, an engine not installed (`archilyzer tts setup`), an // `out` or a cache dir inside the corpus. export async function POST(request: Request) { return ops(request, TTS_FILE_BODY_KEYS, async (body) => diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -151,6 +151,7 @@ // pnpm ops transcribe --json '{"path":"/abs/a.wav","workerId":"parakeet-cpu","out":"/tmp/a.json"}' --wait // pnpm ops tts --json '{"text":"In 2024 the archive spoke."}' --wait // pnpm ops tts --json '{"file":"/abs/script.txt","voice":"bm_george","out":"/abs/line.wav"}' --wait +// pnpm ops tts --json '{"text":"Read it again.","engine":"orpheus","reading":1,"tuning":{"temperature":0.7}}' --wait // pnpm ops web-search --json '{"query":"second shop opening","n":5}' // pnpm ops web-fetch --json '{"url":"https://example.com/news/item","maxChars":4000}' // pnpm ops archive-search --json '{"query":"title:(kitchen) AND mediatype:movies","limit":20}' @@ -606,8 +607,8 @@ const ACTIONS = [ // model, as a job. With --wait the result JSON is what stdout carries. "transcribe", // Speak a line with a local text-to-speech engine and a stock voice - // ({text | file, voice?, engine?, speed?, out?}), as a job on the `tts` - // queue; the same ask again is answered from the cache. With --wait the + // ({text | file, voice?, engine?, speed?, out?, tuning?, reading?}), as a + // job on the `tts` queue; the same ask again is answered from the cache. With --wait the // result JSON is what stdout carries. "tts", // Run an engine over a speech RECORDING ({file, out, engine?, params?, @@ -2194,12 +2195,18 @@ export function usage() { " (one of the engine's stock voices; kokoro: af_heart, bm_george, ...; orpheus:", ' leah, zac, ...), "speed" (0.5-2; orpheus has none) — defaults from', ' settings.tts (kokoro, af_heart, 1) — and "out" (an absolute .wav path the', - " result is copied to, never inside the corpus). The expressive tags <laugh>", + " result is copied to, never inside the corpus). Orpheus also takes \"tuning\"", + ' ({"temperature": 0.1-1.5, "top_p": 0.05-1, "top_k": 0-200, "min_p": 0-0.5,', + ' "repeat_penalty": 1-2, "takes": 1-6}, any of them; the rest its defaults) and', + ' "reading" (0-99999; 0 = the first): the same words read again differently,', + " a new cached file; kokoro and espeak-ng ignore both and say so in the result's", + ' "note". The expressive tags <laugh>', " <chuckle> <sigh> <cough> <sniffle> <groan> <yawn> <gasp> are performed by", " orpheus and stripped for the others; any other <...> is refused. Numbers,", ' years, money and times are spoken (2024: "twenty twenty-four"). The result is', " {wav, seconds, engine, voice, cached, durationMs, waitedMs, sha, sampleRate,", - " speed, disclosure}: wav is the 48 kHz mono WAV the editor wrote (out, or its", + " speed, disclosure} (orpheus: also tuning, reading and seedBase, every value it", + " was made with): wav is the 48 kHz mono WAV the editor wrote (out, or its", " cache), disclosure the line a narrated export carries. The same ask again is", " answered from the cache (cached: true, no engine run). Kokoro and orpheus", " need `archilyzer tts setup [--engine orpheus]` first; orpheus runs on the GPU", diff --git a/scripts/tts.mjs b/scripts/tts.mjs @@ -15,8 +15,10 @@ // 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. +// chunks, sampler, seed base and takes (common/lib/ttsApps.ts +// prepareInput: a synthesis's tuning and reading are already in +// it, so this passes it through untouched); the voice is in it. +// 24 kHz native. // // WHAT IT WRITES is always the same shape whatever the engine: a 48 kHz mono // 16-bit PCM WAV with a bare 44-byte header (ffmpeg, bit-exact, no metadata), diff --git a/scripts/tts_orpheus.py b/scripts/tts_orpheus.py @@ -28,7 +28,10 @@ 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"}]}. +"tagCheck", "chunks": [{"text", "ends", "pauseAfter", "nPredict"}]}. The +editor fills the sampler, seedBase and takes from a synthesis's tuning and +reading (common/lib/ttsApps.ts: seedBase = 1234 + 9973 x reading); with none +they are the defaults, exactly as before. 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 @@ -402,6 +405,12 @@ def selftest(): 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})") + # a reading (the editor's seedBase = 1234 + 9973 x reading): every take's seed moves with it + calls.clear() + script = [take(4.6), take(3.0)] + render_chunk(gen, dict(text=one, nPredict=700), 2, 5, "leah", {}, 1234 + 9973, 3, False) + ok(calls == [11209, 11310], f"a reading's seed base moves every take's seed (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), diff --git a/scripts/tts_orpheus.test.mjs b/scripts/tts_orpheus.test.mjs @@ -27,6 +27,7 @@ test("the Orpheus helper's selftest passes", { skip }, () => { "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", + "a reading's seed base moves every take's seed", "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",