Archilyzer · Source

archilyzer

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

commit 6e2572c1b95c80db6c73064023ed282acf53edc6
parent 17cfdb48f17c1e465883c88c60ff5d24b97cf869
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Fri,  6 Nov 2026 21:53:14 -0500

umtool: the cast -- characters' stock voices across projects, a layer under the project's voice map; every read asks the same function

<reports>/.umtool/cast.json (castStore.mjs: one writer, a token, undo points, a broken file never
overwritten) holds the characters that recur across projects: an id, a name, their handles, the
STOCK voice they read in ("kokoro:am_michael"), an optional convert target, the names their real
voice goes by in speakers.json (a reference, never a target), one narrator.

post-say.mjs voiceSourceOf/resolvePieceVoice: the read's override, the project's map, the CAST,
the narrator's, the map's "*", the default -- with where the voice came from. A voice may name
its engine (in the map too). The thread read asks it per piece and synthesizes each part with its
own engine (parts record theirs; the disclosure names both engines); a single post's take
(posts narrate --take, the bench's Re-take) asks the same function (readVoice.mjs), so a post
read alone and read with its thread agree. A derived take's voice is the bare stock voice.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
Mumtool/app/api/report/post-narration/route.ts | 13++++++++++---
Mumtool/components/projects/PronunciationPanel.tsx | 4++--
Aumtool/lib/report/castStore.mjs | 152+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/postSay.mjs | 30++++++++++++++++++++----------
Mumtool/lib/report/postThreadRead.mjs | 70++++++++++++++++++++++++++++++++++++++++++++++------------------------
Aumtool/lib/report/readVoice.mjs | 33+++++++++++++++++++++++++++++++++
Aumtool/report-to-video/cast.mjs | 250+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/cast.test.mjs | 107+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/package.json | 1+
Mumtool/report-to-video/post-narration.mjs | 16++++++++++++----
Mumtool/report-to-video/post-say.mjs | 80++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----------------
11 files changed, 696 insertions(+), 60 deletions(-)

diff --git a/umtool/app/api/report/post-narration/route.ts b/umtool/app/api/report/post-narration/route.ts @@ -17,6 +17,7 @@ import { withTakeScope } from "@/lib/report/takeScope.mjs"; import { isTakeId } from "@/lib/report/takes.mjs"; import { keepRecording, RECORD_LABEL_RE } from "@/lib/report/postRecord.mjs"; import { fitPostItem } from "@/lib/report/postFit.mjs"; +import { itemReadVoice } from "@/lib/report/readVoice.mjs"; import { projectRedaction } from "@/lib/report/postRedaction.mjs"; import { spokenRead } from "umtool-report-to-video/post-redact"; @@ -108,7 +109,7 @@ export async function GET(request: Request) { const voice = op === "convert" ? (q.get("voice") ?? vr.voice ?? null) : null; const partsRel = rel.replace(/\.wav$/, ".parts"); const derived = { - file: rel, engine: "derived", voice: voice ?? from.voice ?? "?", seconds: meas.seconds, source: { kind: "take", from: takeIdOf(from) }, + file: rel, engine: "derived", voice: (voice ? voice.split(":").pop() : null) ?? from.voice ?? "?", seconds: meas.seconds, source: { kind: "take", from: takeIdOf(from) }, steps: [{ op, ...(engine ? { engine } : {}), ...(voice ? { voice } : {}), ranAt: new Date().toISOString(), job }], script: from.script ?? script, at: new Date().toISOString(), jobId: job, ...(Number.isFinite(meas.lufs) ? { lufs: meas.lufs } : {}), ...(Array.isArray(from.parts) ? { parts: from.parts.map((p) => ({ ...p, file: `${partsRel}/p${String(p.n).padStart(2, "0")}.wav` })) } : {}), @@ -209,8 +210,14 @@ 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 }); - const engine = String(body.engine ?? e.narration?.engine ?? k.engine); - const voice = String(body.voice ?? e.narration?.voice ?? k.voice); + // The voice: the one asked for, the project's voice map, the CAST, the narrator's -- a single read's rule (readVoice.mjs). + const said = await itemReadVoice(r.project, e, { + render: (m.render ?? {}) as Record<string, unknown>, + engine: typeof body.engine === "string" && body.engine ? body.engine : null, + voice: typeof body.voice === "string" && body.voice ? body.voice : null, + }); + const engine = String(said.engine ?? k.engine); + const voice = String(said.voice ?? k.voice); const pid = postIdOf(e); const dir = path.join(r.project.dir, ...takesDirOf(pid).split("/")); await mkdir(dir, { recursive: true }); diff --git a/umtool/components/projects/PronunciationPanel.tsx b/umtool/components/projects/PronunciationPanel.tsx @@ -14,7 +14,7 @@ import { jobsHref } from "@/lib/hrefs"; // --------------------------------------------------------------------------- type Lex = { word: string; say: string; case?: boolean; item?: string; note?: string }; -type Author = { handle: string; items: number; context: number; voice: string; mapped: boolean }; +type Author = { handle: string; items: number; context: number; voice: string; mapped: boolean; from?: string; character?: string }; type View = { lexicon: { json: { lexicon?: Lex[] } | null; error?: string }; voices: { json: { voices?: Record<string, string>; narrator?: string; engine?: string; authors?: Author[] } | null; error?: string }; @@ -144,7 +144,7 @@ export default function PronunciationPanel({ project }: { project: string }) { <tr key={a.handle} className="text-muted" data-voice-author={a.handle}> <td className={cn(cell, "font-mono")}>@{a.handle}</td> <td className={cell}> - {a.voice} (default) · {a.items} item{a.items === 1 ? "" : "s"}, {a.context} context + {a.voice} ({a.from === "cast" ? `cast: ${a.character ?? ""}` : "default"}) · {a.items} item{a.items === 1 ? "" : "s"}, {a.context} context </td> <td className={cn(cell, "text-right")}> <button type="button" onClick={() => setHandle(a.handle)} className={buttonVariants({ variant: "quiet", size: "sm" })}> diff --git a/umtool/lib/report/castStore.mjs b/umtool/lib/report/castStore.mjs @@ -0,0 +1,152 @@ +// THE CAST's FILE and its ONE WRITER (umtool-report-to-video/cast.mjs; umtool/docs/knobs.md, "The cast"). +// +// <REPORTS_ROOT>/.umtool/cast.json the characters, for every project +// <REPORTS_ROOT>/.umtool/cast.undo.json the undo points: the file as it was before each write (the last 50) +// +// Every write is serialised in-process, re-reads the file inside the lock, checks the caller's token (the sha1 of +// the file it read: a write over a newer file is refused), refuses a cast cast.mjs refuses (whole), keeps an undo +// point and writes a temp file renamed over. A file that does not parse is never overwritten (a write refuses +// until it is fixed); a reader treats it as no cast and says so in `error`. +// +// WHICH CAST A PROJECT READS: the reports root's when the project is under it; else the first `.umtool/cast.json` +// up from the project's folder (a test's temp tree); else none. UMTOOL_CAST_FILE names one outright. +// +// Plain ESM: the CLI runs under bare node. +import { createHash } from "node:crypto"; +import { mkdir, readFile, rename, stat, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { CAST_FORMAT, CAST_VERSION, emptyCast, validateCast } from "umtool-report-to-video/cast"; +import { REPORTS_ROOT } from "../paths.mjs"; + +export const CAST_UNDO_KEEP = 50; + +export class CastError extends Error { + constructor(message, status = 400) { + super(message); + this.name = "CastError"; + this.status = status; + } +} + +/** The cast file under a reports root (UMTOOL_CAST_FILE wins). */ +export function castFile(reportsRoot = REPORTS_ROOT) { + return process.env.UMTOOL_CAST_FILE || path.join(/* turbopackIgnore: true */ reportsRoot, ".umtool", "cast.json"); +} +const undoFileOf = (file) => file.replace(/\.json$/, ".undo.json"); + +const inside = (dir, root) => dir === root || dir.startsWith(`${root}${path.sep}`); + +/** The cast file project folder `dir` reads (see the head), or null. */ +export async function castFileFor(dir, reportsRoot = REPORTS_ROOT) { + if (process.env.UMTOOL_CAST_FILE) return process.env.UMTOOL_CAST_FILE; + const d = path.resolve(dir); + const root = path.resolve(reportsRoot); + if (inside(d, root)) return castFile(root); + for (let cur = d; ; cur = path.dirname(cur)) { + const f = path.join(cur, ".umtool", "cast.json"); + if (await stat(f).then((s) => s.isFile(), () => false)) return f; + if (path.dirname(cur) === cur) return null; + } +} + +const sha = (text) => createHash("sha1").update(text).digest("hex").slice(0, 16); + +/** + * The cast as its file holds it: `{ cast, token, file, exists, error? }` -- `token` the sha1 of the text (null with + * no file). A file that does not parse or is refused reads as the empty cast with `error`. + */ +export async function readCastFile(file) { + let text; + try { + text = await readFile(file, "utf8"); + } catch (e) { + if (e?.code === "ENOENT") return { cast: emptyCast(), token: null, file, exists: false, text: null }; + return { cast: emptyCast(), token: null, file, exists: false, text: null, error: `${file} cannot be read: ${e?.message ?? e}` }; + } + let doc; + try { + doc = JSON.parse(text); + } catch (e) { + return { cast: emptyCast(), token: sha(text), file, exists: true, text, error: `${file} is not JSON: ${e instanceof Error ? e.message : e}` }; + } + const errors = validateCast(doc, path.basename(file)); + if (errors.length) return { cast: emptyCast(), token: sha(text), file, exists: true, text, error: `${path.basename(file)} is refused: ${errors.join("; ")}` }; + return { cast: doc, token: sha(text), file, exists: true, text }; +} + +/** The cast under a reports root. */ +export const readCast = (reportsRoot = REPORTS_ROOT) => readCastFile(castFile(reportsRoot)); + +/** The cast project folder `dir` reads (the empty one when it reads none). */ +export async function castForProject(dir, reportsRoot = REPORTS_ROOT) { + const f = await castFileFor(dir, reportsRoot); + if (!f) return { cast: emptyCast(), token: null, file: null, exists: false, text: null }; + return readCastFile(f); +} + +/** The undo points, oldest first: `{ at, what, text }` (`text` null: there was no file). */ +export async function readCastUndo(file) { + try { + const j = JSON.parse(await readFile(undoFileOf(file), "utf8")); + return Array.isArray(j?.points) ? j.points.filter((p) => p && typeof p.what === "string" && (typeof p.text === "string" || p.text === null)) : []; + } catch { + return []; + } +} + +async function writeAtomic(file, text) { + await mkdir(path.dirname(file), { recursive: true }); + const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`; + await writeFile(tmp, text, "utf8"); + await rename(tmp, file); +} + +/** @type {Promise<unknown>} */ +let queue = Promise.resolve(); +function withCastLock(fn) { + const run = queue.then(fn, fn); + queue = run.then(() => undefined, () => undefined); + return run; +} + +/** + * ONE WRITE of the cast: `mutate(characters)` (a copy; it throws CastError to refuse) returns what the caller + * wants back. Refused when the file changed since the caller's `token` (409), when it does not parse, or when the + * result is refused (cast.mjs validateCast). Returns `{ ...result, cast, token, undo: <points left> }`. + * @param {string} file + * @param {(chars: any[]) => any} mutate + * @param {{ token?: string | null, what?: string }} [o] + */ +export function castWrite(file, mutate, { token = null, what = "an edit" } = {}) { + return withCastLock(async () => { + const read = await readCastFile(file); + if (read.error && read.exists) throw new CastError(`${read.error} -- fix the file first; nothing written`, 409); + if (token !== null && token !== undefined && token !== read.token) throw new CastError(`the cast changed since it was read (${token} -> ${read.token}): read it again`, 409); + const chars = JSON.parse(JSON.stringify(read.cast.characters ?? [])); + const result = mutate(chars) ?? {}; + const doc = { format: CAST_FORMAT, version: CAST_VERSION, characters: chars }; + const errors = validateCast(doc); + if (errors.length) throw new CastError(`refused: ${errors.join("; ")}`); + const points = [...(await readCastUndo(file)), { at: new Date().toISOString(), what, text: read.exists ? read.text : null }].slice(-CAST_UNDO_KEEP); + await writeAtomic(undoFileOf(file), `${JSON.stringify({ file: path.basename(file), points }, null, 1)}\n`); + const text = `${JSON.stringify(doc, null, 1)}\n`; + await writeAtomic(file, text); + return { ...result, cast: doc, token: sha(text), undo: points.length }; + }); +} + +/** Put the cast back as it was before its last write (that write's undo point, taken off the list). */ +export function undoCast(file, { token = null } = {}) { + return withCastLock(async () => { + const read = await readCastFile(file); + if (token !== null && token !== undefined && token !== read.token) throw new CastError(`the cast changed since it was read: read it again`, 409); + const points = await readCastUndo(file); + const last = points.pop(); + if (!last) throw new CastError("nothing to undo on the cast"); + if (last.text === null) await writeAtomic(file, `${JSON.stringify(emptyCast(), null, 1)}\n`); + else await writeAtomic(file, last.text); + await writeAtomic(undoFileOf(file), `${JSON.stringify({ file: path.basename(file), points }, null, 1)}\n`); + const now = await readCastFile(file); + return { undone: last.what, at: last.at, left: points.length, cast: now.cast, token: now.token }; + }); +} diff --git a/umtool/lib/report/postSay.mjs b/umtool/lib/report/postSay.mjs @@ -50,8 +50,10 @@ export const VOICES_USAGE = [ " umtool posts voices <project> set <handle|*> <voice> [--json]", " umtool posts voices <project> remove <handle|*> [--json]", " THE VOICE MAP (narration/voices.json): the stock voice each author's words are read in by a thread read", - " (umtool posts narrate <p> <item> --take --thread) -- set kirscheverstahl tara; `*` is everyone it does not name", - " (default leo on Orpheus). The item's own author reads in the item's narrator voice unless the map names them.", + " (umtool posts narrate <p> <item> --take --thread) and a single post's read -- set kirscheverstahl tara, or with its", + " engine set thequartering kokoro:am_michael; `*` is everyone it does not name (default leo on Orpheus). The map is", + " the project's OVERRIDE over the cast (umtool cast: the characters across projects). The item's own author reads in", + " the item's narrator voice unless the map or the cast names them.", " ls: the map, and every author the cut's post items carry with the voice each would get.", ].join("\n"); @@ -283,9 +285,13 @@ export async function voicesCommand(project, rest, { json = false, out = (s) => if (sub !== "ls") throw new SayError(`posts voices: ls, set or remove (not ${sub})`); const map = await readVoiceMap(project.dir); const manifest = (await readManifest(project.dir)) ?? {}; - const { voiceForPiece } = await import("umtool-report-to-video/post-say"); + const { voiceSourceOf } = await import("umtool-report-to-video/post-say"); const { postNarrationKnobs } = await import("umtool-report-to-video/post-narration"); + const { castForProject } = await import("./castStore.mjs"); + const { castVoiceMap, characterOf } = await import("umtool-report-to-video/cast"); const k = postNarrationKnobs({}, manifest.render ?? {}); + const castRead = await castForProject(project.dir); + const cast = castVoiceMap(castRead.cast); // Every author a thread read could voice: the items' own, their parents', quoted and linked posts'. const authors = new Map(); const count = (h, own) => { @@ -303,15 +309,19 @@ export async function voicesCommand(project, rest, { json = false, out = (s) => if (e.quoted) count(e.quoted.handle, false); for (const l of Array.isArray(e.links) ? e.links : []) count(l?.handle, false); } - const rows = [...authors.values()].sort((a, b) => b.items + b.context - (a.items + a.context)).map((a) => ({ - ...a, voice: voiceForPiece({ handle: a.handle, role: "parent:0" }, { map, narrator: k.voice, engine: k.engine }), mapped: a.handle in map, - })); - if (json) out(JSON.stringify({ ok: true, file: VOICES_FILE, voices: map, narrator: k.voice, engine: k.engine, authors: rows }, null, 2)); + // Each author's voice as a context post, and WHERE it comes from: the project's map, the cast, the default. + const rows = [...authors.values()].sort((a, b) => b.items + b.context - (a.items + a.context)).map((a) => { + const v = voiceSourceOf({ handle: a.handle, role: "parent:0" }, { map, cast, narrator: k.voice, engine: k.engine }); + const c = characterOf(castRead.cast, a.handle); + return { ...a, voice: v.spec, from: v.from, mapped: a.handle in map, ...(c ? { character: c.id, castVoice: c.voice } : {}) }; + }); + if (json) out(JSON.stringify({ ok: true, file: VOICES_FILE, voices: map, narrator: k.voice, engine: k.engine, cast: { file: castRead.file, characters: Object.keys(cast).length, ...(castRead.error ? { error: castRead.error } : {}) }, authors: rows }, null, 2)); else { out(`${project.id}: ${Object.keys(map).length} voice(s) on the map (${VOICES_FILE}); the narrator ${k.engine} · ${k.voice}`); - for (const [h, v] of Object.entries(map)) out(` ${h === VOICE_MAP_OTHER ? "* (everyone else)" : `@${h}`} -> ${v}`); - if (rows.length) out(" the cut's authors, as a context post (their own items read in the narrator's voice unless mapped):"); - for (const r of rows) out(` @${r.handle} ${r.voice}${r.mapped ? "" : " (default)"} -- ${r.items} item(s), ${r.context} context post(s)`); + for (const [h, v] of Object.entries(map)) out(` ${h === VOICE_MAP_OTHER ? "* (everyone else)" : `@${h}`} -> ${v}${cast[h] && cast[h] !== v ? ` (the cast says ${cast[h]}: overridden here)` : ""}`); + if (castRead.error) out(` the cast is not read: ${castRead.error}`); + if (rows.length) out(" the cut's authors, as a context post (their own items read in the narrator's voice unless mapped or cast):"); + for (const r of rows) out(` @${r.handle} ${r.voice} (${r.from === "project" ? "project" : r.from === "cast" ? `cast: ${r.character}` : "default"}) -- ${r.items} item(s), ${r.context} context post(s)`); } return 0; } diff --git a/umtool/lib/report/postThreadRead.mjs b/umtool/lib/report/postThreadRead.mjs @@ -23,7 +23,9 @@ // read: such a slur is skipped), the project's pronunciation lexicon applied (post-say.mjs, `umtool posts say`). // // THE VOICES (post-say.mjs voiceForPiece): --voice-for, --voice (his post), the project's voice map -// (`umtool posts voices`), the narrator's for the item's own author, the map's "*", leo (Orpheus). +// (`umtool posts voices`), THE CAST (`umtool cast`: the characters across projects), the narrator's for the item's +// own author, the map's "*", leo (Orpheus). A voice that names its engine ("kokoro:am_michael") is synthesized by +// that engine, the rest by the read's: one read may join parts of two engines (each part records its own). // // THE PARTS: each piece split as a long read is (post-narration.mjs scriptParts: its paragraphs, a paragraph over // 60 words at a sentence end), each part synthesized ONCE and kept in the project's PARTS CACHE -- @@ -54,7 +56,7 @@ import { chronoPieces } from "umtool-report-to-video/post-thread"; import { cardText, parentsOf } from "umtool-report-to-video/post-item"; import { planContext } from "umtool-report-to-video/post-conversation"; import { spokenRead } from "umtool-report-to-video/post-redact"; -import { voiceForPiece } from "umtool-report-to-video/post-say"; +import { resolvePieceVoice } from "umtool-report-to-video/post-say"; import { readManifest } from "../projects/report.mjs"; import { withEditNotes } from "./edit-guard.mjs"; import { manifestToken, updatePostNarration } from "./manifest.mjs"; @@ -92,6 +94,13 @@ export const THREAD_READ_USAGE = [ " could not be synthesized (the parts already made stay cached: run it again).", ].join("\n"); +/** The project's cast as a voice map (castStore.mjs: the cast the project reads; `{}` with none, or a broken one). */ +export async function projectCastMap(dir) { + const { castForProject } = await import("./castStore.mjs"); + const { castVoiceMap } = await import("umtool-report-to-video/cast"); + return castVoiceMap((await castForProject(dir)).cast); +} + /** A part's cache key: sha1 of `voice|text` (an engine other than Orpheus: `engine|voice|text`). */ export const partKey = (engine, voice, text) => createHash("sha1").update(engine === "orpheus" ? `${voice}|${text}` : `${engine}|${voice}|${text}`).digest("hex"); @@ -119,17 +128,21 @@ export function seenIds(manifest, e) { } /** - * THE READ, PIECE BY PIECE, pure: `{ engine, narrator, pieces: [{ role, handle, date, voice, written, text, - * lexicon, slurs }], skipped: [{ role, id?, why }], want, voice, script, lexicon, slurs }` -- `text` what the voice + * THE READ, PIECE BY PIECE, pure: `{ engine, narrator, pieces: [{ role, handle, date, voice, engine, from, written, + * text, lexicon, slurs }], skipped: [{ role, id?, why }], want, voice, script, lexicon, slurs }` -- `text` what the voice * says (spokenRead), `want` the whole read (pieces joined by a blank line), `voice` the take's label (its voices * joined by "+"), `script` his script when he had none (set with the take). * * @param {Record<string, any>} manifest * @param {Record<string, any>} e the post item - * @param {{ red?: any, map?: Record<string, string>, overrides?: Record<string, string>, parents?: string, + * `cast` is the cast as a voice map (cast.mjs castVoiceMap: `{ handle: "engine:voice" }`). Each piece's `engine` is + * its voice's (a voice that names one), else the read's; `from` where its voice came from (post-say.mjs voiceSourceOf). + * The read's `engine` is his piece's. + * + * @param {{ red?: any, map?: Record<string, string>, cast?: Record<string, string>, overrides?: Record<string, string>, parents?: string, * skip?: string[], quoted?: boolean, linked?: boolean, readSeen?: boolean, voice?: string | null, engine?: string | null }} [o] */ -export function threadReadPlan(manifest, e, { red = null, map = {}, overrides = {}, parents = "0", skip = [], quoted = true, linked = true, readSeen = false, voice = null, engine = null } = {}) { +export function threadReadPlan(manifest, e, { red = null, map = {}, cast = {}, overrides = {}, parents = "0", skip = [], quoted = true, linked = true, readSeen = false, voice = null, engine = null } = {}) { const render = manifest?.render ?? {}; const k = postNarrationKnobs(e, render); const eng = engine ?? e.narration?.engine ?? k.engine; @@ -187,27 +200,31 @@ export function threadReadPlan(manifest, e, { red = null, map = {}, overrides = skipped.push({ role: p.role, why: "nothing left to say (all of it redacted)" }); continue; } - const v = voiceForPiece({ handle: p.handle, role: p.role }, { map, overrides, self: str(e.handle), voice, narrator, engine: eng }); - pieces.push({ role: p.role, handle: p.handle, date: p.date, voice: v, written, text: said.text.trim(), lexicon: said.lexicon ?? [], slurs: said.slurs }); + const v = resolvePieceVoice({ handle: p.handle, role: p.role }, { map, cast, overrides, self: str(e.handle), voice, narrator, engine: eng }); + pieces.push({ role: p.role, handle: p.handle, date: p.date, voice: v.voice, engine: v.engine, from: v.from, written, text: said.text.trim(), lexicon: said.lexicon ?? [], slurs: said.slurs }); } if (!pieces.some((p) => p.role === "post")) throw new ThreadReadError(`${e.id} has no words of his own to read (--script "…" first)`); const lexicon = [...new Map(pieces.flatMap((p) => p.lexicon).map((x) => [`${x.word.toLowerCase()}|${x.item ?? ""}`, x])).values()]; const states = pieces.map((p) => p.slurs).filter(Boolean); return { - engine: eng, narrator, pieces, skipped, script, + engine: pieces.find((p) => p.role === "post")?.engine ?? eng, narrator, pieces, skipped, script, want: pieces.map((p) => p.text).join("\n\n"), voice: [...new Set(pieces.map((p) => p.voice))].join("+"), lexicon, slurs: states.includes("said") ? "said" : states[0] ?? null, }; } -/** The read's PARTS, pure: each piece's parts (scriptParts) with its voice, role and cache key, in order. */ +/** The read's PARTS, pure: each piece's parts (scriptParts) with its voice, engine, role and cache key, in order. */ export function readParts(plan) { - return plan.pieces.flatMap((pc, piece) => - scriptParts(pc.text).map((q) => ({ piece, para: q.para, role: pc.role, voice: pc.voice, text: q.text, key: partKey(plan.engine, pc.voice, q.text) })), - ); + return plan.pieces.flatMap((pc, piece) => { + const eng = pc.engine ?? plan.engine; + return scriptParts(pc.text).map((q) => ({ piece, para: q.para, role: pc.role, voice: pc.voice, engine: eng, text: q.text, key: partKey(eng, pc.voice, q.text) })); + }); } +/** Each piece's `engine:voice`, in order, once each -- what a read sounds like, for "is it up to date". */ +const voiceSig = (rows, fallback) => [...new Set(rows.map((p) => `${p.engine ?? fallback}:${p.voice}`))].join("+"); + /** * THE JOIN's TIMES, pure: each part's start in the take, its length, the gap before it (POST_PART_GAP: a new piece, * a new paragraph, inside one) -- the parts meta as `take-<n>.parts.json` holds it -- and the take's length. @@ -220,7 +237,7 @@ export function joinTimes(parts, seconds, { fileOf = (p) => `${PARTS_CACHE}/${p. const gap = !prev ? 0 : p.piece !== prev.piece ? POST_PART_GAP.piece : p.para !== prev.para ? POST_PART_GAP.para : POST_PART_GAP.inside; t += gap; const s = Number(seconds[i]); - const row = { n: i + 1, para: p.piece * 100 + p.para, text: p.text, voice: p.voice, role: p.role, piece: p.piece, file: fileOf(p), start: r3(t), seconds: r3(s), gapBefore: gap }; + const row = { n: i + 1, para: p.piece * 100 + p.para, text: p.text, voice: p.voice, ...(p.engine ? { engine: p.engine } : {}), role: p.role, piece: p.piece, file: fileOf(p), start: r3(t), seconds: r3(s), gapBefore: gap }; t += s; return row; }); @@ -236,10 +253,14 @@ export function readRecordOf({ parents = "0", skip = [], quoted = true, linked = }; } -/** Is the picked take this read already (the same words, voices and engine)? */ +/** Is the picked take this read already (the same words, voices and engines)? */ export function upToDate(e, plan) { const t = pickedTake(e); - return !!t && norm(t.script) === norm(plan.want) && str(t.voice) === plan.voice && (t.engine ?? "orpheus") === plan.engine; + if (!t || norm(t.script) !== norm(plan.want) || str(t.voice) !== plan.voice || (t.engine ?? "orpheus") !== plan.engine) return false; + // A take whose parts say their voices: each piece in the same engine and voice. + const parts = Array.isArray(t.parts) ? t.parts.filter((p) => typeof p?.voice === "string") : []; + if (!parts.length) return true; + return voiceSig(parts, t.engine ?? "orpheus") === voiceSig(plan.pieces, plan.engine); } const fileThere = async (f) => !!(await stat(f).catch(() => null))?.isFile(); @@ -260,7 +281,7 @@ async function durationOf(file) { */ export async function threadTake(project, e, opts = {}) { const { - manifest: m0 = null, red: red0 = undefined, map: map0 = undefined, overrides = {}, parents = "0", skip = [], quoted = true, linked = true, + manifest: m0 = null, red: red0 = undefined, map: map0 = undefined, cast: cast0 = undefined, overrides = {}, parents = "0", skip = [], quoted = true, linked = true, readSeen = false, voice = null, engine = null, note = null, force = false, hold = true, dryRun = false, ask = null, lanes: lanes0 = undefined, emit = () => {}, editor = null, signals = false, } = opts; @@ -268,7 +289,8 @@ export async function threadTake(project, e, opts = {}) { if (!manifest) throw new ThreadReadError(`${project.id} has no manifest`); const red = red0 !== undefined ? red0 : await (await import("./postRedaction.mjs")).projectRedaction(project.dir, manifest); const map = map0 !== undefined ? map0 : await (await import("./postSay.mjs")).readVoiceMap(project.dir); - const plan = threadReadPlan(manifest, e, { red, map, overrides, parents, skip, quoted, linked, readSeen, voice, engine }); + const cast = cast0 !== undefined ? cast0 : await projectCastMap(project.dir); + const plan = threadReadPlan(manifest, e, { red, map, cast, overrides, parents, skip, quoted, linked, readSeen, voice, engine }); const parts = readParts(plan); const cacheDir = path.join(project.dir, ...PARTS_CACHE.split("/")); const wavOf = (p) => path.join(cacheDir, `${p.key}.wav`); @@ -328,10 +350,10 @@ export async function threadTake(project, e, opts = {}) { try { const askTts = ask ?? (await import("umtool-report-to-video/narrate-via-editor")).askEditorTts; for (const [n, { p }] of todo.entries()) { - emit("note", { message: `part ${n + 1}/${todo.length} (${p.role}, ${p.voice}): asking the editor…` }); + emit("note", { message: `part ${n + 1}/${todo.length} (${p.role}, ${p.engine === plan.engine ? p.voice : `${p.engine}:${p.voice}`}): asking the editor…` }); await writeFile(path.join(cacheDir, `${p.key}.txt`), p.text); try { - const { jobId } = await askTts({ text: p.text, engine: plan.engine, voice: p.voice, out: wavOf(p) }, { ...(editor ? { editor } : {}), emit }); + const { jobId } = await askTts({ text: p.text, engine: p.engine ?? plan.engine, voice: p.voice, out: wavOf(p) }, { ...(editor ? { editor } : {}), emit }); if (jobId) jobs.push(jobId); } catch (err) { throw new ThreadReadError(`part ${p.role} "${p.text.slice(0, 60)}${p.text.length > 60 ? "…" : ""}" (${p.voice}) was not synthesized: ${err instanceof Error ? err.message : err} -- the ${fresh + base.cached} part(s) made are cached; run it again`); @@ -370,7 +392,7 @@ export async function threadTake(project, e, opts = {}) { file: rel, engine: plan.engine, voice: plan.voice, seconds: mt.seconds ?? total, source: { kind: "tts", engine: plan.engine, voice: plan.voice, script: plan.want }, script: plan.want, at: new Date().toISOString(), - note: note ?? `thread read: ${plan.pieces.map((p) => `${p.role} (${p.voice})`).join(" + ")}`, + note: note ?? `thread read: ${plan.pieces.map((p) => `${p.role} (${p.engine && p.engine !== plan.engine ? `${p.engine}:` : ""}${p.voice})`).join(" + ")}`, ...(Number.isFinite(mt.lufs) ? { lufs: mt.lufs } : {}), parts: meta, ...(plan.slurs ? { slurs: plan.slurs } : {}), @@ -407,19 +429,19 @@ export async function threadCommand(project, e, o) { } throw err; } - const pieces = r.plan.pieces.map((p) => ({ role: p.role, handle: p.handle, date: p.date, voice: p.voice, words: p.text.split(/\s+/).filter(Boolean).length, ...(p.lexicon.length ? { lexicon: p.lexicon } : {}) })); + const pieces = r.plan.pieces.map((p) => ({ role: p.role, handle: p.handle, date: p.date, voice: p.voice, engine: p.engine, from: p.from, words: p.text.split(/\s+/).filter(Boolean).length, ...(p.lexicon.length ? { lexicon: p.lexicon } : {}) })); const guard = r.take ? await guardOf(project, e.id) : null; if (json) { out(JSON.stringify({ ok: true, id: e.id, upToDate: r.upToDate, dryRun: r.dryRun, engine: r.plan.engine, voice: r.plan.voice, pieces, skipped: r.plan.skipped, - parts: r.parts.map((p) => ({ role: p.role, voice: p.voice, key: p.key, cached: p.cached, text: p.text })), + parts: r.parts.map((p) => ({ role: p.role, voice: p.voice, engine: p.engine, key: p.key, cached: p.cached, text: p.text })), fresh: r.fresh, cached: r.cached, jobs: r.jobs, lane: r.lane, ...(r.take ? { take: r.take, pick: r.result.narration?.pick ?? null, token: r.result.token, snapshot: r.result.snapshot ?? null, guard } : {}), }, null, 2)); return 0; } out(`${e.id}: a thread read of ${pieces.length} piece(s), ${r.parts.length} part(s) (${r.cached} cached${r.dryRun ? `, ${r.parts.length - r.cached} to synthesize` : ""})`); - for (const p of pieces) out(` ${p.role.padEnd(9)} ${p.voice.padEnd(6)} ${p.handle ? `@${p.handle}` : ""}${p.date ? ` ${p.date.slice(0, 16)}` : ""} ${p.words} words${p.lexicon ? ` (said: ${p.lexicon.map((x) => `${x.word} -> ${x.say}`).join(", ")})` : ""}`); + for (const p of pieces) out(` ${p.role.padEnd(9)} ${(p.engine !== r.plan.engine ? `${p.engine}:${p.voice}` : p.voice).padEnd(6)} ${p.from === "cast" ? "(cast) " : ""}${p.handle ? `@${p.handle}` : ""}${p.date ? ` ${p.date.slice(0, 16)}` : ""} ${p.words} words${p.lexicon ? ` (said: ${p.lexicon.map((x) => `${x.word} -> ${x.say}`).join(", ")})` : ""}`); for (const s of r.plan.skipped) out(` (not read: ${s.role}${s.id ? ` ${s.id}` : ""} -- ${s.why})`); if (r.upToDate) { out(` up to date: the picked take already reads this, in these voices (--force makes it again)`); diff --git a/umtool/lib/report/readVoice.mjs b/umtool/lib/report/readVoice.mjs @@ -0,0 +1,33 @@ +// THE VOICE A POST ITEM's OWN READ IS SAID IN (a single post's take: `umtool posts narrate <p> <item> --take`, the +// bench's Re-take), through the SAME function a thread read asks for his piece (post-say.mjs resolvePieceVoice): the +// read's own voice (--voice, the bench's voice field), the project's voice map, the CAST, the narrator's (the item's +// own `narration.voice`, else the cut's). So a post read alone and the same post read with its thread agree. +// +// Plain ESM. +import { postNarrationKnobs } from "umtool-report-to-video/post-narration"; +import { resolvePieceVoice, voiceRefOf } from "umtool-report-to-video/post-say"; + +/** + * `{ engine, voice, from }` for post item `e`'s own read -- `from` "override", "project", "cast", "narrator". + * `map` and `cast` are read from the project when not given (a broken voice map reads as none here: the read is not + * refused for it; `umtool posts voices` says what is wrong with it). + * + * @param {{ dir: string }} project + * @param {Record<string, any>} e + * @param {{ render?: Record<string, any>, engine?: string | null, voice?: string | null, map?: Record<string, string>, cast?: Record<string, string> }} [o] + */ +export async function itemReadVoice(project, e, { render = {}, engine = null, voice = null, map = undefined, cast = undefined } = {}) { + const k = postNarrationKnobs(e, render); + const eng = engine ?? e.narration?.engine ?? k.engine; + const narrator = e.narration?.voice ?? k.voice; + if (voice) { + const ref = voiceRefOf(voice, eng) ?? { engine: eng, voice: String(voice) }; + return { engine: engine ?? ref.engine ?? eng, voice: ref.voice, from: "override" }; + } + const m = map !== undefined ? map : await (await import("./postSay.mjs")).readVoiceMap(project.dir).catch(() => ({})); + const c = cast !== undefined ? cast : await (await import("./postThreadRead.mjs")).projectCastMap(project.dir).catch(() => ({})); + const r = resolvePieceVoice({ handle: e.handle ?? null, role: "post" }, { map: m, cast: c, self: e.handle ?? null, narrator, engine: eng }); + // An engine asked for outright that the resolved voice is not of: the narrator's voice in it. + if (engine && r.engine !== engine) return { engine, voice: narrator, from: "narrator" }; + return r; +} diff --git a/umtool/report-to-video/cast.mjs b/umtool/report-to-video/cast.mjs @@ -0,0 +1,250 @@ +// THE CAST (operator, 6 Nov 2026: "I'd like to be able to pick different voices +// for different characters, and in UI alone be able to try rendering different +// ones to compare … and try to maintain consistent voices for different +// repeating characters"): the CHARACTERS that recur across projects, each with +// the stock voice it reads in, stored ONCE for every project +// (`<REPORTS_ROOT>/.umtool/cast.json`, lib/report/castStore.mjs its one writer). +// +// { "format": "umtool-cast", "version": 1, +// "characters": [ { "id": "thequartering", "name": "TheQuartering", +// "handles": ["thequartering"], // X handles / channel slugs (no @, lower case) +// "voice": "kokoro:am_michael", // <tts engine>:<stock voice> +// "convert": { "engine": "seed-vc", "voice": "kokoro:am_michael" }, // a recording made his (optional) +// "speakers": ["Jeremy"], // his REAL voice's name in a project's speakers.json +// "avatar": "…", "note": "…", "narrator": true } ] } +// +// A project's `narration/voices.json` (post-say.mjs) stays the project's +// OVERRIDE LAYER. The voice a piece of a read is said in, in order: the read's +// own override (--voice-for, --voice), the project's map, the CAST, the +// narrator's (the item's own author), the map's "*", the engine's default -- +// post-say.mjs voiceForPiece, which every read goes through (a single post's +// take, each piece of a thread read), so they agree. +// +// A voice is ALWAYS a stock synthetic one (`<engine>:<voice>`): a character's +// REAL voice (`speakers`) is a reference to compare a candidate with +// (`umtool cast audition`, the Voices panel), never a target -- the editor's +// convert op refuses a file as a target, and this file holds no path to one. +// +// PURE and dependency-free (the CLI, the app and the lint read it). +import { CONTEXT_VOICE_DEFAULTS, TTS_ENGINE_IDS, handleKey, voiceRefOf, voiceSpecOf } from "./post-say.mjs"; + +export { voiceRefOf, voiceSpecOf }; + +export const CAST_FORMAT = "umtool-cast"; +export const CAST_VERSION = 1; +export const CAST_MAX = 300; +export const CAST_KEYS = Object.freeze(["id", "name", "handles", "voice", "convert", "speakers", "avatar", "note", "narrator"]); +/** The tts engines a cast voice may name (the editor's tts op), and the convert engines (its voice-convert op). */ +export const CAST_TTS_ENGINES = TTS_ENGINE_IDS; +export const CAST_CONVERT_ENGINES = Object.freeze(["openvoice", "seed-vc"]); +/** Which engine is heavy to run (the operator's rule: Orpheus pins ~8.5 GB; Kokoro first). */ +export const ENGINE_WEIGHT = Object.freeze({ kokoro: "fast", "espeak-ng": "fast", orpheus: "heavy" }); + +const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); +const str = (v) => (typeof v === "string" ? v : ""); +export const CHARACTER_ID_RE = /^[a-z0-9][a-z0-9_-]{0,47}$/; +const HANDLE_RE = /^[a-z0-9_.-]{1,64}$/; +const SPEAKER_RE = /^[^\s/=,][^/=,]{0,47}$/; + +/** A stock voice with its engine named (a cast voice): "kokoro:am_michael". */ +export const isQualifiedVoice = (spec) => !!voiceRefOf(spec) && str(spec).includes(":"); + +/** The empty cast. */ +export const emptyCast = () => ({ format: CAST_FORMAT, version: CAST_VERSION, characters: [] }); + +/** Every reason a cast document is refused (empty: it is fine). */ +export function validateCast(doc, where = "cast.json") { + if (!isObj(doc)) return [`${where} must be {"format": "${CAST_FORMAT}", "version": ${CAST_VERSION}, "characters": [...]}`]; + const errors = []; + if (doc.format !== CAST_FORMAT) errors.push(`${where}: format must be "${CAST_FORMAT}"`); + if (doc.version !== CAST_VERSION) errors.push(`${where}: version must be ${CAST_VERSION}`); + const list = doc.characters; + if (!Array.isArray(list)) return [...errors, `${where}.characters must be a list`]; + if (list.length > CAST_MAX) errors.push(`${where}: at most ${CAST_MAX} characters`); + const ids = new Set(); + const owner = new Map(); + let narrators = 0; + list.forEach((c, i) => { + const w = `${where}.characters[${i}]`; + if (!isObj(c)) return errors.push(`${w} must be {id, name, handles, voice, …}`); + for (const k of Object.keys(c)) if (!CAST_KEYS.includes(k)) errors.push(`${w}.${k} is not a character key (${CAST_KEYS.join(", ")})`); + if (!CHARACTER_ID_RE.test(str(c.id))) errors.push(`${w}.id must be lower case letters, digits, - and _ (got ${JSON.stringify(c.id)})`); + else if (ids.has(c.id)) errors.push(`${w}: two characters are "${c.id}"`); + ids.add(c.id); + if (!str(c.name).trim() || str(c.name).length > 80) errors.push(`${w}.name must be 1-80 characters`); + if (!Array.isArray(c.handles ?? [])) errors.push(`${w}.handles must be a list of handles`); + else { + if ((c.handles ?? []).length > 20) errors.push(`${w}.handles: at most 20`); + for (const h of c.handles ?? []) { + if (typeof h !== "string" || !HANDLE_RE.test(h) || h !== handleKey(h)) errors.push(`${w}.handles: "${h}" is not a handle as the cast keys it (lower case, no @)`); + else if (owner.has(h) && owner.get(h) !== c.id) errors.push(`${w}.handles: @${h} is ${owner.get(h)}'s already (a handle is one character's)`); + else owner.set(h, c.id); + } + } + if (!isQualifiedVoice(c.voice)) errors.push(`${w}.voice must be a STOCK voice with its engine, "<${CAST_TTS_ENGINES.join("|")}>:<voice>" (got ${JSON.stringify(c.voice)})`); + if (c.convert !== undefined) { + const cv = c.convert; + if (!isObj(cv) || Object.keys(cv).some((k) => !["engine", "voice"].includes(k))) errors.push(`${w}.convert must be {engine?, voice?}`); + else { + if (cv.engine !== undefined && !CAST_CONVERT_ENGINES.includes(cv.engine)) errors.push(`${w}.convert.engine must be one of ${CAST_CONVERT_ENGINES.join(", ")}`); + if (cv.voice !== undefined && !isQualifiedVoice(cv.voice)) errors.push(`${w}.convert.voice must be a STOCK voice, "<engine>:<voice>" (never a file or a recording)`); + } + } + if (c.speakers !== undefined && !(Array.isArray(c.speakers) && c.speakers.length <= 10 && c.speakers.every((s) => typeof s === "string" && SPEAKER_RE.test(s)))) errors.push(`${w}.speakers must be the names his real voice goes by in a project's speakers.json (at most 10)`); + for (const k of ["avatar", "note"]) if (c[k] !== undefined && (typeof c[k] !== "string" || c[k].length > 500)) errors.push(`${w}.${k} must be a string (at most 500)`); + if (c.narrator !== undefined && c.narrator !== true) errors.push(`${w}.narrator must be true or absent`); + if (c.narrator === true) narrators += 1; + }); + if (narrators > 1) errors.push(`${where}: one character at most is the narrator`); + return errors; +} + +/** The cast's characters (the invalid ones dropped, never fatal for a reader). */ +export function charactersOf(cast) { + return (Array.isArray(cast?.characters) ? cast.characters : []).filter((c) => isObj(c) && CHARACTER_ID_RE.test(str(c.id)) && isQualifiedVoice(c.voice)); +} + +/** The character a handle belongs to, or null. */ +export function characterOf(cast, handle) { + const h = handleKey(handle); + if (!h) return null; + return charactersOf(cast).find((c) => (c.handles ?? []).includes(h)) ?? null; +} + +/** The character `ref` names: its id, a handle of it, or its name (any case). */ +export function findCharacter(cast, ref) { + const r = str(ref).trim(); + if (!r) return null; + const low = r.toLowerCase(); + const list = charactersOf(cast); + return list.find((c) => c.id === low) ?? characterOf(cast, r) ?? list.find((c) => str(c.name).toLowerCase() === low) ?? null; +} + +/** The narrator character (`narrator: true`), or null. */ +export const narratorOf = (cast) => charactersOf(cast).find((c) => c.narrator === true) ?? null; + +/** The cast as a voice map for its handles: `{ "<handle>": "<engine>:<voice>" }` (voiceForPiece's `cast`). */ +export function castVoiceMap(cast) { + const out = {}; + for (const c of charactersOf(cast)) for (const h of c.handles ?? []) out[h] = c.voice; + return out; +} + +/** A character's convert target -- what a recording is made into: its convert voice, else its voice. */ +export function convertTargetOf(c) { + return { engine: c?.convert?.engine ?? null, voice: c?.convert?.voice ?? c?.voice ?? null }; +} + +/** The names a character's real voice may go by in a project's speakers.json (lower case, no punctuation). */ +const nameKey = (s) => str(s).toLowerCase().replace(/[^a-z0-9]/g, ""); +export function speakerFor(character, speakers) { + const names = [...(character?.speakers ?? []), character?.name, character?.id, ...(character?.handles ?? [])].map(nameKey).filter(Boolean); + return (Array.isArray(speakers) ? speakers : []).find((s) => names.includes(nameKey(s?.name))) ?? null; +} + +// --------------------------------------------------------------------------- +// Who reads what in a project's picked takes, and where it drifts from the cast. +// --------------------------------------------------------------------------- + +/** The handle a piece of a read is by: a role ("post", "parent:<i>", "quoted", "linked:<i>") of post item `e`. */ +export function handleOfRole(e, role) { + const r = str(role); + if (r === "post") return str(e?.handle) || null; + const m = /^parent:(\d)$/.exec(r); + if (m) return str((Array.isArray(e?.parents) ? e.parents : [])[Number(m[1])]?.handle) || null; + if (r === "quoted") return str(e?.quoted?.handle) || null; + const l = /^linked:(\d)$/.exec(r); + if (l) return str((Array.isArray(e?.links) ? e.links : [])[Number(l[1])]?.handle) || null; + return null; +} + +/** The take an item plays (narration.pick, else the first) -- post-narration.mjs pickedTake's rule, dependency-free. */ +function playing(e) { + const takes = Array.isArray(e?.narration?.takes) ? e.narration.takes : []; + if (!takes.length || e?.narration?.off === true) return null; + const k = Number.isInteger(e.narration.pick) && e.narration.pick >= 0 && e.narration.pick < takes.length ? e.narration.pick : 0; + return takes[k] ?? null; +} + +/** + * WHAT A PICKED TAKE READS EACH AUTHOR IN, pure: `[{ handle, role, engine, voice, kind }]` -- a thread read by its + * parts (each part's role and voice; its engine, else the take's), a single read as his post; `kind` "tts", + * "recorded" (a person's own voice: `voice` is its label) or "converted" (a recording made a stock voice). + */ +export function takeReads(e, take = playing(e)) { + if (!take) return []; + const src = isObj(take.source) ? take.source : null; + const steps = Array.isArray(take.steps) ? take.steps : []; + const conv = steps.find((s) => s?.op === "convert"); + if (conv) { + const ref = voiceRefOf(conv.voice); + return [{ handle: str(e?.handle) || null, role: "post", engine: ref?.engine ?? null, voice: ref?.voice ?? str(take.voice), kind: "converted" }]; + } + if (take.engine === "recorded" || src?.kind === "recorded") return [{ handle: str(e?.handle) || null, role: "post", engine: null, voice: str(take.voice || src?.voice || "operator"), kind: "recorded" }]; + if (take.engine === "derived" || src?.kind === "take") return []; + const parts = Array.isArray(take.parts) ? take.parts : []; + if (parts.some((p) => typeof p?.role === "string" && typeof p?.voice === "string")) { + const seen = new Map(); + for (const p of parts) { + if (typeof p?.role !== "string" || typeof p?.voice !== "string") continue; + const key = p.role; + if (seen.has(key)) continue; + seen.set(key, { handle: handleOfRole(e, p.role), role: p.role, engine: str(p.engine) || str(take.engine) || null, voice: p.voice, kind: "tts" }); + } + return [...seen.values()]; + } + return [{ handle: str(e?.handle) || null, role: "post", engine: str(take.engine) || null, voice: str(take.voice), kind: "tts" }]; +} + +/** Two voices the same (`{engine, voice}`; an engine unknown on either side compares by the voice). */ +export const sameVoice = (a, b) => !!a && !!b && a.voice === b.voice && (!a.engine || !b.engine || a.engine === b.engine); + +/** Is a take a thread read (its parts in their authors' voices)? */ +export const isThreadTake = (t) => t?.read?.kind === "thread" || /-thread\.wav$/.test(str(t?.file)) || (Array.isArray(t?.parts) && new Set(t.parts.map((p) => p?.voice).filter(Boolean)).size > 1); + +/** + * EVERY PICKED READ IN ANOTHER VOICE THAN THE ONE IT WOULD BE READ IN NOW, pure: `[{ id, handle, role, reads, want, + * from, kind, thread }]` -- `resolve(e, role, handle, take, read)` says the voice now (`{ engine, voice, from }`, or + * null: nothing to compare). A recorded read (a person's own voice) is never one. + */ +export function voiceDrift(manifest, resolve) { + const rows = []; + for (const e of Array.isArray(manifest?.timeline) ? manifest.timeline : []) { + if (e?.type !== "post") continue; + const take = playing(e); + for (const r of takeReads(e, take)) { + if (!r.handle || r.kind === "recorded") continue; + const want = resolve(e, r.role, r.handle, take, r); + if (!want || sameVoice({ engine: r.engine, voice: r.voice }, want)) continue; + rows.push({ id: e.id, handle: handleKey(r.handle), role: r.role, reads: voiceSpecOf({ engine: r.engine, voice: r.voice }), want: voiceSpecOf(want), from: want.from ?? null, kind: r.kind, thread: isThreadTake(take) }); + } + } + return rows; +} + +/** + * WHERE A PROJECT DRIFTS FROM THE CAST, pure -- the consistency guard (`umtool lint`, the Voices panel): + * drift a cast character whose picked read is in another voice than the one it reads in now (stale: re-read + * it) -- voiceDrift's rows for the cast's handles, each with its `character` + * overrides a cast character the project's map gives another voice ON PURPOSE -- fine, shown: + * `[{ handle, character, cast, project }]` + * + * @param {Record<string, any>} manifest + * @param {{ cast: any, map?: Record<string, string>, resolve: Function }} o + */ +export function castDrift(manifest, { cast, map = {}, resolve }) { + const drift = voiceDrift(manifest, resolve).flatMap((r) => { + const c = characterOf(cast, r.handle); + return c ? [{ ...r, character: c.id }] : []; + }); + const overrides = []; + for (const [h, v] of Object.entries(map ?? {})) { + const c = characterOf(cast, h); + if (!c) continue; + if (voiceSpecOf(voiceRefOf(v, voiceRefOf(c.voice)?.engine)) !== c.voice) overrides.push({ handle: h, character: c.id, cast: c.voice, project: v }); + } + return { drift, overrides }; +} + +/** The voice an engine reads a context author in when nothing names one (re-exported for the panel). */ +export { CONTEXT_VOICE_DEFAULTS }; diff --git a/umtool/report-to-video/cast.test.mjs b/umtool/report-to-video/cast.test.mjs @@ -0,0 +1,107 @@ +// The cast (cast.mjs): its shape refused whole, a voice with its engine, a character by handle, the cast as a voice +// layer under the project's map (post-say.mjs voiceSourceOf: override → project → cast → narrator → default), what a +// picked take reads each author in, the drift and the overrides. +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { + castDrift, castVoiceMap, characterOf, convertTargetOf, emptyCast, findCharacter, isQualifiedVoice, narratorOf, speakerFor, takeReads, validateCast, voiceDrift, voiceRefOf, +} from "./cast.mjs"; +import { resolvePieceVoice, validateVoiceMap, voiceForPiece, voiceOverridesOf, voiceSourceOf } from "./post-say.mjs"; + +const Q = { id: "thequartering", name: "TheQuartering", handles: ["thequartering"], voice: "kokoro:am_michael", speakers: ["Jeremy"] }; +const S = { id: "savvy", name: "MadamSavvy", handles: ["madamsavvy"], voice: "orpheus:tara", convert: { engine: "seed-vc" }, narrator: true }; +const cast = { ...emptyCast(), characters: [Q, S] }; + +test("a voice is a stock one, bare or with its engine -- never a path", () => { + assert.deepEqual(voiceRefOf("kokoro:am_michael"), { engine: "kokoro", voice: "am_michael" }); + assert.deepEqual(voiceRefOf("tara", "orpheus"), { engine: "orpheus", voice: "tara" }); + assert.equal(voiceRefOf("/home/me/voice.wav"), null); + assert.equal(voiceRefOf("file:me.wav"), null, "an engine the editor has not"); + assert.equal(voiceRefOf("https://x/y"), null); + assert.ok(isQualifiedVoice("orpheus:zac")); + assert.ok(!isQualifiedVoice("zac")); + // The project's map takes either form. + assert.deepEqual(validateVoiceMap({ thequartering: "kokoro:am_michael", madamsavvy: "tara" }), []); + assert.equal(validateVoiceMap({ x: "seedvc:me.wav" }).length, 1); + assert.deepEqual(voiceOverridesOf(["thequartering=kokoro:am_onyx"]), { thequartering: "kokoro:am_onyx" }); +}); + +test("validateCast: the shape, ids, one owner a handle, stock voices only, one narrator", () => { + assert.deepEqual(validateCast(cast), []); + assert.match(validateCast({ ...cast, format: "x" })[0], /format must be "umtool-cast"/); + const two = { ...emptyCast(), characters: [Q, { ...S, handles: ["thequartering"] }] }; + assert.ok(validateCast(two).some((e) => /is thequartering's already/.test(e))); + assert.ok(validateCast({ ...emptyCast(), characters: [{ ...Q, voice: "/tmp/jeremy.wav" }] }).some((e) => /STOCK voice with its engine/.test(e))); + assert.ok(validateCast({ ...emptyCast(), characters: [{ ...Q, convert: { voice: "me.wav" } }] }).some((e) => /never a file/.test(e))); + assert.ok(validateCast({ ...emptyCast(), characters: [{ ...Q, narrator: true }, S] }).some((e) => /one character at most is the narrator/.test(e))); + assert.ok(validateCast({ ...emptyCast(), characters: [{ ...Q, handles: ["@TheQuartering"] }] }).some((e) => /lower case, no @/.test(e))); + assert.ok(validateCast({ ...emptyCast(), characters: [{ ...Q, extra: 1 }] }).some((e) => /extra is not a character key/.test(e))); +}); + +test("a character by handle, id or name; the narrator; a recording's target; the real voice it goes by", () => { + assert.equal(characterOf(cast, "@TheQuartering")?.id, "thequartering"); + assert.equal(findCharacter(cast, "MadamSavvy")?.id, "savvy"); + assert.equal(findCharacter(cast, "savvy")?.id, "savvy"); + assert.equal(findCharacter(cast, "nobody"), null); + assert.equal(narratorOf(cast)?.id, "savvy"); + assert.deepEqual(castVoiceMap(cast), { thequartering: "kokoro:am_michael", madamsavvy: "orpheus:tara" }); + assert.deepEqual(convertTargetOf(S), { engine: "seed-vc", voice: "orpheus:tara" }); + assert.deepEqual(convertTargetOf({ ...Q, convert: { voice: "kokoro:am_onyx" } }), { engine: null, voice: "kokoro:am_onyx" }); + const speakers = [{ name: "Jeremy" }, { name: "Melonie Mac" }]; + assert.equal(speakerFor(Q, speakers)?.name, "Jeremy"); + assert.equal(speakerFor({ id: "mm", name: "MelonieMac", handles: [] }, speakers)?.name, "Melonie Mac", "the name, its punctuation and case aside"); + assert.equal(speakerFor(S, speakers), null); +}); + +test("the cast is a layer: the read's override, then the project's map, then the cast, then the narrator, then the default", () => { + const castMap = castVoiceMap(cast); + const o = { map: {}, cast: castMap, narrator: "zac", engine: "orpheus", self: "TheQuartering" }; + assert.deepEqual(voiceSourceOf({ handle: "TheQuartering", role: "post" }, o), { spec: "kokoro:am_michael", from: "cast" }); + assert.deepEqual(resolvePieceVoice({ handle: "TheQuartering", role: "post" }, o), { engine: "kokoro", voice: "am_michael", from: "cast" }); + assert.deepEqual(voiceSourceOf({ handle: "TheQuartering", role: "post" }, { ...o, map: { thequartering: "zac" } }), { spec: "zac", from: "project" }, "the project overrides the cast"); + assert.deepEqual(resolvePieceVoice({ handle: "TheQuartering", role: "post" }, { ...o, map: { thequartering: "zac" } }), { engine: "orpheus", voice: "zac", from: "project" }); + assert.deepEqual(voiceSourceOf({ handle: "TheQuartering", role: "post" }, { ...o, overrides: { thequartering: "leo" } }), { spec: "leo", from: "override" }); + assert.deepEqual(voiceSourceOf({ handle: "TheQuartering", role: "post" }, { ...o, voice: "dan" }), { spec: "dan", from: "override" }, "--voice: his post"); + assert.deepEqual(voiceSourceOf({ handle: "someone", role: "parent:0" }, o), { spec: "leo", from: "default" }); + assert.deepEqual(voiceSourceOf({ handle: "someone", role: "parent:0" }, { ...o, map: { "*": "dan" } }), { spec: "dan", from: "project" }); + assert.deepEqual(voiceSourceOf({ handle: "nobody", role: "post" }, { ...o, self: "nobody" }), { spec: "zac", from: "narrator" }); + // The cast never beats a map entry, nor does "*" beat the cast. + assert.equal(voiceForPiece({ handle: "MadamSavvy", role: "quoted" }, { ...o, map: { "*": "dan" } }), "orpheus:tara"); +}); + +const post = (id, handle, take, o = {}) => ({ type: "post", id, handle, author: handle, narration: { script: "words", takes: take ? [take] : [], pick: 0 }, ...o }); + +test("takeReads: a single read is his post; a thread read by its parts; a recording and a conversion say so", () => { + const e = post("p-1", "TheQuartering", { file: "narration/posts/1/take-1.orpheus-zac.wav", engine: "orpheus", voice: "zac", seconds: 1 }); + assert.deepEqual(takeReads(e), [{ handle: "TheQuartering", role: "post", engine: "orpheus", voice: "zac", kind: "tts" }]); + const thread = post("p-2", "TheQuartering", { + file: "narration/posts/2/take-1.orpheus-thread.wav", engine: "orpheus", voice: "tara+am_michael", seconds: 2, read: { kind: "thread", parents: "0" }, + parts: [{ n: 1, role: "parent:0", voice: "tara", start: 0, seconds: 1 }, { n: 2, role: "post", voice: "am_michael", engine: "kokoro", start: 1, seconds: 1 }], + }, { parents: [{ id: "9", handle: "MadamSavvy" }] }); + assert.deepEqual(takeReads(thread).map((r) => [r.handle, r.role, r.engine, r.voice]), [["MadamSavvy", "parent:0", "orpheus", "tara"], ["TheQuartering", "post", "kokoro", "am_michael"]]); + const rec = post("p-3", "TheQuartering", { file: "narration/posts/3/take-1.recorded-operator.wav", engine: "recorded", voice: "operator", seconds: 1 }); + assert.equal(takeReads(rec)[0].kind, "recorded"); + const conv = post("p-4", "TheQuartering", { file: "narration/posts/4/take-2.convert-seed-vc.wav", engine: "derived", voice: "am_michael", seconds: 1, source: { kind: "take", from: "take-1.recorded-operator" }, steps: [{ op: "convert", engine: "seed-vc", voice: "kokoro:am_michael" }] }); + assert.deepEqual(takeReads(conv)[0], { handle: "TheQuartering", role: "post", engine: "kokoro", voice: "am_michael", kind: "converted" }); +}); + +test("voiceDrift and castDrift: a cast character read in another voice is drift; a project override is shown, not drift", () => { + const manifest = { + render: {}, + timeline: [ + post("p-1", "TheQuartering", { file: "a.wav", engine: "orpheus", voice: "zac", seconds: 1 }), + post("p-2", "TheQuartering", { file: "b.wav", engine: "kokoro", voice: "am_michael", seconds: 1 }), + post("p-3", "MadamSavvy", { file: "c.wav", engine: "orpheus", voice: "leah", seconds: 1 }), + post("p-4", "TheQuartering", { file: "d.wav", engine: "recorded", voice: "operator", seconds: 1 }), + post("p-5", "someone", { file: "e.wav", engine: "orpheus", voice: "zac", seconds: 1 }), + ], + }; + const map = { madamsavvy: "leah" }; + const castMap = castVoiceMap(cast); + const resolve = (e, role, handle) => resolvePieceVoice({ handle, role }, { map, cast: castMap, self: e.handle, narrator: "zac", engine: "orpheus" }); + const all = voiceDrift(manifest, resolve); + assert.deepEqual(all.map((d) => [d.id, d.reads, d.want, d.from]), [["p-1", "orpheus:zac", "kokoro:am_michael", "cast"]]); + const r = castDrift(manifest, { cast, map, resolve }); + assert.deepEqual(r.drift.map((d) => [d.id, d.character]), [["p-1", "thequartering"]]); + assert.deepEqual(r.overrides, [{ handle: "madamsavvy", character: "savvy", cast: "orpheus:tara", project: "leah" }]); +}); diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json @@ -81,6 +81,7 @@ "./post-picture": "./post-picture.mjs", "./post-redact": "./post-redact.mjs", "./post-say": "./post-say.mjs", + "./cast": "./cast.mjs", "./post-redact-files": "./post-redact-files.mjs", "./post-slurs": "./post-slurs.mjs", "./post-thread": "./post-thread.mjs", diff --git a/umtool/report-to-video/post-narration.mjs b/umtool/report-to-video/post-narration.mjs @@ -191,9 +191,10 @@ const RENDER_KEYS = new Set([...MIX_KEYS.filter((k) => k !== "attach"), "engine" const ITEM_KEYS = new Set([...MIX_KEYS, "script", "excerpt", "engine", "voice", "speed", "takes", "pick", "approved", "off", "window"]); const TAKE_KEYS = new Set(["file", "engine", "voice", "seconds", "script", "at", "note", "speed", "lufs", "jobId", "parts", "label", "source", "steps", "words", "slurs", "lexicon", "read"]); const STEP_KEYS = new Set(["op", "engine", "voice", "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. +// `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). // `tempo`: the part's reading speed in the take's file against its first read (a `tempo` step's; absent: 1). -const PART_KEYS = new Set(["n", "para", "text", "file", "start", "seconds", "gapBefore", "note", "at", "jobId", "role", "voice", "piece", "tempo"]); +const PART_KEYS = new Set(["n", "para", "text", "file", "start", "seconds", "gapBefore", "note", "at", "jobId", "role", "voice", "engine", "piece", "tempo"]); const VOICE_RE = /^[A-Za-z0-9][A-Za-z0-9_.+-]{0,63}$/; /** Orpheus's expressive tags (narration.mjs NARRATION_TAGS, the editor's list). */ const TAGS = ["laugh", "chuckle", "sigh", "cough", "sniffle", "groan", "yawn", "gasp"]; @@ -698,6 +699,7 @@ export function validatePostNarration(e) { if (p.text !== undefined && typeof p.text !== "string") errors.push(`${pw}.text must be the words it reads`); if (p.tempo !== undefined && !numIn(p.tempo, POST_NARRATION_LIMITS.tempo)) errors.push(`${pw}.tempo must be ${POST_NARRATION_LIMITS.tempo.join("–")} (its reading speed in the take)`); if (p.role !== undefined && !(typeof p.role === "string" && /^(post|quoted|parent:\d|media:\d|linked:\d)$/.test(p.role))) errors.push(`${pw}.role must be post, quoted, parent:<i>, linked:<i> or media:<i> (the text it reads)`); + if (p.engine !== undefined && !POST_NARRATION_ENGINES.includes(p.engine)) errors.push(`${pw}.engine must be one of ${POST_NARRATION_ENGINES.join(", ")}`); }); } }); @@ -730,8 +732,14 @@ export function postNarrationDisclosure(entry) { // A recorded take is a person's own voice: nothing synthetic to disclose. if (root.engine === "recorded" || takeSourceOf(root).kind === "recorded") return null; if (root !== t) return postNarrationDisclosure({ ...entry, narration: { ...entry.narration, takes: [root], pick: 0 } }); - const label = { orpheus: "Orpheus", kokoro: "Kokoro-82M", "espeak-ng": "eSpeak NG" }[t.engine] ?? t.engine ?? "a stock voice"; - return `Narration: synthetic voice (${label} · ${t.voice ?? "?"})`; + const labelOf = (e) => ({ orpheus: "Orpheus", kokoro: "Kokoro-82M", "espeak-ng": "eSpeak NG" })[e] ?? e ?? "a stock voice"; + // A read joined from two engines' parts (a cast voice naming its own engine): each engine with its voices. + const parts = Array.isArray(t.parts) ? t.parts.filter((p) => typeof p?.voice === "string") : []; + const engines = [...new Set(parts.map((p) => p.engine ?? t.engine))]; + if (engines.length > 1) { + return `Narration: synthetic voices (${engines.map((e) => `${labelOf(e)} · ${[...new Set(parts.filter((p) => (p.engine ?? t.engine) === e).map((p) => p.voice))].join("+")}`).join("; ")})`; + } + return `Narration: synthetic voice (${labelOf(t.engine)} · ${t.voice ?? "?"})`; } // --------------------------------------------------------------------------- diff --git a/umtool/report-to-video/post-say.mjs b/umtool/report-to-video/post-say.mjs @@ -34,10 +34,15 @@ // // THE VOICE MAP -- `narration/voices.json` in the project, `{ "<handle>": // "<voice>", "*": "<voice>" }`: the stock voice each author's words are read -// in by a thread read (lib/report/postThreadRead.mjs). Handles without "@", -// any case. "*" is everyone the map does not name (default: CONTEXT_VOICE_DEFAULTS -// for the engine). The item's own author reads in the item's narrator voice -// unless the map names them. +// in by a read (a single post's take, each piece of a thread read: +// lib/report/postThreadRead.mjs). Handles without "@", any case. A voice is +// bare ("tara": the read's engine) or names its engine ("kokoro:am_michael"). +// "*" is everyone the map does not name (default: CONTEXT_VOICE_DEFAULTS for +// the engine). The map is the project's OVERRIDE LAYER over THE CAST +// (cast.mjs: the characters that recur across projects, each with its voice): +// the read's own override, the map, the cast, the narrator's (the item's own +// author), the map's "*", the default -- voiceForPiece, the one function every +// read goes through. // // PURE and dependency-free. @@ -57,7 +62,10 @@ export const CONTEXT_VOICE_DEFAULTS = Object.freeze({ orpheus: "leo" }); const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); const str = (v) => (typeof v === "string" ? v : ""); -const VOICE_RE = /^[A-Za-z0-9][A-Za-z0-9_.+-]{0,63}$/; +const VOICE_RE = /^(?:(?:orpheus|kokoro|espeak-ng):)?[A-Za-z0-9][A-Za-z0-9_.+-]{0,63}$/; +const BARE_VOICE_RE = /^[A-Za-z0-9][A-Za-z0-9_.+-]{0,63}$/; +/** The tts engines a voice may name (the editor's tts op). */ +export const TTS_ENGINE_IDS = Object.freeze(["orpheus", "kokoro", "espeak-ng"]); const ITEM_RE = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/; const HANDLE_RE = /^[A-Za-z0-9_.-]{1,64}$/; // (No `-` or `/` escaped: under the `u` flag an escape outside a class must be a syntax character.) @@ -228,28 +236,66 @@ export function validateVoiceMap(map, where = VOICES_FILE) { const errors = []; for (const k of keys) { if (k !== VOICE_MAP_OTHER && (!HANDLE_RE.test(k) || k !== handleKey(k))) errors.push(`${where}: "${k}" is not a handle as the map keys it (lower case, no @), or "*"`); - if (typeof map[k] !== "string" || !VOICE_RE.test(map[k])) errors.push(`${where}.${k} must be a stock voice's id`); + if (typeof map[k] !== "string" || !VOICE_RE.test(map[k])) errors.push(`${where}.${k} must be a stock voice's id ("tara", or with its engine "kokoro:am_michael")`); } return errors; } /** - * The voice one piece of a read is said in, pure. In order: the run's own `overrides` (`--voice-for`), the - * item's `voice` for its own post (`--voice`), the map's for the author, the narrator's for the item's own author, - * the map's "*", the engine's context default, the narrator's. + * A voice as written -- `"kokoro:am_michael"`, or bare `"tara"` (the read's engine, `engine`) -- as `{ engine, + * voice }`; null when it is neither (a path, a URL, an engine the editor has not). + */ +export function voiceRefOf(spec, engine = null) { + const s = str(spec).trim(); + if (!s) return null; + const at = s.indexOf(":"); + if (at < 0) return BARE_VOICE_RE.test(s) ? { engine: engine ?? null, voice: s } : null; + const e = s.slice(0, at); + const v = s.slice(at + 1); + if (!TTS_ENGINE_IDS.includes(e) || !BARE_VOICE_RE.test(v)) return null; + return { engine: e, voice: v }; +} + +/** `{engine, voice}` as `engine:voice` (bare when there is no engine). */ +export const voiceSpecOf = (r) => (r?.engine ? `${r.engine}:${r.voice}` : str(r?.voice)); + +/** + * The voice one piece of a read is said in, and WHERE IT CAME FROM, pure: `{ spec, from }` -- `spec` as written + * (bare or `engine:voice`), `from` one of "override" (`--voice-for`, `--voice`), "project" (the map), "cast" (the + * cast's character for the handle), "narrator" (the item's own author: the narrator's voice), "default". In order: + * the run's own `overrides` (`--voice-for`), the item's `voice` for its own post (`--voice`), the map's for the + * author, the CAST's, the narrator's for the item's own author, the map's "*", the engine's context default, the + * narrator's. * * @param {{ handle?: string | null, role: string }} piece - * @param {{ map?: Record<string, string>, overrides?: Record<string, string>, self?: string | null, voice?: string | null, - * narrator: string, engine?: string }} o + * @param {{ map?: Record<string, string>, cast?: Record<string, string>, overrides?: Record<string, string>, + * self?: string | null, voice?: string | null, narrator: string, engine?: string }} o */ -export function voiceForPiece(piece, { map = {}, overrides = {}, self = null, voice = null, narrator, engine = "orpheus" }) { +export function voiceSourceOf(piece, { map = {}, cast = {}, overrides = {}, self = null, voice = null, narrator, engine = "orpheus" }) { const h = handleKey(piece?.handle); const mine = piece?.role === "post" || (!!h && h === handleKey(self)); - if (h && overrides[h]) return overrides[h]; - if (piece?.role === "post" && voice) return voice; - if (h && map[h]) return map[h]; - if (mine) return narrator; - return map[VOICE_MAP_OTHER] ?? CONTEXT_VOICE_DEFAULTS[engine] ?? narrator; + if (h && overrides[h]) return { spec: overrides[h], from: "override" }; + if (piece?.role === "post" && voice) return { spec: voice, from: "override" }; + if (h && h !== VOICE_MAP_OTHER && map[h]) return { spec: map[h], from: "project" }; + if (h && h !== VOICE_MAP_OTHER && cast?.[h]) return { spec: cast[h], from: "cast" }; + if (mine) return { spec: narrator, from: "narrator" }; + if (map[VOICE_MAP_OTHER]) return { spec: map[VOICE_MAP_OTHER], from: "project" }; + return { spec: CONTEXT_VOICE_DEFAULTS[engine] ?? narrator, from: "default" }; +} + +/** The voice one piece of a read is said in, as written (voiceSourceOf's `spec`). */ +export function voiceForPiece(piece, o) { + return voiceSourceOf(piece, o).spec; +} + +/** + * The voice one piece is said in, RESOLVED: `{ engine, voice, from }` -- a bare voice in the read's `engine`, one that + * names its own engine in that one. The thread read and a single post's take both ask this. + */ +export function resolvePieceVoice(piece, o) { + const { spec, from } = voiceSourceOf(piece, o); + const ref = voiceRefOf(spec, o.engine ?? "orpheus") ?? { engine: o.engine ?? "orpheus", voice: String(spec) }; + return { engine: ref.engine ?? o.engine ?? "orpheus", voice: ref.voice, from }; } /** `--voice-for h=v` words as `{ handle: voice }` (handles keyed as the map keys them); throws naming a bad one. */