Archilyzer · Source

archilyzer

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

commit d0a5dbdaebde2f32a52e7a5ecab9225ee7846a2c
parent 8f6ac97eb4822cabf862de63258340fa0123278a
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Mon, 16 Nov 2026 09:15:45 -0500

Merge lane/orpheus-tuning: an Orpheus reading may be tuned and read again -- a synthesis takes a tuning (temperature, top_p, top_k, min_p, repeat_penalty, takes; range-checked, decimals rounded to three places) and a reading number that moves every seed, both in the cache key and reported on every result, cached or not; pnpm ops tts takes them, a card's narration and a post take record them, umtool posts narrate <p> <item> --take --reading N with the tuning flags makes one, and a cast re-read keeps a take's own; Kokoro and eSpeak NG ignore them and say so; an ask without them, or with only the defaults, is byte-identical to before, cache hits included; the plan for the re-tune work is plans/orpheus-retune.md

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

Diffstat:
MCOMMANDS.md | 2+-
Mcommon/controller/ttsFile.test.ts | 152+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
Mcommon/controller/ttsFile.ts | 98++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----------
Mcommon/lib/ttsApps.test.ts | 72++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/ttsApps.ts | 103++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------
Acommon/lib/ttsTuning.d.mts | 22++++++++++++++++++++++
Acommon/lib/ttsTuning.mjs | 125+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/ttsTuning.test.ts | 117+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/package.json | 1+
Meditor/CHANGELOG.md | 23+++++++++++++++++++++++
Meditor/app/api/ops/tts/route.test.ts | 5++++-
Meditor/app/api/ops/tts/route.ts | 15+++++++++++----
Aplans/orpheus-retune.md | 236+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mscripts/archilyzer-ops.mjs | 15+++++++++++----
Mscripts/tts.mjs | 6++++--
Mscripts/tts_orpheus.py | 11++++++++++-
Mscripts/tts_orpheus.test.mjs | 1+
Mumtool/app/api/report/post-narration/route.ts | 36++++++++++++++++++++++++++++--------
Mumtool/docs/cli.md | 4++--
Mumtool/docs/knobs.md | 1+
Mumtool/docs/report-video.md | 6++++--
Mumtool/e2e/fixtures/editor-stub.mjs | 11+++++++++++
Mumtool/e2e/post-narration.spec.ts | 44++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/cli/groups.mjs | 6++++--
Mumtool/lib/cli/verbs.mjs | 6+++++-
Mumtool/lib/report/cast.test.mjs | 18++++++++++++++++++
Mumtool/lib/report/castProject.mjs | 6++++--
Mumtool/lib/report/postNarration.test.mjs | 77++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mumtool/lib/report/postNarrationCli.mjs | 90+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
Mumtool/lib/report/postsCli.mjs | 2+-
Aumtool/lib/report/readTuning.mjs | 24++++++++++++++++++++++++
Mumtool/report-to-video/narrate-via-editor.mjs | 21++++++++++++++-------
Mumtool/report-to-video/narrate.test.mjs | 32++++++++++++++++++++++++++++++--
Mumtool/report-to-video/narration-store.mjs | 20+++++++++++++++++++-
Mumtool/report-to-video/narration.mjs | 59++++++++++++++++++++++++++++++++++++++++++++++++++++++-----
Mumtool/report-to-video/narration.test.mjs | 36++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/post-narration.mjs | 6+++++-
37 files changed, 1427 insertions(+), 82 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,84 @@ 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("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<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 +382,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 +464,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 +477,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 +495,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 +511,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,19 +3,25 @@ // 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 -// 16-bit) and `<sha>.json`, the sidecar that discloses it (engine, model, -// licence, voice, seconds, `synthetic: true`, the disclosure line). A request +// 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; Orpheus: the tuning, reading and seed base). A request // whose pair is already there is a `done` job with `cached: true` that runs no // engine and waits on no queue. Anything else runs on the `tts` queue, one // synthesis at a time, and checks the cache again when its turn comes (a job @@ -23,8 +29,10 @@ // // 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 -// given, else the cache file. `durationMs` is the engine's time (0-ish for a +// 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. // // WHAT IT TOUCHES: reads `file` (anywhere); writes the cache dir and `out`, @@ -44,9 +52,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 +81,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 +103,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 +147,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 +166,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 +184,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 +236,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 +249,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 +261,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 +382,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 +400,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 +474,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 +542,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 +564,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 +583,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 +626,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 +657,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,8 +13,11 @@ import { ttsVenvPython, ORPHEUS_FILES, ORPHEUS_SAMPLER, + ORPHEUS_SEED_BASE, + normalizeOrpheusAsk, } from "./ttsApps"; import { DEFAULT_TTS_SETTINGS, sanitizeTts } from "./ttsSettings"; +import { ORPHEUS_DEFAULT_TAKES, ORPHEUS_TUNING_DEFAULTS } from "./ttsTuning.mjs"; // Run with: // pnpm --filter yt-dlp-transcript-common exec tsx --test lib/ttsApps.test.ts @@ -190,3 +193,72 @@ 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("the shared defaults (lib/ttsTuning.mjs) are ORPHEUS_SAMPLER's and the settings' takes", () => { + for (const [k, v] of Object.entries(ORPHEUS_TUNING_DEFAULTS)) { + assert.equal(ORPHEUS_SAMPLER[k as keyof typeof ORPHEUS_SAMPLER], v, k); + } + assert.equal(DEFAULT_TTS_SETTINGS.orpheus.takes, ORPHEUS_DEFAULT_TAKES); +}); + +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 { normalizeTtsTuning, 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,43 @@ export const ORPHEUS_SAMPLER = { } as const; export const ORPHEUS_SEED_BASE = 1234; +// The sampler knobs a tuning may set are lib/ttsTuning.mjs's (its +// ORPHEUS_TUNING_DEFAULTS are these values; a test holds them equal); +// repeat_last_n and the presence / frequency penalties stay as above. +// +// NOTE: a change to a value above changes Orpheus's output WITHOUT changing an +// untuned ask's cache key (the key holds only what differs from the defaults): +// bump CACHE_KEY_VERSION (controller/ttsFile.ts) with it. + +/** + * An Orpheus ask with every value that EQUALS its default left out (quantised + * first, lib/ttsTuning.mjs: the sampler's against its defaults, 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 = normalizeTtsTuning(ask.tuning, { takes: tts.orpheus.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 +319,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,22 @@ +// 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 ORPHEUS_TUNING_DEFAULTS: Readonly<Record<Exclude<TtsTuningField, "takes">, number>>; +export const ORPHEUS_DEFAULT_TAKES: number; +export const TTS_READING_MAX: number; +export function quantizeTtsTuningValue(field: TtsTuningField, value: unknown): unknown; +export function normalizeTtsTuning(tuning: unknown, opts?: { takes?: number }): TtsTuning; +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,125 @@ +// 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)); + +/** + * Orpheus's defaults for the tunable fields: common/lib/ttsApps.ts + * ORPHEUS_SAMPLER's (a test holds the two equal) and the settings' default + * takes (ttsSettings.ts DEFAULT_ORPHEUS_TTS_SETTINGS.takes). Here so a caller in + * bare node (umtool) normalises a tuning as the editor does. + */ +export const ORPHEUS_TUNING_DEFAULTS = Object.freeze({ temperature: 0.55, top_p: 0.85, top_k: 50, min_p: 0, repeat_penalty: 1.2 }); +export const ORPHEUS_DEFAULT_TAKES = 3; + +/** 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)); + +/** + * One field's value as it is checked, sent and keyed: a decimal field rounded + * to 3 places (0.550000001 is 0.55, 0.7000000000000001 is 0.7), -0 as 0. A + * value that is not a finite number is returned as it is (and refused). + */ +export function quantizeTtsTuningValue(field, value) { + if (typeof value !== "number" || !Number.isFinite(value)) return value; + const r = TTS_TUNING_RANGES[field]; + const q = r && !r.integer ? Math.round(value * 1000) / 1000 : value; + return q === 0 ? 0 : q; +} + +/** + * A tuning with every value that EQUALS its default left out (after + * quantising): the sampler's against ORPHEUS_TUNING_DEFAULTS, `takes` against + * `opts.takes` (the settings' takes; omitted: `takes` is kept as given). `{}` is + * "no tuning". Unknown and non-numeric fields are dropped. + */ +export function normalizeTtsTuning(tuning, { takes } = {}) { + const out = {}; + if (!isObj(tuning)) return out; + for (const k of TTS_TUNING_FIELDS) { + const v = quantizeTtsTuningValue(k, tuning[k]); + if (typeof v !== "number" || !Number.isFinite(v)) continue; + if (k === "takes" ? takes !== undefined && v === takes : v === ORPHEUS_TUNING_DEFAULTS[k]) continue; + out[k] = v; + } + return out; +} + +/** "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 quantised + * (quantizeTtsTuningValue) and then 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 q = quantizeTtsTuningValue(k, v); + const err = ttsTuningValueError(k, q, `"${name}.${k}"`); + if (err) return { ok: false, error: err }; + value[k] = q; + } + 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,117 @@ +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 { + ORPHEUS_DEFAULT_TAKES, + ORPHEUS_TUNING_DEFAULTS, + TTS_READING_MAX, + TTS_TUNING_FIELDS, + TTS_TUNING_RANGES, + normalizeTtsTuning, + parseTtsTuning, + quantizeTtsTuningValue, + 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); +}); + +test("decimals are quantised to 3 places before the range check, and -0 is 0", () => { + assert.equal(quantizeTtsTuningValue("temperature", 0.550000001), 0.55); + assert.equal(quantizeTtsTuningValue("temperature", 0.7000000000000001), 0.7); + assert.equal(quantizeTtsTuningValue("top_p", 0.12345), 0.123); + assert.ok(Object.is(quantizeTtsTuningValue("min_p", -0), 0)); + assert.ok(Object.is(quantizeTtsTuningValue("top_k", -0), 0)); + assert.equal(quantizeTtsTuningValue("repeat_penalty", 1.0004), 1); + // Whole-number fields are not rounded (2.5 is still refused). + assert.equal(quantizeTtsTuningValue("takes", 2.5), 2.5); + assert.deepEqual(parseTtsTuning({ temperature: 0.7000000000000001, min_p: -0 }), { ok: true, value: { temperature: 0.7, min_p: 0 } }); + assert.ok(Object.is((parseTtsTuning({ min_p: -0 }) as { value: { min_p: number } }).value.min_p, 0)); + // Rounded first, then checked: 1.5004 is 1.5, in range; 1.5006 is 1.501, out. + assert.deepEqual(parseTtsTuning({ temperature: 1.5004 }), { ok: true, value: { temperature: 1.5 } }); + assert.ok(!parseTtsTuning({ temperature: 1.5006 }).ok); +}); + +test("the normaliser drops what equals its default, quantised; takes only against the takes it is given", () => { + assert.deepEqual(ORPHEUS_TUNING_DEFAULTS, { temperature: 0.55, top_p: 0.85, top_k: 50, min_p: 0, repeat_penalty: 1.2 }); + assert.equal(ORPHEUS_DEFAULT_TAKES, 3); + assert.deepEqual(normalizeTtsTuning({ temperature: 0.550000001, top_p: 0.85, min_p: -0, top_k: 50, repeat_penalty: 1.2 }), {}); + assert.deepEqual(normalizeTtsTuning({ temperature: 0.7000000000000001, takes: 3 }), { temperature: 0.7, takes: 3 }); + assert.deepEqual(normalizeTtsTuning({ temperature: 0.7, takes: 3 }, { takes: 3 }), { temperature: 0.7 }); + assert.deepEqual(normalizeTtsTuning({ takes: 3 }, { takes: 5 }), { takes: 3 }); + // In the registry's order, whatever order it was written in; unknown fields gone. + assert.deepEqual(Object.keys(normalizeTtsTuning({ top_k: 40, temperature: 0.7, seed: 4 })), ["temperature", "top_k"]); + assert.deepEqual(normalizeTtsTuning(null), {}); +}); 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,29 @@ # 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. + - Decimal values are rounded to 3 places before they are checked and keyed, so 0.550000001 is the default and + 0.7000000000000001 is 0.7. +- **umtool: a post take can be another reading, tuned, and records how it was made.** Use `umtool posts narrate <p> <item> --take --reading N`, + plus any of `--temperature` `--top-p` `--top-k` `--min-p` `--repeat-penalty` `--chunk-takes`. The post bench's + `op: "take"` takes `tuning` and `reading` too. A value out of range is refused in the flag's words. + - Every take records the editor's `tuning` (every value) and its `reading`, so it can be made again exactly or its + numbers copied into a character. A derived take keeps its source's. + - A cast voice change's re-read (`umtool cast reread`) asks the picked take's own reading and non-default tuning + again, as it does its own speed. + - A card's narration may carry `tuning` and `reading`. A card without them is asked, keyed and kept as before. + - These flags work only on one item's `--take`, not with `--thread` or `--all --take`. Only the spoken read changes: + no card's text changes. - **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.test.ts b/editor/app/api/ops/tts/route.test.ts @@ -57,7 +57,7 @@ test("a wrong token is a 401", async () => { test("an unknown key is a 400 naming the accepted ones", async () => { const { status, json } = await post({ text: "hi", reference: "/voice.wav" }); assert.equal(status, 400); - assert.match(json.error!, /unknown key\(s\): reference — this route accepts text, file, voice, engine, speed, out/); + assert.match(json.error!, /unknown key\(s\): reference — this route accepts text, file, voice, engine, speed, out, tuning, reading/); }); test("the controller's refusals come back as 400s", async () => { @@ -73,6 +73,9 @@ test("the controller's refusals come back as 400s", async () => { [{ text: "hi", engine: "kokoro" }, /Kokoro-82M is not installed .* run `archilyzer tts setup`/], [{ text: "hi", out: path.join(CORPUS, "a.wav") }, /inside the corpus/], [{ text: "hi", out: path.join(ROOT, "a.mp3") }, /must name a \.wav file/], + [{ text: "hi", tuning: { top_p: 2 } }, /^"tuning\.top_p" must be a number from 0\.05 to 1 \(got 2\)$/], + [{ text: "hi", tuning: { seed: 1 } }, /"tuning\.seed" is not a tuning field/], + [{ text: "hi", reading: 100_000 }, /^"reading" must be a whole number from 0 to 99999/], ]; for (const [body, re] of cases) { const { status, json } = await post(body); 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/plans/orpheus-retune.md b/plans/orpheus-retune.md @@ -0,0 +1,236 @@ +# Orpheus re-tune and re-run, by the operator alone + +Status: **planned 15 Nov 2026; S1 in progress (16 Nov 2026, `lane/orpheus-tuning`).** Written to be +picked up cold (after a usage reset). S2, S3 and S4 are not started. + +## The ask (operator, 15 Nov 2026) + +> Stick with Orpheus, but make it much easier to re-tune and re-run in different ways in either the +> character or clip editor without having to ask an AI agent, letting me re-type a message (and maybe +> find/replace over the whole video?) and re-run with a button to re-listen. + +Chatterbox was considered and set aside: Orpheus stays the synthetic engine. The work is UI and plumbing, +not a new model. + +## What exists today (verified 15 Nov against main 976efc77e) + +- **Engine.** `scripts/tts_orpheus.py` renders chunks on llama-server (Vulkan) and SNAC; per chunk up to + `takes` seeded takes, the first that passes its checks is kept. Its `input.json` ALREADY carries + `sampler`, `seedBase`, `takes`, `tagCheck`. Stock voices only (`tara leah jess leo dan mia zac zoe`), no + reference-audio path, and there must never be one. +- **The knobs are constants.** `common/lib/ttsApps.ts`: `ORPHEUS_SAMPLER` (temperature 0.55, top_p 0.85, + top_k 50, min_p 0, repeat_penalty 1.2, repeat_last_n 64; the operator's pick by ear on 12 Oct 2026) and + `ORPHEUS_SEED_BASE = 1234`. Settings carry only `tts.orpheus.takes` / `tagCheck` (and `speed`, which + Orpheus ignores). The cache key's `keyExtra` holds takes and tagCheck, not the sampler or the seed. +- **Consequence:** the same text in the same voice comes back as the same cached file. Today a different + reading of a line can only be got by changing the words or by an agent changing code or settings. That + is the gap. +- **The TTS op.** `editor/app/api/ops/tts/route.ts`: `POST { text | file, voice?, engine?, speed?, out? }` + → a `tts-file` job (`common/controller/ttsFile.ts`), cached, queued on the `tts` lane. +- **Where Orpheus reads are made in umtool:** + - the post bench's narration panel (`umtool/components/projects/PostNarrationPanel.tsx`, route + `app/api/report/post-narration`): an editable script textarea + **Save script**, **Re-take with + direction** (`op: "take"` with note, voice, engine, speed, script), a take tree (synthesized, recorded, + derived), a pick; + - screen lines (`ScreenLineVoice.tsx`, "Make the read" = `umtool posts screen <p> <item> read`); + - card narration (`report-to-video/narration.mjs`, `narrate-via-editor.mjs`); + - thread reads (`lib/report/postThreadRead.mjs`); + - the Voices page (`VoicesPanel.tsx`): an audition of candidate voices side by side, **Use this voice**; + - character presets (`CharacterPresets.tsx`; CLI `umtool cast set`, `umtool cast project …`): the + SYNTHETIC preset is a stock voice and its speed only. +- **Pronunciation** already exists: the lexicon `umtool posts say` and the voice map `umtool posts voices` + (`PronunciationPanel.tsx`), with "try it" and a list of picked reads that still say an entry the old way. + +"Character or clip editor" = the character presets / Voices page and **the post bench** (operator, +15 Nov). The `/projects/<p>/clips` clip editor is out of scope. + +## Operator rulings (15 Nov 2026), binding on every slice + +1. **Scope:** the post bench (and the character presets). Not the `/clips` clip editor. +2. **Tunings:** both the named starting points AND the bare numbers. +3. **Every edit is for READING only.** Re-typing a line, find/replace, a pronunciation entry exist to + change what the voice says: an acronym spelled out, a delivery change (tags, punctuation), a typo + corrected in speech. **The original text is always what is shown on screen**: a post card, a screen + line, a thread tile, a caption. No slice may change displayed text, and a test in each lane pins it + (edit the read → the card's drawn text is byte-identical). + - Consequence to verify in S1's design note: every read needs a SPOKEN text kept apart from its SHOWN + text. A post's `narration.script` is already separate from the post's own text (check that the card + draws from the post, never from the script). A screen line's read is drawn from the screen's lines, + so a screen line needs its own "said as" override (e.g. `saidAs.<n>`), defaulting to the shown line. + A card's `narration.text` is already spoken-only. Thread reads: check. + - The "a read may not say what a screen masks" refusal still applies to the spoken text. +4. **Re-reading only on a press.** A stale read is listed and offered, never re-made by itself. + +## What to build: four slices, each one lane + +### S1. The engine takes a tuning and a seed (`lane/orpheus-tuning`; plumbing, no UI) + +- A synthesis may carry `tuning: { temperature?, top_p?, top_k?, min_p?, repeat_penalty?, takes? }` and + `reading?: integer` (ruled 16 Nov: ONE word end to end — the ops body, the result, the sidecar, the cache + key, a card's `narration.reading`, a post take's `reading`, the CLI's `--reading N`; "variant" already + means a cut and a forked take in umtool). The seed base is `ORPHEUS_SEED_BASE + 9973 × reading`; there is + no explicit `seed`. Ranges (`common/lib/ttsTuning.mjs`): temperature 0.1–1.5, top_p 0.05–1, top_k 0–200 + (whole), min_p 0–0.5, repeat_penalty 1–2, takes 1–6 (whole), reading 0–99,999 (whole); each refused in a + sentence naming the field and its range. A missing value falls back to `ORPHEUS_SAMPLER` and + `tts.orpheus.takes` (no new setting), so **an ask without them is byte-identical to today's, cache hit + included**; a tuning equal to the defaults and reading 0 normalise to none (pinned against main's sha and + input.json literally). +- Tuning and reading go INTO the cache key only when non-default (no CACHE_KEY_VERSION bump): the same ask + again is still free; "another reading" is a new key. + The key holds only what DIFFERS from the code's defaults, so **changing `ORPHEUS_SAMPLER` (or + `ORPHEUS_SEED_BASE`) needs a `CACHE_KEY_VERSION` bump**, or untuned asks keep hitting files made with the + old values (a pre-existing property, not changed by S1). Decimal values are quantised to 3 places (-0 is 0) + before they are checked, normalised and keyed. +- The result JSON, the cache sidecar and a post take's record say the effective tuning, the reading and the + seed base, so a reading can be made again exactly, and its numbers can be copied into a character. +- Through every layer: `ttsApps.ts` → `ttsFile.ts` → `scripts/tts.mjs` → `tts_orpheus.py` (already reads + them from input.json), the ops route, `pnpm ops tts`, `narrate-via-editor.mjs`, the post-narration + `take` op and `umtool posts narrate <p> <item> --take [--reading N] [--temperature t] [--top-p p] + [--top-k k] [--min-p m] [--repeat-penalty r] [--chunk-takes n]` (refused with `--thread` / `--all` in S1). + Kokoro and eSpeak NG ignore a tuning and say so (a note, not an error). +- Docs: COMMANDS.md and umtool's docs/cli.md regenerated. + +### S2. A character carries its tuning (`lane/character-tuning`; UI on the character preset + Voices page) + +- The SYNTHETIC preset gains an Orpheus tuning: temperature, top_p, repeat penalty, takes. It is shown as + three named starting points plus the numbers under "Adjust": **Steady** (cooler; the default's + neighbour), **Default** (`ORPHEUS_SAMPLER`), **Lively** (warmer). The names and values are the + implementer's proposal for the operator to judge by ear; the numbers are always visible and editable. +- **Try it, in the preset:** a text box (prefilled with a line this character actually reads in the + project, or any line typed), **Read it** → a job → plays when done; **Another reading** = the same text + and tuning, the next reading (`reading` + 1); every audition stays in a short list (text, tuning, reading, Play), so + two readings can be compared at one loudness (reuse the Voices page's audition player and its + loudness match). +- **Keep these settings** saves the tuning to the character (the cast's, or this video's own), through + the CLI's own command: `umtool cast set <character> --temperature … --top-p … --repeat-penalty … + --takes …` (and the `cast project` twin). A kept reading's number may be kept too ("use this voice's + reading as the character's sample"). +- Changing a character's tuning makes its existing reads stale, not re-made: the bench lists "N reads by + this character were made with other settings · Re-read them" (one button, S4's queue). + +### S3. Re-type and re-run a line where it is read (`lane/line-rerun`; post bench, screen lines, card narration) + +- For every synthesized read (a post's script, a screen line, a card's narration, a thread read): the + text is editable in place; the buttons are + - **Read again**: the same text, the next reading (`reading` + 1, not the cache); + - **Read edited text**: saves the text (the draft, as Save script does now) and reads it; + - **Tune ▾**: this line's own tuning, prefilled from the character; "use for this line only" or + "keep for the character" (→ S2's command). +- When the job ends the new take **plays by itself** (a toggle, on by default) and joins the take list + with its text, tuning and reading; **Pick** makes it the one the cut plays. The previous pick stays one + press away (no reading is ever deleted by re-running). +- **One sentence only (S3b, optional within the lane or a follow-up):** a take's `parts` already carry + each sentence's file, start and length. **Re-read this sentence** makes a new reading of one part and + joins it into a new take with the others unchanged (the same join and fades as `tts_orpheus.py`), so a + single flubbed sentence does not cost the good ones. +- Recording is untouched: a recorded take, its enhance and convert chain, and the operator's + `*.recorded-operator.*` files are not changed by any of this. + +#### Findings from S1 (16 Nov): where each read's spoken and shown text live + +Paths under `umtool/`, line numbers at main 976efc77e. **No drawn character ever comes from spoken text** — +but for a post's script and a thread read the spoken text steers the LAYOUT, so S3's "byte-identical card" +test must pin the drawn structure (blocks, hidden paragraphs, tile modes), not only the characters. + +- **A post's script.** Spoken: `narration.script` → `spokenRead` (lib/report/postNarrationCli.mjs:356, + 379–381; app/api/report/post-narration/route.ts:302, 325; report-to-video/post-redact.mjs:389–418: anon + names, lexicon, redaction, slurs); the take keeps `script` and, when an anonymous handle changed it, `said` + (postNarrationCli.mjs:417–429). Shown: `cardText(entry)` = `entry.text` (report-to-video/post-item.mjs:111–114), + drawn by `wordsHtml` (:1141) in `postCardHtml` (:1372 plain card, :1461 thread tile) after `redactEntry` (:1301). + **Layout coupling:** read-follow `followParts` builds its blocks from the picked take's `parts[].text`, else + `take.script`, else `narration.script` (report-to-video/read-follow.mjs:203–213); `followBlocks` (:227–283) + matches them to the card's words and wraps them as `data-post-block` (post-item.mjs:1159) — the lit/dim + highlight and the pan. In an excerpt thread tile, blocks no part reads are `display:none` + (post-item.mjs:1385, 1428, 1447, 1496), so an edited script can HIDE drawn paragraphs. `partRoles` falls + back to the script (report-to-video/post-thread.mjs:221–223) and `threadLayout` uses the roles for tile + modes, quoted above/inside and which screens are drawn (:296–298, 319–353, 368); the script counts as a + form of the "post" text when roles are matched (:167). Captions: the chip text is `fx.text` + (post-caption.mjs:9), matched against the card text (:74, :165); only its timing comes from `take.words` + (:131–135) or a script estimate (:137–147). +- **A screen line.** Stored: `timeline[i].screens[j].lines[n].text`, with `read` (all / none / spans), + `who`, `lineTakes` (report-to-video/post-screens.mjs:13–16). Spoken AND shown come from the same `viewOf` + span: `said` and `shown: cut` (post-screens.mjs:264–266) → `screenLineSaid` (:287), `screenPieces` + (:610–617), `chronoPieces` (post-thread.mjs:1343), `draftScript` + `spokenRead` + (lib/report/postThreadRead.mjs:234–235); `lineToRecord` the same (lib/report/screenLineRecord.mjs:60–64); + drawn by `screenRows` (:342) → `screenTileHtml` (:683–740). **There is no per-line "said as" override + today** — only the lexicon (`red.say`, item-scopable; post-redact.mjs:235–236, 397–399), applied to speech + only. Editing `lines[n].text` changes both sides, and the old take is then refused (`screenLineChanged`, + post-thread.mjs:710–727, :573). **S3 needs `saidAs.<n>`**, defaulting to the shown line. +- **A card's narration.** Spoken only: `narration.text` (report-to-video/narration.mjs:88, 101–110; + `narrationsOf` :125–131). Never drawn: render-cards.mjs never reads it; `buildNarratedCardSegment` + (build-video.mjs:2949–2969) uses only its measured seconds (:2956, 7255–7257); burned captions come from + the clip transcript (build-video.mjs:2193–2206, `lookWordsFor` :2276–2280); the disclosure line + (narration.mjs:319–343) goes to the description. Editing it changes only the card's length. +- **A thread read.** Spoken pieces: `chronoPieces` (post-thread.mjs:1330–1345) — parents and quoted posts + their `contextText` (the paraphrase, else the text; post-item.mjs:224–226), linked posts `contextText` + + transcript, his post `narration.script` else `draftScript(cardText)` (postThreadRead.mjs:180–181, 268), + screens their lines; each through `spokenRead` (:273), parts storing the spoken text (:401–403). An + attachment is never read by itself ("media:<i>" is only inferred when a part matches no card text, + post-thread.mjs:259–260). Shown: the tiles draw the same `contextText` / `cardText` (post-item.mjs:1420–1438 + parents/linked, :1449 quoted, :1455–1461 post, :1484–1490 screens). Same structural coupling as a post's + script (parts drive blocks, excerpt hiding and inferred roles). +- **"A read may not say what a screen masks"** lives in post-thread.mjs, not post-redact.mjs: + `readSaysHiddenErrors` (:624–660) checks `take.parts[].text`, else `take.said || take.script` (:647), against + the screens' `shapeSpans` (:640–643) and lines marked `redact`; `screenPartErrors` (:577–579); both gathered + in `itemReadRefusals` (:599–609), called by lib/report/postScreensCli.mjs:260 and the build's lint (:588). + It already judges the SPOKEN text. +- **Surprise:** when a read is refused, `playableAsWritten` drops `narration` (post-thread.mjs:695–699), so + the item previews un-narrated and un-threaded and its drawn layout changes — a bad spoken edit on an item + with screens changes the preview. + +### S4. Find and replace over the whole video, and the re-read queue (`lane/reads-find`) + +- A **Reads** view per project (a tab of the workspace, or a section of the Voices page; implementer + proposes): every line a synthetic voice reads in the cut (posts, screen lines, cards, thread reads), + with its character, its picked take, and whether that take still matches its text and tuning + (`fresh` / `stale`). +- **Find** (plain text, case on/off, whole word) highlights matches across all of them, with a count. + **Replace** never touches shown text (ruling 3). It offers two scopes and says which it does: + 1. **These reads**: rewrites the SPOKEN text of the matched lines (scripts, screen lines' "said as", + card narration), as one undoable draft step, shown as a preview list first; + 2. **Everywhere, from now on**: adds a pronunciation entry (the existing `umtool posts say`), so every + read, present and future, says it that way. +- After either, the reads that changed are `stale`; **Re-read N changed lines** queues them (paced on the + editor's `tts` lane, one job each, or one batch job; GPU arbiter rules as now) and the view fills in + as each one lands. +- **Listen through:** a player that plays the re-read lines one after another (each with its old take + one press away), and "play in the cut" (the Play-the-cut view at that item), so re-listening needs no + render. +- CLI twin: `umtool reads <p> [--find <text>] [--stale]`, `umtool reads <p> replace <from> <to> + [--say-only] [--dry-run]`, `umtool reads <p> reread [--stale] [--wait]`, all `--json`. + +## Rules for this work (from AGENTS.md and the standing rulings) + +- Stock voices only; no reference audio; the disclosure line on every synthesized read stays. +- **Works with no model:** every button is a form and a job; nothing asks an agent or an LLM. +- Every write goes through a umtool command (the CLI twin) and lands in the working draft, as the + bench's writes do now; no hand-edited manifest, take json or notes.json. +- Synthesis is the EDITOR's (`tts-file` jobs on the `tts` lane); umtool never runs Orpheus itself. + Render mode holds that lane, so a re-read waits during a render, and the view must say so. +- Orpheus is heavy (llama-server, `heavyEstimateMB` 4000): a batch re-read is one queue, never a burst + of parallel servers. +- Each lane: design note first → Opus implementer → gates (typecheck, touched unit suites, docs checks, + the lane's umtool e2e spec alone via `pnpm --filter umtool run e2e <spec>`) → independent read-only + review → fixes by the same implementer → merge → post-merge suites → **ask the operator before + restarting umtool** (he records narration in it) → ship → smoke. +- No real people's or channels' names in code, fixtures or docs; fixtures only in tests. + +## Order + +S1 first (everything else needs a seed and a tuning to vary). Then S3 (the button he asked for most +directly), then S2, then S4. S2 and S3 can run as two lanes side by side after S1 merges, since they touch +different components. The machine allows two lanes at most. + +## Questions for the operator + +All four answered 15 Nov (see "Operator rulings" above). None is open. + +## Done means + +- From the post bench, a line can be re-typed, re-read with a new reading or a new tuning, heard on + arrival, and picked, with no agent. +- A character's tuning can be auditioned and kept from its preset. +- A word can be found across every read of a video, replaced (words or pronunciation), the changed lines + re-read in one press and listened through. +- Asks with no tuning and no reading still produce byte-identical audio and cache hits. +- No edit to a read ever changes what is shown on screen. 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", diff --git a/umtool/app/api/report/post-narration/route.ts b/umtool/app/api/report/post-narration/route.ts @@ -11,7 +11,8 @@ import { resolveReport } from "@/lib/report/serve.mjs"; import { readManifest } from "@/lib/projects/report.mjs"; import { refuseCaller } from "@/lib/report/caller"; import { crossSiteRefusal } from "@/lib/report/sameOrigin.mjs"; -import { deleteTake, measureTake } from "@/lib/report/postNarrationCli.mjs"; +import { deleteTake, measureTake, tunedOfResult } from "@/lib/report/postNarrationCli.mjs"; +import { parseTtsTuning, ttsReadingError } from "yt-dlp-transcript-common/lib/ttsTuning.mjs"; import { parseTempoSpec, rereadTake } from "@/lib/report/postReread.mjs"; import { parsePauseSpec, pauseTake } from "@/lib/report/postPause.mjs"; import { withTakeScope } from "@/lib/report/takeScope.mjs"; @@ -43,8 +44,12 @@ const benchVoice = (red: { slurs?: { voice?: string } | null } | null) => (red?. // a RECORDING, part by part: trimmed, joined, // levelled, kept as take-<n>.recorded-<label>.wav // POST {project, op: "set", id, patch, token} updatePostNarration (script, pick, approved, off, the mix) -// POST {project, op: "take", id, note?, voice?, engine?, speed?, script?} -// a new take asked of the EDITOR's tts op (a job) +// POST {project, op: "take", id, note?, voice?, engine?, speed?, script?, tuning?, reading?} +// a new take asked of the EDITOR's tts op (a job); `tuning` +// (Orpheus's temperature, top_p, top_k, min_p, repeat_penalty, +// takes) and `reading` (0 = the first; 1, 2, … another reading) +// are sent as asked -- the take records what the editor says it +// was made with (`tuning`, every value; `reading`) // POST {project, op: "fit", id, linger?} the attachment's best part for the read (posts fit) // GET ?project&id&convert=1 what a convert of this post defaults to: its author's character in // the cast (else the narrator) and that character's convert @@ -156,14 +161,14 @@ export async function GET(request: Request) { const res = resultLine<{ wav?: string }>(st.tail, "@@tts-result "); return Response.json({ state: "failed", error: `the job is done but ${rel} is not there (it wrote ${res?.wav ?? "nothing"})` }, { headers: noStore }); } - const res = resultLine<{ engine?: string; voice?: string }>(st.tail, "@@tts-result ") ?? {}; + const res = resultLine<{ engine?: string; voice?: string; tuning?: Record<string, number>; reading?: number; note?: string }>(st.tail, "@@tts-result ") ?? {}; const meas = await measureTake(abs); const note = q.get("note"); const script = q.get("script") ?? String(e.narration?.script ?? ""); const derive = q.get("derive"); if (derive !== null) { // A derived take: source the take it came from, its step recorded, its parts (renamed) kept. - const takes = (e.narration?.takes ?? []) as Array<{ file: string; voice?: string; script?: string; parts?: Array<{ n: number }>; speed?: number; speedAsked?: true | "item" | "preset"; said?: string }>; + const takes = (e.narration?.takes ?? []) as Array<{ file: string; voice?: string; script?: string; parts?: Array<{ n: number }>; speed?: number; speedAsked?: true | "item" | "preset"; said?: string; tuning?: Record<string, number>; reading?: number }>; const from = takes[Number(derive)]; if (!from) return Response.json({ state: "failed", error: `no take ${derive}` }, { headers: noStore }); const op = String(q.get("op") ?? ""); @@ -181,6 +186,8 @@ export async function GET(request: Request) { script: from.script ?? script, at: new Date().toISOString(), jobId: job, ...(Number.isFinite(meas.lufs) ? { lufs: meas.lufs } : {}), // Its audio is its source's words at its source's speed: what it said and where that speed came from. ...(typeof from.speed === "number" ? { speed: from.speed } : {}), ...(from.speedAsked !== undefined ? { speedAsked: from.speedAsked } : {}), ...(typeof from.said === "string" ? { said: from.said } : {}), + // And the reading it was (its source's tuning and reading). + ...tunedOfResult(from), ...(Array.isArray(from.parts) ? { parts: from.parts.map((p) => ({ ...p, file: `${partsRel}/p${String(p.n).padStart(2, "0")}.wav` })) } : {}), }; const { result } = await withEditNotes(r.project, async () => updatePostNarration(r.project.dir, id, { addTake: derived }, { token: await manifestToken(r.project.dir) })); @@ -199,6 +206,8 @@ export async function GET(request: Request) { // What it said, when an anonymous handle made that differ from the script (post-anon.mjs; the lint reads it). ...(spoken.anonymised ? { said: spoken.text } : {}), ...(slurs ? { slurs } : {}), + // What it was made with, as the editor's result says (Orpheus: every tuning value, the reading). + ...tunedOfResult(res), // The pronunciation entries it said (post-say.mjs), as the POST above applied them. ...(lexicon ? { lexicon } : {}), file: rel, engine: res.engine ?? q.get("engine") ?? "orpheus", voice: res.voice ?? q.get("voice") ?? "zac", seconds: meas.seconds, @@ -208,7 +217,8 @@ export async function GET(request: Request) { const { result } = await withEditNotes(r.project, async () => updatePostNarration(r.project.dir, id, { addTake: take, ...(script !== e.narration?.script ? { script } : {}) }, { token: await manifestToken(r.project.dir) }), ); - return Response.json({ state: "done", file: rel, entry: result.entry, token: result.token }, { headers: noStore }); + // The editor's `note` (a tuning or reading its engine ignored), handed on so the bench can say so. + return Response.json({ state: "done", file: rel, entry: result.entry, token: result.token, ...(typeof res.note === "string" && res.note ? { note: res.note } : {}) }, { headers: noStore }); } return Response.json({ state: "done", file: rel }, { headers: noStore }); } catch (err) { @@ -301,6 +311,12 @@ async function postHere(request: Request) { const k = postNarrationKnobs(e, (m.render ?? {}) as Record<string, unknown>); const script = String(body.script ?? e.narration?.script ?? "").trim(); if (!script) return Response.json({ error: `${id} has no script to read` }, { status: 400 }); + // Its tuning and reading (another reading of the same words): refused here in the editor's words, sent as asked. + const tuned = body.tuning === undefined || body.tuning === null ? null : parseTtsTuning(body.tuning); + if (tuned && !tuned.ok) return Response.json({ error: tuned.error }, { status: 400 }); + const reading = body.reading === undefined || body.reading === null ? null : body.reading; + const readingError = reading === null ? null : ttsReadingError(reading); + if (readingError) return Response.json({ error: readingError }, { status: 400 }); // The voice: the one asked for, the item's own character, the project's characters and voice map, the CAST, the // narrator's -- a single read's rule (readVoice.mjs). const said = await itemReadVoice(r.project, e, { @@ -326,8 +342,12 @@ async function postHere(request: Request) { const out = path.join(r.project.dir, ...rel.split("/")); // Its speed and where it came from, for the take the GET makes when the job is done (a sidecar, removed then). if (speed) await writeFile(`${out}.ask.json`, JSON.stringify({ speed, speedAsked: body.speed !== undefined && body.speed !== null ? true : (e.narration as { speed?: number } | undefined)?.speed != null ? "item" : "preset" })); - const jobId = await startJob("/api/ops/tts", { text: spoken, engine, voice, out, ...(speed ? { speed } : {}) }); - return Response.json({ ok: true, jobId, file: rel, engine, voice, script }, { headers: noStore }); + const tuning = tuned?.ok && Object.keys(tuned.value).length ? tuned.value : null; + const jobId = await startJob("/api/ops/tts", { text: spoken, engine, voice, out, ...(speed ? { speed } : {}), ...(tuning ? { tuning } : {}), ...(reading !== null ? { reading } : {}) }); + // Echoed only for the engine that takes them (Orpheus): Kokoro and eSpeak NG ignore them (the editor's result + // says so in its `note`, which the GET below hands on), so the answer never claims a tuning that is not used. + const tunes = engine === "orpheus"; + return Response.json({ ok: true, jobId, file: rel, engine, voice, script, ...(tunes && tuning ? { tuning } : {}), ...(tunes && reading !== null ? { reading } : {}) }, { headers: noStore }); } if (body.op === "derive") { const takes = (e.narration?.takes ?? []) as Array<{ file: string; parts?: Array<{ n: number; file?: string }> }>; diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md @@ -134,7 +134,7 @@ Inbox cannot disagree about what is wrong with one. | `posts progress <project> [auto\|on\|off\|default] [--json]` | the cut's **progress bar** default (`render.posts.progress`, `updatePostProgressRender`; [report-video.md](report-video.md#the-progress-bar)); bare, which items draw it | | `posts screen <project> <item> list\|add\|set\|rm\|check\|read\|record …` (add: `--media <i> [--at <from>,<to>] --kind dm\|email\|post\|text [--id <id>] [--title "…"] [--from <file>] [--line "who: words"]… [--read all\|none\|<n>,…] [--unread omit\|dim] [--ref <channel>/<postId>]` or `--from-read [--media <i>] [--kind …]`; record: `<id> <line> --recording <file> [--as <the speaker's character>] [--no-clean\|--clean] [--no-trim\|--trim] [--no-convert] [--pitch target\|source\|contour] [--semitones n] [--label l] [--check-words [--worker w]] [--events]`; set: `<id> kind= title= media= at=<a>,<b>\|off unread= ref= read=all\|none\|<n>,… read.<n>="excerpt"\|on\|off line.add="who: words" line.<n>=off line.<n>.who= line.<n>.side=left\|right\|auto line.<n>.text= line.<n>.time= line.<n>.redact=on\|off take.<n>=<take n>\|off [--from <file>]`; check: `<id> [--by <name>] [--undo]`; read: `[--post-take <n>] [--line-take screen:<id>:<line>=<n>]… [--voice-for h=v]… [--force] [--dry-run]`; `--json`, `--dry-run`, `--take <take>`) | a post's **SCREENS** ([report-video.md](report-video.md#screens-text-screenshots-read-as-part-of-the-post), [knobs.md](knobs.md#screens-a-posts-text-screenshots), `post-screens.mjs`): the text screenshots its attachments carry -- a DM exchange or an email shown in its video (`--at`: the seconds it is visible), an image that is a screenshot -- transcribed once (`--from`: a JSON screen, or text lines `[right] who: words \| time`, `- words`, `[redact] …`), checked by a person (`check`; a screen not checked is a lint WARNING; new words take the check away), and read whole or in excerpts. Each write is the post item's one writer (`updatePostItem`'s `screens`, one undo point), refused in the build's words (**exit 1**); an attachment a screen is in cannot be removed. An e-mail address, a phone number, an order or long number in a line is masked on the card and never said. `read` makes the THREAD READ with the screens (as `posts narrate <p> <item> --take --thread`): her own line from the take that plays (or the one the thread read used; `--post-take n` another), never made again; each read line in its speaker's voice (`who`: the post's author in hers, a handle or a character's name in theirs); `--line-take` takes a line from the item's take n (a recording of it), and a line's CHOSEN take (`take.<n>=`, the bench's select) is read in its place -- a recording nobody chose is named, never read in. `add --from-read`: a PICTURE-ONLY post's read (its `narration.script`) made its screen, a line per line, on its picture, read whole, NOT checked -- no speaker parsed out of it. `record`: ONE LINE in your voice ([report-video.md](report-video.md#a-line-in-your-own-voice), `lib/report/screenLineRecord.mjs`) -- the line as the read says it (its shapes and the redaction left out, an anonymous handle as its shown name), kept as new takes through `posts narrate --recording`'s chain: recorded, cleaned, converted to its SPEAKER's character's stock voice (none: kept as recorded, said), NONE picked, each carrying `screenLine`; refused on an item with no read of its own (**exit 1**). A line take is refused picked as the item's read, as `--post-take`, for another line, or once its line's words or speaker changed. `--as` may name only that character (another, or the narrator, **exit 1**). A take is a line's by its content (its screen, words and speaker), not its index. `--check-words` (the editor's transcribe op; opt-in, CLI only): refused when it is heard saying a shape or a number in words, an @handle, an anonymous author's handle or name, or a redacted term -- nothing kept -- and a warning on other words; the take keeps what it was heard saying. Without it nothing hears the recording: the lint warns for each chosen take not heard. A screen made `--from-read` is the post's read: `read` leaves his own piece out and refuses `--post-take`. Usage errors: **exit 2** | | `posts roles <project> [<item> …] [--write] [--set <n>=<role>,…] [--json]` | a narrated read **piece by piece** ([knobs.md](knobs.md#thread-reads-every-part-of-a-read-on-screen-while-it-is-said), [report-video.md](report-video.md#thread-reads)): the text each part of the picked take reads -- `parent:<i>`, `quoted`, `post`, `media:<i>` -- stored or inferred, what the card shows for each, and the build's guard (a part read off a post the card hides is refused). `--write` stores the inferred roles on the picked takes' parts (one write; the import stores them for every new take); `<item> --set n=role,…` sets parts' roles by hand (`off`: inferred again); a part out of range or an unknown role is refused (**exit 1**) | -| `posts narrate <project> --import [--dry-run] [--json]` · `--list` · `<item> [--script "…"] [--pick <n>] [--approve\|--unapprove] [--off\|--on] [lead= tail= ramp= linger= clip=read\|full wet= lowpass= duck=on\|off short=hold\|loop attach=under\|after lufs= pace=fast\|normal]` · `<item> --take [--note "…"] [--voice v] [--engine e] [--speed s] [--script "…"]` · `<item> --derive <n> --op enhance\|convert [--engine e] [--voice v]` · `<item> --delete <n>` · `--all --draft-scripts [--force]` · `--all --take [--limit N]` · `--cut <k=v>…` | a **narrated post item** ([report-video.md](report-video.md#narrated-post-items), [knobs.md](knobs.md#a-narrated-post-item)): `--import` reads `narration/posts/index.json` (`[{id, entry, script, takes: [{file, engine, voice, seconds}], pick}]`, and a take's `take-<n>.parts.json`) into the cut in ONE write, measuring each take (length, loudness); a re-run adds only takes not there. `--take` asks the EDITOR for a new take (`POST /api/ops/tts`, its `out` the next `narration/posts/<postId>/take-<n>.<engine>-<voice>.wav`; a job, waited for; `ARCHILYZER_EDITOR_URL`, `WORKER_TOKEN`) and picks it, its `--note` kept with it; `--pick <n>` is the take's number as `--list` shows it. `--derive <n>` makes a NEW take from take n through the editor's `voice-enhance` / `voice-convert` op (a stock synthetic voice; "not installed" until the editor has the engine), the original kept; `--delete <n>` moves a take's file to the post's `.trash/`. A new script or pick takes the approval away. `--all --draft-scripts` writes every post's words as its script, VERBATIM (cleaned only to be spoken: a reply's leading @handles, links, emoji dropped -- a handle typed inside the message is kept and said "at <handle>", the lexicon first; `plan(s)` → plans, `w/` → with, `&` → and; paragraphs kept). `--cut` sets `render.postNarration` (and its read-follow: `follow=on\|off`, `follow.dim=`, `follow.ease=`; its thread reads: `thread.parent=`, `thread.quoted=`, `thread.carry=`, `thread.reveal=`, `thread.shrink=`, `thread.dim=`, `thread.seconds=`, `thread.pan=`). Refused in the build's words (**exit 1**) A `--take` whose read says a slur the cut BEEPS is word-timed by the editor's transcription before it is kept -- never waited on: with the transcription lane held (as while Orpheus runs) the take is kept as read and the timing deferred (it says so, naming `posts narrate <p> <item> --words` to run after the release; the build refuses the take until then), and a timing still queued after 5 min is deferred the same way. An excerpted item (`posts set-item … excerpt=`) reads its spans. | +| `posts narrate <project> --import [--dry-run] [--json]` · `--list` · `<item> [--script "…"] [--pick <n>] [--approve\|--unapprove] [--off\|--on] [lead= tail= ramp= linger= clip=read\|full wet= lowpass= duck=on\|off short=hold\|loop attach=under\|after lufs= pace=fast\|normal]` · `<item> --take [--note "…"] [--voice v] [--engine e] [--speed s] [--script "…"]` · `<item> --derive <n> --op enhance\|convert [--engine e] [--voice v]` · `<item> --delete <n>` · `--all --draft-scripts [--force]` · `--all --take [--limit N]` · `--cut <k=v>…` | a **narrated post item** ([report-video.md](report-video.md#narrated-post-items), [knobs.md](knobs.md#a-narrated-post-item)): `--import` reads `narration/posts/index.json` (`[{id, entry, script, takes: [{file, engine, voice, seconds}], pick}]`, and a take's `take-<n>.parts.json`) into the cut in ONE write, measuring each take (length, loudness); a re-run adds only takes not there. `--take` asks the EDITOR for a new take (`POST /api/ops/tts`, its `out` the next `narration/posts/<postId>/take-<n>.<engine>-<voice>.wav`; a job, waited for; `ARCHILYZER_EDITOR_URL`, `WORKER_TOKEN`) and picks it, its `--note` kept with it -- with `--reading N` it is ANOTHER READING of the same words (0 the first; Orpheus's seeds move, a new cached file) and `--temperature` `--top-p` `--top-k` `--min-p` `--repeat-penalty` `--chunk-takes` its tuning (the editor's ranges; one item's `--take` only, not `--thread` or `--all`), and the take records every tuning value and the reading it was made with; `--pick <n>` is the take's number as `--list` shows it. `--derive <n>` makes a NEW take from take n through the editor's `voice-enhance` / `voice-convert` op (a stock synthetic voice; "not installed" until the editor has the engine), the original kept; `--delete <n>` moves a take's file to the post's `.trash/`. A new script or pick takes the approval away. `--all --draft-scripts` writes every post's words as its script, VERBATIM (cleaned only to be spoken: a reply's leading @handles, links, emoji dropped -- a handle typed inside the message is kept and said "at <handle>", the lexicon first; `plan(s)` → plans, `w/` → with, `&` → and; paragraphs kept). `--cut` sets `render.postNarration` (and its read-follow: `follow=on\|off`, `follow.dim=`, `follow.ease=`; its thread reads: `thread.parent=`, `thread.quoted=`, `thread.carry=`, `thread.reveal=`, `thread.shrink=`, `thread.dim=`, `thread.seconds=`, `thread.pan=`). Refused in the build's words (**exit 1**) A `--take` whose read says a slur the cut BEEPS is word-timed by the editor's transcription before it is kept -- never waited on: with the transcription lane held (as while Orpheus runs) the take is kept as read and the timing deferred (it says so, naming `posts narrate <p> <item> --words` to run after the release; the build refuses the take until then), and a timing still queued after 5 min is deferred the same way. An excerpted item (`posts set-item … excerpt=`) reads its spans. | | `posts narrate <project> <item> --take --thread [--parents 0\|all\|none\|<n>] [--skip-parent <id\|parent:i>]… [--no-quoted] [--no-linked] [--read-seen] [--voice-for <handle>=<voice>]… [--voice v] [--engine e] [--speed s] [--no-screens] [--line-take screen:<id>:<line>=<n>]… [--note "…"] [--force] [--no-hold] [--dry-run] [--json]` | a **THREAD READ** as one command ([knobs.md](knobs.md#pronunciation-and-voices-the-lexicon-the-voice-map-a-thread-read), `lib/report/postThreadRead.mjs`): the post it answers (`--parents all`: every ancestor; `<n>`: parents 0..n; `none`), the post it quotes and the posts it links to, then his words, in DATE order, each in its author's voice (`--voice-for`, then the item's own character, this video's characters and voice map, the cast: `cast project`; his own: the narrator's) and at its character's speed (its synthetic preset's; `--speed`: every part at that one; Orpheus has none; a part at another speed is another cached part), the redaction, the slur filter (a beep is skipped: a joined read is not word-timed) and the lexicon (`posts say`) applied. A parent or quoted post the item before already shows is not read again (`--read-seen`: it is). Each part is synthesized ONCE by the editor's tts op into `narration/parts-cache/<sha1(voice\|text)>.wav` (the transcription lane held meanwhile, only if it was not; `--no-hold`: left alone), joined (0.8 s between pieces, 0.6 between paragraphs, 0.25 inside one) into `take-<n>.<engine>-thread.wav` with `take-<n>.parts.json`, saved with its parts' roles, its lexicon and how it was asked (`read`) and PICKED — one write (one undo point). `--dry-run`: the pieces, voices and parts (cached or not), nothing asked. Already up to date (same words and voices): nothing done, **exit 0** (`--force`: again). **`--post-take <n>`**: his OWN line is the item's take n (as `--list` numbers them) -- a recording, or one converted to his character's voice -- not synthesized; the context pieces are, in their authors' voices, and each part of the new take records where it came from (a synthesized part its parts-cache file and voice; the take's part its file and `take`: that take's id; the read's `postTake`). A thread take, or one whose file is gone: **exit 1**. A part not synthesized: **exit 1** (the parts made stay cached; run it again); `--json` prints `{ok: false, error}` too. A usage error: **exit 2** Its SCREENS (`posts screen`) are read after his words, each line in its speaker's voice (`--no-screens`: left out); `--line-take screen:<id>:<line>=<n>` takes a line from the item's take n as `--post-take` does his own | | `posts say <project> [ls] [--item <id>]` · `add <word\|phrase> "<spoken>" [--case] [--item <id>] [--note "…"]` · `remove <word\|n> [--item <id>]` · `try "<text>" [--item <id>]` · `stale` `[--json]` | **THE PRONUNCIATION LEXICON** ([knobs.md](knobs.md#pronunciation-and-voices-the-lexicon-the-voice-map-a-thread-read)): `narration/lexicon.json` in the project, a word or phrase said differently in EVERY synthesized read (a script's `--take`, each piece of a thread read, the bench's re-take); the scripts and cards keep their words. Whole words, without case unless `--case`, a phrase across any spaces, regex characters literal; `--item` for one item's reads (it wins over the project's). A masked slur and a redacted word are never replaced. `add` of a word already listed changes what is said. `try` prints what a voice would be asked to say. `stale` lists every picked read that still says an entry the old way, with the command that re-reads it. A bad entry or an unknown item: **exit 2** | | `posts character <project> <item> [<character> \| --clear] [--json]` | **THE CHARACTER ONE ITEM's OWN READ IS MADE WITH** (`narration.character`, [knobs.md](knobs.md#this-videos-own-characters-and-an-items-own)): the id of one of this video's own characters, else of the cast's -- its presets answer for that item before its author's handle does (the synthetic one for `--take` and a thread read, the recorded one for `--recording`). No character: the one it names and what its read resolves to now; `--clear`: by its handle again. One undoable write; no take is made. An id nobody has: **exit 2** | @@ -368,7 +368,7 @@ draft (the project's manifest); *project*: a project's other files, or reads; *c | `posts set <project> <post> key=value…` | the Posts table's writer: thread, hide, attach, crop | form · *draft* | | `posts reel <project> --channel CHANNEL… [--since SINCE] [--until UNTIL] [--own] [--with-media] [--replies include\|only\|exclude] [--order chrono\|reverse] [--limit N] [--after AFTER] [--dry-run]` | post items from posts channels, in one write | form · *draft* | | `posts set-item <project> <item> key=value… [--in-take IN-TAKE]` | a post item's knobs | form · *draft* | -| `posts narrate <project> [<item>] [key=value…] [--script SCRIPT] [--take] [--note NOTE] [--voice VOICE] [--engine ENGINE] [--speed N] [--pick N] [--approve] [--unapprove] [--off] [--on] [--thread] [--parents PARENTS] [--post-take N] [--words] [--import] [--list] [--all] [--draft-scripts] [--limit N] [--force] [--recording RECORDING] [--as AS] [--pitch target\|source\|contour] [--semitones N] [--dry-run] [--in-take IN-TAKE]` | a post item's narration: script, takes, pick, approve, mix | form · queued · *draft* | +| `posts narrate <project> [<item>] [key=value…] [--script SCRIPT] [--take] [--note NOTE] [--voice VOICE] [--engine ENGINE] [--speed N] [--reading N] [--temperature N] [--top-p N] [--top-k N] [--min-p N] [--repeat-penalty N] [--chunk-takes N] [--pick N] [--approve] [--unapprove] [--off] [--on] [--thread] [--parents PARENTS] [--post-take N] [--words] [--import] [--list] [--all] [--draft-scripts] [--limit N] [--force] [--recording RECORDING] [--as AS] [--pitch target\|source\|contour] [--semitones N] [--dry-run] [--in-take IN-TAKE]` | a post item's narration: script, takes, pick, approve, mix | form · queued · *draft* | | `posts screen <project> <item> list\|add\|set\|rm\|check\|read\|record [<screen>] [<line>] [key=value…] [--from-read] [--recording RECORDING] [--as AS] [--no-clean] [--no-convert] [--pitch target\|source\|contour] [--semitones N] [--check-words] [--media N] [--at AT] [--kind dm\|email\|post\|text] [--title TITLE] [--line LINE…] [--read READ] [--unread omit\|dim] [--by BY] [--undo] [--post-take N] [--line-take LINE-TAKE…] [--dry-run] [--in-take IN-TAKE]` | a post item's text screenshots: transcribed, drawn, read | form · *draft* | | `posts say <project> ls\|add\|remove\|try\|stale [<word>] [<spoken>] [--case] [--item ITEM] [--note NOTE]` | the pronunciation lexicon | form · *draft* | | `posts character <project> <item> [<character>] [--clear]` | the character one post item's own read is made with | form · *draft* | diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md @@ -1432,6 +1432,7 @@ the shape, the mix, recordings, parts, the best part). One writer for a post's n | **the recording session** — the cut's posts read aloud in order, part by part, each part on disk as soon as it is kept (a reload resumes), the post's recorded take made and picked when its last part is in -- or, with **Filter before keeping**, the post waits: [filter, preview, Keep](#record-filter-preview-on-the-record-page) | `/projects/<p>/narration/record` (the Cut tab's **Record the narration**): the jump list (recorded / placeholder, n of N), the post's card and attachment, the teleprompter in its parts (the placeholder's `parts.json`, else the script split), the mic, the level, count-in; **Space** record / stop, **r** redo the part, **Enter** the next part (the post done: the next post), **n** / **p** posts; **Play it back**, **Play the placeholder**; **Use a sound file…** (a recording made elsewhere, for the part); the character it is read as, its direction, **▶ <voice> reads it** | — | `GET /api/report/post-narration/record?project&id[&n]` · `POST` multipart `{project, id, n, count, text, para, part}` · `POST {op: "discard", id, n}` · `POST {op: "finish", id, spans?}` | | a recorded take — your own read, part by part, kept as `take-<n>.recorded-<label>.wav`, picked | post bench, **record your read**: the mic, the level, **Record** (R) / **Stop** (S) / **Redo part** / **Next part**, **Keep** / **Discard**, **voice** (the label, default `operator`) | — | `POST` multipart `{project, id, label, script?, part[], text[], para[]}` | | a synthesized take — the editor's tts op, with direction | post bench, **Re-take with direction** (a note, a voice) | `umtool posts narrate <p> <item> --take [--note "…"] [--voice v] [--engine e] [--speed s]` · every missing one: `--all --take` | `op: "take"` → `{jobId, file}` · `GET ?project&id&job&file` keeps it when done | +| ANOTHER READING, tuned — the same words read again differently by Orpheus: `reading` N (0 the first; each one's seeds move, so a new cached file; the same N again the same file) and its `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; the rest Orpheus's defaults). The take records every tuning value and the reading it was made with (`tuning`, `reading`), from the editor's result; Kokoro and eSpeak NG ignore both and say so. Never changes the card's words | — (S3 of the re-tune plan adds the buttons) | `umtool posts narrate <p> <item> --take --reading 1 [--temperature t] [--top-p p] [--top-k k] [--min-p m] [--repeat-penalty r] [--chunk-takes n]` (one item's `--take` only) | `op: "take", tuning?, reading?` → `{jobId, file}` | | a THREAD READ — the post it answers (or every ancestor), the post it quotes, the linked posts and his words, each in its author's voice, parts cached, one take picked ([below](#pronunciation-and-voices-the-lexicon-the-voice-map-a-thread-read)) | — | `umtool posts narrate <p> <item> --take --thread [--parents 0\|all] [--skip-parent <id>]… [--voice-for <handle>=<voice>]… [--dry-run] [--json]` | — | | a derived take — a take run through the editor's `enhance` or `convert` (a stock synthetic voice: `zac`, `leah`, `orpheus:zac`, never a recording) into a NEW take, the original kept; enhance engines `deepfilternet` · `rnnoise`, convert `openvoice` · `seed-vc` (unnamed: the editor's settings.voice, recorded on the take); "not installed" until `archilyzer voice setup --engine <id>`; a convert's **pitch** ([below](#the-pitch-a-converted-read-lands-on)) | post bench, **run AI on take #n** (the op, an engine, a stock voice; for a convert on `seed-vc`, **pitch** and **semitones**) → **Run → a new take**; a derived take's **Re-run**; a recording's **Re-record** with **then re-run the chain** | `umtool posts narrate <p> <item> --derive <n> --op enhance\|convert [--engine e] [--voice v] [--pitch target\|source\|contour] [--semitones n]` | `op: "derive", from, op2, engine?, voice?, pitch?, semitones?` → `{jobId, file}` (or `{installed: false}`) · `GET ?project&id&job&file&derive=<from>&op=…` keeps it | | delete a take (soft: its file to the post's `.trash/`) | post bench, the take's **Delete** | `--delete <n>` | `op: "delete", take` (an index) | diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md @@ -4004,8 +4004,10 @@ It needs the cut's segments on disk; the README's "The podcast" has the rules. ## Narrated cards -A card's `narration` (`{text, voice?, engine?}`) is spoken by a stock synthetic -voice that the EDITOR synthesizes (`POST /api/ops/tts`); `render.narration` sets +A card's `narration` (`{text, voice?, engine?, tuning?, reading?}`) is spoken by a stock synthetic +voice that the EDITOR synthesizes (`POST /api/ops/tts`). An Orpheus card's `tuning` and `reading` +read the same words again differently (the editor's ranges; a card without them is asked and +keyed as before). `render.narration` sets the engine, voice, speed, level and the quiet around the words, and a card's `seconds: "auto"` is their length. umtool never synthesizes: when the manifest carries narration, the build chain gains a step before the build, diff --git a/umtool/e2e/fixtures/editor-stub.mjs b/umtool/e2e/fixtures/editor-stub.mjs @@ -1426,6 +1426,17 @@ const server = http.createServer((req, res) => { sha: id, sampleRate: 48000, speed: body.speed ?? 1, // The editor's own line, which umtool uses verbatim. disclosure: `Narration: synthetic voice (Kokoro-82M · ${body.voice ?? "af_heart"})`, + // Orpheus's report (lane orpheus-tuning): the effective tuning (the asked values over the defaults), the + // reading and its seed base -- always, as the editor gives them; another engine: a note when one was asked. + ...(body.engine === "orpheus" + ? { + tuning: { temperature: 0.55, top_p: 0.85, top_k: 50, min_p: 0, repeat_penalty: 1.2, takes: 3, ...(body.tuning ?? {}) }, + reading: body.reading ?? 0, + seedBase: 1234 + 9973 * (body.reading ?? 0), + } + : body.tuning || body.reading + ? { note: "Kokoro-82M has no sampler or seed: the tuning and reading were ignored (it reads the same every time)" } + : {}), }, }); json(res, 202, { ok: true, jobId: id }); diff --git a/umtool/e2e/post-narration.spec.ts b/umtool/e2e/post-narration.spec.ts @@ -259,6 +259,50 @@ test("the post bench: the lanes, a re-take with direction (the editor's tts job) if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "post-narration-bench-derived.png"), fullPage: true }); }); +test("ANOTHER READING, TUNED (lane orpheus-tuning): the take op sends a tuning and a reading to the editor's tts op, refuses one out of range in its words, and the take records what the editor says it was made with -- the card's own words untouched", async ({ page }) => { + const api = "/api/report/post-narration"; + const shownBefore = JSON.stringify((timeline().find((e) => e.id === "p-11") as Record<string, unknown>).text); + const takesBefore = narr("p-11").takes!.length; + const bad = await page.request.post(api, { data: { project: PROJECT, op: "take", id: "p-11", reading: -1 } }); + expect(bad.status()).toBe(400); + expect((await bad.json()).error).toMatch(/^"reading" must be a whole number from 0 to 99999/); + const badT = await page.request.post(api, { data: { project: PROJECT, op: "take", id: "p-11", tuning: { temperature: 3 } } }); + expect(badT.status()).toBe(400); + expect((await badT.json()).error).toBe('"tuning.temperature" must be a number from 0.1 to 1.5 (got 3)'); + expect(narr("p-11").takes).toHaveLength(takesBefore); + const res = await page.request.post(api, { data: { project: PROJECT, op: "take", id: "p-11", tuning: { temperature: 0.7, top_k: 40 }, reading: 2 } }); + expect(res.ok()).toBe(true); + const { jobId, file } = (await res.json()) as { jobId: string; file: string }; + // What the editor was asked: the tuning and the reading, as given. + const asked = (JSON.parse(readFileSync(path.join(FIXTURE, "editor-stub.requests.json"), "utf8")) as { route?: string; out?: string; tuning?: unknown; reading?: unknown; engine?: string }[]) + .filter((r) => r.route === "tts").at(-1)!; + expect(asked).toMatchObject({ engine: "orpheus", tuning: { temperature: 0.7, top_k: 40 }, reading: 2 }); + const q = `${api}?project=${encodeURIComponent(PROJECT)}&id=p-11&job=${encodeURIComponent(jobId)}&file=${encodeURIComponent(file)}`; + await expect.poll(async () => ((await (await page.request.get(q)).json()) as { state?: string }).state, { timeout: 20_000 }).toBe("done"); + const t = narr("p-11").takes!.at(-1) as Take & { tuning?: Record<string, number>; reading?: number }; + expect(t.file).toBe(file); + // Every value it was made with, the defaults included, and its reading: enough to make it again. + expect(t.tuning).toEqual({ temperature: 0.7, top_p: 0.85, top_k: 40, min_p: 0, repeat_penalty: 1.2, takes: 3 }); + expect(t.reading).toBe(2); + expect(JSON.stringify((timeline().find((e) => e.id === "p-11") as Record<string, unknown>).text)).toBe(shownBefore); + // An engine that ignores them (Kokoro): the answer does not claim a tuning or a reading, the take records none, and + // the editor's note comes back with the kept take so the bench can say it was ignored. + const k = await page.request.post(api, { data: { project: PROJECT, op: "take", id: "p-11", engine: "kokoro", voice: "af_heart", tuning: { temperature: 0.7 }, reading: 1 } }); + expect(k.ok()).toBe(true); + const kj = (await k.json()) as { jobId: string; file: string; engine: string; tuning?: unknown; reading?: unknown }; + expect(kj.engine).toBe("kokoro"); + expect("tuning" in kj).toBe(false); + expect("reading" in kj).toBe(false); + const kq = `${api}?project=${encodeURIComponent(PROJECT)}&id=p-11&job=${encodeURIComponent(kj.jobId)}&file=${encodeURIComponent(kj.file)}`; + let done: { state?: string; note?: string } = {}; + await expect.poll(async () => (done = (await (await page.request.get(kq)).json()) as typeof done).state, { timeout: 20_000 }).toBe("done"); + expect(done.note).toMatch(/has no sampler or seed: the tuning and reading were ignored/); + const kt = narr("p-11").takes!.at(-1) as Take & { tuning?: unknown; reading?: unknown }; + expect(kt.file).toBe(kj.file); + expect(kt.tuning).toBeUndefined(); + expect(kt.reading).toBeUndefined(); +}); + test.describe("the recording session", () => { test("record a long script part by part, play it back, Keep: a recorded take, picked, and it plays", async ({ page }) => { await page.setViewportSize({ width: 1440, height: 1400 }); diff --git a/umtool/lib/cli/groups.mjs b/umtool/lib/cli/groups.mjs @@ -1031,7 +1031,9 @@ export const GROUPS = [ " a re-run adds only posts not already in the cut", " umtool posts set-item <project> <item> [hold=<s>|off] [layout=sequence|grid] [redact=on|off|auto] [media.<i>.start=<s>]", " [media.<i>.end=<s>] [media.<i>.mute=on|off] [media.<i>.crop=x,y,w,h|off] [media.<i>.push=on|off] [--json]", - " umtool posts narrate <project> [--import | --list | <item> [--script \"…\"] [--take [--note \"…\"]] [--pick n] [--approve] [k=v …]", + " umtool posts narrate <project> [--import | --list | <item> [--script \"…\"] [--take [--note \"…\"] [--reading n]", + " [--temperature t] [--top-p p] [--top-k k] [--min-p m] [--repeat-penalty r] [--chunk-takes n]]", + " [--pick n] [--approve] [k=v …]", " | --all --draft-scripts | --all --take | --cut k=v …] a post read aloud (its takes: the editor's tts or yours)", " umtool posts narrate <project> <item> --take --thread [--parents 0|all] [--skip-parent <id>]… [--no-quoted]", " [--voice-for <handle>=<voice>]… [--dry-run] [--json] a THREAD READ: its context and his words in date", @@ -1083,7 +1085,7 @@ export const GROUPS = [ ["`posts roles <project> [<item> …] [--write] [--set <n>=<role>,…] [--json]`", "a narrated read **piece by piece** ([knobs.md](knobs.md#thread-reads-every-part-of-a-read-on-screen-while-it-is-said), [report-video.md](report-video.md#thread-reads)): the text each part of the picked take reads -- `parent:<i>`, `quoted`, `post`, `media:<i>` -- stored or inferred, what the card shows for each, and the build's guard (a part read off a post the card hides is refused). `--write` stores the inferred roles on the picked takes' parts (one write; the import stores them for every new take); `<item> --set n=role,…` sets parts' roles by hand (`off`: inferred again); a part out of range or an unknown role is refused (**exit 1**)"], ["`posts narrate <project> --import [--dry-run] [--json]` · `--list` · `<item> [--script \"…\"] [--pick <n>] [--approve\\|--unapprove] [--off\\|--on] [lead= tail= ramp= linger= clip=read\\|full wet= lowpass= duck=on\\|off short=hold\\|loop attach=under\\|after lufs= pace=fast\\|normal]` · `<item> --take [--note \"…\"] [--voice v] [--engine e] [--speed s] [--script \"…\"]` · `<item> --derive <n> --op enhance\\|convert [--engine e] [--voice v]` · `<item> --delete <n>` · `--all --draft-scripts [--force]` · `--all --take [--limit N]` · `--cut <k=v>…`", - "a **narrated post item** ([report-video.md](report-video.md#narrated-post-items), [knobs.md](knobs.md#a-narrated-post-item)): `--import` reads `narration/posts/index.json` (`[{id, entry, script, takes: [{file, engine, voice, seconds}], pick}]`, and a take's `take-<n>.parts.json`) into the cut in ONE write, measuring each take (length, loudness); a re-run adds only takes not there. `--take` asks the EDITOR for a new take (`POST /api/ops/tts`, its `out` the next `narration/posts/<postId>/take-<n>.<engine>-<voice>.wav`; a job, waited for; `ARCHILYZER_EDITOR_URL`, `WORKER_TOKEN`) and picks it, its `--note` kept with it; `--pick <n>` is the take's number as `--list` shows it. `--derive <n>` makes a NEW take from take n through the editor's `voice-enhance` / `voice-convert` op (a stock synthetic voice; \"not installed\" until the editor has the engine), the original kept; `--delete <n>` moves a take's file to the post's `.trash/`. A new script or pick takes the approval away. `--all --draft-scripts` writes every post's words as its script, VERBATIM (cleaned only to be spoken: a reply's leading @handles, links, emoji dropped -- a handle typed inside the message is kept and said \"at <handle>\", the lexicon first; `plan(s)` → plans, `w/` → with, `&` → and; paragraphs kept). `--cut` sets `render.postNarration` (and its read-follow: `follow=on\\|off`, `follow.dim=`, `follow.ease=`; its thread reads: `thread.parent=`, `thread.quoted=`, `thread.carry=`, `thread.reveal=`, `thread.shrink=`, `thread.dim=`, `thread.seconds=`, `thread.pan=`). Refused in the build's words (**exit 1**) A `--take` whose read says a slur the cut BEEPS is word-timed by the editor's transcription before it is kept -- never waited on: with the transcription lane held (as while Orpheus runs) the take is kept as read and the timing deferred (it says so, naming `posts narrate <p> <item> --words` to run after the release; the build refuses the take until then), and a timing still queued after 5 min is deferred the same way. An excerpted item (`posts set-item … excerpt=`) reads its spans."], + "a **narrated post item** ([report-video.md](report-video.md#narrated-post-items), [knobs.md](knobs.md#a-narrated-post-item)): `--import` reads `narration/posts/index.json` (`[{id, entry, script, takes: [{file, engine, voice, seconds}], pick}]`, and a take's `take-<n>.parts.json`) into the cut in ONE write, measuring each take (length, loudness); a re-run adds only takes not there. `--take` asks the EDITOR for a new take (`POST /api/ops/tts`, its `out` the next `narration/posts/<postId>/take-<n>.<engine>-<voice>.wav`; a job, waited for; `ARCHILYZER_EDITOR_URL`, `WORKER_TOKEN`) and picks it, its `--note` kept with it -- with `--reading N` it is ANOTHER READING of the same words (0 the first; Orpheus's seeds move, a new cached file) and `--temperature` `--top-p` `--top-k` `--min-p` `--repeat-penalty` `--chunk-takes` its tuning (the editor's ranges; one item's `--take` only, not `--thread` or `--all`), and the take records every tuning value and the reading it was made with; `--pick <n>` is the take's number as `--list` shows it. `--derive <n>` makes a NEW take from take n through the editor's `voice-enhance` / `voice-convert` op (a stock synthetic voice; \"not installed\" until the editor has the engine), the original kept; `--delete <n>` moves a take's file to the post's `.trash/`. A new script or pick takes the approval away. `--all --draft-scripts` writes every post's words as its script, VERBATIM (cleaned only to be spoken: a reply's leading @handles, links, emoji dropped -- a handle typed inside the message is kept and said \"at <handle>\", the lexicon first; `plan(s)` → plans, `w/` → with, `&` → and; paragraphs kept). `--cut` sets `render.postNarration` (and its read-follow: `follow=on\\|off`, `follow.dim=`, `follow.ease=`; its thread reads: `thread.parent=`, `thread.quoted=`, `thread.carry=`, `thread.reveal=`, `thread.shrink=`, `thread.dim=`, `thread.seconds=`, `thread.pan=`). Refused in the build's words (**exit 1**) A `--take` whose read says a slur the cut BEEPS is word-timed by the editor's transcription before it is kept -- never waited on: with the transcription lane held (as while Orpheus runs) the take is kept as read and the timing deferred (it says so, naming `posts narrate <p> <item> --words` to run after the release; the build refuses the take until then), and a timing still queued after 5 min is deferred the same way. An excerpted item (`posts set-item … excerpt=`) reads its spans."], ["`posts narrate <project> <item> --take --thread [--parents 0\\|all\\|none\\|<n>] [--skip-parent <id\\|parent:i>]… [--no-quoted] [--no-linked] [--read-seen] [--voice-for <handle>=<voice>]… [--voice v] [--engine e] [--speed s] [--no-screens] [--line-take screen:<id>:<line>=<n>]… [--note \"…\"] [--force] [--no-hold] [--dry-run] [--json]`", "a **THREAD READ** as one command ([knobs.md](knobs.md#pronunciation-and-voices-the-lexicon-the-voice-map-a-thread-read), `lib/report/postThreadRead.mjs`): the post it answers (`--parents all`: every ancestor; `<n>`: parents 0..n; `none`), the post it quotes and the posts it links to, then his words, in DATE order, each in its author's voice (`--voice-for`, then the item's own character, this video's characters and voice map, the cast: `cast project`; his own: the narrator's) and at its character's speed (its synthetic preset's; `--speed`: every part at that one; Orpheus has none; a part at another speed is another cached part), the redaction, the slur filter (a beep is skipped: a joined read is not word-timed) and the lexicon (`posts say`) applied. A parent or quoted post the item before already shows is not read again (`--read-seen`: it is). Each part is synthesized ONCE by the editor's tts op into `narration/parts-cache/<sha1(voice\\|text)>.wav` (the transcription lane held meanwhile, only if it was not; `--no-hold`: left alone), joined (0.8 s between pieces, 0.6 between paragraphs, 0.25 inside one) into `take-<n>.<engine>-thread.wav` with `take-<n>.parts.json`, saved with its parts' roles, its lexicon and how it was asked (`read`) and PICKED — one write (one undo point). `--dry-run`: the pieces, voices and parts (cached or not), nothing asked. Already up to date (same words and voices): nothing done, **exit 0** (`--force`: again). **`--post-take <n>`**: his OWN line is the item's take n (as `--list` numbers them) -- a recording, or one converted to his character's voice -- not synthesized; the context pieces are, in their authors' voices, and each part of the new take records where it came from (a synthesized part its parts-cache file and voice; the take's part its file and `take`: that take's id; the read's `postTake`). A thread take, or one whose file is gone: **exit 1**. A part not synthesized: **exit 1** (the parts made stay cached; run it again); `--json` prints `{ok: false, error}` too. A usage error: **exit 2** Its SCREENS (`posts screen`) are read after his words, each line in its speaker's voice (`--no-screens`: left out); `--line-take screen:<id>:<line>=<n>` takes a line from the item's take n as `--post-take` does his own"], ["`posts say <project> [ls] [--item <id>]` · `add <word\\|phrase> \"<spoken>\" [--case] [--item <id>] [--note \"…\"]` · `remove <word\\|n> [--item <id>]` · `try \"<text>\" [--item <id>]` · `stale` `[--json]`", diff --git a/umtool/lib/cli/verbs.mjs b/umtool/lib/cli/verbs.mjs @@ -523,7 +523,11 @@ function posts() { p("set-item", "draft", "a post item's knobs", [item(), pairs({ help: "hold=4, layout=grid, media.0.start=2 …" }), inTake()], POST_ITEM), p("narrate", "draft", "a post item's narration: script, takes, pick, approve, mix", [ item({ required: false, help: "the post item (none: --list, --import, --all or --cut)" }), opt("--script", { type: "text" }), bool("--take", "a new read (the editor's tts)"), opt("--note"), - opt("--voice"), opt("--engine"), num("--speed"), num("--pick"), bool("--approve"), bool("--unapprove"), bool("--off"), bool("--on"), + opt("--voice"), opt("--engine"), num("--speed"), + num("--reading", { help: "with --take: another reading of the same words, 0-99999 (0 = the first)" }), num("--temperature", { help: "with --take: Orpheus's tuning, 0.1-1.5" }), + num("--top-p", { help: "with --take: 0.05-1" }), num("--top-k", { help: "with --take: 0-200" }), num("--min-p", { help: "with --take: 0-0.5" }), + num("--repeat-penalty", { help: "with --take: 1-2" }), num("--chunk-takes", { help: "with --take: the tries a sentence gets, 1-6" }), + num("--pick"), bool("--approve"), bool("--unapprove"), bool("--off"), bool("--on"), bool("--thread", "with --take: a thread read"), opt("--parents"), num("--post-take", { help: "with --thread: his own line is this take of the item (as --list numbers them)" }), bool("--words", "the picked take's word timings"), bool("--import"), bool("--list"), bool("--all"), bool("--draft-scripts"), num("--limit"), bool("--force"), file("--recording", { help: "a person's recording (a file of the project) made the read" }), opt("--as"), pick("--pitch", ["target", "source", "contour"], { help: "a convert's pitch (--recording, --derive)" }), num("--semitones", { help: "-12…12, moves a followed pitch" }), dry(), diff --git a/umtool/lib/report/cast.test.mjs b/umtool/lib/report/cast.test.mjs @@ -243,6 +243,24 @@ test("rereadPlan: a thread read's own options kept, the changed author's overrid assert.equal(plan.skipped[0].id, "p-8"); }); +test("rereadPlan: a single take's own tuning and reading are asked again (lane orpheus-tuning); defaults and thread reads add nothing", () => { + const made = (o) => ({ temperature: 0.55, top_p: 0.85, top_k: 50, min_p: 0, repeat_penalty: 1.2, takes: 3, ...o }); + const m = { timeline: [ + { type: "post", id: "p-1", handle: "x", narration: { takes: [{ file: "a.wav", engine: "orpheus", voice: "zac", tuning: made({ temperature: 0.7 }), reading: 2 }], pick: 0 } }, + { type: "post", id: "p-2", handle: "x", narration: { takes: [{ file: "b.wav", engine: "orpheus", voice: "zac", tuning: made({}), reading: 0 }], pick: 0 } }, + { type: "post", id: "p-3", handle: "x", narration: { takes: [{ file: "c.wav", engine: "orpheus", voice: "zac", speed: 1.2, speedAsked: true, tuning: made({ top_k: 40, takes: 5 }), reading: 0 }], pick: 0 } }, + { type: "post", id: "p-4", handle: "x", narration: { takes: [{ file: "d.wav", engine: "orpheus", voice: "zac", tuning: made({ temperature: 0.9 }), reading: 3, read: { kind: "thread" } }], pick: 0 } }, + ] }; + const drift = (id, thread = false) => ({ id, handle: "x", role: "post", reads: "orpheus:zac", want: "orpheus:leah", kind: "tts", thread }); + const plan = rereadPlan("p", m, [drift("p-1"), drift("p-2"), drift("p-3"), drift("p-4", true)], ["x"]); + assert.deepEqual(plan.items.map((x) => x.argv.slice(4)), [ + ["--take", "--reading", "2", "--temperature", "0.7"], + ["--take"], + ["--take", "--speed", "1.2", "--top-k", "40", "--chunk-takes", "5"], + ["--take", "--thread"], + ]); +}); + test("an audition: candidates checked, synthesized once, levelled, scored for closeness to the real voice", async () => { assert.throws(() => candidatesOf(["/home/me/voice.wav"]), /never a candidate/); assert.throws(() => candidatesOf(["a", "b", "c", "d", "e", "f", "g"].map((v) => `kokoro:${v}`)), /at most 6/); diff --git a/umtool/lib/report/castProject.mjs b/umtool/lib/report/castProject.mjs @@ -13,6 +13,7 @@ import { shownNameOf, speakerFor, takeReads, voiceDrift, ENGINE_WEIGHT, } from "umtool-report-to-video/cast"; import { characterLines } from "./castAudition.mjs"; +import { tuningArgvOf } from "./readTuning.mjs"; const str = (v) => (typeof v === "string" ? v : ""); @@ -220,9 +221,10 @@ export function rereadPlan(projectId, manifest, drift, handles) { const takes = e?.narration?.takes ?? []; const t = takes[Number.isInteger(e?.narration?.pick) ? e.narration.pick : 0] ?? null; // A single take's own speed is asked again -- an old read never comes back at another speed -- unless it came - // from the character's preset or the item (that is what a re-read takes anew). + // from the character's preset or the item (that is what a re-read takes anew). Its own tuning and reading too + // (readTuning.mjs: what is not Orpheus's default) -- a reading picked by ear is read again the same way. const keepSpeed = !r.thread && typeof t?.speed === "number" && t.speed !== 1 && t.speedAsked !== "preset" && t.speedAsked !== "item"; - const argv = ["posts", "narrate", projectId, r.id, "--take", ...(r.thread ? ["--thread", ...threadArgvOf(t?.read, { handles: [...want], author: e?.handle, takes })] : keepSpeed ? ["--speed", String(t.speed)] : [])]; + const argv = ["posts", "narrate", projectId, r.id, "--take", ...(r.thread ? ["--thread", ...threadArgvOf(t?.read, { handles: [...want], author: e?.handle, takes })] : [...(keepSpeed ? ["--speed", String(t.speed)] : []), ...tuningArgvOf(t)])]; return { ...r, take: t?.file ?? null, argv }; }); return { items, skipped }; diff --git a/umtool/lib/report/postNarration.test.mjs b/umtool/lib/report/postNarration.test.mjs @@ -8,7 +8,7 @@ import { tmpdir } from "node:os"; import path from "node:path"; import { after, test } from "node:test"; import { postsCommand } from "./postsCli.mjs"; -import { importPatches, makeTake, mixPatchOf, pitchFlags } from "./postNarrationCli.mjs"; +import { importPatches, makeTake, mixPatchOf, pitchFlags, tunedOfResult, tuningFlags } from "./postNarrationCli.mjs"; import { fitPostItem, rmsFrames, scanAttachment, scoreWindows } from "./postFit.mjs"; import { manifestToken, updatePostNarration } from "./manifest.mjs"; import { postItemPlan } from "umtool-report-to-video/post-item"; @@ -167,6 +167,81 @@ test("a take with direction: asked of the editor (stubbed), written into the pro assert.equal(r2.take.file, "narration/posts/1/take-2.orpheus-zac.wav"); }); +test("ANOTHER READING, TUNED (lane orpheus-tuning): --reading and the tuning are sent as asked, the take records what the editor says, and an ask without them is the ask it always was", async () => { + const p = await project("tr", [item("1", { narration: { script: "read me" } })]); + const asked = []; + const made = { temperature: 0.7, top_p: 0.85, top_k: 50, min_p: 0, repeat_penalty: 1.2, takes: 3 }; + const ask = async (body) => { + asked.push(body); + wav(body.out, 1.2); + // The editor's report (ttsFile.ts): every value it was made with, the reading and its seed base. + return { jobId: `job-${asked.length}`, result: { wav: body.out, engine: body.engine, voice: body.voice, seconds: 1.2, ...(body.engine === "orpheus" ? { tuning: { ...made, ...(body.tuning ?? {}), temperature: body.tuning?.temperature ?? 0.55 }, reading: body.reading ?? 0, seedBase: 1234 + 9973 * (body.reading ?? 0) } : {}) } }; + }; + const plain = await makeTake(p, (await manifest(p)).timeline[0], { ask }); + assert.deepEqual(Object.keys(asked[0]).sort(), ["engine", "out", "text", "voice"], "no tuning asked: none sent"); + assert.deepEqual(plain.take.tuning, { ...made, temperature: 0.55 }); + assert.equal(plain.take.reading, 0); + const r = await makeTake(p, (await manifest(p)).timeline[0], { tuning: { temperature: 0.7 }, reading: 2, ask }); + assert.deepEqual(asked[1].tuning, { temperature: 0.7 }); + assert.equal(asked[1].reading, 2); + assert.deepEqual(r.take.tuning, made); + assert.equal(r.take.reading, 2); + const n = (await manifest(p)).timeline[0].narration; + assert.deepEqual({ tuning: n.takes[1].tuning, reading: n.takes[1].reading }, { tuning: made, reading: 2 }); + // The card's own words are never the read's: untouched. + assert.equal((await manifest(p)).timeline[0].text, item("1").text); + // A take's tuning is checked in the editor's ranges when it is written. + await assert.rejects( + updatePostNarration(p.dir, "p-1", { addTake: { ...n.takes[1], file: "narration/posts/1/take-9.orpheus-zac.wav", tuning: { temperature: 9 }, reading: -1 } }, { token: await manifestToken(p.dir) }), + (err) => /takes\[2\]\.tuning\.temperature must be a number from 0\.1 to 1\.5 \(got 9\)/.test(JSON.stringify(err.errors ?? err.message)) && /takes\[2\]\.reading must be a whole number from 0 to 99999/.test(JSON.stringify(err.errors ?? err.message)), + ); + // An engine without a sampler: the editor's note is said, the take records no tuning. + const notes = []; + const k = await makeTake(p, (await manifest(p)).timeline[0], { engine: "kokoro", voice: "af_heart", reading: 1, ask: async (body) => { const x = await ask(body); return { ...x, result: { ...x.result, note: "Kokoro-82M has no sampler or seed: the tuning and reading were ignored" } }; }, emit: (_ev, f) => notes.push(f.message) }); + assert.equal(k.take.tuning, undefined); + assert.equal(k.take.reading, undefined); + assert.ok(notes.some((m) => /has no sampler or seed/.test(m)), notes.join("\n")); +}); + +test("a field a later editor adds to its tuning is not copied: the take is still written (its validator knows only today's)", async () => { + const made = { temperature: 0.7, top_p: 0.85, top_k: 50, min_p: 0, repeat_penalty: 1.2, takes: 3 }; + // An unknown field is left out, and so is a known one that is not a number. + const { top_k: _k, ...noTopK } = made; + assert.deepEqual(tunedOfResult({ tuning: { ...made, mirostat: 2, top_k: "50" }, reading: 1 }), { tuning: noTopK, reading: 1 }); + assert.deepEqual(tunedOfResult({ reading: -1 }), {}); + assert.deepEqual(tunedOfResult(null), {}); + const p = await project("tn", [item("1", { narration: { script: "read me" } })]); + const ask = async (body) => { + wav(body.out, 1); + return { jobId: "j", result: { wav: body.out, engine: "orpheus", voice: "zac", seconds: 1, tuning: { ...made, mirostat: 2 }, reading: 0, seedBase: 1234 } }; + }; + const r = await makeTake(p, (await manifest(p)).timeline[0], { ask }); + assert.deepEqual(r.take.tuning, made); + assert.deepEqual((await manifest(p)).timeline[0].narration.takes[0].tuning, made); +}); + +test("the tuning flags are quantised as the editor quantises them", () => { + const s = (o) => (f) => o[f] ?? null; + assert.deepEqual(tuningFlags(s({ "--temperature": "0.7000000000000001", "--min-p": "-0" })).tuning, { temperature: 0.7, min_p: 0 }); + assert.equal(tuningFlags(s({ "--temperature": "1.5004" })).tuning.temperature, 1.5); +}); + +test("the tuning flags: refused out of range in the flag's words, and anywhere but one item's --take", async () => { + await project("tf", [item("1", { narration: { script: "read me" } })]); + for (const [args, re] of [ + [["narrate", "tf", "p-1", "--take", "--top-p", "3"], /--top-p must be a number from 0\.05 to 1 \(got 3\)/], + [["narrate", "tf", "p-1", "--take", "--chunk-takes", "2.5"], /--chunk-takes must be a whole number from 1 to 6/], + [["narrate", "tf", "p-1", "--take", "--reading", "-2"], /--reading must be a whole number from 0 to 99999/], + [["narrate", "tf", "p-1", "--reading", "1"], /--reading go with one item's --take/], + [["narrate", "tf", "p-1", "--take", "--thread", "--temperature", "0.7"], /--temperature go with one item's --take .* a thread read and --all --take do not take them/], + [["narrate", "tf", "--all", "--take", "--reading", "1"], /--reading go with one item's --take/], + ]) { + const r = await cli(args); + assert.notEqual(r.code, 0, args.join(" ")); + assert.match(r.err, re, `${args.join(" ")}: ${r.err}`); + } +}); + test("THE BEST PART: the scorer prefers a loud burst in the middle over the start, and snaps to a cut near it", () => { const rms = Array.from({ length: 120 }, (_, i) => (i >= 60 && i < 80 ? 0.5 : 0.01)); const w = scoreWindows({ rms, duration: 12, L: 3 }); diff --git a/umtool/lib/report/postNarrationCli.mjs b/umtool/lib/report/postNarrationCli.mjs @@ -9,6 +9,7 @@ // umtool posts narrate <p> <item> one item's // umtool posts narrate <p> <item> --script "…" set (replace) the script // umtool posts narrate <p> <item> --take [--note "…"] [--voice v] [--engine e] [--speed s] [--script "…"] +// [--reading N] [--temperature t] [--top-p p] [--top-k k] [--min-p m] [--repeat-penalty r] [--chunk-takes n] // a new take, asked of the editor (a job; waits) // umtool posts narrate <p> <item> --pick <n> | --approve | --unapprove | --off | --on // umtool posts narrate <p> <item> k=v … this post's mix: lead tail ramp linger clip wet lowpass duck short attach lufs rate @@ -35,6 +36,8 @@ import { projectRedaction } from "./postRedaction.mjs"; import { readManifest } from "../projects/report.mjs"; import { withEditNotes } from "./edit-guard.mjs"; import { manifestToken, updatePostNarration, updatePostNarrationRender, updatePostNarrations } from "./manifest.mjs"; +import { TUNING_FLAGS } from "./readTuning.mjs"; +import { TTS_TUNING_FIELDS, quantizeTtsTuningValue, ttsReadingError, ttsTuningValueError } from "yt-dlp-transcript-common/lib/ttsTuning.mjs"; const execFileP = promisify(execFile); const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); @@ -45,6 +48,7 @@ export const NARRATE_USAGE = [ "usage: umtool posts narrate <project> --import [--dry-run] [--json]", " umtool posts narrate <project> --list [--json]", " umtool posts narrate <project> <item> [--script \"…\"] [--take [--note \"…\"] [--voice v] [--engine e] [--speed s]]", + " [--reading N] [--temperature t] [--top-p p] [--top-k k] [--min-p m] [--repeat-penalty r] [--chunk-takes n]", " [--pick <n>] [--approve|--unapprove] [--off|--on] [lead=… tail=… ramp=… linger=… clip=read|full", " wet=… lowpass=… duck=on|off short=hold|loop attach=under|after lufs=… rate=… pace=fast|normal] [--json]", " umtool posts narrate <project> <item> --recording <file> [--as <character>] [--no-clean|--clean] [--no-trim|--trim] [--no-convert]", @@ -91,6 +95,12 @@ export const NARRATE_USAGE = [ " nothing again; --discard-preview removes it. --events: its progress as one JSON object a line.", " --speed <s> (--take, --take --thread): the speed the read is asked at (0.5-2; Orpheus has none) -- default the", " item's own, else its character's (the synthetic preset's: umtool cast set <id> --speed). A thread read: every part.", + " --reading N (--take): ANOTHER READING of the same words -- 0 the first (the default), 1, 2, … each read anew by", + " Orpheus (its seeds move; a new cached file), the same N again the same file. --temperature (0.1-1.5) --top-p", + " (0.05-1) --top-k (0-200) --min-p (0-0.5) --repeat-penalty (1-2) --chunk-takes (1-6, the tries a sentence gets):", + " Orpheus's TUNING for this read, any of them, the rest its defaults. The take records the tuning (every value) and", + " the reading it was made with. Kokoro and eSpeak NG ignore both (the editor says so). One item's --take only: not", + " --thread, not --all.", " --post-take <n> (--take --thread): his own line is the item's take n (as --list numbers them: a recording, or one", " converted to his character's voice), not synthesized -- the context around it is; each part records where it came from.", " --derive <n> --op enhance|convert [--engine e] [--voice v]: a NEW take made from take n by the editor's op", @@ -351,7 +361,7 @@ export async function transcriptionLaneHeld() { } } -export async function makeTake(project, e, { script = null, note = null, engine = null, voice = null, speed = null, render = {}, emit = () => {}, editor = null, ask = null, askOp = null, redaction = undefined, laneHeld = null, timingDeadlineMs = BEEP_TIMING_DEADLINE_MS } = {}) { +export async function makeTake(project, e, { script = null, note = null, engine = null, voice = null, speed = null, tuning = null, reading = null, render = {}, emit = () => {}, editor = null, ask = null, askOp = null, redaction = undefined, laneHeld = null, timingDeadlineMs = BEEP_TIMING_DEADLINE_MS } = {}) { const k = postNarrationKnobs(e, render); const words = String(script ?? e.narration?.script ?? "").trim(); if (!words) throw new NarrateError(`${e.id} has no script to read (--script "…", or --all --draft-scripts)`); @@ -377,8 +387,13 @@ export async function makeTake(project, e, { script = null, note = null, engine // pronunciation lexicon said its way (post-say.mjs) -- the script itself is kept as written. const red = redaction !== undefined ? redaction : await projectRedaction(project.dir, (await readManifest(project.dir)) ?? {}); const said = spokenRead(words, e, red); - const ttsBody = (text) => ({ text, engine: eng, voice: vox, out, ...(spd !== null && eng !== "orpheus" ? { speed: spd } : {}) }); + // Its tuning and reading (--reading, --temperature, …): sent only when asked -- an ask without them is the one it always was. + const ttsBody = (text) => ({ + text, engine: eng, voice: vox, out, ...(spd !== null && eng !== "orpheus" ? { speed: spd } : {}), + ...(tuning && Object.keys(tuning).length ? { tuning } : {}), ...(reading !== null ? { reading } : {}), + }); let { jobId, result } = await askTts(ttsBody(said.text), { ...(editor ? { editor } : {}), emit }); + if (result?.note) emit("note", { message: `${e.id}: ${result.note}` }); if (!(await stat(out).catch(() => null))?.isFile()) throw new NarrateError(`the editor's job ${jobId} finished but ${rel} is not there (its result names ${result?.wav ?? "no file"})`); // A BEEP needs the slur's time: the take is word-timed now (the editor's transcription). When that cannot be // done, the read is synthesized again with the slur left out -- a published take never says one it cannot cover. @@ -421,6 +436,9 @@ export async function makeTake(project, e, { script = null, note = null, engine // character's preset (drift when that changes). No speed asked: no key. ...(spd !== null && eng !== "orpheus" ? { speedAsked: speed !== null ? true : e.narration?.speed != null ? "item" : "preset" } : {}), ...(Number.isFinite(m.lufs) ? { lufs: m.lufs } : {}), jobId, + // What it was made with, as the editor's result says it (Orpheus: every tuning value and the reading), so it can be + // made again exactly; an engine without a sampler reports neither. + ...tunedOfResult(result), // What its audio does with the slurs the script holds (post-slurs.mjs), and its words when timed for a beep. ...(slurs ? { slurs } : {}), ...(timed ? { words: timed } : {}), // The pronunciation entries it said (post-say.mjs; `umtool posts say <p> stale` reads them). @@ -434,6 +452,56 @@ export async function makeTake(project, e, { script = null, note = null, engine } /** + * The tuning and reading a tts result says a take was made with (Orpheus's), as take keys; `{}` for any other engine. + * Only the known tuning fields are copied, as numbers: a field a later editor adds never makes the take's write (its + * validator) fail after the audio exists. + */ +export function tunedOfResult(result) { + const tuning = {}; + if (isObj(result?.tuning)) { + for (const k of TTS_TUNING_FIELDS) if (typeof result.tuning[k] === "number" && Number.isFinite(result.tuning[k])) tuning[k] = result.tuning[k]; + } + return { + ...(Object.keys(tuning).length ? { tuning } : {}), + ...(Number.isInteger(result?.reading) && result.reading >= 0 ? { reading: result.reading } : {}), + }; +} + +// The flags that make a read's tuning (readTuning.mjs, which the cast's re-reads share). +export { TUNING_FLAGS } from "./readTuning.mjs"; + +/** + * `--reading N` and the tuning flags as a take asks them: `{ tuning, reading, flags }` (the flags given), or null when + * none is. A value the tts op would refuse is refused here, in the flag's name (lib/ttsTuning.mjs: the same ranges). + */ +export function tuningFlags(str) { + const flags = []; + const tuning = {}; + const num = (flag) => { + const raw = str(flag); + if (raw === null) return null; + flags.push(flag); + return String(raw).trim() === "" ? Number.NaN : Number(raw); + }; + for (const [flag, field] of Object.entries(TUNING_FLAGS)) { + const raw = num(flag); + if (raw === null) continue; + // Quantised as the editor's tts op quantises (3 places, -0 as 0), then checked. + const v = quantizeTtsTuningValue(field, raw); + const err = ttsTuningValueError(field, v, flag); + if (err) throw new NarrateError(err.replace(/ \(got NaN\)$/, ` (got ${str(flag) || "nothing"})`)); + tuning[field] = v; + } + const reading = num("--reading"); + if (reading !== null) { + const err = ttsReadingError(reading, "--reading"); + if (err) throw new NarrateError(err.replace(/got NaN\)$/, `got ${str("--reading") || "nothing"})`)); + } + if (!flags.length) return null; + return { tuning: Object.keys(tuning).length ? tuning : null, reading, flags }; +} + +/** * A just-made take's WORD TIMINGS (for a beep over a slur it says): the editor's * transcription of its file, aligned to the script it read (word-zoom.mjs * scriptWordTimes) -- `posts narrate --words`' way, before the take is kept. @@ -461,6 +529,11 @@ export async function narrateCommand(project, words, flags, { json = false, dryR const pairs = words.filter((w) => /^[A-Za-z][A-Za-z.]*=/.test(w)); const ref = words.find((w) => !/^[A-Za-z][A-Za-z.]*=/.test(w)) ?? null; const write = async (fn) => withEditNotes(project, async () => fn(await manifestToken(project.dir))); + // A read's tuning and reading are one item's new take's (not a thread read's, not --all's: S1 of the re-tune plan). + const tuned = tuningFlags(str); + if (tuned && !(flags.has("--take") && !flags.has("--thread") && !flags.has("--all") && ref)) { + throw new NarrateError(`${tuned.flags.join(", ")} go with one item's --take (umtool posts narrate <p> <item> --take --reading 1); a thread read and --all --take do not take them`); + } if (flags.has("--import")) { const idxFile = path.join(project.dir, ...NARRATION_INDEX.split("/")); @@ -710,10 +783,10 @@ export async function narrateCommand(project, words, flags, { json = false, dryR if (flags.has("--take")) { const r = await makeTake(project, e, { script: str("--script"), note: str("--note"), engine: str("--engine"), voice: str("--voice"), - speed: speedFlag(str), render, emit: (_ev, f) => !json && f?.message && out(f.message), + speed: speedFlag(str), ...(tuned ? { tuning: tuned.tuning, reading: tuned.reading } : {}), render, emit: (_ev, f) => !json && f?.message && out(f.message), }); if (json) out(JSON.stringify({ ok: true, id: e.id, take: r.take, narration: r.result.narration, token: r.result.token }, null, 2)); - else out(`${e.id}: take ${r.take.file} (${r.take.seconds} s), picked${r.take.note ? ` — note: ${r.take.note}` : ""}`); + else out(`${e.id}: take ${r.take.file} (${r.take.seconds} s), picked${r.take.note ? ` — note: ${r.take.note}` : ""}${tunedLabel(tuned)}`); return 0; } const patch = pairs.length ? mixPatchOf(pairs) : {}; @@ -853,6 +926,13 @@ export async function fitCommand(project, refs, { all = false, linger = null, js return 0; } +/** " — reading 2, temperature 0.7": what the flags asked of this read (the take records every value); "" for none. */ +function tunedLabel(tuned) { + if (!tuned) return ""; + const said = [...(tuned.reading !== null ? [`reading ${tuned.reading}`] : []), ...Object.entries(tuned.tuning ?? {}).map(([k, v]) => `${k} ${v}`)]; + return said.length ? ` — ${said.join(", ")}` : ""; +} + /** `--speed` as a read takes it (null: not given); a value the tts op would refuse is refused here, in the flag's name. */ function speedFlag(str) { const raw = str("--speed"); @@ -948,6 +1028,8 @@ export async function deriveTake(project, e, { from, op, engine = null, voice = ...(Number.isFinite(m.lufs) ? { lufs: m.lufs } : {}), ...(parts ? { parts } : {}), // Its audio is its source's words at its source's speed: what it said and where that speed came from, copied. ...(typeof t.speed === "number" ? { speed: t.speed } : {}), ...(t.speedAsked !== undefined ? { speedAsked: t.speedAsked } : {}), ...(typeof t.said === "string" ? { said: t.said } : {}), + // And the reading it was: the tuning and reading its source was synthesized with. + ...tunedOfResult(t), // A recording of a screen line stays that line's (and, as it, never picked). ...(isObj(t.screenLine) ? { screenLine: { ...t.screenLine } } : {}), }; diff --git a/umtool/lib/report/postsCli.mjs b/umtool/lib/report/postsCli.mjs @@ -199,7 +199,7 @@ export const POSTS_USAGE = [ " none: the rule as it stands", ].join("\n"); -const VALUED = new Set(["--in-take", "--set", "--attach", "--flag", "--author", "--id", "--crop", "--since", "--until", "--replies", "--order", "--limit", "--after", "--script", "--note", "--voice", "--engine", "--speed", "--pick", "--linger", "--derive", "--op", "--pitch", "--semitones", "--delete", "--match", "--target", "--occurrence", "--at", "--scale", "--hold", "--lead", "--ease", "--highlight", "--worker", "--without", "--drop-parts", "--text", "--place", "--rewind", "--zone", "--gap", "--from-scale", "--color", "--outline", "--outline-width", "--size", "--face", "--sfx", "--volume", "--bar", "--bar-style", "--tempo-for", "--tempo", "--parts", "--stretch", "--yell-gain", "--yell-style", "--pause", "--revoice", "--say", "--xfade", "--splice", "--parents", "--skip-parent", "--voice-for", "--item", "--recording", "--as", "--label", "--out", "--trim-span", "--post-take", "--line-take", "--from", "--media", "--kind", "--title", "--line", "--read", "--unread", "--by", "--ref"]); +const VALUED = new Set(["--in-take", "--set", "--attach", "--flag", "--author", "--id", "--crop", "--since", "--until", "--replies", "--order", "--limit", "--after", "--script", "--note", "--voice", "--engine", "--speed", "--reading", "--temperature", "--top-p", "--top-k", "--min-p", "--repeat-penalty", "--chunk-takes", "--pick", "--linger", "--derive", "--op", "--pitch", "--semitones", "--delete", "--match", "--target", "--occurrence", "--at", "--scale", "--hold", "--lead", "--ease", "--highlight", "--worker", "--without", "--drop-parts", "--text", "--place", "--rewind", "--zone", "--gap", "--from-scale", "--color", "--outline", "--outline-width", "--size", "--face", "--sfx", "--volume", "--bar", "--bar-style", "--tempo-for", "--tempo", "--parts", "--stretch", "--yell-gain", "--yell-style", "--pause", "--revoice", "--say", "--xfade", "--splice", "--parents", "--skip-parent", "--voice-for", "--item", "--recording", "--as", "--label", "--out", "--trim-span", "--post-take", "--line-take", "--from", "--media", "--kind", "--title", "--line", "--read", "--unread", "--by", "--ref"]); /** The valued flags that may be given more than once (each value kept, in order). */ const MULTI = new Set(["--skip-parent", "--voice-for", "--trim-span", "--line-take", "--line"]); const SLUG_RE = /^[A-Za-z0-9._-]+$/; diff --git a/umtool/lib/report/readTuning.mjs b/umtool/lib/report/readTuning.mjs @@ -0,0 +1,24 @@ +// A READ's Orpheus tuning and reading as umtool's words (lane orpheus-tuning): the flags `umtool posts narrate <p> +// <item> --take` takes for them, and the flags that ask a take's own again -- what a re-read keeps, as it keeps a +// take's own --speed. The ranges and the defaults are the editor's (yt-dlp-transcript-common/lib/ttsTuning.mjs). +// +// Plain ESM, pure. +import { ORPHEUS_DEFAULT_TAKES, normalizeTtsTuning } from "yt-dlp-transcript-common/lib/ttsTuning.mjs"; + +/** The flags that make a read's tuning, and the tuning field each sets. */ +export const TUNING_FLAGS = Object.freeze({ + "--temperature": "temperature", "--top-p": "top_p", "--top-k": "top_k", "--min-p": "min_p", "--repeat-penalty": "repeat_penalty", "--chunk-takes": "takes", +}); + +/** + * The flags that ask a take's tuning and reading again: `--reading N` when it was not the first reading, and a flag + * for each tuning value that is not Orpheus's default (the take records every value; `takes` against the settings' + * default). `[]` for a take made with the defaults, or one that records neither (another engine, an older take). + */ +export function tuningArgvOf(take) { + const a = []; + if (Number.isInteger(take?.reading) && take.reading > 0) a.push("--reading", String(take.reading)); + const off = normalizeTtsTuning(take?.tuning, { takes: ORPHEUS_DEFAULT_TAKES }); + for (const [flag, field] of Object.entries(TUNING_FLAGS)) if (off[field] !== undefined) a.push(flag, String(off[field])); + return a; +} diff --git a/umtool/report-to-video/narrate-via-editor.mjs b/umtool/report-to-video/narrate-via-editor.mjs @@ -9,7 +9,7 @@ // review plays it before anything is approved). // // Every card `narration` in the manifest (or in one cut of it, `--variant`) is -// one `POST /api/ops/tts` -- `{ text, engine, voice, speed }`, the engine and +// one `POST /api/ops/tts` -- `{ text, engine, voice, speed, tuning?, reading? }`, the engine and // voice always named (narration.mjs's defaults: kokoro · af_heart) -- all asked // up front, as one batch; then each job is followed (`GET /api/ops/job/<id>`) // to its end, and its log's `@@tts-result <json>` line names the WAV the @@ -18,8 +18,8 @@ // reads it from there. A narration already kept is not asked again; the editor // answers a repeat ask from its own cache too. // -// The ask's body keys are the editor's (`{text, engine, voice, speed}` of its -// `{text, file, voice, engine, speed, out}`); `out` is never sent -- the +// The ask's body keys are the editor's (`{text, engine, voice, speed, tuning?, +// reading?}` of its `{text, file, voice, engine, speed, out, tuning, reading}`); `out` is never sent -- the // editor writes into its own cache and its result names the file. Its result // line carries the disclosure ("Narration: synthetic voice (Kokoro-82M · // af_heart)"), which is kept with the narration and used verbatim. @@ -88,8 +88,15 @@ export function ttsResultIn(lines) { return found; } -/** The body one narration is asked with: its words, and the engine, voice and speed always named. */ -export const ttsBody = (n) => ({ text: n.text, engine: n.engine, voice: n.voice, speed: n.speed }); +/** + * The body one narration is asked with: its words, and the engine, voice and speed always named; its tuning and + * reading only when the card asks for them (narration.mjs), so a card without them is the same ask as before. + */ +export const ttsBody = (n) => ({ + text: n.text, engine: n.engine, voice: n.voice, speed: n.speed, + ...(n.tuning ? { tuning: n.tuning } : {}), + ...(n.reading > 0 ? { reading: n.reading } : {}), +}); /** * Ask the editor for every narration in `narrations` (narrationsOf) not yet @@ -124,7 +131,7 @@ export async function narrateCut({ narrations, dir, editor = editorFromEnv(), em }; // One batch: every ask posted before any is waited for. Two cards with the - // same words, voice and speed are one ask. + // same words, voice, speed, tuning and reading are one ask (one key). const pending = new Map(); // jobId -> { ns: narration[], last: status, place: line } const byKey = new Map(); for (const n of ask) { @@ -226,7 +233,7 @@ export async function narrateCut({ narrations, dir, editor = editorFromEnv(), em * `@@tts-result` of its log. `onJob(jobId)` is told the job's id as soon as * the editor answers (a caller that is stopped can say where it runs). * - * @param {{ text: string, engine?: string, voice?: string, speed?: number, out?: string }} body + * @param {{ text: string, engine?: string, voice?: string, speed?: number, out?: string, tuning?: Record<string, number>, reading?: number }} body * @param {{ editor?: { url: string, token: string }, emit?: (ev: string, f?: object) => void, pollMs?: number, onJob?: (id: string) => void }} [o] */ export async function askEditorTts(body, o = {}) { diff --git a/umtool/report-to-video/narrate.test.mjs b/umtool/report-to-video/narrate.test.mjs @@ -21,9 +21,9 @@ import { fileURLToPath } from "node:url"; import { buildVideo, cardEncodeArgs, narratedCardEncodeArgs, setProgressMode } from "./build-video.mjs"; import { MONO_BOLD_FONT_FILE, MONO_FONT_FILE } from "./brand.mjs"; -import { TTS_RESULT_MARKER, narrateCut, ttsResultIn } from "./narrate-via-editor.mjs"; +import { TTS_RESULT_MARKER, narrateCut, ttsBody, ttsResultIn } from "./narrate-via-editor.mjs"; import { narrationKey, narrationsOf } from "./narration.mjs"; -import { narrationDir, readNarrationRecord } from "./narration-store.mjs"; +import { keepNarration, narrationDir, readNarrationRecord } from "./narration-store.mjs"; const SCRIPT = path.join(path.dirname(fileURLToPath(import.meta.url)), "narrate-via-editor.mjs"); const haveFf = ["ffmpeg", "ffprobe"].every((b) => spawnSync(b, ["-version"]).status === 0); @@ -131,6 +131,34 @@ const maxVolume = (file) => { return m ? (m[1] === "-inf" ? -Infinity : Number(m[1])) : NaN; }; +test("the ask's body: engine, voice and speed always; a tuning and reading only when the card asks (lane orpheus-tuning)", () => { + const plain = { text: "Hi.", engine: "orpheus", voice: "zac", speed: 1, key: "k", id: "c1" }; + assert.deepEqual(ttsBody(plain), { text: "Hi.", engine: "orpheus", voice: "zac", speed: 1 }); + assert.deepEqual(ttsBody({ ...plain, tuning: { temperature: 0.7 }, reading: 2 }), { + text: "Hi.", engine: "orpheus", voice: "zac", speed: 1, tuning: { temperature: 0.7 }, reading: 2, + }); + const [n] = narrationsOf({ render: {}, timeline: [{ type: "card", id: "c1", seconds: "auto", narration: { text: "Hi.", engine: "orpheus", voice: "zac", reading: 1 } }] }); + assert.deepEqual(ttsBody(n), { text: "Hi.", engine: "orpheus", voice: "zac", speed: 1, reading: 1 }); +}); + +test("a kept narration records what Orpheus made it with (its known tuning fields, the reading, the seed base); one without still reads", { skip: !haveFf && "needs ffmpeg and ffprobe" }, async (t) => { + const root = mkdtempSync(path.join(tmpdir(), "narration-made-with-")); + t.after(() => rmSync(root, { recursive: true, force: true })); + const dir = narrationDir(root); + const src = path.join(root, "editor.wav"); + spawnSync("ffmpeg", ["-v", "error", "-y", "-f", "lavfi", "-i", "sine=f=220:d=1", "-ar", "48000", "-ac", "1", src]); + const n = { id: "c1", key: narrationKey({ text: "Hi.", engine: "orpheus", voice: "zac", speed: 1, reading: 2 }), text: "Hi.", engine: "orpheus", voice: "zac", speed: 1 }; + const made = { temperature: 0.7, top_p: 0.85, top_k: 50, min_p: 0, repeat_penalty: 1.2, takes: 3 }; + const rec = await keepNarration(dir, n, { wav: src, engine: "orpheus", voice: "zac", tuning: { ...made, someday: 1 }, reading: 2, seedBase: 21_180 }, { jobId: "j1" }); + assert.deepEqual({ tuning: rec.tuning, reading: rec.reading, seedBase: rec.seedBase }, { tuning: made, reading: 2, seedBase: 21_180 }); + assert.deepEqual((await readNarrationRecord(dir, n.key)).tuning, made); + // Kokoro's result carries none: neither does its record, and it reads as before. + const k = { ...n, id: "c2", key: narrationKey({ text: "Hi.", engine: "kokoro", voice: "af_heart", speed: 1 }), engine: "kokoro", voice: "af_heart" }; + const kr = await keepNarration(dir, k, { wav: src, engine: "kokoro", voice: "af_heart" }); + assert.ok(!("tuning" in kr) && !("reading" in kr) && !("seedBase" in kr)); + assert.equal((await readNarrationRecord(dir, k.key)).engine, "kokoro"); +}); + test("the result line is found anywhere on a log line, the last one winning", () => { assert.equal(ttsResultIn(["a", "b"]), null); assert.deepEqual(ttsResultIn([`${TTS_RESULT_MARKER}{"wav":"/a.wav"}`, `[12:00] ${TTS_RESULT_MARKER}{"wav":"/b.wav"}`]), { wav: "/b.wav" }); diff --git a/umtool/report-to-video/narration-store.mjs b/umtool/report-to-video/narration-store.mjs @@ -21,6 +21,7 @@ import { promisify } from "node:util"; import { disclosureLine, disclosureLines, narrationsOf } from "./narration.mjs"; import { postNarrationDisclosure } from "./post-narration.mjs"; import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; +import { TTS_TUNING_FIELDS } from "yt-dlp-transcript-common/lib/ttsTuning.mjs"; const execFileP = promisify(execFile); const FFMPEG = () => process.env.FFMPEG_BIN ?? "ffmpeg"; @@ -81,7 +82,8 @@ const sha256File = async (file) => createHash("sha256").update(await readFile(fi * @param {string} dir narrationDir(outRoot) * @param {{ id: string, key: string, text: string, engine: string, voice: string, speed: number }} n * @param {{ wav: string, seconds?: number, engine?: string, voice?: string, cached?: boolean, - * durationMs?: number, waitedMs?: number }} result the editor's `@@tts-result` + * durationMs?: number, waitedMs?: number, tuning?: Record<string, number>, reading?: number, + * seedBase?: number }} result the editor's `@@tts-result` * @param {{ jobId?: string }} [meta] * @returns the record */ @@ -116,6 +118,9 @@ export async function keepNarration(dir, n, result, { jobId = null } = {}) { lufs: lufs === null ? null : Number(lufs.toFixed(2)), sha256: await sha256File(wav), wav: path.basename(wav), + // What Orpheus made it with, as the editor says (every tuning value, the reading, its seed base), so the reading + // can be made again exactly. Absent for another engine, and in a record kept before (it still reads). + ...madeWith(result), editor: { jobId, cached: result.cached === true, @@ -136,6 +141,19 @@ export async function keepNarration(dir, n, result, { jobId = null } = {}) { return record; } +/** The editor's `tuning` (its known fields), `reading` and `seedBase`, as a record's keys; `{}` when it gave none. */ +function madeWith(result) { + const tuning = {}; + if (result?.tuning && typeof result.tuning === "object") { + for (const k of TTS_TUNING_FIELDS) if (typeof result.tuning[k] === "number" && Number.isFinite(result.tuning[k])) tuning[k] = result.tuning[k]; + } + return { + ...(Object.keys(tuning).length ? { tuning } : {}), + ...(Number.isInteger(result?.reading) && result.reading >= 0 ? { reading: result.reading } : {}), + ...(Number.isInteger(result?.seedBase) ? { seedBase: result.seedBase } : {}), + }; +} + /** * A cut's disclosure, from the narrations it keeps (`out/narration/`): the * editor's lines, each once, joined by `sep`; null when nothing is narrated. diff --git a/umtool/report-to-video/narration.mjs b/umtool/report-to-video/narration.mjs @@ -6,6 +6,12 @@ // { "type": "card", "id": "ch2", "seconds": "auto", "heading": "…", // "narration": { "text": "Six months later, the county said yes.", "voice": "af_heart" } } // +// An Orpheus card may carry its own `tuning` ({temperature, top_p, top_k, min_p, +// repeat_penalty, takes}, any of them) and `reading` (0 = the first; 1, 2, … +// read the same words again differently) -- the editor's tts op's, checked +// against the same ranges (yt-dlp-transcript-common/lib/ttsTuning.mjs). A card +// without them is asked, and keyed, exactly as before. +// // "render": { "narration": { "engine": "kokoro", "voice": "af_heart", "speed": 1, // "lufs": -17.7, "lead": 0.8, "tail": 0.8 } } // @@ -16,6 +22,7 @@ // filter and the disclosure line -- shared by the build, the lint, the deck's // estimate and the exports. No ffmpeg, no fs, no network. import { createHash } from "node:crypto"; +import { TTS_TUNING_FIELDS, normalizeTtsTuning, ttsReadingError, ttsTuningValueError } from "yt-dlp-transcript-common/lib/ttsTuning.mjs"; /** The engines a manifest may name (`orpheus` is refused by the editor until it lands there). */ export const NARRATION_ENGINES = Object.freeze(["kokoro", "orpheus", "espeak-ng"]); @@ -67,7 +74,7 @@ export const NARRATION_TAGS = Object.freeze(["laugh", "chuckle", "sigh", "cough" export const NARRATION_ENGINE_LABELS = Object.freeze({ kokoro: "Kokoro-82M", "espeak-ng": "eSpeak NG", orpheus: "Orpheus" }); const RENDER_KEYS = new Set(Object.keys(NARRATION_DEFAULTS)); -const CARD_KEYS = new Set(["text", "voice", "engine"]); +const CARD_KEYS = new Set(["text", "voice", "engine", "tuning", "reading"]); // A stock voice's id: `af_heart`, `bm_george`, `en-us` (espeak-ng). Never a path. const VOICE_RE = /^[A-Za-z0-9][A-Za-z0-9_.+-]{0,63}$/; const TAG_RE = /<([^<>]*)>/g; @@ -75,6 +82,41 @@ const TAG_RE = /<([^<>]*)>/g; const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v); const numIn = (v, [lo, hi]) => typeof v === "number" && Number.isFinite(v) && v >= lo && v <= hi; +/** + * A narration's tuning as it is asked and keyed: the editor's normaliser + * (lib/ttsTuning.mjs: quantised, a sampler value equal to Orpheus's default + * dropped, in the registry's order), or null when nothing is left -- so a card + * spelling a default asks and keys as one without it. `takes` is kept as + * written: its default is the editor's settings, which a cut cannot see. + */ +export function narrationTuningOf(tuning) { + const out = normalizeTtsTuning(tuning); + return Object.keys(out).length ? out : null; +} + +/** The problems with a tuning and a reading, as sentences, each naming where it is. */ +export function tuningProblems(tuning, reading, where) { + const out = []; + if (tuning !== undefined && tuning !== null) { + if (!isObj(tuning)) { + out.push(`${where}.tuning must be an object of ${TTS_TUNING_FIELDS.join(", ")}`); + } else { + for (const [k, v] of Object.entries(tuning)) { + if (!TTS_TUNING_FIELDS.includes(k)) out.push(`${where}.tuning.${k} is not a tuning field (${TTS_TUNING_FIELDS.join(", ")})`); + else if (v !== null) { + const p = ttsTuningValueError(k, v, `${where}.tuning.${k}`); + if (p) out.push(p); + } + } + } + } + if (reading !== undefined && reading !== null) { + const p = ttsReadingError(reading, `${where}.reading`); + if (p) out.push(p); + } + return out; +} + /** The text without its expressive tags, whitespace collapsed. */ export const stripNarrationTags = (text) => String(text ?? "").replace(TAG_RE, " ").replace(/\s+/g, " ").trim(); @@ -102,22 +144,28 @@ export function resolveNarration(entry, render) { if (!hasNarration(entry)) return null; const r = resolveNarrationRender(render); const n = entry.narration; + const tuning = narrationTuningOf(n.tuning); return { text: String(n.text ?? "").trim(), engine: n.engine ?? r.engine, voice: n.voice ?? r.voice, speed: r.speed, + // Only when asked: a card without them resolves -- and keys -- as it always did. + ...(tuning ? { tuning } : {}), + ...(Number.isInteger(n.reading) && n.reading > 0 ? { reading: n.reading } : {}), }; } /** * The content key of one narration: what the synthesized sound depends on. * The record and its copy of the sound are named by it, so a changed word, a - * different voice or speed is a new ask and the old one is never reused. + * different voice or speed is a new ask and the old one is never reused. A + * tuning or a reading is in it only when the card asks for one. */ -export function narrationKey({ text, engine, voice, speed }) { +export function narrationKey({ text, engine, voice, speed, tuning = null, reading = 0 }) { + const t = narrationTuningOf(tuning); return createHash("sha256") - .update(JSON.stringify({ v: 1, text: String(text), engine, voice, speed: Number(speed) })) + .update(JSON.stringify({ v: 1, text: String(text), engine, voice, speed: Number(speed), ...(t ? { tuning: t } : {}), ...(reading > 0 ? { reading } : {}) })) .digest("hex"); } @@ -209,7 +257,7 @@ export function validateNarration(whole) { continue; } if (!isObj(e.narration)) { - errors.push(`${where}.narration must be an object { text, voice?, engine? }`); + errors.push(`${where}.narration must be an object { text, voice?, engine?, tuning?, reading? }`); continue; } for (const k of Object.keys(e.narration)) { @@ -224,6 +272,7 @@ export function validateNarration(whole) { const p = voiceProblem(e.narration.voice); if (p) errors.push(`${where}.narration.${p}`); } + errors.push(...tuningProblems(e.narration.tuning, e.narration.reading, `${where}.narration`)); } if (e.seconds === "auto" && !hasNarration(e)) { errors.push(`${where}: seconds "auto" is the narration's length, and this entry has no narration`); diff --git a/umtool/report-to-video/narration.test.mjs b/umtool/report-to-video/narration.test.mjs @@ -95,6 +95,42 @@ test("the key moves with the words, the voice and the speed, and nothing else", assert.equal(list[0].key, list[1].key, "the same words, voice and speed are one sound"); }); +test("a card's tuning and reading: checked in the editor's ranges, asked and keyed only when set (lane orpheus-tuning)", () => { + // Captured on main 976efc77e, before the tuning: a card without one keys exactly as it did. + const base = { text: "The archive spoke.", engine: "orpheus", voice: "zac", speed: 1 }; + assert.equal(narrationKey(base), "11ec71a5326048c695cb4f228550747bdc6999b00a451b8a8fdb14754856c95d"); + assert.equal(narrationKey({ ...base, tuning: {}, reading: 0 }), narrationKey(base)); + const warm = narrationKey({ ...base, tuning: { temperature: 0.7 } }); + assert.notEqual(warm, narrationKey(base)); + assert.notEqual(narrationKey({ ...base, reading: 1 }), narrationKey(base)); + assert.notEqual(narrationKey({ ...base, reading: 1 }), narrationKey({ ...base, reading: 2 })); + // A card spelling a default -- or a default within rounding -- asks and keys as one without it (the editor's + // normaliser, lib/ttsTuning.mjs); takes is kept as written (its default is the editor's settings). + assert.equal(narrationKey({ ...base, tuning: { temperature: 0.55, top_p: 0.85, top_k: 50, min_p: -0, repeat_penalty: 1.2 } }), narrationKey(base)); + assert.equal(narrationKey({ ...base, tuning: { temperature: 0.550000001 } }), narrationKey(base)); + assert.equal(narrationKey({ ...base, tuning: { temperature: 0.7000000000000001 } }), warm); + assert.notEqual(narrationKey({ ...base, tuning: { takes: 3 } }), narrationKey(base)); + const spelled = resolveNarration(card({ narration: { text: "Six.", engine: "orpheus", tuning: { temperature: 0.55 }, reading: 0 } }), {}); + assert.ok(!("tuning" in spelled) && !("reading" in spelled)); + // The fields' order does not matter. + assert.equal(narrationKey({ ...base, tuning: { top_k: 40, temperature: 0.7 } }), narrationKey({ ...base, tuning: { temperature: 0.7, top_k: 40 } })); + const tuned = card({ narration: { text: "Six months later.", engine: "orpheus", voice: "zac", tuning: { temperature: 0.7 }, reading: 2 } }); + assert.deepEqual(validateNarration(M([tuned])), []); + const n = resolveNarration(tuned, {}); + assert.deepEqual({ tuning: n.tuning, reading: n.reading }, { tuning: { temperature: 0.7 }, reading: 2 }); + // Not asked: nothing added. + const plain = resolveNarration(card(), {}); + assert.ok(!("tuning" in plain) && !("reading" in plain)); + assert.deepEqual( + validateNarration(M([card({ narration: { text: "Words.", tuning: { temperature: 3, seed: 1 }, reading: -1 } })])), + [ + "timeline[0] k1.narration.tuning.temperature must be a number from 0.1 to 1.5 (got 3)", + "timeline[0] k1.narration.tuning.seed is not a tuning field (temperature, top_p, top_k, min_p, repeat_penalty, takes)", + "timeline[0] k1.narration.reading must be a whole number from 0 to 99999 (0 = the first reading; got -1)", + ], + ); +}); + test("seconds \"auto\": lead + words + tail, up to the tenth; a number is itself, and short when under", () => { assert.equal(narratedCardSeconds(3.21, {}), 4.9); // 0.8 + 3.21 + 0.8 = 4.81 -> 4.9 assert.equal(narratedCardSeconds(3.2, { narration: { lead: 1, tail: 1 } }), 5.2); diff --git a/umtool/report-to-video/post-narration.mjs b/umtool/report-to-video/post-narration.mjs @@ -34,6 +34,7 @@ import { followKnobErrors } from "./read-follow.mjs"; import { threadKnobErrors } from "./post-thread.mjs"; import { takeLexiconErrors } from "./post-say.mjs"; +import { tuningProblems } from "./narration.mjs"; /** The engines a post's narration may name (the editor's tts op). */ export const POST_NARRATION_ENGINES = Object.freeze(["orpheus", "kokoro", "espeak-ng"]); @@ -195,7 +196,9 @@ const ITEM_KEYS = new Set([...MIX_KEYS, "script", "excerpt", "engine", "voice", // `said`: what a synthesized read SAID when an anonymous handle made it differ from its script (post-anon.mjs; the // lint reads it); `speedAsked`: where its speed came from -- true (the command's --speed: kept as asked), "item" (the // item's own), "preset" (its character's: drift when that changes). Absent: unknown -- never speed drift. -const TAKE_KEYS = new Set(["file", "engine", "voice", "seconds", "script", "at", "note", "speed", "lufs", "jobId", "parts", "label", "source", "steps", "words", "slurs", "lexicon", "read", "said", "speedAsked", "screenLine"]); +// `tuning`, `reading` (lane orpheus-tuning): what an Orpheus take was made with, as the editor's result said it -- +// every tuning value (the defaults included) and the reading (0 = the first) -- so it can be made again exactly. +const TAKE_KEYS = new Set(["file", "engine", "voice", "seconds", "script", "at", "note", "speed", "lufs", "jobId", "parts", "label", "source", "steps", "words", "slurs", "lexicon", "read", "said", "speedAsked", "screenLine", "tuning", "reading"]); const STEP_KEYS = new Set(["op", "engine", "voice", "pitch", "semitones", "params", "ranAt", "job", "drop", "tempo", "spans", "pauses", "revoice"]); // `role` (post-thread.mjs): the text a part reads -- "post", "quoted", "parent:<i>", "media:<i>"; `voice`, `piece`: the batch's; // `engine`: the part's own when it is not the take's (a cast voice that names its engine: postThreadRead.mjs). @@ -657,6 +660,7 @@ export function validatePostNarration(e) { errors.push(...takeLexiconErrors(t.lexicon, `${tw}.lexicon`)); if (t.said !== undefined && (typeof t.said !== "string" || t.said.length > 50000)) errors.push(`${tw}.said must be the words its read said`); if (t.speedAsked !== undefined && t.speedAsked !== true && t.speedAsked !== "item" && t.speedAsked !== "preset") errors.push(`${tw}.speedAsked must be true, "item" or "preset"`); + errors.push(...tuningProblems(t.tuning, t.reading, tw)); if (t.read !== undefined && !(isObj(t.read) && t.read.kind === "thread" && JSON.stringify(t.read).length <= 4000)) errors.push(`${tw}.read must be {kind: "thread", …} (how the thread read was asked for)`); // A RECORDING OF ONE SCREEN LINE (postScreensCli.mjs `posts screen … record`, post-screens.mjs): the line it was // recorded for -- its screen, its index, its words as a read writes them, its speaker. Never the item's read.