commit 09d24d6fb305ee40a38c2f53d668555e70c81a03
parent 8a3024a4409cfd6000a713b6e6ebcf61488d8f6b
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Fri, 6 Nov 2026 23:05:54 -0500
Merge lane/cast: a cast of voices -- per-character stock voices shared across projects (<reports>/.umtool/cast.json), one resolver for every read, a Voices page that auditions candidates side by side scored for closeness to the real speaker (a reference, never a target), re-reads queued for approval, a recording cleaned and converted to a character's voice; umtool cast CLI and a lint guard (operator, 6 Nov: "pick different voices for different characters, and in UI alone be able to try rendering different ones to compare … maintain consistent voices for different repeating characters")
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
30 files changed, 3237 insertions(+), 69 deletions(-)
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -1,6 +1,7 @@
# Changelog
## [Unreleased]
+- **umtool: each character has a voice, auditioned on a page, the same in every project.** The operator wanted 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" -- tonight TheQuartering's reads were re-voiced by hand after scoring five voices against his real one. `/projects/<p>/voices` (from the Cut tab's Reads and voices) lists every character a project's reads use, the voice each reads in now and where it comes from (the cast, the project, the narrator's, the default), its reads in another voice, and its real voice. **Audition** reads one line (its own words here, a stock line, or typed) in 2-6 stock voices -- a job: the editor's tts, then each one's closeness to the real voice (speakers.json, TitaNet, local) -- played side by side at one loudness beside the real voice, a reference never a target. **Use for this project** or **Use everywhere** (the cast, `<reports>/.umtool/cast.json`), then the items to re-read, queued. A recording of an item can be made a character's read: kept, cleaned, converted to its stock voice. Every read -- a single post's and each piece of a thread read -- asks the same order (the read's own, the project's map, the cast, the narrator's, the default), and a cast voice of another engine is synthesized by it. `umtool cast ls|add|set|rm|undo|project|audition|use|reread`, `posts narrate … --recording`, and `umtool lint` warns when a cast character is read in another voice.
- **Rumble clips play the words their quotes say: one clock per recording.** On 6 Nov seven Rumble clips of the weight video played other words than their quotes, c43 13.1 seconds early (the "310" clip), and one stream was right at 10 minutes and 13.6 seconds off at 38. A Rumble channel's transcript is made from a separate audio download, and its clips were cut from another file; the two do not keep the same time, and not by a constant. The operator: "stop trying to grab rumble individual clips and instead grab whole streams and clip after." **Whole, never seeked:** umtool's fetch (the bench's fetch more, `umtool fetch`, a build's fetch) asks for a Rumble clip through Fetch windows, which saves the stream once and cuts the clip from it; nothing falls back to a seek, and a failed save says why. **The right video:** a report cites a Rumble video by its embed id while the archive keeps it under its page's id; every fetch, save and render now finds the video under either (6 Nov: every such fetch went to a folder that did not exist, and one got a Rumble 403). **The time map:** before a clip is cut from a saved Rumble stream, the stream's audio is matched against the audio the transcript was made from, every 5 minutes and around each clip, and the map (`clock.json` beside the video, with how well it fits) moves every cut onto the transcript's time; clips cut before the map, or by a seek, are cut again. A stretch where the two files part (a dropped piece of the stream) is narrowed to a few seconds, and a clip on it is said to be uncertain. **The check:** `umtool quote-check <project>` has the editor transcribe what each clip will actually play and finds the quote in it: `moved` (heard seconds away), `not-found`, or `ok`; `umtool window <p> <clip> --align` puts the cut on the words as heard, `umtool check` blocks on a moved or missing quote, a take refuses one unless a person rules it (`--quote-ruled`), and `umtool prep --status` counts them. Needs a restart of the editor (umtool's half works at once).
- **umtool: a counter series nobody counted shows 0, and a text card can count.** The Leaflit side-tally video has no title or totals cards, so the deck's counter is the only place the counts show, and it left out "Left" (the point of the video: she never once says she is on the left) because the tally drew only the series some mark used. A series of `deck.counter` that says `showAt: "always"` (its own, or the counter's) is now a cell from the first frame, dim at 0, whether or not anything counts it; a series that says nothing (so a counter `umtool migrate` wrote draws what it drew), a `first` series, and the fact-check verdicts' tally of a cut without a `deck.counter` are as before, and a cut that counts nothing still draws no counter. Her two X posts are text cards (`teaser`s), which could not carry a mark, so they did not step the count. A teaser now takes marks as a clip does (`umtool set <p> x-d28 mark.add=CENTER@2.15`, the second counted from the card's start; validated, stamped over the card, counted, in Play and the On-screen table), and a teaser that carries one keeps the deck up over it, with no title of its own, so the count is seen to step. A teaser that dips still hides the deck at the black.
- **Free disk, weekly, with one command: `archilyzer housekeeping`.** On 6 Nov /home was at 37 GB free, and a session freed 83 GB by hand. The operator: "We should build a regularly run command for this after we're done." It runs three passes of the apps' own commands. **Superseded takes:** `umtool prune --versions` deletes whole takes through `umtool takes delete`. Per version line it keeps the highest built number; the line is the take id with its digits folded (`draft-3` and `draft-4`), and a letter is never folded (`v6c` is not `v6d`, `release-6u` is not `release-6`). An older take goes only once the newer one is 7 days old (`--grace`). It also keeps any take picked, pinned, given any verdict, rendering, a build's base, the manifest's, with operator notes on it, or refused by `takes delete`, and skips a project whose verdicts file cannot be read. **Work files:** every project's takes' work files by its prune policy; in a project idle 3 days, the newest and picked takes' work goes too (`--idle-work`). **Worktrees:** `pnpm wt prune` removes merged, clean, idle worktrees with no process in them and no ignored files of anyone's (a corpus, an env file, a changed settings file, a nested repository), keeping their branches. A project or worktree touched in the last 3 days is left alone, and a run is skipped while a render, an e2e suite or a heavy job runs, or when that cannot be checked. Each run is recorded in `~/.local/state/archilyzer/housekeeping.json`. **Worktree ports no longer move:** a worktree's port block is recorded when it is added, so removing another worktree cannot shift a running suite's ports. **Upgrading:** `archilyzer service install` (host mode) now also installs `archilyzer-housekeeping.timer`, weekly; `--dry-run` shows it first, and `--no-housekeeping` leaves it out. OPERATING.md, "Free disk".
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/app/api/report/voices/route.ts b/umtool/app/api/report/voices/route.ts
@@ -0,0 +1,194 @@
+import { existsSync } from "node:fs";
+import { mkdir, writeFile } from "node:fs/promises";
+import path from "node:path";
+import { listTtsEngines } from "yt-dlp-transcript-common/lib/ttsApps";
+import { getJob, jobView, runningJob, startJob } from "@/lib/jobs";
+import { projectRef } from "@/lib/projects";
+import { refuseCaller } from "@/lib/report/caller";
+import { castCommand } from "@/lib/report/castCli.mjs";
+import { auditionSteps, auditionView, referenceFor, AUDITION_MAX } from "@/lib/report/castAudition.mjs";
+import { castForProject } from "@/lib/report/castStore.mjs";
+import { UMTOOL_DIR } from "@/lib/report/driver.mjs";
+import { addStep } from "@/lib/queue/store.mjs";
+import { kickQueue, queueDir } from "@/lib/queue/runner";
+import { REPORTS_ROOT } from "@/lib/projects/core.mjs";
+import { CAST_CONVERT_ENGINES, ENGINE_WEIGHT, charactersOf } from "umtool-report-to-video/cast";
+
+export const dynamic = "force-dynamic";
+
+// THE VOICES PANEL (operator, 6 Nov 2026: "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"): /projects/<p>/voices. Every write is the CLI's own command (lib/report/castCli.mjs), run here;
+// the long work is a JOB (lib/jobs.ts: its log, Cancel) or steps of the QUEUE (/jobs).
+//
+// GET ?project the project's characters (umtool cast project), the cast, the
+// engines and their stock voices, the job running
+// GET ?project&who&voices=a,b[&text|&item] an audition as it is kept (auditionView: nothing asked)
+// GET ?job=<id>[&since&sinceEvent] that job
+// POST { project, op: "audition", who, voices: [..], text?, item? } a JOB: the editor's tts for the candidates not
+// kept, then (with a reference) their closeness to the real voice
+// through the heavy slot
+// POST { project, op: "use", who, voice, scope: "project" | "cast" } umtool cast use <p> <who> <voice> [--everywhere]
+// POST { project, op: "reread", who } QUEUED: one `posts narrate … --take [--thread …]` step per item
+// whose picked read says them in another voice (the argv built here)
+// POST { project, op: "cast-rm", id } | { op: "cast-undo" } | { op: "cast-set", id, convertEngine?, narrator? }
+// POST multipart { project, op: "recording", item, as?, clean?, convert?, file } a JOB: posts narrate <p> <item>
+// --recording <file> (kept, cleaned, converted to a STOCK voice)
+const headers = { "cache-control": "no-store" };
+
+async function cli(args: string[]) {
+ const out: string[] = [];
+ const err: string[] = [];
+ const code = await castCommand([...args, "--json"], { reportsRoot: REPORTS_ROOT, log: (s: string) => out.push(s), err: (s: string) => err.push(s) });
+ let json: Record<string, unknown> | null = null;
+ try {
+ json = JSON.parse(out.join("\n") || "null");
+ } catch {
+ json = null;
+ }
+ return { code, json, error: code === 0 ? null : (json?.error as string | undefined) ?? (err.join("\n") || "refused") };
+}
+
+/** The checkout's heavy-slot CLI, when this umtool sits in the checkout (speakerCheck.mjs's rule). */
+function queueLockScript() {
+ const file = path.join(/* turbopackIgnore: true */ UMTOOL_DIR, "..", "scripts", "queue-lock.mjs");
+ return existsSync(/* turbopackIgnore: true */ file) ? file : null;
+}
+
+const mine = (project: string) => {
+ const r = runningJob();
+ return r && r.project === project && (r.kind.startsWith("cast-audition ") || r.kind.startsWith("cast-recording ")) ? jobView(r) : null;
+};
+
+export async function GET(request: Request) {
+ const url = new URL(request.url);
+ const id = url.searchParams.get("job");
+ if (id) {
+ const job = getJob(id);
+ if (!job) return Response.json({ error: "no such job" }, { status: 404 });
+ return Response.json(jobView(job, Number(url.searchParams.get("since") ?? 0), Number(url.searchParams.get("sinceEvent") ?? 0)), { headers });
+ }
+ const project = await projectRef(String(url.searchParams.get("project") ?? ""));
+ if (!project) return Response.json({ error: "no such project" }, { status: 404 });
+ const who = url.searchParams.get("who");
+ try {
+ if (who) {
+ const castRead = await castForProject(project.dir);
+ const voices = String(url.searchParams.get("voices") ?? "").split(",").map((s) => s.trim()).filter(Boolean).slice(0, AUDITION_MAX);
+ const view = await auditionView(project, castRead.cast, who, { voices, text: url.searchParams.get("text"), item: url.searchParams.get("item") });
+ return Response.json(view, { headers });
+ }
+ const r = await cli(["project", project.id]);
+ if (r.code !== 0) return Response.json({ error: r.error }, { status: 400 });
+ const castRead = await castForProject(project.dir);
+ return Response.json(
+ {
+ ...r.json,
+ cast: charactersOf(castRead.cast),
+ castToken: castRead.token,
+ engines: listTtsEngines().map((e) => ({ id: e.id, label: e.label, voices: e.voices, defaultVoice: e.defaultVoice, weight: ENGINE_WEIGHT[e.id as keyof typeof ENGINE_WEIGHT] ?? "fast" })),
+ convertEngines: CAST_CONVERT_ENGINES,
+ running: mine(project.id),
+ },
+ { headers },
+ );
+ } catch (e) {
+ return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 400 });
+ }
+}
+
+export async function POST(request: Request) {
+ const refused = refuseCaller(request, "/api/report/voices");
+ if (refused) return refused;
+ const multipart = (request.headers.get("content-type") ?? "").startsWith("multipart/");
+ let b: Record<string, unknown> | null = null;
+ let form: FormData | null = null;
+ if (multipart) {
+ form = await request.formData().catch(() => null);
+ if (!form) return Response.json({ error: "bad form" }, { status: 400 });
+ b = Object.fromEntries([...form.entries()].filter(([, v]) => typeof v === "string"));
+ } else b = (await request.json().catch(() => null)) as Record<string, unknown> | null;
+ if (!b) return Response.json({ error: "bad json" }, { status: 400 });
+ const project = await projectRef(String(b.project ?? ""));
+ if (!project) return Response.json({ error: "no such project" }, { status: 404 });
+ const s = (k: string) => (typeof b![k] === "string" ? (b![k] as string).trim() : "");
+ const op = s("op");
+ try {
+ if (op === "audition") {
+ const who = s("who");
+ const voices = (Array.isArray(b.voices) ? b.voices : String(b.voices ?? "").split(",")).map((v) => String(v).trim()).filter(Boolean);
+ if (!who || !voices.length) return Response.json({ error: "an audition is of a character, with its candidates" }, { status: 400 });
+ if (voices.length > AUDITION_MAX) return Response.json({ error: `at most ${AUDITION_MAX} candidates` }, { status: 400 });
+ const running = runningJob();
+ if (running) return Response.json({ error: `a job is already running (${running.kind})`, running: jobView(running) }, { status: 409 });
+ const castRead = await castForProject(project.dir);
+ // Check the ask before it is a job: the candidates, the character, the line (auditionView refuses what the CLI would).
+ const view = await auditionView(project, castRead.cast, who, { voices, text: s("text") || null, item: s("item") || null });
+ const reference = await referenceFor(project, view.character);
+ const plan = auditionSteps(project, { who, voices: view.candidates.map((c) => c.spec), text: s("text") || null, item: s("item") || null, score: !!reference, umtoolDir: UMTOOL_DIR, queueLock: queueLockScript() });
+ const job = startJob(plan.kind, plan.steps, { project: project.id });
+ return Response.json({ ok: true, job: jobView(job), audition: view }, { headers });
+ }
+ if (op === "use") {
+ const scope = s("scope") === "cast" ? "cast" : "project";
+ const r = await cli(["use", project.id, s("who"), s("voice"), ...(scope === "cast" ? ["--everywhere"] : [])]);
+ return Response.json(r.code === 0 ? r.json : { error: r.error }, { status: r.code === 0 ? 200 : 400, headers });
+ }
+ if (op === "reread") {
+ // The plan the CLI makes (its argv built from the take's own read record), each item a step of the queue.
+ const r = await cli(["reread", project.id, s("who"), "--dry-run"]);
+ if (r.code !== 0) return Response.json({ error: r.error }, { status: 400 });
+ const items = ((r.json?.items ?? []) as Array<{ id: string; argv: string[] }>).filter((x) => Array.isArray(x.argv) && x.argv[0] === "posts" && x.argv[1] === "narrate" && x.argv[2] === project.id);
+ const queued: string[] = [];
+ for (const x of items) {
+ const step = (await addStep(queueDir(), {
+ argv: x.argv,
+ label: `re-read ${x.id} of ${project.id} (${s("who")}'s new voice)`,
+ target: { project: project.id, take: null },
+ by: "the umtool app (Voices)",
+ })) as { qid: string };
+ queued.push(step.qid);
+ }
+ if (queued.length) kickQueue();
+ return Response.json({ ok: true, queued, items: items.map((x) => x.id), skipped: r.json?.skipped ?? [] }, { headers });
+ }
+ if (op === "cast-rm") {
+ const r = await cli(["rm", s("id")]);
+ return Response.json(r.code === 0 ? r.json : { error: r.error }, { status: r.code === 0 ? 200 : 400, headers });
+ }
+ if (op === "cast-undo") {
+ const r = await cli(["undo"]);
+ return Response.json(r.code === 0 ? r.json : { error: r.error }, { status: r.code === 0 ? 200 : 400, headers });
+ }
+ if (op === "cast-set") {
+ const args = ["set", s("id")];
+ if (s("convertEngine")) args.push("--convert-engine", s("convertEngine"));
+ if (b.narrator === true || s("narrator") === "on") args.push("--narrator");
+ if (b.narrator === false || s("narrator") === "off") args.push("--no-narrator");
+ if (s("name")) args.push("--name", s("name"));
+ const r = await cli(args);
+ return Response.json(r.code === 0 ? r.json : { error: r.error }, { status: r.code === 0 ? 200 : 400, headers });
+ }
+ if (op === "recording") {
+ const file = form?.get("file");
+ const item = s("item");
+ if (!(file instanceof Blob) || !file.size) return Response.json({ error: "a recording is a sound file" }, { status: 400 });
+ if (!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(item)) return Response.json({ error: "which post item?" }, { status: 400 });
+ const running = runningJob();
+ if (running) return Response.json({ error: `a job is already running (${running.kind})`, running: jobView(running) }, { status: 409 });
+ const name = String((file as File).name ?? "recording").replace(/[^A-Za-z0-9._-]+/g, "-").slice(-80) || "recording";
+ const dir = path.join(project.dir, "narration", "uploads");
+ await mkdir(dir, { recursive: true });
+ const abs = path.join(dir, `${new Date().toISOString().replace(/[:.]/g, "-")}-${name}`);
+ await writeFile(abs, Buffer.from(await file.arrayBuffer()));
+ const cliPath = path.join(/* turbopackIgnore: true */ UMTOOL_DIR, "bin", "umtool.mjs");
+ const argv = [process.execPath, cliPath, "posts", "narrate", project.id, item, "--recording", abs, ...(s("as") ? ["--as", s("as")] : []), ...(s("clean") === "off" ? ["--no-clean"] : []), ...(s("convert") === "off" ? ["--no-convert"] : []), "--json"];
+ const job = startJob(`cast-recording ${project.id}`, [{ label: `${item}: the recording kept, cleaned, converted`, argv, cwd: path.join(/* turbopackIgnore: true */ UMTOOL_DIR, ".."), env: {}, timeoutMs: 45 * 60 * 1000 }], { project: project.id });
+ return Response.json({ ok: true, job: jobView(job), file: path.relative(project.dir, abs) }, { headers });
+ }
+ return Response.json({ error: "op must be audition, use, reread, cast-rm, cast-undo, cast-set or recording" }, { status: 400 });
+ } catch (e) {
+ const status = (e as { status?: number }).status ?? 400;
+ return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status, headers });
+ }
+}
diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs
@@ -15,6 +15,7 @@
// umtool show <project> [--json]
// umtool check [<project> | --all] [--json] exit 1 on anything blocking
// umtool links <project> [--json] [--fix] do the clip QRs open on their sites (out/links.json)
+// umtool cast [ls|add|set|rm|undo|project|audition|use|reread] … the characters' voices across projects (castCli.mjs)
// umtool speaker-check <project> [--clip <id> …] [--set 'Name=…'] [--list] which named voice each clip is (speaker-check.json)
// umtool quote-check <project> [--clips a,b] [--status] is each clip's quote in the seconds it plays (quote-check.json)
// umtool check-joins <project> --take <id> [--json] [--all] do the post joins of a rendered take carry on, or jump
@@ -866,6 +867,10 @@ function usage() {
" umtool check [<project>] [--json] exit 1 on anything blocking",
" umtool links <project> [--json] [--fix] do the clip QRs open on their sites? (corpus.json -> slugToPage",
" -> the shard's record; polite, cached; out/links.json, which check reads); exit 1 when one is dead",
+ " umtool cast [ls] | add <id> --name … --voice <engine:voice> [--handles a,b] | set <id> … | rm <id> | undo",
+ " | project <p> | audition <character> --voices a,b,c [--project <p>] [--text …] | use <p> <character> <voice>",
+ " [--everywhere] | reread <p> <character> the CAST: characters' stock voices across projects (cast.json), a",
+ " project's characters and their drift, an audition of candidate voices (scored against the real voice)",
" umtool speaker-check <project> [--clip <id> …] [--json] which of the project's named voices (speakers.json) each",
" clip is: TitaNet-small, local -> speaker-check.json; --set 'Name=<clip>,<channel>/<id>,channel:<slug>' / --remove / --list",
" umtool quote-check <project> [--clips a,b] [--pad S] [--json] | --status is each clip's quote in the seconds it plays?",
@@ -1184,6 +1189,8 @@ const COMMANDS = {
vertical: async () => process.exit(await (await import("../lib/report/verticalCli.mjs")).verticalCommand(argv.slice(argv.indexOf("vertical") + 1))),
// Do the QR links open on their sites (UI notes #8): lib/report/linksCli.mjs.
links: async () => process.exit(await (await import("../lib/report/linksCli.mjs")).linksCommand(argv.slice(argv.indexOf("links") + 1))),
+ // The cast: characters' voices across projects, auditions, a project's voices (operator, 6 Nov): lib/report/castCli.mjs.
+ cast: async () => process.exit(await (await import("../lib/report/castCli.mjs")).castCommand(argv.slice(argv.indexOf("cast") + 1))),
// Which named voice each clip is (UI notes #15): lib/report/speakerCheck.mjs.
"speaker-check": async () => process.exit(await (await import("../lib/report/speakerCheck.mjs")).speakerCheckCommand(argv.slice(argv.indexOf("speaker-check") + 1))),
// Is each clip's quote in the seconds it plays (lane one-clock): the editor transcribes, quote-check.json keeps the rows.
diff --git a/umtool/components/projects/ProjectView.tsx b/umtool/components/projects/ProjectView.tsx
@@ -11,6 +11,7 @@ import TakesPage from "./TakesPage";
import TakesComparePage from "./TakesComparePage";
import NarrationPage from "./NarrationPage";
import RecordPage from "./RecordPage";
+import VoicesPage from "./VoicesPage";
import ReviewPage from "./ReviewPage";
import ClipDeckPage from "./ClipDeckPage";
import PlayCutPage from "./PlayCutPage";
@@ -84,6 +85,8 @@ export default async function ProjectView({
if (rest.length === 1 && rest[0] === "narration") return <NarrationPage project={project} />;
// `/projects/<project>/narration/record` -- the recording session: the cut's posts read aloud, part by part.
if (rest.length === 2 && rest[0] === "narration" && rest[1] === "record") return <RecordPage project={project} search={search} />;
+ // `/projects/<project>/voices` -- each character's voice, auditions, the cast (lib/report/castCli.mjs).
+ if (rest.length === 1 && rest[0] === "voices") return <VoicesPage project={project} search={search} />;
// `/browse/<project>/review` -- every drafted field, approved / rejected
// before a final build, and the alternatives a draft task kept.
if (rest.length === 1 && rest[0] === "review") return <ReviewPage project={project} view={search.view} />;
diff --git a/umtool/components/projects/PronunciationPanel.tsx b/umtool/components/projects/PronunciationPanel.tsx
@@ -3,7 +3,7 @@
import { useCallback, useEffect, useState } from "react";
import { buttonVariants } from "@/components/ui/button";
import { cn } from "@/lib/utils";
-import { jobsHref } from "@/lib/hrefs";
+import { jobsHref, voicesHref } from "@/lib/hrefs";
// ---------------------------------------------------------------------------
// READS AND VOICES for a cut of posts (lane/ui-simplify, 5 Nov): the
@@ -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 };
@@ -123,6 +123,9 @@ export default function PronunciationPanel({ project }: { project: string }) {
<section data-voice-map={Object.keys(v?.voices ?? {}).length}>
<h3 className="micro mb-1">
Voices · the narrator {v?.engine ?? ""} {v?.narrator ?? ""}
+ <a href={voicesHref(project)} data-voices-link="" className="ink-link ml-2 normal-case tracking-normal">
+ audition and compare voices · the cast →
+ </a>
</h3>
<table className="w-full border-collapse">
<tbody>
@@ -144,7 +147,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/components/projects/VoicesPage.tsx b/umtool/components/projects/VoicesPage.tsx
@@ -0,0 +1,34 @@
+import { notFound } from "next/navigation";
+import AppShell from "@/components/shell/AppShell";
+import VoicesPanel from "./VoicesPanel";
+import { readManifest } from "@/lib/projects/report.mjs";
+import { projectHref } from "@/lib/hrefs";
+import type { ProjectRef } from "@/lib/project-types";
+
+// THE VOICES PAGE (operator, 6 Nov 2026: "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"): /projects/<p>/voices -- every character the project's reads use and the voice each reads in now
+// (and where it comes from: the cast, the project, the default), an audition of candidate voices side by side at
+// one loudness with their closeness to the real voice, Use this voice (here, or everywhere: the cast) and the
+// re-reads it asks for, and a recording made a character's read. The panel is VoicesPanel; the routes
+// /api/report/voices (the CLI's own commands: umtool cast).
+
+type Entry = { id: string; type?: string; handle?: string; author?: string; text?: string };
+
+export default async function VoicesPage({ project, search = {} }: { project: ProjectRef; search?: Record<string, string | undefined> }) {
+ const m = (await readManifest(project.dir)) as { timeline?: Entry[] } | null;
+ if (!m) notFound();
+ const posts = (m.timeline ?? []).filter((e) => e?.type === "post").map((e) => ({ id: e.id, handle: String(e.handle ?? ""), author: String(e.author ?? ""), text: String(e.text ?? "").slice(0, 80) }));
+ return (
+ <div className="flex h-full flex-col">
+ <AppShell
+ active="projects"
+ crumbs={[{ href: "/projects", label: "Projects" }, { href: projectHref(project.id, { tab: "cut" }), label: project.name }, { label: "voices" }]}
+ note="each character's voice · auditions · the cast"
+ />
+ <main className="deck-main flex-1 overflow-auto p-4">
+ <VoicesPanel project={project.id} posts={posts} initialWho={search.who ?? null} />
+ </main>
+ </div>
+ );
+}
diff --git a/umtool/components/projects/VoicesPanel.tsx b/umtool/components/projects/VoicesPanel.tsx
@@ -0,0 +1,615 @@
+"use client";
+
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { buttonVariants } from "@/components/ui/button";
+import { cn } from "@/lib/utils";
+import { jobsHref, postBenchHref } from "@/lib/hrefs";
+
+// ---------------------------------------------------------------------------
+// THE VOICES PANEL (components/projects/VoicesPage.tsx; /api/report/voices; the CLI is `umtool cast`). Works with
+// the operator alone: nothing here needs an agent.
+//
+// the characters every author the project's reads use, the voice each reads in NOW and where it comes from
+// (cast · project · narrator · default), how many items it reads, its picked reads in another
+// voice (drift), its real voice (speakers.json) -- Audition opens the box below for it
+// the audition a line (its own words in this project, a stock line, or typed), 2-6 candidate stock voices
+// (Kokoro fast, Orpheus heavy), Render: a job (the editor's tts; then the closeness to the real
+// voice through the heavy slot), each candidate played side by side at ONE loudness, with its
+// closeness score; the real voice beside them as a reference, never a target
+// use this voice for this project (its voice map) or everywhere (the cast), then the re-reads it asks for,
+// confirmed, queued (each a new take, picked, awaiting approval)
+// the cast every character across projects; remove one, undo the last change
+// a recording a person's read of an item made a character's: kept, cleaned, converted to its stock voice
+// ---------------------------------------------------------------------------
+
+type Voice = { engine: string; voice: string; spec: string; from: string };
+type Drift = { id: string; handle: string; role: string; reads: string; want: string; from: string | null; kind: string; thread: boolean };
+type Character = {
+ key: string; name: string; handles: string[];
+ character: { id: string; name: string; voice: string; convert?: { engine?: string; voice?: string }; note?: string; narrator?: boolean } | null;
+ items: number; context: number; itemIds: string[]; contextIds: string[];
+ voice: Voice; contextVoice?: Voice; weight: string;
+ reads: { id: string; role: string; spec: string; kind: string }[];
+ drift: Drift[]; speaker: string | null; lines: { item: string; text: string; own: boolean }[];
+};
+type CastChar = { id: string; name: string; handles?: string[]; voice: string; convert?: { engine?: string; voice?: string }; speakers?: string[]; note?: string; narrator?: boolean };
+type Engine = { id: string; label: string; voices: string[]; defaultVoice: string; weight: string };
+type View = {
+ project: string; castFile: string | null; castError?: string; map: Record<string, string>;
+ narrator: { engine: string; voice: string; spec: string; from: string; character: { id: string; name: string; voice: string } | null; recorded: { id: string; kind: string; voice: string }[] };
+ characters: Character[]; overrides: { handle: string; character: string; cast: string; project: string }[];
+ cast: CastChar[]; engines: Engine[]; convertEngines: string[]; running: { id: string; state: string; kind: string } | null;
+};
+type Candidate = { spec: string; engine: string; voice: string; weight: string; key: string; rel: string; cached: boolean; seconds: number | null; lufs: number | null; score: number | null };
+type Audition = { character: { id: string; name: string; handles: string[]; voice: string | null }; text: string; from: string; speaker: string | null; reference: string | null; candidates: Candidate[] };
+type JobPoll = { id: string; state: "running" | "done" | "failed"; error: string | null; log: string[]; stepIndex?: number; steps?: { label: string }[] };
+type Post = { id: string; handle: string; author: string; text: string };
+
+const whoOf = (c: Character) => (c.character ? c.character.id : `@${c.handles[0]}`);
+const pretty = (spec: string) => spec.replace(":", " · ");
+const FROM: Record<string, string> = { cast: "the cast", project: "this project", narrator: "the narrator's", default: "the default", override: "a read's own" };
+const fileUrl = (project: string, rel: string, v?: string | number | null) => `/api/report/file?project=${encodeURIComponent(project)}&path=${encodeURIComponent(rel)}${v ? `&v=${v}` : ""}`;
+
+export default function VoicesPanel({ project, posts, initialWho = null }: { project: string; posts: Post[]; initialWho?: string | null }) {
+ const [view, setView] = useState<View | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const [status, setStatus] = useState<string | null>(null);
+ const [busy, setBusy] = useState(false);
+ const [who, setWho] = useState<string | null>(initialWho);
+ const [line, setLine] = useState<string>("first");
+ const [custom, setCustom] = useState("");
+ const [candidates, setCandidates] = useState<string[]>([]);
+ const [addEngine, setAddEngine] = useState("kokoro");
+ const [addVoice, setAddVoice] = useState("");
+ const [audition, setAudition] = useState<Audition | null>(null);
+ const [job, setJob] = useState<JobPoll | null>(null);
+ const [reread, setReread] = useState<{ who: string; voice: string; scope: string; items: { id: string; reads: { role: string; reads: string; want: string }[] }[]; removed: string[] } | null>(null);
+ const [queued, setQueued] = useState<string[] | null>(null);
+ const [rec, setRec] = useState<{ item: string; as: string; clean: boolean; convert: boolean; file: File | null }>({ item: posts[0]?.id ?? "", as: "", clean: true, convert: true, file: null });
+ const [drag, setDrag] = useState(false);
+ const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const audios = useRef<Map<string, HTMLAudioElement>>(new Map());
+
+ const load = useCallback(async () => {
+ const r = await fetch(`/api/report/voices?project=${encodeURIComponent(project)}`, { cache: "no-store" });
+ const j = await r.json().catch(() => null);
+ if (!r.ok || !j) setError(j?.error ?? `HTTP ${r.status}`);
+ else setView(j as View);
+ }, [project]);
+ useEffect(() => {
+ void load();
+ return () => {
+ if (timer.current) clearTimeout(timer.current);
+ };
+ }, [load]);
+
+ const chosen = useMemo(() => view?.characters.find((c) => whoOf(c) === who) ?? null, [view, who]);
+ // A character that joined (or left) the cast keeps its audition open: the same handle, its new key.
+ useEffect(() => {
+ if (!view || !who || chosen) return;
+ const h = who.replace(/^@/, "");
+ const row = view.characters.find((c) => c.handles.includes(h) || c.character?.id === h);
+ if (row) setWho(whoOf(row));
+ }, [view, who, chosen]);
+ // A character picked: its voice now is the first candidate.
+ useEffect(() => {
+ if (!chosen) return;
+ setCandidates((cs) => (cs.length ? cs : [chosen.voice.spec]));
+ }, [chosen]);
+
+ const lineQuery = useMemo(() => {
+ if (line === "custom") return custom.trim() ? `&text=${encodeURIComponent(custom.trim())}` : null;
+ if (line === "stock") return `&text=${encodeURIComponent("__stock__")}`;
+ if (line.startsWith("item:")) return `&item=${encodeURIComponent(line.slice(5))}`;
+ return "";
+ }, [line, custom]);
+ const lineBody = useMemo(() => {
+ if (line === "custom") return { text: custom.trim() };
+ if (line === "stock") return { text: "__stock__" };
+ if (line.startsWith("item:")) return { item: line.slice(5) };
+ return {};
+ }, [line, custom]);
+
+ const loadAudition = useCallback(async () => {
+ if (!who || !candidates.length || lineQuery === null) {
+ setAudition(null);
+ return;
+ }
+ const r = await fetch(`/api/report/voices?project=${encodeURIComponent(project)}&who=${encodeURIComponent(who)}&voices=${encodeURIComponent(candidates.join(","))}${lineQuery}`, { cache: "no-store" });
+ const j = await r.json().catch(() => null);
+ if (!r.ok || !j) setError(j?.error ?? `HTTP ${r.status}`);
+ else {
+ setError(null);
+ setAudition(j as Audition);
+ }
+ }, [project, who, candidates, lineQuery]);
+ useEffect(() => {
+ void loadAudition();
+ }, [loadAudition]);
+
+ const follow = useCallback(
+ (id: string, then: () => void) => {
+ const tick = async () => {
+ const r = await fetch(`/api/report/voices?job=${encodeURIComponent(id)}`, { cache: "no-store" });
+ const j = (await r.json().catch(() => null)) as JobPoll | null;
+ if (!j) return;
+ setJob(j);
+ if (j.state === "running") timer.current = setTimeout(() => void tick(), 1000);
+ else then();
+ };
+ void tick();
+ },
+ [],
+ );
+
+ const post = async (body: Record<string, unknown>) => {
+ setBusy(true);
+ setError(null);
+ const r = await fetch("/api/report/voices", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, ...body }) });
+ const j = (await r.json().catch(() => ({}))) as Record<string, unknown> & { error?: string };
+ setBusy(false);
+ if (!r.ok) {
+ setError(j.error ?? `HTTP ${r.status}`);
+ return null;
+ }
+ return j;
+ };
+
+ const render = async () => {
+ setStatus(null);
+ const j = (await post({ op: "audition", who, voices: candidates, ...lineBody })) as { job?: { id: string } } | null;
+ if (j?.job) follow(j.job.id, () => void loadAudition());
+ };
+
+ const use = async (spec: string, scope: "project" | "cast") => {
+ if (!who) return;
+ const j = (await post({ op: "use", who, voice: spec, scope })) as { reread?: { id: string; reads: { role: string; reads: string; want: string }[] }[]; removed?: string[] } | null;
+ if (!j) return;
+ setStatus(`${chosen?.name ?? who} reads in ${pretty(spec)} ${scope === "cast" ? "everywhere (the cast)" : "in this project"}${j.removed?.length ? " — this project's own override of it removed" : ""}`);
+ setReread({ who, voice: spec, scope, items: j.reread ?? [], removed: j.removed ?? [] });
+ setQueued(null);
+ void load();
+ void loadAudition();
+ };
+
+ const queueRereads = async () => {
+ if (!reread) return;
+ const j = (await post({ op: "reread", who: reread.who })) as { queued?: string[] } | null;
+ if (j) {
+ setQueued(j.queued ?? []);
+ setReread(null);
+ }
+ };
+
+ const playAll = () => {
+ const list = (audition?.candidates ?? []).filter((c) => c.cached).map((c) => audios.current.get(c.key)).filter(Boolean) as HTMLAudioElement[];
+ const ref = audios.current.get("reference");
+ const seq = ref ? [ref, ...list] : list;
+ seq.forEach((a, i) => {
+ a.onended = i + 1 < seq.length ? () => void seq[i + 1].play() : null;
+ });
+ if (seq[0]) {
+ seq[0].currentTime = 0;
+ void seq[0].play();
+ }
+ };
+
+ const sendRecording = async () => {
+ if (!rec.file || !rec.item) return;
+ setBusy(true);
+ setError(null);
+ const fd = new FormData();
+ fd.set("project", project);
+ fd.set("op", "recording");
+ fd.set("item", rec.item);
+ if (rec.as) fd.set("as", rec.as);
+ fd.set("clean", rec.clean ? "on" : "off");
+ fd.set("convert", rec.convert ? "on" : "off");
+ fd.set("file", rec.file);
+ const r = await fetch("/api/report/voices", { method: "POST", body: fd });
+ const j = (await r.json().catch(() => ({}))) as { job?: { id: string }; error?: string };
+ setBusy(false);
+ if (!r.ok || !j.job) {
+ setError(j.error ?? `HTTP ${r.status}`);
+ return;
+ }
+ follow(j.job.id, () => {
+ void load();
+ setStatus(`${rec.item}: the recording is in — its takes on the item's bench`);
+ });
+ };
+
+ if (!view) return error ? <p role="alert" className="text-[12px] text-reject-text">{error}</p> : <p className="text-[12px] text-muted">reading the voices…</p>;
+
+ const input = "rounded-[3px] border border-seam-2 bg-ground px-1.5 py-[3px] text-[11.5px] text-text outline-none focus:border-signal";
+ const cell = "border-t border-seam px-2 py-1 align-top";
+ const running = job?.state === "running" || (!!view.running && !job);
+ const engine = view.engines.find((e) => e.id === addEngine) ?? view.engines[0];
+ // The closest candidate, marked only when one is closer than the rest (a tie marks none).
+ const scored = (audition?.candidates ?? []).map((c) => c.score).filter((x): x is number => typeof x === "number").sort((a, b) => b - a);
+ const best = scored.length > 1 && scored[0] > scored[1] ? scored[0] : null;
+ const missing = (audition?.candidates ?? []).filter((c) => !c.cached).length;
+ const heavy = (audition?.candidates ?? []).some((c) => !c.cached && c.weight === "heavy");
+
+ return (
+ <div className="space-y-5 text-[12.5px]" data-voices-panel={project}>
+ {/* --- the characters ------------------------------------------------------------ */}
+ <section>
+ <h2 className="micro mb-1.5">
+ the characters · {view.characters.length}
+ <span className="ml-2 normal-case tracking-normal text-muted">
+ a voice comes from a read's own choice, this project's map, the cast (every project), the narrator's, or the default — in that order
+ </span>
+ </h2>
+ {view.castError && <p className="m-0 mb-1 text-doubt-text" data-cast-error="">the cast is not read: {view.castError}</p>}
+ <table className="w-full border-collapse" data-voices-characters={view.characters.length}>
+ <thead>
+ <tr className="text-left text-[11px] text-muted">
+ <th className="px-2 font-normal">character</th>
+ <th className="px-2 font-normal">reads in</th>
+ <th className="px-2 font-normal">reads</th>
+ <th className="px-2 font-normal">its picked reads</th>
+ <th className="px-2 font-normal">real voice</th>
+ <th />
+ </tr>
+ </thead>
+ <tbody>
+ {view.characters.map((c) => {
+ const k = whoOf(c);
+ return (
+ <tr key={c.key} data-voices-character={k} data-voice-from={c.voice.from} className={cn(who === k && "bg-panel-2")}>
+ <td className={cell}>
+ <span className="font-medium text-text">{c.name}</span>
+ <span className="ml-1.5 font-mono text-[11px] text-muted">{c.handles.map((h) => `@${h}`).join(" ")}</span>
+ {c.character && <span className="ml-1.5 rounded-[3px] border border-seam-2 px-1 text-[10.5px] text-signal-text" title="in the cast: the same voice in every project">cast</span>}
+ </td>
+ <td className={cell}>
+ <span className="font-mono text-[12px]" data-voice-now={c.voice.spec}>{pretty(c.voice.spec)}</span>
+ {c.weight === "heavy" && <span className="ml-1 text-[10.5px] text-doubt-text" title="Orpheus pins ~8.5 GB while it reads">heavy</span>}
+ <div className="text-[11px] text-muted">from {FROM[c.voice.from] ?? c.voice.from}{c.contextVoice ? ` · as a context post: ${pretty(c.contextVoice.spec)} (${FROM[c.contextVoice.from] ?? c.contextVoice.from})` : ""}</div>
+ </td>
+ <td className={cn(cell, "text-text-2")}>
+ {c.items} item{c.items === 1 ? "" : "s"}
+ {c.context ? ` · ${c.context} as context` : ""}
+ </td>
+ <td className={cell}>
+ {c.drift.length ? (
+ <span className="text-doubt-text" data-voice-drift={c.drift.length} title={c.drift.map((d) => `${d.id} ${d.role}: ${d.reads} → ${d.want}`).join("\n")}>
+ {c.drift.length} in another voice ({[...new Set(c.drift.map((d) => pretty(d.reads)))].join(", ")})
+ </span>
+ ) : c.reads.length ? (
+ <span className="text-text-2" data-voice-drift="0">{c.reads.length} in its voice</span>
+ ) : (
+ <span className="text-muted" data-voice-drift="0">none yet</span>
+ )}
+ </td>
+ <td className={cn(cell, "text-text-2")} data-voice-speaker={c.speaker ?? ""}>
+ {c.speaker ?? <span className="text-muted" title="name it in speakers.json (the walk's Add to a voice) to score candidates against it">—</span>}
+ </td>
+ <td className={cn(cell, "text-right")}>
+ <button
+ type="button"
+ data-voices-audition-open={k}
+ onClick={() => {
+ setWho(k);
+ setCandidates([c.voice.spec]);
+ setLine("first");
+ setReread(null);
+ setQueued(null);
+ }}
+ className={buttonVariants({ variant: who === k ? "pressed" : "outline", size: "sm" })}
+ >
+ Audition
+ </button>
+ </td>
+ </tr>
+ );
+ })}
+ <tr data-voices-narrator={view.narrator.spec} className="text-text-2">
+ <td className={cell}>
+ <span className="font-medium">the narrator</span>
+ {view.narrator.character && <span className="ml-1.5 text-[11px] text-muted">(the cast's: {view.narrator.character.name} — a recording's default)</span>}
+ </td>
+ <td className={cell}>
+ <span className="font-mono text-[12px]">{pretty(view.narrator.spec)}</span>
+ <div className="text-[11px] text-muted">from {FROM[view.narrator.from] ?? view.narrator.from} (the cut's narration voice)</div>
+ </td>
+ <td className={cell} colSpan={4}>
+ {view.narrator.recorded.length ? `${view.narrator.recorded.length} recorded read(s): ${view.narrator.recorded.map((r) => `${r.id}${r.kind === "converted" ? ` → ${r.voice}` : ""}`).join(", ")}` : <span className="text-muted">no recorded reads</span>}
+ </td>
+ </tr>
+ </tbody>
+ </table>
+ {view.overrides.length > 0 && (
+ <ul className="m-0 mt-1.5 list-none p-0 text-[11.5px] text-text-2" data-voices-overrides={view.overrides.length}>
+ {view.overrides.map((o) => (
+ <li key={o.handle}>
+ @{o.handle} reads in <span className="font-mono">{pretty(o.project)}</span> here — the cast says <span className="font-mono">{pretty(o.cast)}</span> (an override on purpose)
+ </li>
+ ))}
+ </ul>
+ )}
+ </section>
+
+ {/* --- the audition ------------------------------------------------------------- */}
+ {chosen && (
+ <section className="rounded-[4px] border border-seam-2 p-3" data-audition-panel={whoOf(chosen)}>
+ <h2 className="micro mb-2">audition · {chosen.name}</h2>
+ <div className="flex flex-wrap items-center gap-2">
+ <label className="inline-flex items-center gap-1.5">
+ <span className="text-muted">the line</span>
+ <select data-audition-line="" value={line} onChange={(e) => setLine(e.target.value)} className={cn(input, "max-w-[28rem]")}>
+ {chosen.lines.length > 0 && <option value="first">a line of its own here (8+ words)</option>}
+ {chosen.lines.map((l) => (
+ <option key={`${l.item}:${l.text}`} value={`item:${l.item}`}>
+ {l.item}: {l.text.slice(0, 70)}
+ {l.text.length > 70 ? "…" : ""}
+ </option>
+ ))}
+ <option value="stock">a stock line</option>
+ <option value="custom">type a line…</option>
+ </select>
+ </label>
+ {line === "custom" && <input data-audition-text="" value={custom} onChange={(e) => setCustom(e.target.value)} placeholder="what the voice reads" className={cn(input, "w-80")} />}
+ </div>
+ {audition && (
+ <p className="m-0 mt-1.5 text-text-2" data-audition-said="">
+ reads: “{audition.text}”
+ </p>
+ )}
+ <div className="mt-2 flex flex-wrap items-center gap-1.5" data-audition-candidates={candidates.length}>
+ <span className="text-muted">candidates</span>
+ {candidates.map((spec) => (
+ <span key={spec} data-audition-candidate={spec} className="inline-flex items-center gap-1 rounded-[3px] border border-seam-2 px-1.5 py-[1px] font-mono text-[11.5px]">
+ {pretty(spec)}
+ <button type="button" aria-label={`drop ${spec}`} onClick={() => setCandidates((cs) => cs.filter((x) => x !== spec))} className="text-muted hover:text-text">
+ ✕
+ </button>
+ </span>
+ ))}
+ <select data-audition-engine="" value={addEngine} onChange={(e) => { setAddEngine(e.target.value); setAddVoice(""); }} className={input}>
+ {view.engines.map((e) => (
+ <option key={e.id} value={e.id}>
+ {e.label} ({e.weight === "heavy" ? "heavy, ~8.5 GB" : "fast"})
+ </option>
+ ))}
+ </select>
+ <select data-audition-voice="" value={addVoice} onChange={(e) => setAddVoice(e.target.value)} className={input}>
+ <option value="">a voice…</option>
+ {(engine?.voices ?? []).map((v) => (
+ <option key={v} value={v} disabled={candidates.includes(`${addEngine}:${v}`)}>
+ {v}
+ </option>
+ ))}
+ </select>
+ <button
+ type="button"
+ data-audition-add=""
+ disabled={!addVoice || candidates.length >= 6 || candidates.includes(`${addEngine}:${addVoice}`)}
+ onClick={() => {
+ setCandidates((cs) => [...cs, `${addEngine}:${addVoice}`]);
+ setAddVoice("");
+ }}
+ className={buttonVariants({ variant: "outline", size: "sm" })}
+ >
+ Add
+ </button>
+ <span className="text-[11px] text-muted">2–6 · Kokoro first: Orpheus pins ~8.5 GB and waits its turn</span>
+ </div>
+ <div className="mt-2 flex flex-wrap items-center gap-2">
+ <button type="button" data-audition-render="" disabled={busy || running || !candidates.length || lineQuery === null || (!missing && !!audition && !audition.speaker)} onClick={() => void render()} className={buttonVariants({ variant: "go", size: "sm" })}>
+ {running ? "Rendering…" : missing ? `Render ${missing} candidate${missing === 1 ? "" : "s"}` : audition?.speaker ? "Score again" : "All rendered"}
+ </button>
+ {heavy && <span className="text-[11px] text-doubt-text">an Orpheus candidate: the editor runs it through its heavy slot, after a render you are waiting for</span>}
+ {job && (
+ <span className="text-[11.5px] text-text-2" data-audition-job={job.state}>
+ {job.state === "running" ? `step ${(job.stepIndex ?? 0) + 1}/${job.steps?.length ?? 1}: ${job.steps?.[job.stepIndex ?? 0]?.label ?? "…"} — ${job.log.at(-1) ?? ""}` : job.state === "done" ? "done" : `failed: ${job.error ?? job.log.at(-1) ?? ""}`}
+ </span>
+ )}
+ {(audition?.candidates ?? []).some((c) => c.cached) && (
+ <button type="button" data-audition-play-all="" onClick={playAll} className={buttonVariants({ variant: "quiet", size: "sm" })} title="the real voice first (when there is one), then each candidate">
+ ▶ Play each in turn
+ </button>
+ )}
+ </div>
+
+ {audition && (
+ <div className="mt-3 grid grid-cols-1 gap-2 md:grid-cols-2 xl:grid-cols-3" data-audition-results={audition.candidates.filter((c) => c.cached).length}>
+ {audition.reference && (
+ <div className="rounded-[4px] border border-dashed border-seam-2 p-2" data-audition-reference={audition.speaker ?? ""}>
+ <div className="flex items-baseline justify-between gap-2">
+ <span className="font-medium">the real voice · {audition.speaker}</span>
+ <span className="text-[10.5px] text-muted">a reference to compare with — never a target</span>
+ </div>
+ <audio ref={(a) => { if (a) audios.current.set("reference", a); }} controls preload="none" src={fileUrl(project, audition.reference)} className="mt-1 w-full" data-audition-reference-audio="" />
+ </div>
+ )}
+ {audition.candidates.map((c) => {
+ const top = best !== null && c.score === best;
+ return (
+ <div key={c.key} className={cn("rounded-[4px] border p-2", top ? "border-signal" : "border-seam-2")} data-audition-result={c.spec} data-audition-state={c.cached ? "ready" : "missing"} {...(top ? { "data-audition-best": "" } : {})}>
+ <div className="flex items-baseline justify-between gap-2">
+ <span className="font-mono font-medium">{pretty(c.spec)}</span>
+ <span className={cn("text-[10.5px]", c.weight === "heavy" ? "text-doubt-text" : "text-muted")}>{c.weight === "heavy" ? "Orpheus · heavy" : "fast"}</span>
+ </div>
+ {c.cached ? (
+ <audio ref={(a) => { if (a) audios.current.set(c.key, a); }} controls preload="none" src={fileUrl(project, c.rel, c.key)} className="mt-1 w-full" data-audition-audio={c.spec} />
+ ) : (
+ <p className="m-0 mt-1 text-[11.5px] text-muted">not rendered yet</p>
+ )}
+ <div className="mt-1 flex flex-wrap items-center gap-x-2 text-[11px] text-text-2">
+ {c.seconds !== null && <span>{c.seconds.toFixed(1)} s</span>}
+ {c.lufs !== null && <span title="every candidate is brought to one loudness, so they compare by ear, not by level">{c.lufs.toFixed(1)} LUFS</span>}
+ {typeof c.score === "number" ? (
+ <span data-audition-score={c.score.toFixed(3)} title={`closeness to ${audition.speaker}'s real voice (TitaNet, local): higher is closer`}>
+ closeness to {audition.speaker} <b className={top ? "text-signal-text" : ""}>{c.score.toFixed(3)}</b>
+ <span className="ml-1 inline-block h-[5px] w-16 rounded bg-seam align-middle">
+ <span className="block h-full rounded bg-signal" style={{ width: `${Math.max(2, Math.min(100, ((c.score + 0.3) / 1.3) * 100))}%` }} />
+ </span>
+ </span>
+ ) : audition.speaker ? (
+ <span className="text-muted">not scored yet</span>
+ ) : null}
+ </div>
+ <div className="mt-1.5 flex flex-wrap gap-1.5">
+ <button type="button" data-audition-use="project" disabled={busy} onClick={() => void use(c.spec, "project")} className={buttonVariants({ variant: "outline", size: "sm" })}>
+ Use for this project
+ </button>
+ <button type="button" data-audition-use="cast" disabled={busy} onClick={() => void use(c.spec, "cast")} className={buttonVariants({ variant: "outline", size: "sm" })} title="the cast: this character reads in it in every project">
+ Use everywhere
+ </button>
+ </div>
+ </div>
+ );
+ })}
+ </div>
+ )}
+ {audition && !audition.speaker && (
+ <p className="m-0 mt-2 text-[11.5px] text-muted" data-audition-no-reference="">
+ no real voice named for {chosen.name}{" "}in this project (speakers.json — the walk's “Add to a voice”): the candidates are not scored
+ </p>
+ )}
+
+ {reread && (
+ <div className="mt-3 rounded-[4px] border border-seam-2 bg-panel-2 p-2" data-reread-confirm={reread.items.length}>
+ {reread.items.length ? (
+ <>
+ <p className="m-0">
+ {reread.items.length} item{reread.items.length === 1 ? "" : "s"} read {chosen.name} in another voice. Re-read {reread.items.length === 1 ? "it" : "them"} in {pretty(reread.voice)}? Each is a new take, picked, awaiting your approval.
+ </p>
+ <ul className="m-0 mt-1 list-none p-0 font-mono text-[11px] text-text-2">
+ {reread.items.map((x) => (
+ <li key={x.id} data-reread-item={x.id}>
+ <a href={postBenchHref(project, x.id)} className="ink-link">{x.id}</a> — {x.reads.map((r) => `${r.role} ${pretty(r.reads)} → ${pretty(r.want)}`).join(", ")}
+ </li>
+ ))}
+ </ul>
+ <div className="mt-1.5 flex gap-1.5">
+ <button type="button" data-reread-queue="" disabled={busy} onClick={() => void queueRereads()} className={buttonVariants({ variant: "go", size: "sm" })}>
+ Queue {reread.items.length} re-read{reread.items.length === 1 ? "" : "s"}
+ </button>
+ <button type="button" data-reread-skip="" onClick={() => setReread(null)} className={buttonVariants({ variant: "quiet", size: "sm" })}>
+ Not now
+ </button>
+ </div>
+ </>
+ ) : (
+ <p className="m-0 text-text-2">no picked read says {chosen.name} in another voice — nothing to re-read</p>
+ )}
+ </div>
+ )}
+ {queued && (
+ <p className="m-0 mt-2 text-text-2" data-reread-queued={queued.length}>
+ queued {queued.length} re-read{queued.length === 1 ? "" : "s"} ({queued.join(", ")}) —{" "}
+ <a href={jobsHref()} className="ink-link">
+ on Jobs
+ </a>
+ </p>
+ )}
+ </section>
+ )}
+
+ {/* --- a recording made a character's read ------------------------------------------ */}
+ <section data-recording-import="">
+ <h2 className="micro mb-1.5">a recording, made a character's read</h2>
+ <p className="m-0 mb-1.5 text-[11.5px] text-muted">
+ your read of an item, kept as it is (the original), cleaned, then converted to the character's STOCK voice — each a new take on the item, the last one picked
+ </p>
+ <div className="flex flex-wrap items-center gap-2">
+ <select data-recording-item="" value={rec.item} onChange={(e) => setRec({ ...rec, item: e.target.value })} className={cn(input, "max-w-[22rem]")}>
+ {posts.map((p) => (
+ <option key={p.id} value={p.id}>
+ {p.id} @{p.handle}: {p.text}
+ </option>
+ ))}
+ </select>
+ <select data-recording-as="" value={rec.as} onChange={(e) => setRec({ ...rec, as: e.target.value })} className={input}>
+ <option value="">as: the post's author (else the narrator)</option>
+ {view.cast.map((c) => (
+ <option key={c.id} value={c.id}>
+ as {c.name} ({pretty(c.convert?.voice ?? c.voice)})
+ </option>
+ ))}
+ </select>
+ <label
+ data-recording-drop={drag ? "over" : ""}
+ onDragOver={(e) => {
+ e.preventDefault();
+ setDrag(true);
+ }}
+ onDragLeave={() => setDrag(false)}
+ onDrop={(e) => {
+ e.preventDefault();
+ setDrag(false);
+ const f = e.dataTransfer.files?.[0];
+ if (f) setRec((r) => ({ ...r, file: f }));
+ }}
+ className={cn("inline-flex cursor-pointer items-center gap-1.5 rounded-[3px] border border-dashed px-2 py-1 text-[11.5px]", drag ? "border-signal text-text" : "border-seam-2 text-text-2")}
+ >
+ {rec.file ? rec.file.name : "drop a sound file, or choose one"}
+ <input type="file" accept="audio/*,video/*" data-recording-file="" className="hidden" onChange={(e) => setRec({ ...rec, file: e.target.files?.[0] ?? null })} />
+ </label>
+ <label className="inline-flex items-center gap-1">
+ <input type="checkbox" data-recording-clean="" checked={rec.clean} onChange={(e) => setRec({ ...rec, clean: e.target.checked })} /> clean
+ </label>
+ <label className="inline-flex items-center gap-1">
+ <input type="checkbox" data-recording-convert="" checked={rec.convert} onChange={(e) => setRec({ ...rec, convert: e.target.checked })} /> convert
+ </label>
+ <button type="button" data-recording-send="" disabled={busy || running || !rec.file || !rec.item} onClick={() => void sendRecording()} className={buttonVariants({ variant: "outline", size: "sm" })}>
+ Import
+ </button>
+ </div>
+ </section>
+
+ {/* --- the cast ----------------------------------------------------------------- */}
+ <section data-cast-list={view.cast.length}>
+ <h2 className="micro mb-1.5">
+ the cast · {view.cast.length}
+ <span className="ml-2 normal-case tracking-normal text-muted">the same voice for a character in every project</span>
+ </h2>
+ {view.cast.length ? (
+ <table className="w-full border-collapse">
+ <tbody>
+ {view.cast.map((c) => (
+ <tr key={c.id} data-cast-row={c.id}>
+ <td className={cell}>
+ <span className="font-medium">{c.name}</span>
+ <span className="ml-1.5 font-mono text-[11px] text-muted">{(c.handles ?? []).map((h) => `@${h}`).join(" ")}</span>
+ {c.narrator && <span className="ml-1.5 text-[11px] text-muted">the narrator</span>}
+ </td>
+ <td className={cn(cell, "font-mono")}>{pretty(c.voice)}</td>
+ <td className={cn(cell, "text-[11px] text-text-2")}>
+ {c.convert ? `a recording → ${pretty(c.convert.voice ?? c.voice)}${c.convert.engine ? ` (${c.convert.engine})` : ""}` : ""}
+ {c.speakers?.length ? ` · real voice: ${c.speakers.join(", ")}` : ""}
+ {c.note ? ` · ${c.note}` : ""}
+ </td>
+ <td className={cn(cell, "text-right")}>
+ <button type="button" data-cast-remove={c.id} disabled={busy} onClick={() => void post({ op: "cast-rm", id: c.id }).then((j) => j && load())} className={buttonVariants({ variant: "quiet", size: "sm" })} aria-label={`remove ${c.name} from the cast`}>
+ ✕
+ </button>
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ ) : (
+ <p className="m-0 text-muted">nobody yet — an audition's “Use everywhere” puts a character in it</p>
+ )}
+ <button type="button" data-cast-undo="" disabled={busy} onClick={() => void post({ op: "cast-undo" }).then((j) => j && (setStatus(`undone: ${String((j as { undone?: string }).undone ?? "")}`), load()))} className={cn(buttonVariants({ variant: "quiet", size: "sm" }), "mt-1")}>
+ Undo the last cast change
+ </button>
+ </section>
+
+ {status && (
+ <p className="m-0 text-text-2" data-voices-status="">
+ {status}
+ </p>
+ )}
+ {error && (
+ <p role="alert" className="m-0 text-reject-text" data-voices-error="">
+ {error}
+ </p>
+ )}
+ </div>
+ );
+}
diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md
@@ -107,6 +107,10 @@ Inbox cannot disagree about what is wrong with one.
| `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] [--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 project's voice map, `posts voices`; his own: the narrator's), 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). 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** |
| `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 voices <project> [ls] \| set <handle\|*> <voice> \| remove <handle\|*> [--json]` | **THE VOICE MAP** (`narration/voices.json`): the stock voice a thread read gives each author (`*`: everyone it does not name; default `leo` on Orpheus); `ls` lists the map and every author the cut's items carry with the voice each would get. A bad handle or voice: **exit 2** |
+| `cast [ls] \| add <id> --name … --voice <engine:voice> [--handles a,b] [--speakers …] [--convert-engine e] [--convert-voice v] [--narrator] \| set <id> … \| rm <id> \| undo [--json]` | **THE CAST** (`<reports>/.umtool/cast.json`, [knobs.md](knobs.md#the-cast-each-characters-voice-in-every-project-and-the-voices-page)): the characters across projects and their STOCK voices, a layer under each project's voice map; one writer, an undo point a write |
+| `cast project <project> [--json]` · `cast use <project> <character\|@handle> <voice> [--everywhere]` · `cast reread <project> <character> [--dry-run]` | a project's characters (each voice now, where it comes from, its stale reads), the voice for this project or everywhere, and the re-reads that asks for |
+| `cast audition <character\|@handle> --voices a,b,… [--project <p>] [--text "…" \| --item <id> \| --line <n> \| --stock] [--no-score \| --score-only] [--json] [--progress ndjson]` | **AN AUDITION**: one line read by 2-6 stock voices through the editor's tts op, levelled to -20 LUFS in `<p>/narration/auditions/` (cached), scored for closeness to the character's real voice (`speakers.json`; TitaNet, local) |
+| `posts narrate <project> <item> --recording <file> [--as <character>] [--no-clean] [--no-convert] [--label l]` | **a recording made a character's read**: kept (recorded), cleaned (voice-enhance), converted (voice-convert) to the character's STOCK voice, each a new take, the last picked |
| `posts fx <project> <item> add caption --match "…" --text "…" [--target post\|quoted\|parent:<i>] [--occurrence n] [--at s] [--lead s] [--hold s] [--place below\|above\|side]` · `add clock [--rewind auto\|on\|off] [--off]` · `set <n> [--text …] [--place …] [--rewind …]` | a post item's **caption** ([report-video.md](report-video.md#a-caption), [knobs.md](knobs.md#a-caption-a-chip-explaining-a-phrase-as-it-is-read)): a chip explaining a phrase (any script: CJK drawn), up as it is read -- `--at`, else the take's word timings, else the reading estimate -- held `--hold` s, by the phrase and never over a word read while it is up; it waits for a word zoom. Its **clock** ([knobs.md](knobs.md#the-clock-each-posts-own-time-on-its-card-run-between-items)): the post's own time on the card, run from the clock item before it (forward; a REWIND when earlier: `--rewind`), `--off` not on this item. Through `updatePostFx`, refused in the build's words (**exit 1**); a zoom's knob on a caption, or a caption's on a zoom (**exit 1**) |
| `posts clock <project> [on\|off\|default] [--zone <IANA zone>] [--json]` | the cut's **clock** default (`render.posts.clock`, `updatePostClock`); bare, which items show it and their times |
| `posts fx <project> <item> add slam --text "不動心" [--match "…" \| --at s] [--whole \| --per-glyph] [--gap s] [--hold s] [--from-scale x] [--color #rrggbb] [--outline #rrggbb] [--outline-width px] [--place over-match\|center] [--size px] [--face jp\|sc\|tc\|kr] [--sfx trailer-hit\|off] [--volume x] [--swell \| --no-swell] [--bar "…" [--bar-style dark\|gold\|plain]]` · `set <n> [those flags; --bar off clears it]` | a post item's **slam** ([report-video.md](report-video.md#a-slam), [knobs.md](knobs.md#a-slam-a-trailer-style-title-slam-over-a-word-as-it-is-read)): a corny trailer title slam -- each glyph huge, shrinking onto the card just above the matched words' line and HITTING (a flash, dust, the frame's punch, a trailer hit's boom: the teaser's generator, `trailer-hits.mjs`), gold with a black outline; the hits spread evenly over the words' spoken span (`--gap` spaces them, `--at` moves the first), held `--hold` s; `--bar` lands the glyphs on a translation bar (rising in at the first hit, faded with them); a caption up with it waits for it. Through `updatePostFx`, refused in the build's words (**exit 1**); a slam's knob on another effect, or another's on a slam (**exit 2**) |
diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md
@@ -908,8 +908,8 @@ entry its words hold that it did not apply with the same spoken form (a recordin
not the manifest: changing it never re-renders a card, it makes new takes. Beep slurs: a take with a lexicon entry is
still word-timed against its script as written (the replaced words are placed between the words heard).
-**The voice map** (`narration/voices.json`, `updateVoiceMap`): `{"<handle>": "<voice>", "*": "<voice>"}` -- the stock
-voice a thread read gives each author (handles without `@`, any case; `*` everyone it does not name, default `leo` on
+**The voice map** (`narration/voices.json`, `updateVoiceMap`): `{"<handle>": "<voice>", "*": "<voice>"}` -- the
+project's override of THE CAST (below, "The cast"); the stock voice a read gives each author (handles without `@`, any case; `*` everyone it does not name, default `leo` on
Orpheus). The item's own author reads in the item's narrator voice (`narration.voice`, else the cut's) unless the map
names them; `--voice-for <handle>=<voice>` overrides it for one read, `--voice` sets his post's.
@@ -945,6 +945,60 @@ umtool posts narrate <p> <item> --take --thread --parents all --skip-parent 2117
umtool posts roles <p> <item> # the guard: every part on screen while it is said
```
+## The cast (each character's voice, in every project) and the Voices page
+
+The operator, 6 Nov 2026: "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 cast** (`report-to-video/cast.mjs`; `<reports>/.umtool/cast.json`, one writer `lib/report/castStore.mjs`
+`castWrite` -- a token, an undo point a write, a broken file never overwritten): the CHARACTERS that recur across
+projects -- `{id, name, handles, voice, convert?, speakers?, avatar?, note?, narrator?}`. `voice` is a STOCK voice
+with its engine (`kokoro:am_michael`, `orpheus:zac`); `convert` the voice (and engine, openvoice | seed-vc) a
+recording of them is converted to (default: `voice`); `speakers` the names their REAL voice goes by in a project's
+`speakers.json` -- a reference to compare a candidate with, never a target (the editor's convert op refuses a file;
+the cast holds no path). One character may be the `narrator` (a recording's default character).
+
+**Every read asks one function** (`post-say.mjs` `voiceSourceOf` / `resolvePieceVoice`): the read's own voice
+(`--voice-for`, `--voice`, the bench's voice field), the project's voice map (`narration/voices.json` -- the
+project's OVERRIDE LAYER; a value may name its engine too), **the cast**, the narrator's (the item's own author),
+the map's `*`, the default. A single post's take (`posts narrate --take`, the bench's Re-take: `readVoice.mjs`) and
+each piece of a thread read agree. A voice that names another engine than the read's is synthesized by it: a
+thread read may join Orpheus and Kokoro parts (each part records its `engine`; the disclosure names both). Projects
+without a cast read as before.
+
+**The guard**: `umtool lint <p>` warns for each picked read that says a cast character in another voice than now
+(`umtool cast reread`), and notes each cast voice the project's map overrides on purpose.
+
+**An audition** (`lib/report/castAudition.mjs`): one line -- the character's own words in the project (its post's
+script, a context post's words), a stock line, or typed -- read by 2-6 candidate stock voices through the editor's
+tts op (a job each on its queue: the GPU and the heavy slot are its; Orpheus pins ~8.5 GB, Kokoro is fast -- Kokoro
+first), each kept in `<p>/narration/auditions/<sha1(engine|voice|text)>.wav` brought to -20 LUFS (they compare by
+ear, not by level; a re-audition is a cache hit), and scored for **closeness to the character's real voice** (the
+project's `speakers.json`, speaker-check's arithmetic: TitaNet-small, local) into `narration/auditions/scores.json`,
+with an excerpt of the real voice (`ref-<speaker>.wav`) to listen to beside them.
+
+**A recording made a character's read**: `posts narrate <p> <item> --recording <file> [--as <character>]` keeps it as
+a recorded take (the original), cleans it (the editor's voice-enhance, when installed) and converts it (its
+voice-convert) to the character's stock voice -- each a new take, the last picked, the disclosure line said.
+
+| Knob | In umtool | From a terminal | Route |
+|---|---|---|---|
+| the cast -- `<reports>/.umtool/cast.json` | **Voices** (`/projects/<p>/voices`, from the Cut tab's Reads and voices): **the cast** list, ✕ removes, **Undo the last cast change**; an audition's **Use everywhere** adds or changes a character | `umtool cast ls` · `add <id> --name … --voice kokoro:am_michael --handles a,b [--speakers Jeremy] [--convert-engine seed-vc] [--convert-voice …] [--narrator]` · `set <id> …` (`--add-handle`, `--remove-handle`, `--no-convert`) · `rm <id>` · `undo` | `POST /api/report/voices {op: "cast-rm" \| "cast-undo" \| "cast-set"}` |
+| a project's characters -- each one's voice now and where it comes from, its reads, its drift, its real voice | **Voices**: the characters table | `umtool cast project <p> [--json]` | `GET /api/report/voices?project` |
+| an audition | **Voices** → a character's **Audition**: the line, the candidates (engine, voice, Add), **Render** (a job: the editor's tts, then the closeness through the heavy slot), each played at one loudness, **▶ Play each in turn** (the real voice first) | `umtool cast audition <character\|@handle> --project <p> --voices kokoro:am_michael,kokoro:am_onyx,orpheus:zac [--text "…" \| --item <id> \| --line <n> \| --stock] [--no-score \| --score-only] [--json]` | `POST /api/report/voices {op: "audition", who, voices, text?, item?}` |
+| the voice a character reads in -- this project, or everywhere | an audition's **Use for this project** / **Use everywhere** | `umtool cast use <p> <character\|@handle> <voice> [--everywhere]` (the project's own override goes with `--everywhere`) | `POST … {op: "use", who, voice, scope}` |
+| the re-reads a voice change asks for | the confirm under the audition: the items, **Queue N re-reads** (steps of the queue: /jobs; each a new take, picked, awaiting approval) | `umtool cast reread <p> <character> [--dry-run]` | `POST … {op: "reread", who}` |
+| a recording made a character's read | **Voices** → *a recording*: the item, as whom, drop a file, clean / convert, **Import** (a job) | `umtool posts narrate <p> <item> --recording <file> [--as <character>] [--no-clean] [--no-convert]` | `POST … multipart {op: "recording", item, as?, file}` |
+
+```sh
+umtool cast add thequartering --name TheQuartering --voice kokoro:am_michael --handles thequartering --speakers Jeremy
+umtool cast project quartering-diet # who reads in what, from where; the stale reads
+umtool cast audition thequartering --project quartering-diet --voices kokoro:am_michael,kokoro:am_onyx,orpheus:zac
+umtool cast use quartering-diet thequartering kokoro:am_michael --everywhere # then:
+umtool cast reread quartering-diet thequartering # each stale read made again (a take each, picked)
+umtool posts narrate quartering-diet <item> --recording my-read.wav --as thequartering
+```
+
## A caption (a chip explaining a phrase as it is read)
`fx: [{kind: "caption", match, text, …}]` on a post item ([report-video.md](report-video.md#a-caption): the shape,
diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs
@@ -37,6 +37,7 @@ import { makeBenchShellFixture } from "./bench-shell-fixture.mjs";
import { makeTakeWalkFixture } from "./take-walk-fixture.mjs";
import { makeCutIntegrityFixture } from "./cut-integrity-fixture.mjs";
import { makeUiOpsFixture } from "./ui-ops-fixture.mjs";
+import { makeVoicesFixture } from "./voices-fixture.mjs";
import { makeYoutubeFixture } from "./youtube-fixture.mjs";
import { makeBoardFixture, makeResearchFixture } from "./research-fixture.mjs";
import { makeCaseStagesFixture } from "./case-stages-fixture.mjs";
@@ -1903,6 +1904,8 @@ makeTakeWalkFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out",
makeCutIntegrityFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4") });
// ui-ops.spec's own project and channels (UI notes #9 #10 #15 #18).
makeUiOpsFixture({ reports, channels: CHANNELS, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), ff });
+// The Voices page (voices.spec.ts): Host's clips (the real voice) and post items by @hostman and @guest.
+makeVoicesFixture({ reports, channels: CHANNELS, manifest, ff });
// Release 28 M6: the YouTube text, previewed and built (media-draft-e.spec.ts).
makeYoutubeFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4") });
// Release 36 lane D: the assistant's labels, Suggest, Ask and Apply in the clip editor (clips-suggest.spec.ts).
diff --git a/umtool/e2e/fixtures/voices-fixture.mjs b/umtool/e2e/fixtures/voices-fixture.mjs
@@ -0,0 +1,63 @@
+// THE VOICES PAGE (voices.spec.ts; lib/report/castCli.mjs, components/projects/VoicesPanel.tsx): a cut of two clips
+// of "Host Man" (the real voice: speakers.json names them) and three post items --
+//
+// reports/voices-fixture/
+// k01, k02 Host's clips (a 150 Hz voice and its octave), each window in the corpus under voicescast
+// p-1 @hostman "Host's first line, read aloud." -- its picked take orpheus · zac (a 262 Hz tone)
+// p-2 @hostman answers @guest's post (a parent): no take yet
+// p-3 @guest "The guest's own line." -- no take yet
+// speakers.json Host Man: k01, k02 (the cast finds him by his name)
+//
+// The cast (<fixture>/.umtool/cast.json) is the spec's to write and remove. The editor is the suite's stub (its tts
+// writes a tone; its voice-convert copies), the speaker embedder the test kit's fake (VOICE_MATCH_* in
+// playwright.config.ts). Synthetic, like every fixture.
+import { mkdirSync, writeFileSync } from "node:fs";
+import path from "node:path";
+
+export const VOICES = "voices-fixture";
+
+const write = (dir, name, doc) => {
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(path.join(dir, name), typeof doc === "string" ? doc : JSON.stringify(doc, null, 2) + "\n");
+};
+
+/** @param {{ reports: string, channels: string, manifest: Function, ff: (args: string[]) => void }} o */
+export function makeVoicesFixture({ reports, channels, manifest, ff }) {
+ const chan = "voicescast";
+ const timeline = [];
+ for (const id of ["k01", "k02"]) {
+ const vid = `voice-${id}`;
+ const vdir = path.join(channels, chan, "data", vid);
+ mkdirSync(path.join(vdir, "clips"), { recursive: true });
+ write(vdir, "transcript.cues.json", { title: `Host ${vid}`, uploadDate: "20250101", channel: "Voices Cast", webpageUrl: `https://example.invalid/watch?v=${vid}`, duration: 20, cues: [{ start: 2, end: 4.5, text: "slow news day." }] });
+ ff([
+ "-f", "lavfi", "-i", "color=c=gray:size=160x90:rate=15:duration=6",
+ "-f", "lavfi", "-i", "aevalsrc=0.3*sin(2*PI*150*t)+0.15*sin(2*PI*300*t):s=48000:d=6",
+ "-map", "0:v", "-map", "1:a", "-t", "6",
+ "-c:v", "libx264", "-pix_fmt", "yuv420p", "-c:a", "aac", "-ar", "48000", "-ac", "2",
+ path.join(vdir, "clips", "0.00-6.00.mp4"),
+ ]);
+ timeline.push({ type: "clip", id, channel: chan, video: vid, start: 0.5, end: 5.5, cutStart: 2, cutEnd: 4.5, cite: 2, section: 0, lock: true, quote: "slow news day." });
+ }
+ const dir = path.join(reports, VOICES);
+ const post = (id, handle, author, text, o = {}) => ({
+ type: "post", id: `p-${id}`, post: `voicescast-x/${id}`, platform: "x", author, handle, date: `2026-10-30T1${id}:00:00.000Z`, text,
+ url: `https://x.com/${handle}/status/${id}`, engagement: { likes: 1 }, section: 0, ...o,
+ });
+ const takes = path.join(dir, "narration", "posts", "1");
+ mkdirSync(takes, { recursive: true });
+ ff(["-f", "lavfi", "-i", "sine=frequency=262:sample_rate=48000:duration=2", "-ac", "1", "-c:a", "pcm_s16le", path.join(takes, "take-1.orpheus-zac.wav")]);
+ timeline.push(
+ post("1", "hostman", "Host Man", "Host's first line, read aloud.", {
+ narration: { script: "Host's first line, read aloud.", takes: [{ file: "narration/posts/1/take-1.orpheus-zac.wav", engine: "orpheus", voice: "zac", seconds: 2, script: "Host's first line, read aloud.", at: "2026-11-02T00:00:00.000Z" }], pick: 0 },
+ }),
+ post("2", "hostman", "Host Man", "Host answers the guest.", {
+ parents: [{ id: "20", handle: "guest", author: "The Guest", date: "2026-10-30T09:00:00.000Z", text: "The guest asks a question first." }],
+ narration: { script: "Host answers the guest." },
+ }),
+ post("3", "guest", "The Guest", "The guest's own line.", { narration: { script: "The guest's own line." } }),
+ );
+ write(dir, "video.manifest.json", manifest(VOICES, "The Voices Fixture", { siteOrigin: "https://archive.example", channelSlug: chan }, timeline));
+ write(dir, "speakers.json", { speakers: [{ name: "Host Man", clips: ["k01", "k02"] }] });
+ return dir;
+}
diff --git a/umtool/e2e/voices.spec.ts b/umtool/e2e/voices.spec.ts
@@ -0,0 +1,212 @@
+import { test, expect, type Page } from "@playwright/test";
+import { copyFileSync, existsSync, mkdirSync, readFileSync, rmSync } from "node:fs";
+import { execFileSync } from "node:child_process";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import * as urls from "./urls";
+
+// ---------------------------------------------------------------------------
+// THE VOICES PAGE (operator, 6 Nov 2026: "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"; components/projects/VoicesPanel.tsx, /api/report/voices, lib/report/castCli.mjs). Fixture:
+// e2e/fixtures/voices-fixture.mjs -- Host's clips (the real voice), @hostman's two items (one read in orpheus zac),
+// @guest's. Every step a press:
+//
+// the characters, each voice and where it comes from (umtool cast project)
+// Audition: candidates added, Render -> a job (the stub editor's tts, then the fake embedder's closeness),
+// played side by side at one loudness beside the real voice
+// Use everywhere -> the cast; the re-read confirm -> queued; the item re-read in the new voice
+// Use for this project -> the project's voice map; the lint's override note
+// a recording dropped on an item -> kept, converted to the character's stock voice
+// the cast: remove, undo
+// ---------------------------------------------------------------------------
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const FIXTURE = path.join(HERE, "..", ".e2e-song");
+const P = "reports/voices-fixture";
+const DIR = path.join(FIXTURE, "reports", "voices-fixture");
+const MANIFEST = path.join(DIR, "video.manifest.json");
+const CAST = path.join(FIXTURE, ".umtool", "cast.json");
+const SHOTS = process.env.E2E_VOICES_SHOTS ?? null;
+const REC = path.join(FIXTURE, "voices-recording.wav");
+
+type Take = { file: string; engine?: string; voice?: string; steps?: { op: string; voice?: string }[] };
+type Entry = { id: string; narration?: { takes?: Take[]; pick?: number } };
+const entry = (id: string) => (JSON.parse(readFileSync(MANIFEST, "utf8")) as { timeline: Entry[] }).timeline.find((e) => e.id === id)!;
+const picked = (id: string) => {
+ const n = entry(id).narration ?? {};
+ return (n.takes ?? [])[n.pick ?? 0] ?? null;
+};
+const shot = async (page: Page, name: string, el?: ReturnType<Page["locator"]>) => {
+ if (!SHOTS) return;
+ mkdirSync(SHOTS, { recursive: true });
+ if (el) await el.screenshot({ path: path.join(SHOTS, `${name}.png`) });
+ else await page.screenshot({ path: path.join(SHOTS, `${name}.png`), fullPage: true });
+};
+
+test.beforeAll(() => {
+ if (!existsSync(`${MANIFEST}.pristine`)) copyFileSync(MANIFEST, `${MANIFEST}.pristine`);
+ if (!existsSync(REC)) execFileSync("ffmpeg", ["-v", "error", "-y", "-f", "lavfi", "-i", "sine=frequency=500:sample_rate=48000:duration=2", "-ac", "1", REC]);
+});
+const reset = () => {
+ copyFileSync(`${MANIFEST}.pristine`, MANIFEST);
+ for (const f of [CAST, CAST.replace(/\.json$/, ".undo.json"), path.join(DIR, "narration", "voices.json")]) rmSync(f, { force: true });
+ for (const d of ["auditions", "uploads", "parts-cache"]) rmSync(path.join(DIR, "narration", d), { recursive: true, force: true });
+ for (const id of ["1", "2", "3"]) {
+ const dir = path.join(DIR, "narration", "posts", id);
+ if (!existsSync(dir)) continue;
+ for (const f of execFileSync("ls", ["-A", dir], { encoding: "utf8" }).split("\n").filter(Boolean)) if (f !== "take-1.orpheus-zac.wav") rmSync(path.join(dir, f), { recursive: true, force: true });
+ }
+ rmSync(path.join(DIR, "revisions"), { recursive: true, force: true });
+};
+test.beforeEach(() => {
+ test.setTimeout(240_000);
+ reset();
+});
+test.afterAll(reset);
+
+test("each character's voice and where it comes from; an audition side by side with its closeness to the real voice; Use everywhere and the re-reads", async ({ page }) => {
+ await page.goto(urls.voicesHref(P));
+ const host = page.locator('[data-voices-character="@hostman"]');
+ const guest = page.locator('[data-voices-character="@guest"]');
+ // The page's first read on a cold server (the project's characters, the cast, the engines): give it time.
+ await expect(host).toBeVisible({ timeout: 30_000 });
+ // Nothing in the cast yet: his own items read in the narrator's voice; the guest's too, and as a context post the default.
+ await expect(host).toHaveAttribute("data-voice-from", "narrator");
+ await expect(host.locator("[data-voice-now]")).toHaveAttribute("data-voice-now", "orpheus:zac");
+ await expect(host.locator("[data-voice-speaker]")).toHaveAttribute("data-voice-speaker", "Host Man");
+ await expect(host.locator("[data-voice-drift]")).toHaveAttribute("data-voice-drift", "0");
+ await expect(guest).toContainText("1 item · 1 as context");
+ await expect(guest).toContainText("as a context post: orpheus · leo (the default)");
+ await expect(page.locator("[data-cast-list]")).toHaveAttribute("data-cast-list", "0");
+ await shot(page, "1-characters");
+
+ // Audition him: his current voice is the first candidate; two Kokoro voices added from the engine's list.
+ await host.locator("[data-voices-audition-open]").click();
+ // The audition box (its key follows the character into the cast: @hostman, then hostman).
+ const box = page.locator("[data-audition-panel]");
+ await expect(box).toHaveAttribute("data-audition-panel", "@hostman");
+ await expect(box.locator('[data-audition-candidate="orpheus:zac"]')).toBeVisible();
+ await expect(box.locator("[data-audition-said]")).toContainText("Host's first line, read aloud.");
+ for (const v of ["am_michael", "bm_george"]) {
+ await box.locator("[data-audition-engine]").selectOption("kokoro");
+ await box.locator("[data-audition-voice]").selectOption(v);
+ await box.locator("[data-audition-add]").click();
+ }
+ await expect(box.locator("[data-audition-candidates]")).toHaveAttribute("data-audition-candidates", "3");
+ await expect(box.locator('[data-audition-result="kokoro:am_michael"]')).toHaveAttribute("data-audition-state", "missing");
+ await expect(box.locator("[data-audition-render]")).toHaveText("Render 3 candidates");
+ await box.locator("[data-audition-render]").click();
+ await expect(box.locator("[data-audition-job]")).toHaveAttribute("data-audition-job", "done", { timeout: 120_000 });
+ await expect(box.locator("[data-audition-results]")).toHaveAttribute("data-audition-results", "3");
+ for (const spec of ["orpheus:zac", "kokoro:am_michael", "kokoro:bm_george"]) {
+ const card = box.locator(`[data-audition-result="${spec}"]`);
+ await expect(card).toHaveAttribute("data-audition-state", "ready");
+ await expect(card.locator("[data-audition-score]")).toHaveAttribute("data-audition-score", /^-?\d\.\d{3}$/);
+ await expect(card).toContainText("closeness to Host Man");
+ await expect(card).toContainText(/-2\d\.\d LUFS|-19\.\d LUFS|-20\.\d LUFS/);
+ }
+ // The real voice beside them: a reference, never a target.
+ await expect(box.locator('[data-audition-reference="Host Man"]')).toContainText("never a target");
+ const ref = await box.locator("[data-audition-reference-audio]").getAttribute("src");
+ expect((await page.request.get(ref!)).status()).toBe(200);
+ const src = await box.locator('[data-audition-audio="kokoro:am_michael"]').getAttribute("src");
+ expect((await page.request.get(src!)).headers()["content-type"]).toBe("audio/wav");
+ // The editor was asked once a candidate, each in its own engine.
+ const asked = (JSON.parse(readFileSync(path.join(FIXTURE, "editor-stub.requests.json"), "utf8")) as { route?: string; engine?: string; voice?: string; text?: string }[])
+ .filter((r) => r.route === "tts" && r.text === "Host's first line, read aloud.");
+ expect(asked.map((r) => `${r.engine}:${r.voice}`).sort()).toEqual(["kokoro:am_michael", "kokoro:bm_george", "orpheus:zac"]);
+ await expect(box.locator("[data-audition-render]")).toHaveText("Score again");
+ await shot(page, "2-audition", box);
+
+ // Use everywhere: the cast; then the re-read his picked take (orpheus zac) asks for, confirmed and queued.
+ await box.locator('[data-audition-result="kokoro:am_michael"] [data-audition-use="cast"]').click();
+ const confirm = box.locator("[data-reread-confirm]");
+ await expect(confirm).toHaveAttribute("data-reread-confirm", "1");
+ await expect(confirm.locator('[data-reread-item="p-1"]')).toContainText("post orpheus · zac → kokoro · am_michael");
+ const cast = JSON.parse(readFileSync(CAST, "utf8")) as { characters: { id: string; voice: string; handles: string[] }[] };
+ expect(cast.characters).toEqual([{ id: "hostman", name: "Host Man", handles: ["hostman"], voice: "kokoro:am_michael" }]);
+ await expect(page.locator('[data-voices-character="hostman"]')).toHaveAttribute("data-voice-from", "cast");
+ await expect(page.locator('[data-voices-character="hostman"] [data-voice-drift]')).toHaveAttribute("data-voice-drift", "1");
+ await shot(page, "3-reread-confirm", confirm);
+ await confirm.locator("[data-reread-queue]").click();
+ await expect(box.locator("[data-reread-queued]")).toHaveAttribute("data-reread-queued", "1");
+ // The queue makes it: a new take in the cast's voice, picked (awaiting approval).
+ await expect.poll(() => picked("p-1")?.voice ?? null, { timeout: 120_000 }).toBe("am_michael");
+ expect(picked("p-1")!.engine).toBe("kokoro");
+ await page.reload();
+ await expect(page.locator('[data-voices-character="hostman"] [data-voice-drift]')).toHaveAttribute("data-voice-drift", "0");
+ await expect(page.locator('[data-cast-row="hostman"]')).toContainText("kokoro · am_michael");
+ await shot(page, "4-after-reread");
+});
+
+test("Use for this project: the project's own map, shown as an override of the cast; the cast removed and put back", async ({ page }) => {
+ await page.goto(urls.voicesHref(P));
+ const guest = page.locator('[data-voices-character="@guest"]');
+ await guest.locator("[data-voices-audition-open]").click();
+ const box = page.locator("[data-audition-panel]");
+ await expect(box).toHaveAttribute("data-audition-panel", "@guest");
+ // No real voice named for the guest: candidates are not scored.
+ await box.locator("[data-audition-line]").selectOption("stock");
+ await expect(box.locator("[data-audition-said]")).toContainText("you cannot make this stuff up");
+ await box.locator("[data-audition-engine]").selectOption("kokoro");
+ await box.locator("[data-audition-voice]").selectOption("af_heart");
+ await box.locator("[data-audition-add]").click();
+ await box.locator("[data-audition-render]").click();
+ await expect(box.locator("[data-audition-job]")).toHaveAttribute("data-audition-job", "done", { timeout: 120_000 });
+ await expect(box.locator("[data-audition-no-reference]")).toBeVisible();
+ await expect(box.locator('[data-audition-result="kokoro:af_heart"]')).toHaveAttribute("data-audition-state", "ready");
+ // Everywhere first (the cast), then this project's own choice over it.
+ await box.locator('[data-audition-result="kokoro:af_heart"] [data-audition-use="cast"]').click();
+ await expect(page.locator('[data-cast-row="guest"]')).toBeVisible();
+ await box.locator('[data-audition-result="orpheus:zac"] [data-audition-use="project"]').click();
+ await expect(page.locator('[data-voices-character="guest"]')).toHaveAttribute("data-voice-from", "project");
+ expect(JSON.parse(readFileSync(path.join(DIR, "narration", "voices.json"), "utf8"))).toEqual({ guest: "orpheus:zac" });
+ await expect(page.locator("[data-voices-overrides]")).toContainText("@guest reads in orpheus · zac here — the cast says kokoro · af_heart (an override on purpose)");
+ await shot(page, "5-override");
+ // The cast: removed, then put back by Undo.
+ await page.locator('[data-cast-remove="guest"]').click();
+ await expect(page.locator("[data-cast-list]")).toHaveAttribute("data-cast-list", "0");
+ await page.locator("[data-cast-undo]").click();
+ await expect(page.locator('[data-cast-row="guest"]')).toBeVisible();
+ await expect(page.locator("[data-voices-status]")).toContainText("undone: rm guest");
+});
+
+test("a recording dropped on an item: kept as recorded, converted to the character's stock voice, picked", async ({ page }) => {
+ await page.goto(urls.voicesHref(P));
+ // Put the host in the cast (Use everywhere, from an audition of his current voice: nothing to render twice).
+ await page.locator('[data-voices-character="@hostman"] [data-voices-audition-open]').click();
+ // The audition box (its key follows the character into the cast: @hostman, then hostman).
+ const box = page.locator("[data-audition-panel]");
+ await expect(box).toHaveAttribute("data-audition-panel", "@hostman");
+ await box.locator("[data-audition-render]").click();
+ await expect(box.locator("[data-audition-job]")).toHaveAttribute("data-audition-job", "done", { timeout: 120_000 });
+ await box.locator('[data-audition-result="orpheus:zac"] [data-audition-use="cast"]').click();
+ await expect(page.locator('[data-cast-row="hostman"]')).toBeVisible();
+ // The guest's item, read by the operator, made the host's voice (as Host Man).
+ const rec = page.locator("[data-recording-import]");
+ await rec.locator("[data-recording-item]").selectOption("p-3");
+ await rec.locator("[data-recording-as]").selectOption("hostman");
+ await rec.locator("[data-recording-file]").setInputFiles(REC);
+ await expect(rec).toContainText("voices-recording.wav");
+ await shot(page, "6-recording", rec);
+ await rec.locator("[data-recording-send]").click();
+ await expect.poll(() => picked("p-3")?.steps?.[0]?.op ?? null, { timeout: 120_000 }).toBe("convert");
+ const takes = entry("p-3").narration!.takes!;
+ expect(takes[0].engine).toBe("recorded");
+ expect(picked("p-3")!.steps![0].voice).toBe("orpheus:zac");
+ expect(picked("p-3")!.voice).toBe("zac");
+ await expect(page.locator("[data-voices-status]")).toContainText("p-3: the recording is in");
+ // The editor's convert was asked for a STOCK voice, never a file.
+ const conv = (JSON.parse(readFileSync(path.join(FIXTURE, "editor-stub.requests.json"), "utf8")) as { route?: string; voice?: string }[]).filter((r) => r.route === "voice-convert").at(-1)!;
+ expect(conv.voice).toBe("orpheus:zac");
+});
+
+test("the Cut tab's Reads and voices reaches the Voices page", async ({ page }) => {
+ await page.goto(urls.projectHref(P, { tab: "cut" }));
+ const { openPanel } = await import("./panels");
+ await openPanel(page, "options", "cut-reads");
+ await page.locator("[data-voices-link]").click();
+ await expect(page).toHaveURL(/\/voices$/);
+ await expect(page.locator("[data-voices-panel]")).toBeVisible();
+});
diff --git a/umtool/lib/hrefs.ts b/umtool/lib/hrefs.ts
@@ -427,6 +427,11 @@ export function narrationRecordHref(project: string, q: { post?: string | null }
return withQuery(`/projects/${encodePath(project)}/narration/record`, q.post ? { post: q.post } : {});
}
+/** The project's voices: each character's voice, auditions, the cast (operator, 6 Nov: per-character voices). */
+export function voicesHref(project: string, q: { who?: string | null } = {}): string {
+ return withQuery(`/projects/${encodePath(project)}/voices`, q.who ? { who: q.who } : {});
+}
+
/** The drafts review (release 28). */
export function reviewHref(project: string, q: NoteOpt & { view?: "list" } = {}): string {
return withQuery(`/projects/${encodePath(project)}/review`, q.view ? { view: q.view } : {}, q.note);
diff --git a/umtool/lib/report/cast.test.mjs b/umtool/lib/report/cast.test.mjs
@@ -0,0 +1,281 @@
+// The cast across projects (castStore.mjs, castCli.mjs, castProject.mjs, castAudition.mjs): its one writer (a token,
+// undo points, a broken file never overwritten), the CLI, a project's characters and their drift, `use` (the
+// project's map or the cast) and the re-reads it asks for, every read agreeing (a single take and a thread read
+// through the cast, a cast voice of another engine synthesized by it), an audition (cached, levelled, scored for
+// closeness to the real voice with the test kit's fake embedder), a recording made a character's read, and the
+// lint's guard. No editor: the tts and voice ops are stubs; every project is a temp dir.
+import assert from "node:assert/strict";
+import { execFileSync } from "node:child_process";
+import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises";
+import { existsSync } from "node:fs";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import { after, test } from "node:test";
+import { encodeWav16 } from "yt-dlp-transcript-common/lib/montage/voiceMatch.mjs";
+import { VOICE_A, VOICE_B, syntheticVoice, withSilence } from "yt-dlp-transcript-common/testing/audio/syntheticVoice.mjs";
+import { CastError, castFile, castWrite, readCast, readCastFile, undoCast } from "./castStore.mjs";
+import { castCommand } from "./castCli.mjs";
+import { rereadPlan, threadArgvOf } from "./castProject.mjs";
+import { auditionKey, candidatesOf, characterLines, STOCK_LINE } from "./castAudition.mjs";
+import { makeTake, importRecording } from "./postNarrationCli.mjs";
+import { threadReadPlan, threadTake } from "./postThreadRead.mjs";
+import { castProblems } from "./lintCli.mjs";
+import { castVoiceMap } from "umtool-report-to-video/cast";
+
+const ROOT = await mkdtemp(path.join(tmpdir(), "umtool-cast-"));
+after(() => rm(ROOT, { recursive: true, force: true }));
+const FAKE_EMBED = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "..", "..", "common", "testing", "audio", "fakeSpeakerEmbed.mjs");
+process.env.VOICE_MATCH_PYTHON = process.execPath;
+process.env.VOICE_MATCH_SCRIPT = FAKE_EMBED;
+process.env.VOICE_MATCH_MODEL = "fake.onnx";
+const ff = (args) => execFileSync("ffmpeg", ["-v", "error", "-y", ...args]);
+const wavOf = async (file, voice, seconds = 2.5) => {
+ await mkdir(path.dirname(file), { recursive: true });
+ await writeFile(file, encodeWav16(withSilence(syntheticVoice({ ...voice, seconds }), { before: 0.3, after: 0.3 })));
+};
+const io = () => {
+ const lines = [];
+ return { lines, opts: { reportsRoot: ROOT, log: (s) => lines.push(s), err: (s) => lines.push(s) }, text: () => lines.join("\n"), json: () => JSON.parse(lines.join("\n")) };
+};
+const cast = async (args, extra = {}) => {
+ const o = io();
+ const code = await castCommand(args, { ...o.opts, ...extra });
+ return { code, ...o };
+};
+
+/** A tts stub: `out` written as VOICE_A for am_michael and zac, VOICE_B for any other. */
+const stubAsk = (asked) => async (body) => {
+ asked.push(body);
+ await wavOf(body.out, ["am_michael", "zac"].includes(body.voice) ? VOICE_A : VOICE_B, 1.5);
+ return { jobId: `job-${asked.length}`, result: { wav: body.out, engine: body.engine, voice: body.voice, disclosure: `Narration: synthetic voice (${body.engine} · ${body.voice})` } };
+};
+
+// THE PROJECT: two clips of "Host" (VOICE_A, the real voice), post items by @hostman (two, one a thread answering
+// @guest), and the guest's own item.
+const DIR = path.join(ROOT, "voices");
+const CH = path.join(ROOT, "channels");
+{
+ const timeline = [];
+ for (const id of ["k01", "k02"]) {
+ const d = path.join(CH, "chan", "data", `v${id}`);
+ await mkdir(path.join(d, "clips"), { recursive: true });
+ await writeFile(path.join(d, "transcript.cues.json"), JSON.stringify({ id: `v${id}`, cues: [{ start: 102.5, end: 104, text: "slow news day" }] }));
+ await wavOf(path.join(d, "clips", "x.wav"), VOICE_A, 2.5);
+ ff(["-i", path.join(d, "clips", "x.wav"), "-af", "adelay=2000:all=1,apad=pad_dur=3.5", "-c:a", "aac", path.join(d, "clips", "100.00-108.00.mp4")]);
+ await rm(path.join(d, "clips", "x.wav"));
+ timeline.push({ type: "clip", id, channel: "chan", video: `v${id}`, start: 100, end: 108, cutStart: 102.5, cutEnd: 104, cite: 102.5, quote: "slow news day" });
+ }
+ const post = (id, handle, o = {}) => ({ type: "post", id: `p-${id}`, post: `hostx/${id}`, platform: "x", author: handle === "hostman" ? "Host Man" : "The Guest", handle, date: `2026-10-30T1${id}:00:00.000Z`, text: `words of ${id} from ${handle}.`, ...o });
+ timeline.push(
+ post("1", "hostman", { narration: { script: "Host's first line, read aloud.", takes: [{ file: "narration/posts/1/take-1.orpheus-zac.wav", engine: "orpheus", voice: "zac", seconds: 1.5, script: "Host's first line, read aloud." }], pick: 0 } }),
+ post("2", "hostman", { parents: [{ id: "20", handle: "guest", author: "The Guest", date: "2026-10-30T09:00:00.000Z", text: "the guest asks a question" }], narration: { script: "Host answers the guest." } }),
+ post("3", "guest", { narration: { script: "The guest's own line." } }),
+ );
+ await mkdir(DIR, { recursive: true });
+ await writeFile(path.join(DIR, "video.manifest.json"), JSON.stringify({
+ schemaVersion: 1, slug: "voices", title: "Voices", kind: "report-video", provenance: { channelsDir: "../channels", channelSlug: "chan" },
+ render: { width: 1920, height: 1080, fps: 30, palette: { bg: "#000000", fg: "#ffffff", muted: "#888888", accent: "#c8752a" } }, timeline,
+ }, null, 2));
+ await wavOf(path.join(DIR, "narration", "posts", "1", "take-1.orpheus-zac.wav"), VOICE_A, 1.5);
+ await writeFile(path.join(DIR, "speakers.json"), JSON.stringify({ speakers: [{ name: "Host", clips: ["k01", "k02"] }] }));
+}
+const project = { id: "voices", dir: DIR };
+const manifest = async () => JSON.parse(await readFile(path.join(DIR, "video.manifest.json"), "utf8"));
+
+test("the store: one writer, a stale token refused, undo points, a broken file never overwritten", async () => {
+ const file = path.join(ROOT, "store", ".umtool", "cast.json");
+ const r0 = await readCastFile(file);
+ assert.equal(r0.exists, false);
+ const a = await castWrite(file, (chars) => chars.push({ id: "a", name: "A", handles: ["a"], voice: "kokoro:am_adam" }), { what: "add a" });
+ await assert.rejects(castWrite(file, (chars) => chars.push({ id: "b", name: "B", handles: [], voice: "kokoro:am_echo" }), { token: "stale" }), (e) => e instanceof CastError && e.status === 409);
+ await castWrite(file, (chars) => { chars[0].voice = "orpheus:zac"; }, { token: a.token, what: "a reads zac" });
+ await assert.rejects(castWrite(file, (chars) => { chars[0].voice = "/tmp/me.wav"; }), /STOCK voice/);
+ assert.equal((await readCastFile(file)).cast.characters[0].voice, "orpheus:zac");
+ const u = await undoCast(file);
+ assert.equal(u.undone, "a reads zac");
+ assert.equal((await readCastFile(file)).cast.characters[0].voice, "kokoro:am_adam");
+ await undoCast(file);
+ assert.deepEqual((await readCastFile(file)).cast.characters, []);
+ await assert.rejects(undoCast(file), /nothing to undo/);
+ await writeFile(file, "{ not json");
+ const broken = await readCastFile(file);
+ assert.match(broken.error, /not JSON/);
+ await assert.rejects(castWrite(file, () => {}), /fix the file first/);
+ assert.equal(await readFile(file, "utf8"), "{ not json");
+});
+
+test("umtool cast ls/add/set/rm/undo: the characters across projects", async () => {
+ let r = await cast(["add", "hostman", "--name", "Host Man", "--voice", "orpheus:zac", "--handles", "@HostMan", "--speakers", "Host", "--json"]);
+ assert.equal(r.code, 0, r.text());
+ assert.deepEqual(r.json().character, { id: "hostman", name: "Host Man", handles: ["hostman"], voice: "orpheus:zac", speakers: ["Host"] });
+ r = await cast(["add", "hostman", "--name", "Again", "--voice", "orpheus:zac"]);
+ assert.equal(r.code, 1);
+ assert.match(r.text(), /in the cast already/);
+ r = await cast(["add", "me", "--name", "Me", "--voice", "seedvc:/home/me.wav"]);
+ assert.equal(r.code, 1);
+ assert.match(r.text(), /STOCK voice/);
+ r = await cast(["add", "me", "--name", "Me", "--voice", "kokoro:bm_george", "--narrator", "--convert-engine", "seed-vc"]);
+ assert.equal(r.code, 0, r.text());
+ r = await cast(["set", "me", "--note", "the operator", "--add-handle", "operator"]);
+ assert.equal(r.code, 0, r.text());
+ r = await cast(["ls", "--json"]);
+ assert.deepEqual(r.json().characters.map((c) => [c.id, c.voice, c.handles.join(",")]), [["hostman", "orpheus:zac", "hostman"], ["me", "kokoro:bm_george", "operator"]]);
+ assert.equal(r.json().characters[1].narrator, true);
+ r = await cast(["rm", "me"]);
+ assert.equal(r.code, 0);
+ r = await cast(["undo"]);
+ assert.match(r.text(), /undone: rm me/);
+ assert.equal((await readCast(ROOT)).cast.characters.length, 2);
+ assert.equal(castFile(ROOT), path.join(ROOT, ".umtool", "cast.json"));
+});
+
+test("every read agrees: a single take and a thread read ask the same layers -- a cast voice of another engine is that engine's", async () => {
+ const m = await manifest();
+ const asked = [];
+ // The cast says hostman reads zac (orpheus); the project's map nothing: his single take is zac.
+ const e1 = m.timeline.find((e) => e.id === "p-1");
+ const t1 = await makeTake(project, e1, { render: m.render, ask: stubAsk(asked), redaction: null });
+ assert.deepEqual([t1.take.engine, t1.take.voice], ["orpheus", "zac"]);
+ // The cast moves him to Kokoro: the next single take, and his piece of a thread read, are Kokoro's.
+ await castWrite(castFile(ROOT), (chars) => { chars.find((c) => c.id === "hostman").voice = "kokoro:am_michael"; });
+ const e1b = (await manifest()).timeline.find((e) => e.id === "p-1");
+ const t2 = await makeTake(project, e1b, { render: m.render, ask: stubAsk(asked), redaction: null });
+ assert.deepEqual([t2.take.engine, t2.take.voice], ["kokoro", "am_michael"]);
+ assert.match(t2.take.file, /take-\d+\.kokoro-am_michael\.wav$/);
+ const e2 = m.timeline.find((e) => e.id === "p-2");
+ const castMap = castVoiceMap((await readCast(ROOT)).cast);
+ const plan = threadReadPlan(m, e2, { cast: castMap, map: { guest: "tara" } });
+ assert.deepEqual(plan.pieces.map((p) => [p.role, p.engine, p.voice, p.from]), [["parent:0", "orpheus", "tara", "project"], ["post", "kokoro", "am_michael", "cast"]]);
+ assert.equal(plan.engine, "kokoro", "the read's engine is his piece's");
+ asked.length = 0;
+ const r = await threadTake(project, e2, { manifest: m, red: null, map: { guest: "tara" }, ask: stubAsk(asked), lanes: null });
+ assert.deepEqual(asked.map((b) => [b.engine, b.voice]), [["orpheus", "tara"], ["kokoro", "am_michael"]], "each part asked of its own engine");
+ assert.deepEqual(r.take.parts.map((p) => [p.role, p.engine, p.voice]), [["parent:0", "orpheus", "tara"], ["post", "kokoro", "am_michael"]]);
+ const { postNarrationDisclosure } = await import("umtool-report-to-video/post-narration");
+ const after = (await manifest()).timeline.find((e) => e.id === "p-2");
+ assert.equal(postNarrationDisclosure(after), "Narration: synthetic voices (Orpheus · tara; Kokoro-82M · am_michael)");
+ // Up to date: the same read again asks nothing.
+ const again = await threadTake(project, after, { red: null, map: { guest: "tara" }, ask: stubAsk(asked), lanes: null });
+ assert.equal(again.upToDate, true);
+});
+
+test("cast project: each character's voice now and where it comes from, its drift, its reference; use and reread", async () => {
+ // p-1's picked take is the latest (kokoro am_michael); pick the first (orpheus zac) again: drift.
+ const { updatePostNarration, manifestToken } = await import("./manifest.mjs");
+ await updatePostNarration(DIR, "p-1", { pick: 0 }, { token: await manifestToken(DIR) });
+ let r = await cast(["project", "voices", "--json"]);
+ assert.equal(r.code, 0, r.text());
+ const v = r.json();
+ const host = v.characters.find((c) => c.key === "hostman");
+ assert.equal(host.voice.spec, "kokoro:am_michael");
+ assert.equal(host.voice.from, "cast");
+ assert.equal(host.speaker, "Host");
+ assert.deepEqual([host.items, host.context], [2, 0]);
+ assert.deepEqual(host.drift.map((d) => [d.id, d.reads, d.want]), [["p-1", "orpheus:zac", "kokoro:am_michael"]]);
+ assert.ok(host.lines.some((l) => l.text === "Host's first line, read aloud."));
+ const guest = v.characters.find((c) => c.key === "@guest");
+ assert.deepEqual([guest.items, guest.context, guest.voice.from], [1, 1, "narrator"]);
+ assert.equal(guest.contextVoice.spec, "orpheus:leo");
+ // The lint's guard: the drift a warning, nothing overridden yet.
+ let g = await castProblems(await manifest(), project, ROOT);
+ assert.equal(g.warnings.length, 1);
+ assert.match(g.warnings[0], /@hostman \(hostman\) reads in orpheus:zac -- now kokoro:am_michael \(the cast\): umtool cast reread voices hostman/);
+ // use, for this project: the map; the re-reads it asks for.
+ r = await cast(["use", "voices", "@guest", "orpheus:leah", "--json"]);
+ assert.equal(r.code, 0, r.text());
+ assert.equal(r.json().scope, "project");
+ assert.deepEqual(JSON.parse(await readFile(path.join(DIR, "narration", "voices.json"), "utf8")), { guest: "orpheus:leah" });
+ assert.deepEqual(r.json().reread.map((x) => x.id), ["p-2"], "the thread read says the guest in tara");
+ assert.deepEqual(r.json().reread[0].argv, ["posts", "narrate", "voices", "p-2", "--take", "--thread"]);
+ // A project override of a cast voice is a note, not a warning.
+ r = await cast(["use", "voices", "hostman", "kokoro:am_onyx", "--json"]);
+ g = await castProblems(await manifest(), project, ROOT);
+ assert.equal(g.notes.length, 1);
+ assert.match(g.notes[0], /@hostman \(hostman\) reads in kokoro:am_onyx in this project -- the cast says kokoro:am_michael \(an override on purpose/);
+ // --everywhere: the cast, and the project's own override goes.
+ r = await cast(["use", "voices", "hostman", "kokoro:am_michael", "--everywhere", "--json"]);
+ assert.equal(r.code, 0, r.text());
+ assert.deepEqual(r.json().removed, ["hostman"]);
+ assert.deepEqual(JSON.parse(await readFile(path.join(DIR, "narration", "voices.json"), "utf8")), { guest: "orpheus:leah" });
+ assert.deepEqual(r.json().reread.map((x) => x.id), ["p-1"]);
+ // --everywhere for an author the cast does not know: a new character from the handle.
+ r = await cast(["use", "voices", "@guest", "kokoro:af_heart", "--everywhere", "--json"]);
+ assert.equal(r.code, 0, r.text());
+ assert.deepEqual((await readCast(ROOT)).cast.characters.find((c) => c.id === "guest"), { id: "guest", name: "The Guest", handles: ["guest"], voice: "kokoro:af_heart" });
+ // reread --dry-run lists; reread makes them (the stub editor is not here: the plan alone).
+ r = await cast(["reread", "voices", "hostman", "--dry-run", "--json"]);
+ assert.deepEqual(r.json().items.map((x) => x.argv.join(" ")), ["posts narrate voices p-1 --take"]);
+});
+
+test("rereadPlan: a thread read's own options kept, the changed author's overrides dropped; a conversion is skipped", () => {
+ assert.deepEqual(threadArgvOf({ kind: "thread", parents: "all", skip: ["5"], quoted: false, voiceFor: { guest: "dan", other: "leo" }, voice: "zac" }, { handles: ["guest"], author: "hostman" }),
+ ["--parents", "all", "--skip-parent", "5", "--no-quoted", "--voice-for", "other=leo", "--voice", "zac"]);
+ assert.deepEqual(threadArgvOf({ kind: "thread", voice: "zac" }, { handles: ["hostman"], author: "HostMan" }), []);
+ const m = { timeline: [{ type: "post", id: "p-9", handle: "x", narration: { takes: [{ file: "a.wav", read: { kind: "thread", parents: "1" } }], pick: 0 } }] };
+ const plan = rereadPlan("p", m, [{ id: "p-9", handle: "x", role: "post", reads: "orpheus:zac", want: "kokoro:am_michael", kind: "tts", thread: true }, { id: "p-8", handle: "x", role: "post", kind: "converted", thread: false }], ["x"]);
+ assert.deepEqual(plan.items[0].argv, ["posts", "narrate", "p", "p-9", "--take", "--thread", "--parents", "1"]);
+ assert.equal(plan.skipped[0].id, "p-8");
+});
+
+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/);
+ assert.deepEqual(candidatesOf(["kokoro:am_michael,orpheus:zac", "am_onyx"]).map((c) => [c.spec, c.weight]), [["kokoro:am_michael", "fast"], ["orpheus:zac", "heavy"], ["kokoro:am_onyx", "fast"]]);
+ assert.deepEqual(characterLines(await manifest(), ["hostman"]).map((l) => l.item), ["p-1", "p-2"]);
+ const asked = [];
+ let r = await cast(["audition", "hostman", "--project", "voices", "--voices", "kokoro:am_michael,kokoro:bm_george", "--json"], { ask: stubAsk(asked), lanes: null });
+ assert.equal(r.code, 0, r.text());
+ const a = r.json();
+ assert.equal(a.text, "Host's first line, read aloud.");
+ assert.equal(a.from, "item:p-1");
+ assert.equal(a.speaker, "Host");
+ assert.equal(a.reference, "narration/auditions/ref-host.wav");
+ assert.ok(existsSync(path.join(DIR, "narration", "auditions", "ref-host.wav")));
+ const [mich, geo] = a.candidates;
+ assert.equal(mich.key, auditionKey("kokoro", "am_michael", a.text));
+ assert.ok(mich.score > geo.score, `the candidate in the host's voice is closer (${mich.score} vs ${geo.score})`);
+ for (const c of a.candidates) {
+ assert.ok(existsSync(path.join(DIR, c.rel)));
+ assert.ok(Math.abs(c.lufs - -20) < 2.5, `levelled to -20 LUFS (${c.lufs})`);
+ }
+ assert.equal(asked.length, 2);
+ // Again: nothing asked, the scores kept.
+ r = await cast(["audition", "hostman", "--project", "voices", "--voices", "kokoro:am_michael,kokoro:bm_george", "--no-score", "--json"], { ask: stubAsk(asked), lanes: null });
+ assert.equal(asked.length, 2, "a re-audition is a cache hit");
+ assert.equal(r.json().candidates[0].score, mich.score);
+ // A stock line for a character with no line; an author not in the cast by @handle; nothing to score against.
+ r = await cast(["audition", "@guest", "--project", "voices", "--voices", "kokoro:af_heart", "--text", "Hello there.", "--json"], { ask: stubAsk(asked), lanes: null });
+ assert.equal(r.code, 0, r.text());
+ assert.match(r.json().why, /no reference voice/);
+ assert.equal(STOCK_LINE.length > 20, true);
+ const files = await readdir(path.join(DIR, "narration", "auditions"));
+ assert.ok(!files.some((f) => f.endsWith(".raw.wav")), "no raw file left behind");
+});
+
+test("a recording made a character's read: kept, cleaned (when the editor can), converted to its stock voice", async () => {
+ const rec = path.join(ROOT, "my-read.wav");
+ await wavOf(rec, VOICE_B, 2);
+ const askOp = async (route, body) => {
+ if (route.endsWith("voice-enhance")) {
+ const e = new Error("the editor has no engine for /api/ops/voice-enhance yet (not installed: DeepFilterNet)");
+ e.name = "OpNotInstalled";
+ throw e;
+ }
+ await wavOf(body.out, VOICE_A, 2);
+ return { jobId: "conv-1", result: { engine: body.engine ?? "openvoice", voice: body.voice } };
+ };
+ const e = (await manifest()).timeline.find((x) => x.id === "p-3");
+ const r = await importRecording(project, e, rec, { ask: askOp });
+ assert.equal(r.character.id, "guest", "the post's author in the cast");
+ assert.deepEqual(r.takes.map((t) => t.step), ["recorded", "converted to kokoro:af_heart"]);
+ assert.match(r.notes[0], /not cleaned: .*not installed/);
+ const after = (await manifest()).timeline.find((x) => x.id === "p-3");
+ const picked = after.narration.takes[after.narration.pick];
+ assert.equal(picked.file, r.picked);
+ assert.equal(picked.voice, "af_heart");
+ assert.deepEqual(picked.steps[0], { ...picked.steps[0], op: "convert", voice: "kokoro:af_heart" });
+ assert.equal(after.narration.takes[0].engine, "recorded", "the original kept");
+ assert.equal(r.disclosure, "Narration: voice converted to a synthetic voice (openvoice · kokoro:af_heart)");
+ await assert.rejects(importRecording(project, e, rec, { as: "nobody", ask: askOp }), /no such character/);
+});
diff --git a/umtool/lib/report/castAudition.mjs b/umtool/lib/report/castAudition.mjs
@@ -0,0 +1,420 @@
+// AN AUDITION (operator, 6 Nov 2026: "in UI alone be able to try rendering different ones to compare"): ONE LINE
+// read by 2-6 candidate stock voices, each synthesized by the EDITOR (its tts op, a job on its queue: the GPU and the
+// heavy slot are its to arbitrate -- Orpheus pins ~8.5 GB, Kokoro is fast), kept beside the project and brought to
+// ONE LOUDNESS so they compare by ear, not by level; and each scored for its CLOSENESS TO THE CHARACTER'S REAL VOICE
+// when the project names one (speakers.json, as `umtool speaker-check` reads it: TitaNet-small, local) -- a
+// reference to compare with, NEVER a target.
+//
+// <project>/narration/auditions/<key>.wav the candidate, -20 LUFS, 48 kHz mono (key: sha1(engine|voice|text))
+// <project>/narration/auditions/<key>.json { key, engine, voice, text, seconds, lufs, at, jobId, disclosure }
+// <project>/narration/auditions/ref-<speaker>.wav an excerpt of the real voice, the same loudness (to listen to)
+// <project>/narration/auditions/scores.json { version, rows: { "<key>|<speaker>": { score, speaker, at, model } } }
+//
+// Without a project the candidates are kept in <REPORTS_ROOT>/.umtool/cast/auditions/ and not scored. The same line
+// in the same voice is never asked twice: a re-audition is a cache hit.
+//
+// Plain ESM: the CLI runs under bare node.
+import { execFile } from "node:child_process";
+import { createHash } from "node:crypto";
+import { mkdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
+import path from "node:path";
+import { promisify } from "node:util";
+import { draftScript, scriptParts } from "umtool-report-to-video/post-narration";
+import { cardText } from "umtool-report-to-video/post-item";
+import { handleKey, voiceRefOf, voiceSpecOf } from "umtool-report-to-video/post-say";
+import { ENGINE_WEIGHT, speakerFor } from "umtool-report-to-video/cast";
+import { REPORTS_ROOT } from "../paths.mjs";
+
+const execFileP = promisify(execFile);
+const FFMPEG = () => process.env.FFMPEG_BIN ?? "ffmpeg";
+const r3 = (v) => Math.round(v * 1000) / 1000;
+const str = (v) => (typeof v === "string" ? v : "");
+
+/** Where a project's auditions are kept (relative to it). */
+export const AUDITION_DIR = "narration/auditions";
+export const AUDITION_SCORES = `${AUDITION_DIR}/scores.json`;
+/** The level every candidate (and the reference) is brought to. */
+export const AUDITION_LUFS = -20;
+/** At most this many candidates in one audition; at most this many characters in its line. */
+export const AUDITION_MAX = 6;
+export const AUDITION_TEXT_MAX = 400;
+/** The line read when the character has none of its own in the project. */
+export const STOCK_LINE = "Well, here's the thing. I said it before, and I'll say it again: you cannot make this stuff up.";
+/** The words that ask for the stock line (the panel's "a stock line", the CLI's --stock). */
+export const STOCK_ASK = "__stock__";
+/** How long the reference excerpt of the real voice is, at most. */
+export const REFERENCE_SECONDS = 12;
+
+export class AuditionError extends Error {
+ constructor(message) {
+ super(message);
+ this.name = "AuditionError";
+ }
+}
+
+/** A candidate's cache key: sha1 of `engine|voice|text`, 20 hex. */
+export const auditionKey = (engine, voice, text) => createHash("sha1").update(`${engine}|${voice}|${text}`).digest("hex").slice(0, 20);
+
+/** The candidates as `[{ engine, voice, spec, weight }]` from `kokoro:am_michael,orpheus:zac` (a bare voice: `engine`). */
+export function candidatesOf(list, engine = "kokoro") {
+ const out = [];
+ for (const raw of (Array.isArray(list) ? list : [list]).flatMap((x) => String(x ?? "").split(",")).map((x) => x.trim()).filter(Boolean)) {
+ const ref = voiceRefOf(raw, engine);
+ if (!ref?.engine) throw new AuditionError(`"${raw}" is not a stock voice ("kokoro:am_michael", "orpheus:zac"): a file or a recording is never a candidate`);
+ const spec = voiceSpecOf(ref);
+ if (!out.some((c) => c.spec === spec)) out.push({ engine: ref.engine, voice: ref.voice, spec, weight: ENGINE_WEIGHT[ref.engine] ?? "fast" });
+ }
+ if (!out.length) throw new AuditionError("--voices names the candidates: --voices kokoro:am_michael,kokoro:am_onyx,orpheus:zac");
+ if (out.length > AUDITION_MAX) throw new AuditionError(`at most ${AUDITION_MAX} candidates in one audition (got ${out.length})`);
+ return out;
+}
+
+/** A line cut to what an audition reads: its first part (post-narration.mjs scriptParts), at most AUDITION_TEXT_MAX at a sentence end. */
+export function auditionText(text) {
+ const first = scriptParts(str(text).trim())[0]?.text ?? str(text).trim();
+ if (first.length <= AUDITION_TEXT_MAX) return first;
+ const cut = first.slice(0, AUDITION_TEXT_MAX);
+ const at = Math.max(cut.lastIndexOf(". "), cut.lastIndexOf("? "), cut.lastIndexOf("! "));
+ return (at > 80 ? cut.slice(0, at + 1) : cut).trim();
+}
+
+/**
+ * THE CHARACTER's LINES in a project, pure: `[{ item, text, own }]` -- each post item of theirs (its script, else its
+ * words cleaned to be spoken), then each context post of theirs another item carries (its words). `handles` keyed
+ * as the map keys them.
+ */
+export function characterLines(manifest, handles) {
+ const hs = new Set((handles ?? []).map(handleKey).filter(Boolean));
+ const lines = [];
+ for (const e of Array.isArray(manifest?.timeline) ? manifest.timeline : []) {
+ if (e?.type !== "post") continue;
+ if (hs.has(handleKey(e.handle))) {
+ const t = str(e.narration?.script).trim() || draftScript(cardText(e)).script;
+ if (t) lines.push({ item: e.id, text: auditionText(t), own: true });
+ }
+ const ctx = [...(Array.isArray(e.parents) ? e.parents : []), ...(e.quoted ? [e.quoted] : []), ...(Array.isArray(e.links) ? e.links : [])];
+ for (const p of ctx) {
+ if (!hs.has(handleKey(p?.handle))) continue;
+ const t = draftScript(str(p.paraphrase) || str(p.text)).script;
+ if (t) lines.push({ item: e.id, text: auditionText(t), own: false, context: str(p.id) || null });
+ }
+ }
+ return lines.filter((l, i) => lines.findIndex((x) => x.text === l.text) === i);
+}
+
+/**
+ * The character `who` names for an audition: a cast character (its id, a handle, its name), else an AUTHOR of the
+ * project by @handle (`{ id, name, handles, voice: null }`). Throws AuditionError naming what is missing.
+ */
+export async function auditionCharacter(cast, who, { project = null, manifest = null } = {}) {
+ const { characterOf, findCharacter } = await import("umtool-report-to-video/cast");
+ const w = String(who ?? "").trim();
+ if (!w) throw new AuditionError("an audition is of a character (its id, or @handle)");
+ if (!w.startsWith("@")) {
+ const c = findCharacter(cast, w);
+ if (c) return c;
+ }
+ const h = handleKey(w);
+ const c = characterOf(cast, h);
+ if (c) return c;
+ if (!project) throw new AuditionError(`${w} is not in the cast (umtool cast ls), and no --project names it`);
+ const { authorsOf } = await import("./castProject.mjs");
+ const a = manifest ? authorsOf(manifest).get(h) : null;
+ if (!a) throw new AuditionError(`${w} is neither in the cast nor an author in ${project.id}`);
+ return { id: h, name: a.name || h, handles: [h], voice: null };
+}
+
+/**
+ * THE LINE an audition reads: `text`, else the character's line from `item`, else its `line`-th (1-based), else its
+ * first own line of AUDITION_MIN_WORDS words or more (else its longest: defaultLine), else STOCK_LINE -- cut to one part, and with a project WHAT A VOICE SAYS (its redaction, slur
+ * filter -- a slur skipped -- and lexicon). Returns `{ text, from }` (`from`: "text", "item:<id>", "stock").
+ */
+export async function auditionLine(project, manifest, character, { text = null, item = null, line = null } = {}) {
+ // The stock line asked for outright (`--stock`; the panel's "a stock line").
+ if (text === STOCK_ASK) return { text: STOCK_LINE, from: "stock" };
+ let t = text ? String(text) : null;
+ let from = t ? "text" : null;
+ let e = null;
+ if (!t && manifest) {
+ const lines = characterLines(manifest, character.handles ?? []);
+ const pick = item ? lines.find((l) => l.item === item) : line ? lines[Number(line) - 1] : defaultLine(lines);
+ if ((item || line) && !pick) throw new AuditionError(`${character.name} has no such line in ${project?.id ?? "the project"} (umtool cast project ${project?.id ?? "<p>"} lists them)`);
+ if (pick) {
+ t = pick.text;
+ from = `item:${pick.item}`;
+ e = manifest.timeline.find((x) => x?.id === pick.item) ?? null;
+ }
+ }
+ if (!t) {
+ t = STOCK_LINE;
+ from = "stock";
+ }
+ t = auditionText(t);
+ if (project && manifest) {
+ const { projectRedaction } = await import("./postRedaction.mjs");
+ const { spokenRead } = await import("umtool-report-to-video/post-redact");
+ const red = await projectRedaction(project.dir, manifest);
+ t = spokenRead(t, e ?? { id: null }, red, { voice: "skip" }).text.trim() || t;
+ }
+ return { text: t, from };
+}
+
+/** Enough words to hear a voice by (and for its closeness to be scored: a two-word line is too little speech). */
+export const AUDITION_MIN_WORDS = 8;
+/** The line an audition reads by default: the first of the character's own with enough words, else its longest. */
+export function defaultLine(lines) {
+ const words = (l) => l.text.split(/\s+/).filter(Boolean).length;
+ return lines.find((l) => l.own && words(l) >= AUDITION_MIN_WORDS) ?? lines.find((l) => words(l) >= AUDITION_MIN_WORDS) ?? [...lines].sort((a, b) => words(b) - words(a))[0] ?? null;
+}
+
+/** The folder an audition is kept in: the project's, else the cast's own. */
+export const auditionDirOf = (project, reportsRoot = REPORTS_ROOT) =>
+ project ? path.join(project.dir, ...AUDITION_DIR.split("/")) : path.join(/* turbopackIgnore: true */ reportsRoot, ".umtool", "cast", "auditions");
+
+const fileThere = async (f) => !!(await stat(f).catch(() => null))?.isFile();
+
+/** Each candidate's record and file: `[{ ...candidate, key, file, rel, cached, meta }]`. */
+export async function auditionPlan(dir, candidates, text, { relBase = AUDITION_DIR } = {}) {
+ const out = [];
+ for (const c of candidates) {
+ const key = auditionKey(c.engine, c.voice, text);
+ const file = path.join(dir, `${key}.wav`);
+ const meta = await readFile(path.join(dir, `${key}.json`), "utf8").then((t) => JSON.parse(t), () => null);
+ out.push({ ...c, key, file, rel: `${relBase}/${key}.wav`, cached: !!meta && (await fileThere(file)), meta });
+ }
+ return out;
+}
+
+/** A sound brought to AUDITION_LUFS, 48 kHz mono (one loudnorm pass), `from` -> `to`; `from` removed when asked. */
+export async function levelTo(from, to, { start = null, seconds = null } = {}) {
+ const tmp = `${to}.tmp-${process.pid}.wav`;
+ await execFileP(FFMPEG(), [
+ "-nostdin", "-v", "error", "-y", ...(start !== null ? ["-ss", String(start)] : []), "-i", from, ...(seconds !== null ? ["-t", String(seconds)] : []),
+ "-vn", "-af", `loudnorm=I=${AUDITION_LUFS}:TP=-2:LRA=11`, "-ar", "48000", "-ac", "1", "-c:a", "pcm_s16le", tmp,
+ ], { maxBuffer: 1 << 24 });
+ await rename(tmp, to);
+}
+
+/**
+ * SYNTHESIZE THE CANDIDATES not kept yet: each asked of the editor's tts op in turn (`ask`: askEditorTts's shape, the
+ * tests' to stub), levelled, its record written. With an Orpheus candidate to make the transcription lane is held
+ * while they are asked (only when it was not held; released after -- `lanes`, renderMode.mjs editorLanes' shape, or
+ * null: none; `hold: false` leaves it alone). Returns the plan with `fresh` and the editor's `jobs`.
+ */
+export async function synthesizeAuditions(dir, plan, text, { ask = null, editor = null, emit = () => {}, hold = true, lanes: lanes0 = undefined } = {}) {
+ await mkdir(dir, { recursive: true });
+ const todo = plan.filter((c) => !c.cached);
+ const jobs = [];
+ let release = async () => {};
+ if (hold && todo.some((c) => c.engine === "orpheus")) {
+ let lanes = lanes0;
+ if (lanes === undefined) {
+ const { editorLanes } = await import("./renderMode.mjs");
+ const { editorConfig } = await import("./fetchWindows.mjs");
+ lanes = editorLanes(editorConfig(process.env));
+ }
+ try {
+ if (lanes && !(await lanes.isHeld("transcription"))) {
+ await lanes.hold("transcription");
+ emit("note", { message: "the transcription lane: held while Orpheus reads, released after" });
+ release = async () => {
+ await lanes.release("transcription").catch((err) => emit("note", { message: `the transcription lane could NOT be released (${err?.message ?? err}): pnpm ops lane --json '{"lane":"transcription","held":false}'` }));
+ };
+ }
+ } catch (err) {
+ emit("note", { message: `the transcription lane: not held (${err instanceof Error ? err.message : err})` });
+ }
+ }
+ try {
+ const askTts = ask ?? (await import("umtool-report-to-video/narrate-via-editor")).askEditorTts;
+ for (const [n, c] of todo.entries()) {
+ emit("audition", { phase: "ask", n: n + 1, of: todo.length, voice: c.spec, weight: c.weight });
+ emit("note", { message: `${c.spec}${c.weight === "heavy" ? " (heavy: Orpheus)" : ""}: asking the editor (${n + 1}/${todo.length})…` });
+ const raw = path.join(dir, `${c.key}.raw.wav`);
+ let res;
+ try {
+ res = await askTts({ text, engine: c.engine, voice: c.voice, out: raw }, { ...(editor ? { editor } : {}), emit });
+ } catch (err) {
+ throw new AuditionError(`${c.spec} was not synthesized: ${err instanceof Error ? err.message : err} -- the candidates made are kept; run it again`);
+ }
+ if (!(await fileThere(raw))) throw new AuditionError(`the editor's job ${res?.jobId ?? "?"} finished but ${c.key}.raw.wav is not there`);
+ await levelTo(raw, c.file);
+ await rm(raw, { force: true });
+ const { measureTake } = await import("./postNarrationCli.mjs");
+ const m = await measureTake(c.file);
+ const meta = {
+ key: c.key, engine: c.engine, voice: c.voice, text, seconds: m.seconds, lufs: m.lufs, at: new Date().toISOString(),
+ ...(res?.jobId ? { jobId: res.jobId } : {}), ...(typeof res?.result?.disclosure === "string" ? { disclosure: res.result.disclosure } : {}),
+ };
+ await writeFile(path.join(dir, `${c.key}.json`), `${JSON.stringify(meta, null, 1)}\n`);
+ c.meta = meta;
+ c.cached = true;
+ c.fresh = true;
+ if (res?.jobId) jobs.push(res.jobId);
+ }
+ } finally {
+ await release();
+ }
+ return { plan, fresh: todo.length, jobs };
+}
+
+// ---------------------------------------------------------------------------
+// The closeness to the real voice (speaker-check's arithmetic, on the candidates).
+// ---------------------------------------------------------------------------
+
+/** The project's audition scores (`{ rows: {} }` with none). */
+export async function readAuditionScores(dir) {
+ try {
+ const j = JSON.parse(await readFile(path.join(dir, ...AUDITION_SCORES.split("/")), "utf8"));
+ return j && typeof j.rows === "object" && j.rows ? j : { version: 1, rows: {} };
+ } catch {
+ return { version: 1, rows: {} };
+ }
+}
+
+const slug = (s) => str(s).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "") || "voice";
+/** The reference excerpt's file for a speaker (relative to the project). */
+export const referenceRelOf = (speaker) => `${AUDITION_DIR}/ref-${slug(speaker)}.wav`;
+
+/**
+ * The project's REFERENCE for a character: the speakers.json voice it goes by (cast.mjs speakerFor: its `speakers`,
+ * its name, its id, its handles), or null.
+ */
+export async function referenceFor(project, character) {
+ const { readSpeakers } = await import("./speakerCheck.mjs");
+ const speakers = await readSpeakers(project.dir).catch(() => []);
+ return speakerFor(character, speakers);
+}
+
+/**
+ * SCORE THE CANDIDATES against the character's real voice in the project: one run of the speaker check's scorer
+ * (common/lib/montage/speakerCheck.mjs runSpeakerCheck: TitaNet-small, local; the test kit's fake embedder under
+ * VOICE_MATCH_*) with the candidates as the clips to check and the one reference voice, and an excerpt of that voice
+ * kept to listen to. Returns `{ speaker, rows: { key: { score, ... } }, reference: rel | null, why? }`.
+ */
+export async function scoreAuditions(project, character, plan, { engineOpts = {}, emit = () => {} } = {}) {
+ const speaker = await referenceFor(project, character);
+ if (!speaker) return { speaker: null, rows: {}, reference: null, why: `no reference voice for ${character?.name ?? character?.id ?? "it"} in ${project.id}'s speakers.json (umtool speaker-check ${project.id} --set 'Name=<clip>,<channel>/<id>')` };
+ const { readManifest, channelsDirFor, hasShadowChannels } = await import("../projects/report.mjs");
+ const { planSpeakerCheck } = await import("./speakerCheck.mjs");
+ const { runSpeakerCheck } = await import("yt-dlp-transcript-common/lib/montage/speakerCheck.mjs");
+ const { DEFAULT_THRESHOLDS, resolveEngine } = await import("yt-dlp-transcript-common/lib/montage/voiceMatch.mjs");
+ const { REPO_ROOT } = await import("../paths.mjs");
+ const manifest = await readManifest(project.dir);
+ if (!manifest) throw new AuditionError(`${project.id} has no manifest`);
+ const channelsDir = channelsDirFor(project.dir, manifest, { shadowExists: await hasShadowChannels(project.dir) });
+ const ref = await planSpeakerCheck(project.dir, manifest, { clipIds: [], channelsDir, speakers: [speaker] });
+ const voice = ref.voices[0];
+ // The excerpt to listen to: the first piece of the reference set.
+ const firstClip = voice?.clipKeys?.map((k) => ref.clips.find((c) => c.key === k)).find((c) => c?.file) ?? null;
+ const firstItem = voice?.items?.[0] ?? null;
+ const src = firstClip ? { file: firstClip.file, start: firstClip.start, dur: firstClip.dur } : firstItem ? { file: firstItem.file, start: firstItem.start, dur: firstItem.dur } : null;
+ let reference = null;
+ if (src) {
+ const rel = referenceRelOf(speaker.name);
+ const abs = path.join(project.dir, ...rel.split("/"));
+ await mkdir(path.dirname(abs), { recursive: true });
+ try {
+ await levelTo(src.file, abs, { start: Math.max(0, src.start), seconds: Math.min(REFERENCE_SECONDS, Math.max(1, src.dur)) });
+ reference = rel;
+ } catch (err) {
+ emit("note", { message: `the reference excerpt was not made: ${err instanceof Error ? err.message : err}` });
+ }
+ }
+ const made = plan.filter((c) => c.cached && c.meta?.seconds > 0);
+ if (!made.length) return { speaker: speaker.name, rows: {}, reference, why: "no candidate to score (synthesize them first)" };
+ let settings = null;
+ try {
+ settings = JSON.parse(await readFile(process.env.SETTINGS_FILE ?? path.join(/* turbopackIgnore: true */ REPO_ROOT, "settings.json"), "utf8"));
+ } catch {
+ settings = null;
+ }
+ const engine = resolveEngine({ repoRoot: REPO_ROOT, settings, ...engineOpts });
+ emit("audition", { phase: "score", n: made.length, speaker: speaker.name });
+ const clips = [
+ ...ref.clips.map((c) => (c.file ? { key: c.key, id: c.id, file: c.file, start: c.start, dur: c.dur, fallback: c.fallback ?? null } : { key: c.key, id: c.id, file: null, start: 0, dur: 0, missing: c.missing })),
+ ...made.map((c) => ({ key: `audition:${c.key}`, id: null, file: c.file, start: 0, dur: c.meta.seconds })),
+ ];
+ const doc = await runSpeakerCheck({
+ clips,
+ check: made.map((c) => `audition:${c.key}`),
+ speakers: ref.voices,
+ engine,
+ scratch: path.join(/* turbopackIgnore: true */ project.dir, ".cast-audition-work"),
+ thresholds: DEFAULT_THRESHOLDS,
+ });
+ const scores = await readAuditionScores(project.dir);
+ const rows = {};
+ const at = new Date().toISOString();
+ for (const c of made) {
+ const row = /** @type {any} */ (doc.clips[`audition:${c.key}`]);
+ const s = row?.scores?.[0];
+ rows[c.key] = s ? { score: r3(s.score), speaker: speaker.name, at, model: doc.model } : { score: null, speaker: speaker.name, at, why: row?.why ?? "not scored" };
+ scores.rows[`${c.key}|${speaker.name}`] = rows[c.key];
+ }
+ const file = path.join(project.dir, ...AUDITION_SCORES.split("/"));
+ await mkdir(path.dirname(file), { recursive: true });
+ const tmp = `${file}.tmp-${process.pid}`;
+ await writeFile(tmp, `${JSON.stringify({ version: 1, rows: scores.rows }, null, 1)}\n`);
+ await rename(tmp, file);
+ return { speaker: speaker.name, rows, reference, pieces: doc.speakers?.[0]?.kept ?? null };
+}
+
+/**
+ * WHAT AN AUDITION HOLDS NOW, for the panel (nothing asked, nothing written): the character, the line, each candidate
+ * `{ spec, engine, voice, weight, key, rel, cached, seconds, lufs, score }`, the real voice it is scored against and
+ * the reference excerpt (when made).
+ * @param {{ id: string, dir: string }} project
+ * @param {any} cast
+ * @param {string} who
+ * @param {{ voices?: string[], text?: string | null, item?: string | null, line?: string | null }} [o]
+ */
+export async function auditionView(project, cast, who, { voices = [], text = null, item = null, line = null } = {}) {
+ const { readManifest } = await import("../projects/report.mjs");
+ const manifest = await readManifest(project.dir);
+ const character = await auditionCharacter(cast, who, { project, manifest });
+ const said = await auditionLine(project, manifest, character, { text, item, line });
+ const plan = await auditionPlan(auditionDirOf(project), voices.length ? candidatesOf(voices) : [], said.text);
+ const speaker = (await referenceFor(project, character))?.name ?? null;
+ const scores = await readAuditionScores(project.dir);
+ const reference = speaker && (await fileThere(path.join(project.dir, ...referenceRelOf(speaker).split("/")))) ? referenceRelOf(speaker) : null;
+ return {
+ character: { id: character.id, name: character.name, handles: character.handles ?? [], voice: character.voice ?? null },
+ text: said.text, from: said.from, speaker, reference,
+ candidates: plan.map((c) => ({
+ spec: c.spec, engine: c.engine, voice: c.voice, weight: c.weight, key: c.key, rel: c.rel, cached: c.cached,
+ seconds: c.meta?.seconds ?? null, lufs: c.meta?.lufs ?? null, score: speaker ? scores.rows[`${c.key}|${speaker}`]?.score ?? null : null,
+ })),
+ };
+}
+
+/** What an audition's scoring declares to the heavy slot (speaker-check's: TitaNet-small on a few seconds each). */
+export const AUDITION_SCORE_ESTIMATE_MB = 800;
+
+/**
+ * THE PANEL's AUDITION AS A JOB (lib/jobs.ts): step 1 asks the editor for the candidates not kept (its tts queue
+ * arbitrates the GPU and the heavy slot -- this step takes no slot of its own, or an Orpheus job behind it would
+ * wait on it); step 2, when the project has the character's real voice, scores them through the machine's heavy
+ * slot with its estimate (after a render the operator is waiting for), nice'd.
+ * @param {{ id: string }} project
+ * @param {{ who: string, voices: string[], text?: string | null, item?: string | null, score?: boolean, umtoolDir: string, queueLock?: string | null }} o
+ */
+export function auditionSteps(project, { who, voices, text = null, item = null, score = true, umtoolDir, queueLock = null }) {
+ const cli = path.join(/* turbopackIgnore: true */ umtoolDir, "bin", "umtool.mjs");
+ const base = ["cast", "audition", who, "--project", project.id, "--voices", voices.join(","), ...(text ? ["--text", text] : item ? ["--item", item] : [])];
+ const cwd = path.join(/* turbopackIgnore: true */ umtoolDir, "..");
+ const steps = [{
+ label: `synthesize ${voices.length} candidate voice(s) (the editor's tts)`,
+ argv: [process.execPath, cli, ...base, "--no-score", "--progress", "ndjson"],
+ cwd, env: {}, ndjson: /** @type {const} */ (true), timeoutMs: 45 * 60 * 1000,
+ }];
+ if (score) {
+ const cmd = ["nice", "-n", "10", process.execPath, cli, ...base, "--score-only", "--progress", "ndjson"];
+ steps.push({
+ label: "score each against the real voice (TitaNet, local)",
+ argv: queueLock ? [process.execPath, queueLock, "--heavy", "--estimate", String(AUDITION_SCORE_ESTIMATE_MB), "--", ...cmd] : cmd,
+ cwd, env: {}, ndjson: /** @type {const} */ (true), timeoutMs: 20 * 60 * 1000,
+ });
+ }
+ return { kind: `cast-audition ${project.id}`, steps };
+}
diff --git a/umtool/lib/report/castCli.mjs b/umtool/lib/report/castCli.mjs
@@ -0,0 +1,365 @@
+// `umtool cast` (umtool-report-to-video/cast.mjs; umtool/docs/knobs.md, "The cast"): the CHARACTERS across projects
+// and their voices, a project's characters, an AUDITION of candidate voices, and the voice a character reads in --
+// for a project (its voice map) or everywhere (the cast) -- with the re-reads that asks for.
+//
+// umtool cast [ls] [--json]
+// umtool cast add <id> --name "…" --voice <engine:voice> [--handles a,b] [--speakers Name,…] [--convert-engine e]
+// [--convert-voice <engine:voice>] [--avatar …] [--note "…"] [--narrator] [--json]
+// umtool cast set <id> [the same flags] [--add-handle h] [--remove-handle h] [--no-convert] [--no-narrator] [--json]
+// umtool cast rm <id> [--json] · umtool cast undo [--json]
+// umtool cast project <p> [--json]
+// umtool cast audition <character|@handle> --voices a,b,… [--project <p>] [--text "…" | --item <id> | --line <n>]
+// [--no-score | --score-only] [--no-hold] [--json] [--progress ndjson]
+// umtool cast use <p> <character|@handle> <voice> [--everywhere] [--json]
+// umtool cast reread <p> <character|@handle> [--dry-run] [--json]
+//
+// Plain ESM: the CLI runs under bare node.
+import path from "node:path";
+import { CAST_CONVERT_ENGINES, characterOf, charactersOf, findCharacter, isQualifiedVoice } from "umtool-report-to-video/cast";
+import { handleKey, voiceRefOf } from "umtool-report-to-video/post-say";
+import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs";
+import { readManifest } from "../projects/report.mjs";
+import { CastError, castFile, castForProject, castWrite, readCast, undoCast } from "./castStore.mjs";
+
+export const CAST_USAGE = [
+ "usage: umtool cast [ls] [--json]",
+ " umtool cast add <id> --name \"…\" --voice <engine:voice> [--handles a,b] [--speakers Name,…] [--convert-engine openvoice|seed-vc]",
+ " [--convert-voice <engine:voice>] [--avatar …] [--note \"…\"] [--narrator] [--json]",
+ " umtool cast set <id> [those flags] [--add-handle h] [--remove-handle h] [--no-convert] [--no-narrator] [--json]",
+ " umtool cast rm <id> [--json]",
+ " umtool cast undo [--json]",
+ " umtool cast project <project> [--json]",
+ " umtool cast audition <character|@handle> --voices kokoro:am_michael,kokoro:am_onyx,orpheus:zac [--project <p>]",
+ " [--text \"…\" | --item <id> | --line <n> | --stock] [--no-score | --score-only] [--no-hold] [--json] [--progress ndjson]",
+ " umtool cast use <project> <character|@handle> <engine:voice> [--everywhere] [--json]",
+ " umtool cast reread <project> <character|@handle> [--dry-run] [--json]",
+ "",
+ " THE CAST (<reports>/.umtool/cast.json, one writer, an undo point per write): the characters that recur across",
+ " projects -- an id, a name, their handles (X handles / channel slugs), the STOCK voice they read in (engine:voice),",
+ " optionally the voice a recording of them is converted to (--convert-voice, its engine --convert-engine), the",
+ " names their REAL voice goes by in a project's speakers.json (--speakers: a reference to compare with, never a",
+ " target), and one --narrator (a recording's default character). A project's narration/voices.json overrides it",
+ " (umtool posts voices); every read asks the same function: the read's own voice, the project's map, the cast, the",
+ " narrator's, the default.",
+ " project: every character the project's reads use, the voice each reads in now and where it comes from, its",
+ " picked reads in another voice (drift: re-read them), the cast voices the project overrides, its reference.",
+ " audition: one line (--text; --item: the character's line from that item; --line n: its n-th line; default its",
+ " first, else a stock line) read by each candidate (2-6) through the editor's tts op (a job; Orpheus is heavy,",
+ " Kokoro fast), kept at one loudness in <p>/narration/auditions/ (a re-audition is a cache hit), and with --project",
+ " scored for closeness to the character's real voice (TitaNet-small, local; speakers.json). --no-score: synthesize",
+ " only; --score-only: score what is kept.",
+ " use: the voice for this project (its voice map) or --everywhere (the cast; the project's own override of it is",
+ " removed); then the items whose picked reads say the character in another voice -- reread makes them (a new take",
+ " each, picked, awaiting approval). Exit 0 done · 1 refused or failed · 2 usage.",
+].join("\n");
+
+const VALUED = new Set(["--name", "--voice", "--handles", "--speakers", "--convert-engine", "--convert-voice", "--avatar", "--note", "--add-handle", "--remove-handle", "--voices", "--project", "--text", "--item", "--line", "--progress"]);
+const splitList = (v) => String(v ?? "").split(",").map((x) => x.trim()).filter(Boolean);
+
+function parse(args) {
+ const words = [];
+ /** @type {Map<string, string[]>} */
+ const flags = new Map();
+ for (let i = 0; i < args.length; i += 1) {
+ const a = args[i];
+ if (VALUED.has(a)) {
+ if (i + 1 >= args.length) throw new CastError(`${a} needs a value`);
+ flags.set(a, [...(flags.get(a) ?? []), args[++i]]);
+ } else if (a.startsWith("--")) flags.set(a, [...(flags.get(a) ?? []), ""]);
+ else words.push(a);
+ }
+ return { words, flags, str: (k) => flags.get(k)?.at(-1) ?? null, has: (k) => flags.has(k), all: (k) => flags.get(k) ?? [] };
+}
+
+/** The fields `add`/`set` take from the flags (only those given). */
+function fieldsOf(p) {
+ const f = {};
+ if (p.str("--name") !== null) f.name = p.str("--name").trim();
+ if (p.str("--voice") !== null) {
+ const v = p.str("--voice").trim();
+ if (!isQualifiedVoice(v)) throw new CastError(`--voice is a STOCK voice with its engine: kokoro:am_michael, orpheus:zac (got ${v})`);
+ f.voice = v;
+ }
+ if (p.str("--handles") !== null) f.handles = splitList(p.str("--handles")).map(handleKey);
+ if (p.str("--speakers") !== null) f.speakers = splitList(p.str("--speakers"));
+ if (p.str("--avatar") !== null) f.avatar = p.str("--avatar");
+ if (p.str("--note") !== null) f.note = p.str("--note");
+ if (p.str("--convert-engine") !== null || p.str("--convert-voice") !== null) {
+ const ce = p.str("--convert-engine");
+ if (ce !== null && !CAST_CONVERT_ENGINES.includes(ce)) throw new CastError(`--convert-engine is ${CAST_CONVERT_ENGINES.join(" or ")}`);
+ f.convert = { ...(ce ? { engine: ce } : {}), ...(p.str("--convert-voice") ? { voice: p.str("--convert-voice") } : {}) };
+ }
+ return f;
+}
+
+const line = (c) => `${c.id.padEnd(16)} ${c.voice.padEnd(20)} ${c.name}${c.handles?.length ? ` ${c.handles.map((h) => `@${h}`).join(" ")}` : ""}${c.convert ? ` convert: ${c.convert.engine ?? "default"} -> ${c.convert.voice ?? c.voice}` : ""}${c.speakers?.length ? ` real voice: ${c.speakers.join(", ")}` : ""}${c.narrator ? " (the narrator)" : ""}${c.note ? ` -- ${c.note}` : ""}`;
+
+async function projectOf(ref, reportsRoot) {
+ const r = await resolveProject(ref, reportsRoot);
+ if (r.ambiguous) throw new CastError(`"${ref}" is the name of ${r.ambiguous.length} projects — pass its id`);
+ if (!r.project) throw new CastError(`no project matches "${ref}"`);
+ return r.project;
+}
+
+/** A project's characters view (castProject.mjs projectCharacters) with the files it read. */
+export async function projectView(project, { reportsRoot = REPORTS_ROOT } = {}) {
+ const manifest = await readManifest(project.dir);
+ if (!manifest) throw new CastError(`${project.id} has no manifest`);
+ const { readVoiceMap } = await import("./postSay.mjs");
+ const { readSpeakers } = await import("./speakerCheck.mjs");
+ const { projectCharacters } = await import("./castProject.mjs");
+ const castRead = await castForProject(project.dir, reportsRoot);
+ const map = await readVoiceMap(project.dir).catch(() => ({}));
+ const speakers = await readSpeakers(project.dir).catch(() => []);
+ const view = projectCharacters(manifest, { map, cast: castRead.cast, speakers });
+ return { manifest, map, castRead, speakers, view };
+}
+
+/** The handles `ref` names in a project: a character's (the cast's), or one @handle. */
+function handlesOf(ref, castRead, view) {
+ const c = findCharacter(castRead.cast, String(ref).replace(/^@+/, ""));
+ if (c && !String(ref).startsWith("@")) return { character: c, handles: [...(c.handles ?? [])] };
+ const h = handleKey(ref);
+ const row = view?.characters?.find((r) => r.handles.includes(h)) ?? null;
+ return { character: characterOf(castRead.cast, h), handles: [h], row };
+}
+
+/**
+ * `umtool cast …`
+ * @param {string[]} args
+ * @param {{ reportsRoot?: string, log?: (s: string) => void, err?: (s: string) => void, ask?: any, lanes?: any }} [o]
+ */
+export async function castCommand(args, { reportsRoot = REPORTS_ROOT, log = console.log, err = console.error, ask = undefined, lanes = undefined } = {}) {
+ let p;
+ try {
+ p = parse(args);
+ } catch (e) {
+ err(`umtool cast: ${e instanceof Error ? e.message : e}`);
+ return 2;
+ }
+ const json = p.has("--json");
+ const out = (o, text) => log(json ? JSON.stringify(o, null, 2) : text);
+ const [sub = "ls", ...rest] = p.words;
+ if (p.has("--help") || sub === "help") {
+ log(CAST_USAGE);
+ return 0;
+ }
+ const file = castFile(reportsRoot);
+ try {
+ if (sub === "ls") {
+ const r = await readCast(reportsRoot);
+ const chars = charactersOf(r.cast);
+ out({ ok: true, file, token: r.token, characters: chars, ...(r.error ? { error: r.error } : {}) }, [
+ `the cast: ${chars.length} character(s) (${file})${r.error ? `\n NOT READ: ${r.error}` : ""}${chars.length ? "" : " -- umtool cast add <id> --name \"…\" --voice kokoro:am_michael --handles <handle>"}`,
+ ...chars.map((c) => ` ${line(c)}`),
+ ].join("\n"));
+ return 0;
+ }
+ if (sub === "add" || sub === "set") {
+ const [id] = rest;
+ if (!id) throw new CastError(`cast ${sub} takes the character's id`);
+ const f = fieldsOf(p);
+ const r = await castWrite(file, (chars) => {
+ const at = chars.findIndex((c) => c.id === id);
+ if (sub === "add") {
+ if (at >= 0) throw new CastError(`${id} is in the cast already (umtool cast set ${id} …)`);
+ if (!f.name || !f.voice) throw new CastError('cast add takes --name "…" and --voice <engine:voice>');
+ const c = { id, name: f.name, handles: f.handles ?? [], voice: f.voice, ...(f.convert ? { convert: f.convert } : {}), ...(f.speakers ? { speakers: f.speakers } : {}), ...(f.avatar ? { avatar: f.avatar } : {}), ...(f.note ? { note: f.note } : {}), ...(p.has("--narrator") ? { narrator: true } : {}) };
+ if (c.narrator) for (const x of chars) delete x.narrator;
+ chars.push(c);
+ return { changed: "added", character: c };
+ }
+ if (at < 0) throw new CastError(`no ${id} in the cast (umtool cast ls)`);
+ const c = { ...chars[at], ...f };
+ for (const h of p.all("--add-handle").map(handleKey)) if (h && !c.handles.includes(h)) c.handles = [...c.handles, h];
+ for (const h of p.all("--remove-handle").map(handleKey)) c.handles = c.handles.filter((x) => x !== h);
+ if (p.has("--no-convert")) delete c.convert;
+ if (p.has("--narrator")) {
+ for (const x of chars) delete x.narrator;
+ c.narrator = true;
+ }
+ if (p.has("--no-narrator")) delete c.narrator;
+ for (const k of ["note", "avatar"]) if (c[k] === "") delete c[k];
+ chars[at] = c;
+ return { changed: "updated", character: c };
+ }, { what: `${sub} ${id}` });
+ out({ ok: true, changed: r.changed, character: r.character, token: r.token }, `${r.changed} ${line(r.character)}`);
+ return 0;
+ }
+ if (sub === "rm" || sub === "remove") {
+ const [id] = rest;
+ if (!id) throw new CastError("cast rm takes the character's id");
+ const r = await castWrite(file, (chars) => {
+ const at = chars.findIndex((c) => c.id === id);
+ if (at < 0) throw new CastError(`no ${id} in the cast`);
+ const [gone] = chars.splice(at, 1);
+ return { removed: gone };
+ }, { what: `rm ${id}` });
+ out({ ok: true, removed: r.removed, token: r.token }, `removed ${id} from the cast (umtool cast undo puts it back)`);
+ return 0;
+ }
+ if (sub === "undo") {
+ const r = await undoCast(file);
+ out({ ok: true, undone: r.undone, at: r.at, left: r.left, token: r.token }, `undone: ${r.undone} (${r.left} undo point(s) left)`);
+ return 0;
+ }
+ if (sub === "project") {
+ const [ref] = rest;
+ if (!ref) throw new CastError("cast project takes the project");
+ const project = await projectOf(ref, reportsRoot);
+ const { view, map, castRead } = await projectView(project, { reportsRoot });
+ if (json) {
+ log(JSON.stringify({ ok: true, project: project.id, castFile: castRead.file, ...(castRead.error ? { castError: castRead.error } : {}), map, ...view }, null, 2));
+ return 0;
+ }
+ log(`${project.id}: ${view.characters.length} character(s); the narrator ${view.narrator.spec} (${view.narrator.from})${castRead.error ? `\n the cast is NOT read: ${castRead.error}` : ""}`);
+ for (const c of view.characters) {
+ log(` ${(c.character ? c.character.id : c.key).padEnd(18)} ${c.voice.spec.padEnd(20)} (${c.voice.from}) ${c.items} item(s), ${c.context} context${c.speaker ? ` real voice: ${c.speaker}` : ""}`);
+ if (c.drift.length) log(` ${c.drift.length} read(s) in another voice: ${c.drift.map((d) => `${d.id} ${d.reads} (now ${d.want})`).join(", ")} -- umtool cast reread ${project.id} ${c.character?.id ?? `@${c.handles[0]}`}`);
+ }
+ for (const o of view.overrides) log(` note: @${o.handle} (${o.character}) reads in ${o.project} here -- the cast says ${o.cast} (an override on purpose)`);
+ return 0;
+ }
+ if (sub === "use") {
+ const [ref, who, voice] = rest;
+ if (!ref || !who || !voice) throw new CastError("cast use takes the project, the character (or @handle) and the voice: cast use quartering-diet thequartering kokoro:am_michael");
+ const project = await projectOf(ref, reportsRoot);
+ const before = await projectView(project, { reportsRoot });
+ const t = handlesOf(who, before.castRead, before.view);
+ if (!t.handles.length) throw new CastError(`${who} has no handles to give a voice (umtool cast set ${who} --add-handle <h>)`);
+ if (!voiceRefOf(voice)) throw new CastError(`${voice} is not a stock voice (tara, kokoro:am_michael): a file or a recording is never a voice`);
+ const { updateVoiceMap } = await import("./postSay.mjs");
+ const removed = [];
+ let scope = "project";
+ if (p.has("--everywhere")) {
+ if (!isQualifiedVoice(voice)) throw new CastError(`--everywhere takes a voice with its engine (kokoro:am_michael), so every project reads it the same`);
+ scope = "cast";
+ const castPath = before.castRead.file ?? file;
+ await castWrite(castPath, (chars) => {
+ const c = t.character ? chars.find((x) => x.id === t.character.id) : null;
+ if (c) c.voice = voice;
+ else {
+ const h = t.handles[0];
+ const id = h.replace(/[^a-z0-9_-]/g, "-").replace(/^[^a-z0-9]+/, "").slice(0, 48) || "character";
+ if (chars.some((x) => x.id === id)) throw new CastError(`${id} is in the cast already, without @${h}: umtool cast set ${id} --add-handle ${h}`);
+ chars.push({ id, name: (t.row?.name || h).slice(0, 80), handles: [h], voice });
+ }
+ return {};
+ }, { what: `${t.character?.id ?? `@${t.handles[0]}`} reads in ${voice} (from ${project.id})` });
+ // Its voice everywhere -- here too: the project's own override of it goes.
+ for (const h of t.handles) {
+ if (h in before.map) {
+ await updateVoiceMap(project.dir, { remove: h });
+ removed.push(h);
+ }
+ }
+ } else {
+ for (const h of t.handles) await updateVoiceMap(project.dir, { set: { handle: h, voice } });
+ }
+ const after = await projectView(project, { reportsRoot });
+ const { rereadPlan } = await import("./castProject.mjs");
+ const plan = rereadPlan(project.id, after.manifest, after.view.characters.flatMap((c) => c.drift), t.handles);
+ out(
+ { ok: true, scope, handles: t.handles, voice, removed, reread: plan.items.map((x) => ({ id: x.id, take: x.take, thread: x.thread, reads: x.reads, argv: x.argv })), skipped: plan.skipped },
+ [
+ `${t.handles.map((h) => `@${h}`).join(", ")} read${t.handles.length === 1 ? "s" : ""} in ${voice} ${scope === "cast" ? "everywhere (the cast)" : `in ${project.id} (its voice map)`}${removed.length ? `; ${project.id}'s own override removed (${removed.join(", ")})` : ""}`,
+ plan.items.length ? ` ${plan.items.length} item(s) read them in another voice -- umtool cast reread ${project.id} ${who}:` : " no picked read says them in another voice",
+ ...plan.items.map((x) => ` ${x.id} ${x.reads.map((r) => `${r.role} ${r.reads} -> ${r.want}`).join(", ")}`),
+ ].join("\n"),
+ );
+ return 0;
+ }
+ if (sub === "reread") {
+ const [ref, who] = rest;
+ if (!ref || !who) throw new CastError("cast reread takes the project and the character (or @handle)");
+ const project = await projectOf(ref, reportsRoot);
+ const v = await projectView(project, { reportsRoot });
+ const t = handlesOf(who, v.castRead, v.view);
+ const { rereadPlan } = await import("./castProject.mjs");
+ const plan = rereadPlan(project.id, v.manifest, v.view.characters.flatMap((c) => c.drift), t.handles);
+ if (p.has("--dry-run") || !plan.items.length) {
+ out({ ok: true, dryRun: p.has("--dry-run"), items: plan.items, skipped: plan.skipped }, [
+ plan.items.length ? `${plan.items.length} item(s) to re-read:` : `no picked read says ${who} in another voice`,
+ ...plan.items.map((x) => ` umtool ${x.argv.join(" ")}`),
+ ...plan.skipped.map((s) => ` (not re-read: ${s.id} -- ${s.why})`),
+ ].join("\n"));
+ return 0;
+ }
+ const { postsCommand } = await import("./postsCli.mjs");
+ const done = [];
+ for (const x of plan.items) {
+ const said = [];
+ const code = await postsCommand([...x.argv.slice(1), "--json"], { root: reportsRoot, out: (s) => said.push(s), err: (s) => said.push(s) });
+ done.push({ id: x.id, code });
+ if (!json) log(`${x.id}: ${code === 0 ? "re-read, picked (awaiting approval)" : `FAILED -- ${said.join(" ").slice(0, 300)}`}`);
+ }
+ const failed = done.filter((d) => d.code !== 0).length;
+ if (json) log(JSON.stringify({ ok: failed === 0, done, skipped: plan.skipped }, null, 2));
+ return failed ? 1 : 0;
+ }
+ if (sub === "audition") return await auditionCommand(rest, p, { reportsRoot, log, err, ask, lanes });
+ throw new CastError(`cast: ls, add, set, rm, undo, project, audition, use or reread (not ${sub})`);
+ } catch (e) {
+ if (e instanceof CastError || e?.name === "AuditionError" || e?.name === "SayError") {
+ if (json) log(JSON.stringify({ ok: false, error: e.message }, null, 2));
+ err(`umtool cast: ${e.message}`);
+ return 1;
+ }
+ err(`umtool cast: ${e instanceof Error ? e.stack ?? e.message : String(e)}`);
+ return 1;
+ }
+}
+
+/** `umtool cast audition …` */
+async function auditionCommand(rest, p, { reportsRoot, log, err, ask, lanes }) {
+ const A = await import("./castAudition.mjs");
+ const [who] = rest;
+ if (!who) throw new CastError("cast audition takes the character (its id, or @handle)");
+ const json = p.has("--json");
+ const ndjson = p.str("--progress") === "ndjson";
+ const say = (s) => (ndjson ? err(s) : !json && log(s));
+ const emit = (ev, f = {}) => {
+ if (ev === "note") say(f.message);
+ else if (ndjson) log(JSON.stringify({ ev: "cast-audition", ...f }));
+ };
+ const project = p.str("--project") ? await projectOf(p.str("--project"), reportsRoot) : null;
+ const castRead = project ? await castForProject(project.dir, reportsRoot) : await readCast(reportsRoot);
+ const manifest = project ? await readManifest(project.dir) : null;
+ const character = await A.auditionCharacter(castRead.cast, who, { project, manifest });
+ const { text, from } = await A.auditionLine(project, manifest, character, { text: p.has("--stock") ? A.STOCK_ASK : p.str("--text"), item: p.str("--item"), line: p.str("--line") });
+ const candidates = A.candidatesOf(p.all("--voices"));
+ const dir = A.auditionDirOf(project, reportsRoot);
+ const relBase = project ? A.AUDITION_DIR : path.relative(reportsRoot, dir);
+ const plan = await A.auditionPlan(dir, candidates, text, { relBase });
+ let fresh = 0;
+ let jobs = [];
+ if (!p.has("--score-only")) {
+ const r = await A.synthesizeAuditions(dir, plan, text, { ask, emit, hold: !p.has("--no-hold"), lanes });
+ fresh = r.fresh;
+ jobs = r.jobs;
+ }
+ let score = null;
+ if (project && !p.has("--no-score")) score = await A.scoreAuditions(project, character, plan, { emit });
+ const prior = project ? await A.readAuditionScores(project.dir) : { rows: {} };
+ // Not scored this time: the scores kept for these candidates against the same real voice.
+ const speaker = score?.speaker ?? (project ? (await A.referenceFor(project, character))?.name ?? null : null);
+ const scoreOf = (k) => score?.rows?.[k]?.score ?? (speaker ? prior.rows[`${k}|${speaker}`]?.score : null) ?? null;
+ const rows = plan.map((c) => ({
+ spec: c.spec, engine: c.engine, voice: c.voice, weight: c.weight, key: c.key, rel: c.rel, cached: c.cached, fresh: !!c.fresh,
+ seconds: c.meta?.seconds ?? null, lufs: c.meta?.lufs ?? null, score: scoreOf(c.key), ...(c.meta?.disclosure ? { disclosure: c.meta.disclosure } : {}),
+ }));
+ if (json) {
+ log(JSON.stringify({ ok: true, character: { id: character.id, name: character.name, handles: character.handles ?? [], voice: character.voice ?? null }, project: project?.id ?? null, text, from, candidates: rows, fresh, jobs, speaker, reference: score?.reference ?? (speaker ? A.referenceRelOf(speaker) : null), ...(score?.why ? { why: score.why } : {}) }, null, 2));
+ return 0;
+ }
+ if (ndjson) {
+ log(JSON.stringify({ ev: "cast-audition", phase: "done", fresh, candidates: rows.length }));
+ return 0;
+ }
+ log(`${character.name}: "${text}" (${from})`);
+ for (const r of rows) log(` ${r.spec.padEnd(22)} ${r.weight === "heavy" ? "heavy" : "fast "} ${r.seconds ? `${r.seconds.toFixed(1)} s` : "-"} ${r.score !== null ? `closeness ${r.score.toFixed(3)}${speaker ? ` to ${speaker}` : ""}` : ""} ${r.rel}${r.fresh ? "" : " (kept)"}`);
+ const unscored = Object.values(score?.rows ?? {}).find((r) => r?.score === null && r?.why);
+ if (score?.why || unscored) log(` not scored: ${score?.why ?? unscored.why}${score?.why ? "" : " (the reference's windows: umtool prep, or fetch them)"}`);
+ if (score?.reference) log(` the real voice (a reference, never a target): ${score.reference}`);
+ return 0;
+}
diff --git a/umtool/lib/report/castProject.mjs b/umtool/lib/report/castProject.mjs
@@ -0,0 +1,160 @@
+// A PROJECT's CAST (the Voices panel; `umtool cast project <p>`): every character the project's reads use -- the
+// post items' authors, the authors of the posts they answer, quote and link, and the narrator -- with the voice each
+// reads in NOW and where it comes from (the project's map, the cast, the narrator's, the default), how many items it
+// reads, what its picked reads are actually in (stale ones: DRIFT), its real-voice reference (speakers.json) and its
+// lines to audition; and THE RE-READS a voice change asks for, as the commands that make them.
+//
+// Plain ESM.
+import { postNarrationKnobs } from "umtool-report-to-video/post-narration";
+import { handleKey, resolvePieceVoice, voiceRefOf, voiceSpecOf } from "umtool-report-to-video/post-say";
+import { castDrift, castVoiceMap, characterOf, charactersOf, convertTargetOf, narratorOf, speakerFor, takeReads, voiceDrift, ENGINE_WEIGHT } from "umtool-report-to-video/cast";
+import { characterLines } from "./castAudition.mjs";
+
+const str = (v) => (typeof v === "string" ? v : "");
+
+/**
+ * The voice a piece of a picked read would be said in NOW, as the read that made it would ask (its own --voice-for
+ * and --voice kept: an override made on purpose): `(e, role, handle, take, read) => { engine, voice, from }`. A read
+ * converted from a recording is compared with its character's convert target (the cast's), else not at all.
+ */
+export function resolverFor({ map = {}, cast = null, render = {} }) {
+ const castMap = castVoiceMap(cast);
+ return (e, role, handle, take, read = null) => {
+ if (read?.kind === "converted") {
+ const c = characterOf(cast, handle);
+ const ref = c ? voiceRefOf(convertTargetOf(c).voice) : null;
+ return ref ? { ...ref, from: "cast" } : null;
+ }
+ const k = postNarrationKnobs(e, render);
+ const tr = take?.read?.kind === "thread" ? take.read : null;
+ return resolvePieceVoice({ handle, role }, {
+ map, cast: castMap, overrides: tr?.voiceFor ?? {}, voice: tr?.voice ?? null, self: e.handle ?? null,
+ narrator: e.narration?.voice ?? k.voice, engine: e.narration?.engine ?? k.engine,
+ });
+ };
+}
+
+/** The post items' authors and context authors: `Map<handle, { handle, name, items: id[], context: id[] }>`. */
+export function authorsOf(manifest) {
+ const out = new Map();
+ const add = (h, name, id, own) => {
+ const key = handleKey(h);
+ if (!key || key === "*") return;
+ const a = out.get(key) ?? { handle: key, name: "", items: [], context: [] };
+ if (!a.name && str(name)) a.name = str(name);
+ const list = own ? a.items : a.context;
+ if (!list.includes(id)) list.push(id);
+ out.set(key, a);
+ };
+ for (const e of Array.isArray(manifest?.timeline) ? manifest.timeline : []) {
+ if (e?.type !== "post") continue;
+ add(e.handle, e.author, e.id, true);
+ for (const p of Array.isArray(e.parents) ? e.parents : []) add(p?.handle, p?.author, e.id, false);
+ if (e.quoted) add(e.quoted.handle, e.quoted.author, e.id, false);
+ for (const l of Array.isArray(e.links) ? e.links : []) add(l?.handle, l?.author, e.id, false);
+ }
+ return out;
+}
+
+/**
+ * THE PROJECT's CHARACTERS, pure: `{ narrator, characters: [...], drift, overrides }` -- each character
+ * `{ key, character, name, handles, items, context, itemIds, contextIds, voice: {engine, voice, spec, from},
+ * contextVoice?, reads: [{ id, role, spec, kind }], drift: [...], speaker, lines, weight }`, the most-read first.
+ */
+export function projectCharacters(manifest, { map = {}, cast = null, speakers = [] } = {}) {
+ const render = manifest?.render ?? {};
+ const k = postNarrationKnobs({}, render);
+ const resolve = resolverFor({ map, cast, render });
+ const castMap = castVoiceMap(cast);
+ const drift = voiceDrift(manifest, resolve);
+ const groups = new Map();
+ for (const a of authorsOf(manifest).values()) {
+ const c = characterOf(cast, a.handle);
+ const key = c ? c.id : `@${a.handle}`;
+ const g = groups.get(key) ?? { key, character: c, name: c?.name ?? a.name ?? a.handle, handles: [], itemIds: [], contextIds: [] };
+ g.handles.push(a.handle);
+ for (const id of a.items) if (!g.itemIds.includes(id)) g.itemIds.push(id);
+ for (const id of a.context) if (!g.contextIds.includes(id)) g.contextIds.push(id);
+ groups.set(key, g);
+ }
+ const tl = Array.isArray(manifest?.timeline) ? manifest.timeline : [];
+ const reads = [];
+ for (const e of tl) if (e?.type === "post") for (const r of takeReads(e)) reads.push({ id: e.id, ...r });
+ const rows = [...groups.values()].map((g) => {
+ const h = g.handles[0];
+ const first = tl.find((e) => e?.type === "post" && g.itemIds.includes(e.id)) ?? null;
+ const ctxItem = tl.find((e) => e?.type === "post" && g.contextIds.includes(e.id)) ?? null;
+ const own = first ? resolve(first, "post", h, null) : null;
+ const ctx = ctxItem ? resolve(ctxItem, "parent:0", h, null) : resolvePieceVoice({ handle: h, role: "parent:0" }, { map, cast: castMap, narrator: k.voice, engine: k.engine });
+ const now = own ?? ctx;
+ const mine = new Set(g.handles);
+ const sp = speakerFor(g.character ?? { name: g.name, handles: g.handles, id: h }, speakers);
+ return {
+ key: g.key, name: g.name, handles: g.handles,
+ character: g.character ? { id: g.character.id, name: g.character.name, voice: g.character.voice, ...(g.character.convert ? { convert: g.character.convert } : {}), ...(g.character.note ? { note: g.character.note } : {}), ...(g.character.narrator ? { narrator: true } : {}) } : null,
+ items: g.itemIds.length, context: g.contextIds.length, itemIds: g.itemIds, contextIds: g.contextIds,
+ voice: { ...now, spec: voiceSpecOf(now) },
+ ...(own && ctx && voiceSpecOf(own) !== voiceSpecOf(ctx) ? { contextVoice: { ...ctx, spec: voiceSpecOf(ctx) } } : {}),
+ weight: ENGINE_WEIGHT[now.engine] ?? "fast",
+ reads: reads.filter((r) => r.handle && mine.has(handleKey(r.handle))).map((r) => ({ id: r.id, role: r.role, spec: voiceSpecOf({ engine: r.engine, voice: r.voice }), kind: r.kind })),
+ drift: drift.filter((d) => mine.has(d.handle)),
+ speaker: sp?.name ?? null,
+ lines: characterLines(manifest, g.handles).slice(0, 8),
+ };
+ });
+ rows.sort((a, b) => b.items + b.context - (a.items + a.context) || a.name.localeCompare(b.name));
+ const nar = narratorOf(cast);
+ const recorded = reads.filter((r) => r.kind === "recorded" || r.kind === "converted");
+ return {
+ narrator: { engine: k.engine, voice: k.voice, spec: `${k.engine}:${k.voice}`, from: render?.postNarration?.voice ? "project" : "default", character: nar ? { id: nar.id, name: nar.name, voice: nar.voice } : null, recorded: recorded.map((r) => ({ id: r.id, kind: r.kind, voice: r.voice })) },
+ characters: rows,
+ ...castDrift(manifest, { cast, map, resolve }),
+ cast: charactersOf(cast).length,
+ };
+}
+
+/** A thread take's `read` record as the argv that asks for it again, leaving out the overrides of `handles`. */
+export function threadArgvOf(read, { handles = [], author = null } = {}) {
+ if (!read || read.kind !== "thread") return [];
+ const drop = new Set(handles.map(handleKey));
+ const a = [];
+ if (read.parents !== undefined && String(read.parents) !== "0") a.push("--parents", String(read.parents));
+ for (const s of read.skip ?? []) a.push("--skip-parent", String(s));
+ if (read.quoted === false) a.push("--no-quoted");
+ if (read.linked === false) a.push("--no-linked");
+ if (read.seen === true) a.push("--read-seen");
+ for (const [h, v] of Object.entries(read.voiceFor ?? {})) if (!drop.has(handleKey(h))) a.push("--voice-for", `${h}=${v}`);
+ if (read.voice && !(author && drop.has(handleKey(author)))) a.push("--voice", String(read.voice));
+ return a;
+}
+
+/**
+ * THE RE-READS a voice change for `handles` asks for, pure: every post item whose picked read says one of them in
+ * another voice than now -- `[{ id, take, thread, reads: [{ role, reads, want }], argv }]`, `argv` the umtool words
+ * that make the new take (a thread read again with its own options, the changed authors' overrides dropped; a
+ * single read). A read converted from a recording is not re-read by a voice (`skipped`: record it, or derive it again).
+ */
+export function rereadPlan(projectId, manifest, drift, handles) {
+ const want = new Set((handles ?? []).map(handleKey));
+ const byItem = new Map();
+ const skipped = [];
+ for (const d of drift) {
+ if (want.size && !want.has(d.handle)) continue;
+ if (d.kind === "converted") {
+ if (!skipped.some((s) => s.id === d.id)) skipped.push({ id: d.id, why: "a recording converted to a stock voice: derive it again (Import a recording, or the bench's Run AI on it)" });
+ continue;
+ }
+ const row = byItem.get(d.id) ?? { id: d.id, thread: d.thread, reads: [] };
+ row.reads.push({ role: d.role, handle: d.handle, reads: d.reads, want: d.want });
+ byItem.set(d.id, row);
+ }
+ const tl = Array.isArray(manifest?.timeline) ? manifest.timeline : [];
+ const items = [...byItem.values()].map((r) => {
+ const e = tl.find((x) => x?.id === r.id);
+ const takes = e?.narration?.takes ?? [];
+ const t = takes[Number.isInteger(e?.narration?.pick) ? e.narration.pick : 0] ?? null;
+ const argv = ["posts", "narrate", projectId, r.id, "--take", ...(r.thread ? ["--thread", ...threadArgvOf(t?.read, { handles: [...want], author: e?.handle })] : [])];
+ return { ...r, take: t?.file ?? null, argv };
+ });
+ return { items, skipped };
+}
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/lintCli.mjs b/umtool/lib/report/lintCli.mjs
@@ -15,6 +15,8 @@ export const LINT_USAGE = [
" the manifest lint (report-to-video/lint.mjs, what a build runs before it renders) on the project's manifest, or",
" with --take on the take's (its patches applied, as its render reads it), and the files its post items name: a",
" picked read, an attachment, a context post's media not in the project is an ERROR; another named file a warning.",
+ " And the cast's guard (umtool cast): a picked read that says a cast character in another voice than now is a",
+ " warning (umtool cast reread); a cast voice the project's voice map overrides on purpose is a note.",
" Exit 0 no error · 1 an error · 2 usage.",
].join("\n");
@@ -55,6 +57,29 @@ export async function namedFileProblems(manifest, dir) {
}
/**
+ * THE CAST's CONSISTENCY GUARD (umtool-report-to-video/cast.mjs castDrift): a WARNING for each picked read that says a
+ * cast character in another voice than it reads in now (stale: `umtool cast reread`), a NOTE for each cast voice the
+ * project's map overrides on purpose. A project that reads no cast says nothing.
+ * @param {Record<string, any>} manifest
+ * @param {{ id: string, dir: string }} project
+ */
+export async function castProblems(manifest, project, reportsRoot = REPORTS_ROOT) {
+ const { castForProject } = await import("./castStore.mjs");
+ const castRead = await castForProject(project.dir, reportsRoot);
+ if (castRead.error) return { warnings: [`the cast is not read (${castRead.error})`], notes: [] };
+ const { charactersOf, castDrift } = await import("umtool-report-to-video/cast");
+ if (!charactersOf(castRead.cast).length) return { warnings: [], notes: [] };
+ const { readVoiceMap } = await import("./postSay.mjs");
+ const { resolverFor } = await import("./castProject.mjs");
+ const map = await readVoiceMap(project.dir).catch(() => ({}));
+ const { drift, overrides } = castDrift(manifest, { cast: castRead.cast, map, resolve: resolverFor({ map, cast: castRead.cast, render: manifest?.render ?? {} }) });
+ return {
+ warnings: drift.map((d) => `timeline ${d.id}: @${d.handle} (${d.character}) reads in ${d.reads} -- now ${d.want} (${d.from === "project" ? "the project's voice map" : d.from === "cast" ? "the cast" : d.from}): umtool cast reread ${project.id} ${d.character}`),
+ notes: overrides.map((o) => `@${o.handle} (${o.character}) reads in ${o.project} in this project -- the cast says ${o.cast} (an override on purpose; umtool posts voices ${project.id} remove ${o.handle} follows the cast)`),
+ };
+}
+
+/**
* @param {string[]} args the words after `lint`
* @param {{ reportsRoot?: string, log?: (s: string) => void, err?: (s: string) => void }} [opts]
*/
@@ -117,11 +142,13 @@ export async function lintCommand(args, { reportsRoot = REPORTS_ROOT, log = cons
}
const lint = await lintManifestFile(file, { variant, final: flags.has("--final") });
const files = await namedFileProblems(selectVariant(manifest, variant), project.dir);
+ const voices = await castProblems(selectVariant(manifest, variant), project, reportsRoot);
const errors = [...lint.errors, ...files.errors];
- const warnings = [...lint.warnings, ...files.warnings];
- if (flags.has("--json")) log(JSON.stringify({ ok: errors.length === 0, project: project.id, take, variant, entries: manifest.timeline?.length ?? 0, errors, warnings }, null, 2));
+ const warnings = [...lint.warnings, ...files.warnings, ...voices.warnings];
+ if (flags.has("--json")) log(JSON.stringify({ ok: errors.length === 0, project: project.id, take, variant, entries: manifest.timeline?.length ?? 0, errors, warnings, notes: voices.notes }, null, 2));
else {
for (const line of lintReport({ errors, warnings })) log(line);
+ for (const n of voices.notes) log(`note: ${n}`);
log(`${project.id}${take ? ` take ${take}` : ""}: ${manifest.timeline?.length ?? 0} entries, ${errors.length ? "NOT ready to render" : "ready to render as far as the lint can tell"}`);
}
return errors.length ? 1 : 0;
diff --git a/umtool/lib/report/postNarrationCli.mjs b/umtool/lib/report/postNarrationCli.mjs
@@ -44,6 +44,7 @@ export const NARRATE_USAGE = [
" umtool posts narrate <project> <item> [--script \"…\"] [--take [--note \"…\"] [--voice v] [--engine e] [--speed s]]",
" [--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] [--no-convert]",
" umtool posts narrate <project> <item> --take --thread [--parents 0|all|none|<n>] [--skip-parent <id>]… [--no-quoted]",
" [--no-linked] [--read-seen] [--voice-for <handle>=<voice>]… [--voice v] [--force] [--dry-run]",
" umtool posts narrate <project> <item> … --in-take <take> any of these on a TAKE of the project: the pick, a new",
@@ -64,6 +65,10 @@ export const NARRATE_USAGE = [
" A new take is picked; a new script or pick takes the approval away. Scripts are the post VERBATIM (cleaned",
" for pronunciation only); add emotion with Orpheus's tags <sigh> <laugh> <chuckle> <groan> <gasp> ….",
" --delete <n>: the take out of the list, its file moved to narration/posts/<postId>/.trash/ (soft).",
+ " --recording <file> [--as <character>] [--no-clean] [--no-convert] [--label operator]: a person's RECORDING of the",
+ " item made a character's read -- kept as a recorded take (the original), cleaned (the editor's voice-enhance), then",
+ " converted to the character's STOCK voice (umtool cast: its convert voice; default the post's author's, else the",
+ " narrator) -- each a new take, the last picked, the disclosure line said.",
" --derive <n> --op enhance|convert [--engine e] [--voice v]: a NEW take made from take n by the editor's op",
" (enhance: denoise, level; convert: the performance kept, the timbre a STOCK synthetic voice) -- the original kept.",
" A narrated post lasts lead + its read + tail + linger (1.8 s); a longer video is cut to that -- its best part,",
@@ -196,6 +201,7 @@ export function normalizeParts(raw) {
// The text it reads (post-thread.mjs), the voice and the piece the batch read it in.
...(typeof p.role === "string" && /^(post|quoted|parent:\d|media:\d|linked:\d)$/.test(p.role) ? { role: p.role } : {}),
...(typeof p.voice === "string" && /^[A-Za-z0-9][A-Za-z0-9_.+-]{0,63}$/.test(p.voice) ? { voice: p.voice } : {}),
+ ...(typeof p.engine === "string" && /^(orpheus|kokoro|espeak-ng)$/.test(p.engine) ? { engine: p.engine } : {}),
...(Number.isInteger(p.piece) && p.piece >= 0 ? { piece: p.piece } : {}),
}));
}
@@ -313,8 +319,11 @@ export async function makeTake(project, e, { script = null, note = null, engine
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)`);
- const eng = engine ?? e.narration?.engine ?? k.engine;
- const vox = voice ?? e.narration?.voice ?? k.voice;
+ // The voice his own read is said in: the one asked for, the project's voice map, the CAST, the narrator's (readVoice.mjs).
+ const { itemReadVoice } = await import("./readVoice.mjs");
+ const said0 = await itemReadVoice(project, e, { render, engine, voice });
+ const eng = said0.engine;
+ const vox = said0.voice;
const spd = speed ?? e.narration?.speed ?? null;
const pid = postIdOf(e);
const dir = path.join(project.dir, ...takesDirOf(pid).split("/"));
@@ -509,6 +518,20 @@ export async function narrateCommand(project, words, flags, { json = false, dryR
out(json ? JSON.stringify({ ok: true, id: e.id, narration: r.narration, token: r.token }, null, 2) : `${e.id}: take ${k} moved to the post's .trash/ (out of the list)\n${narrationLines(r.entry, render).join("\n")}`);
return 0;
}
+ if (str("--recording") !== null) {
+ // A RECORDING made a character's read: kept as a take (the original), cleaned, converted to its stock voice.
+ const r = await importRecording(project, e, str("--recording"), {
+ as: str("--as"), label: str("--label") ?? "operator", clean: !flags.has("--no-clean"), convert: !flags.has("--no-convert"), note: str("--note"),
+ emit: (_ev, f) => !json && f?.message && out(f.message),
+ });
+ if (json) out(JSON.stringify({ ok: true, id: e.id, ...r }, null, 2));
+ else {
+ out(`${e.id}: ${r.takes.map((t) => `${t.step} -> ${t.file}`).join(", ")}; picked ${r.picked}`);
+ for (const n of r.notes) out(` ${n}`);
+ if (r.disclosure) out(` disclosure: ${r.disclosure}`);
+ }
+ return 0;
+ }
if (str("--derive") !== null) {
const k = Number(str("--derive"));
if (!Number.isInteger(k) || k < 1) throw new NarrateError("--derive takes a take's number as --list shows it (1 = the first)");
@@ -675,7 +698,8 @@ export async function deriveTake(project, e, { from, op, engine = null, voice =
const ran = engine ?? (typeof said?.engine === "string" ? said.engine : null);
const landed = op === "convert" ? (target ?? (typeof said?.voice === "string" ? said.voice : null)) : null;
const take = {
- file: rel, engine: "derived", voice: landed ?? t.voice ?? "?", seconds: m.seconds ?? t.seconds,
+ // A take's voice is the bare stock voice ("am_michael"); its step keeps the target as asked ("kokoro:am_michael").
+ file: rel, engine: "derived", voice: (landed ? String(landed).split(":").pop() : null) ?? t.voice ?? "?", seconds: m.seconds ?? t.seconds,
source: { kind: "take", from: takeIdOf(t) },
steps: [{ op, ...(ran ? { engine: ran } : {}), ...(landed ? { voice: landed } : {}), ...(params ? { params } : {}), ranAt: new Date().toISOString(), job: jobId }],
script: t.script ?? e.narration?.script ?? "", at: new Date().toISOString(), jobId,
@@ -686,6 +710,63 @@ export async function deriveTake(project, e, { from, op, engine = null, voice =
}
/**
+ * A RECORDING MADE A CHARACTER's READ (operator, 6 Nov: "running AI voice changing on a recording of me so I can
+ * provide the wording and such while you clean up any audio issues"): `file` (any sound or video ffmpeg reads) kept
+ * as a RECORDED take (postRecord.mjs keepRecording: trimmed, levelled -- the original, never overwritten), then a
+ * derived take CLEANED by the editor's voice-enhance (skipped, and said, when it has no engine for it), then a
+ * derived take CONVERTED by its voice-convert to the character's STOCK voice (cast.mjs convertTargetOf: its convert
+ * voice, else its voice) -- the character `as` names (an id, a handle), else the post's author's in the cast, else
+ * the cast's narrator; none: kept as recorded (and cleaned). Each step a new take, the last one picked, with the
+ * disclosure line the cut will carry. Returns `{ takes: [{ step, file }], picked, notes, disclosure, character }`.
+ */
+export async function importRecording(project, e0, file, { as = null, label = "operator", clean = true, convert = true, note = null, emit = () => {}, editor = null, ask = null } = {}) {
+ const abs = path.resolve(String(file ?? ""));
+ if (!(await stat(abs).catch(() => null))?.isFile()) throw new NarrateError(`--recording takes a sound file (no ${file})`);
+ const { keepRecording } = await import("./postRecord.mjs");
+ const { castForProject } = await import("./castStore.mjs");
+ const { characterOf, convertTargetOf, findCharacter, narratorOf } = await import("umtool-report-to-video/cast");
+ const { postNarrationDisclosure } = await import("umtool-report-to-video/post-narration");
+ const castRead = await castForProject(project.dir);
+ const character = as ? findCharacter(castRead.cast, String(as).replace(/^@+/, "")) : characterOf(castRead.cast, e0.handle) ?? narratorOf(castRead.cast);
+ if (as && !character) throw new NarrateError(`--as ${as}: no such character in the cast (umtool cast ls)`);
+ const notes = [];
+ const takes = [];
+ const fresh = async () => findPostItem(await readManifest(project.dir), e0.id);
+ const kept = await keepRecording(project, e0, [{ file: abs, text: String(e0.narration?.script ?? "") }], { label, manifest: await readManifest(project.dir), note: note ?? `recorded${character ? ` for ${character.name}` : ""}` });
+ takes.push({ step: "recorded", file: kept.take.file });
+ emit("note", { message: `kept as recorded: ${kept.take.file} (levelled ${kept.gain >= 0 ? "+" : ""}${kept.gain} dB)` });
+ let e = await fresh();
+ const indexOf = (rel) => (e?.narration?.takes ?? []).findIndex((t) => t.file === rel);
+ let from = indexOf(kept.take.file);
+ if (clean) {
+ try {
+ const r = await deriveTake(project, e, { from, op: "enhance", emit, editor, ask });
+ takes.push({ step: "cleaned", file: r.take.file });
+ e = await fresh();
+ from = indexOf(r.take.file);
+ } catch (err) {
+ if (err?.name !== "OpNotInstalled" && !/not installed/i.test(String(err?.message))) throw err;
+ notes.push(`not cleaned: ${err.message} (archilyzer voice setup --engine deepfilternet)`);
+ }
+ }
+ if (convert) {
+ if (!character) notes.push("not converted: no character to convert to (--as <character>, or the post's author or a narrator in the cast: umtool cast add …)");
+ else {
+ const target = convertTargetOf(character);
+ try {
+ const r = await deriveTake(project, e, { from, op: "convert", engine: target.engine, voice: target.voice, emit, editor, ask });
+ takes.push({ step: `converted to ${target.voice}`, file: r.take.file });
+ e = await fresh();
+ } catch (err) {
+ if (err?.name !== "OpNotInstalled" && !/not installed/i.test(String(err?.message))) throw err;
+ notes.push(`not converted: ${err.message} (archilyzer voice setup --engine ${target.engine ?? "openvoice"})`);
+ }
+ }
+ }
+ return { takes, picked: takes.at(-1).file, notes, disclosure: e ? postNarrationDisclosure(e) : null, character: character ? { id: character.id, name: character.name, voice: character.voice } : null };
+}
+
+/**
* DELETE A TAKE, SOFTLY: its file (and its parts) moved into the post's
* `narration/posts/<postId>/.trash/`, the take out of the list (the pick
* follows). Returns the write's result.
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/postsCli.mjs b/umtool/lib/report/postsCli.mjs
@@ -194,7 +194,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", "--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"]);
+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", "--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"]);
/** The valued flags that may be given more than once (each value kept, in order). */
const MULTI = new Set(["--skip-parent", "--voice-for"]);
const SLUG_RE = /^[A-Za-z0-9._-]+$/;
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
@@ -83,6 +83,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. */