commit 1f2944ac135e4e65de8f701d5ee5669ee8207281
parent 065ed70ea3a9b050a08fba4abfffa177e533396a
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Fri, 6 Nov 2026 22:01:34 -0500
umtool: the Voices page -- each character's voice and where it comes from, an audition side by side at one loudness with closeness to the real voice, Use for this project or everywhere, the re-reads queued, a recording made a character's read, the cast
/projects/<p>/voices (reached from the Cut tab's Reads and voices): every character the project's
reads use with its voice now (cast · project · narrator · default), its items, its picked reads in
another voice, its real voice. Audition: a line (its own words here, a stock line, or typed), 2-6
candidates (Kokoro fast, Orpheus heavy), Render -- one job: the editor's tts for the candidates not
kept, then their closeness to the real voice through the heavy slot -- each played at -20 LUFS
beside the real voice (a reference, never a target), the closest marked. Use for this project /
Use everywhere, then a confirm listing the items to re-read, queued as steps (/jobs). A recording
dropped on an item: kept, cleaned, converted to the character's stock voice (a job). The cast:
remove, undo. /api/report/voices runs the CLI's own commands (umtool cast).
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
8 files changed, 968 insertions(+), 44 deletions(-)
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/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
@@ -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>
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,606 @@
+"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 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];
+ const best = Math.max(...(audition?.candidates ?? []).map((c) => (typeof c.score === "number" ? c.score : -Infinity)));
+ 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">its first line here</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} onClick={() => void render()} className={buttonVariants({ variant: "go", size: "sm" })}>
+ {running ? "Rendering…" : missing ? `Render ${missing} candidate${missing === 1 ? "" : "s"}` : "Score again"}
+ </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 = typeof c.score === "number" && c.score === best && audition.candidates.filter((x) => typeof x.score === "number").length > 1;
+ 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/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/castAudition.mjs b/umtool/lib/report/castAudition.mjs
@@ -40,6 +40,8 @@ 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;
@@ -100,6 +102,63 @@ export function characterLines(manifest, handles) {
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 in the project, 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] : lines[0];
+ 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 };
+}
+
/** 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");
@@ -292,3 +351,62 @@ export async function scoreAuditions(project, character, plan, { engineOpts = {}
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
@@ -30,7 +30,7 @@ export const CAST_USAGE = [
" 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>] [--no-score | --score-only] [--no-hold] [--json] [--progress ndjson]",
+ " [--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]",
"",
@@ -324,48 +324,9 @@ async function auditionCommand(rest, p, { reportsRoot, log, err, ask, lanes }) {
};
const project = p.str("--project") ? await projectOf(p.str("--project"), reportsRoot) : null;
const castRead = project ? await castForProject(project.dir, reportsRoot) : await readCast(reportsRoot);
- let manifest = null;
- let character = findCharacter(castRead.cast, who.replace(/^@+/, ""));
- if (who.startsWith("@") || !character) {
- const h = handleKey(who);
- const c = characterOf(castRead.cast, h);
- if (c) character = c;
- else {
- manifest = project ? await readManifest(project.dir) : null;
- const { authorsOf } = await import("./castProject.mjs");
- const a = manifest ? authorsOf(manifest).get(h) : null;
- if (!a && !project) throw new CastError(`${who} is not in the cast (umtool cast ls), and no --project names it`);
- if (!a) throw new CastError(`${who} is neither in the cast nor an author in ${project?.id}`);
- character = { id: h, name: a.name || h, handles: [h], voice: null };
- }
- }
- manifest ??= project ? await readManifest(project.dir) : null;
- // The line: --text, an item's, the n-th, the first of the character's, a stock line -- what a voice SAYS (the
- // project's redaction, slur filter and lexicon applied).
- let text = p.str("--text");
- let from = text ? "text" : null;
- let item = null;
- if (!text && manifest) {
- const lines = A.characterLines(manifest, character.handles ?? []);
- const pick = p.str("--item") ? lines.find((l) => l.item === p.str("--item")) : p.str("--line") ? lines[Number(p.str("--line")) - 1] : lines[0];
- if ((p.str("--item") || p.str("--line")) && !pick) throw new CastError(`${character.name} has no such line in ${project?.id} (cast project ${project?.id} lists them)`);
- if (pick) {
- text = pick.text;
- from = `item:${pick.item}`;
- item = manifest.timeline.find((e) => e?.id === pick.item) ?? null;
- }
- }
- if (!text) {
- text = A.STOCK_LINE;
- from = "stock";
- }
- text = A.auditionText(text);
- 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);
- text = spokenRead(text, item ?? { id: null }, red, { voice: "skip" }).text.trim() || text;
- }
+ 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);