"use client"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { buttonVariants } from "@/components/ui/button"; import { cn } from "@/lib/utils"; import { jobsHref, postBenchHref, readsHref } from "@/lib/hrefs"; import { PresetEditor, ProjectCharacters, recordedWords, type ItemCharacter, type PresetCharacter } from "./CharacterPresets"; import type { StaleRead } from "./CharacterTuning"; import { ProposedCharacters, type Proposal } from "./ProposedCharacters"; // --------------------------------------------------------------------------- // 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 // (the item's own character · this video's · the cast · 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; Presets opens its two presets (CharacterPresets.tsx); an author // with no character: "Add to the pool" / "Keep in this video only" // proposed a character for each author with none, BY RULE (ProposedCharacters.tsx; umtool cast assign): // Accept / Change / Reject, nothing applied before; the model only on "Ask the model too" // this video's own the characters that live in this video only (anonymous ones under a shown name), and the items // read as a character of their own // 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; speed?: number; character?: 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: (PresetCharacter & { layer: "cast" | "project" }) | 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 }[]; // Its reads made with other settings than its Orpheus tuning now (stale: listed, never re-made). stale?: StaleRead[]; }; // What a recording of the character is made into: the stock voice, the engine, and the pitch the converted read // lands on (`umtool cast set --convert-pitch source|contour|target --convert-semitones n`). type Convert = { engine?: string; voice?: string; pitch?: "target" | "source" | "contour"; semitones?: number }; type CastChar = PresetCharacter & { voice: string }; /** A convert entry's pitch in words — "follows your pitch", "your intonation at the voice's register +2 st" — "" for the stock voice's own. */ function pitchWords(cv?: Convert): string { if (!cv?.pitch || cv.pitch === "target") return ""; const n = Number(cv.semitones) || 0; const st = n ? ` ${n > 0 ? "+" : "−"}${Math.abs(n)} st` : ""; return cv.pitch === "source" ? `follows your pitch${st}` : `your intonation at the voice's register${st}`; } type Engine = { id: string; label: string; voices: string[]; defaultVoice: string; weight: string }; type View = { project: string; castFile: string | null; castError?: string; map: Record; 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 }[]; tuningStale?: StaleRead[]; cast: CastChar[]; engines: Engine[]; convertEngines: string[]; running: { id: string; state: string; kind: string } | null; // This video's own characters (narration/characters.json) and the items that name a character of their own. own?: PresetCharacter[]; itemCharacters?: ItemCharacter[]; charactersError?: string; // PROPOSED characters (umtool cast assign), applied to nothing until accepted; where the model would run. proposed?: Proposal[]; assignModel?: { route: string | null; model: string | null; why: string | null } | 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 = { cast: "the cast", project: "this project", narrator: "the narrator's", default: "the default", override: "a read's own", item: "the item's own character" }; 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(null); const [error, setError] = useState(null); const [status, setStatus] = useState(null); const [busy, setBusy] = useState(false); const [who, setWho] = useState(initialWho); const [line, setLine] = useState("first"); const [custom, setCustom] = useState(""); const [candidates, setCandidates] = useState([]); const [addEngine, setAddEngine] = useState("kokoro"); const [addVoice, setAddVoice] = useState(""); const [audition, setAudition] = useState(null); const [job, setJob] = useState(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(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); // The character whose presets are open: the cast's, or one of this video's own. const [preset, setPreset] = useState<{ scope: "cast" | "project"; id: string } | null>(null); const timer = useRef | null>(null); const audios = useRef>(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: (j: JobPoll) => 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(j); }; void tick(); }, [], ); const post = async (body: Record) => { 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 & { 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`); }); }; const changed = (what: string) => { setStatus(what); void load(); void loadAudition(); }; // "Ask the model too" (optional): a job -- the editor's cast-assign task -- followed; the proposals reloaded after. const [modelJob, setModelJob] = useState(false); const askModel = async () => { const j = (await post({ op: "assign", model: true })) as { job?: { id: string } } | null; if (!j?.job) return; setModelJob(true); follow(j.job.id, (done) => { setModelJob(false); changed(done.state === "done" ? "the model's answers are laid over the proposals (each field checked; a refused one keeps the rule's)" : `the model was not heard — the rule's proposals stand: ${done.error ?? done.log.at(-1) ?? ""}`); }); }; // An author with no character: into the pool (the cast: the voice they read in now, everywhere) or this video only. const poolAuthor = async (c: Character) => { const j = await post({ op: "use", who: whoOf(c), voice: c.voice.spec, scope: "cast" }); if (j) changed(`${c.name} is in the pool now (${pretty(c.voice.spec)}), for every project`); }; const keepHere = async (who: string, name: string) => { const j = (await post({ op: "character-keep", who })) as { character?: { id: string } } | null; if (!j) return; changed(`${name} is a character of this video only`); if (j.character?.id) setPreset({ scope: "project", id: j.character.id }); }; if (!view) return error ?

{error}

:

reading the voices…

; 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"); const own = view.own ?? []; const presetOf = preset ? (preset.scope === "project" ? own.find((c) => c.id === preset.id) : view.cast.find((c) => c.id === preset.id)) ?? null : null; return (
{/* --- the characters ------------------------------------------------------------ */}

the characters · {view.characters.length} a voice comes from a read's own choice, the item's own character, this video's characters and map, the cast (every project), the narrator's, or the default — in that order

{view.castError &&

the cast is not read: {view.castError}

} {view.characters.map((c) => { const k = whoOf(c); return ( ); })}
character reads in reads its picked reads real voice
{c.name} {c.handles.map((h) => `@${h}`).join(" ")} {c.character && c.character.layer !== "project" && cast} {c.character?.layer === "project" && this video} {c.character?.anonymous && anonymous} {pretty(c.voice.spec)} {typeof c.voice.speed === "number" && ×{c.voice.speed}} {c.weight === "heavy" && heavy}
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})` : ""}
{c.items} item{c.items === 1 ? "" : "s"} {c.context ? ` · ${c.context} as context` : ""} {c.drift.length ? ( `${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(", ")}) ) : c.reads.length ? ( {c.reads.length} in its voice ) : ( none yet )} {c.stale && c.stale.length > 0 && (
d.id)).size} title={c.stale.map((d) => `${d.id} ${d.role}: made with temperature ${d.made.temperature}, top_p ${d.made.top_p}, repeat penalty ${d.made.repeat_penalty}, takes ${d.made.takes}`).join("\n")}> {new Set(c.stale.map((d) => d.id)).size} made with other settings{" · "} Reads
)}
{c.speaker ?? —} {c.character ? ( ) : ( <> {" "} )}{" "}
the narrator {view.narrator.character && (the cast's: {view.narrator.character.name} — a recording's default)} {pretty(view.narrator.spec)}
from {FROM[view.narrator.from] ?? view.narrator.from} (the cut's narration voice)
{view.narrator.recorded.length ? `${view.narrator.recorded.length} recorded read(s): ${view.narrator.recorded.map((r) => `${r.id}${r.kind === "converted" ? ` → ${r.voice}` : ""}`).join(", ")}` : no recorded reads}
{view.overrides.length > 0 && (
    {view.overrides.map((o) => (
  • @{o.handle} reads in {pretty(o.project)} here — the cast says {pretty(o.cast)} (an override on purpose)
  • ))}
)}
{/* --- proposed characters (by rule; the model only when asked) ------------------- */} void askModel()} modelRunning={modelJob} /> {/* --- one character's presets --------------------------------------------------- */} {preset && presetOf && ( <> setPreset(null)} project={project} stale={(view.tuningStale ?? []).filter((d) => d.character === preset.id)} /> {preset.scope === "cast" && !own.some((c) => c.id === preset.id) && (

{" "} — a copy of {presetOf.name} for this video: change its presets here and the pool's stay as they are

)} )} {/* --- this video's own characters ------------------------------------------------ */} setPreset({ scope: "project", id })} open={preset?.scope === "project" ? preset.id : null} /> {/* --- the audition ------------------------------------------------------------- */} {chosen && (

audition · {chosen.name}

{line === "custom" && setCustom(e.target.value)} placeholder="what the voice reads" className={cn(input, "w-80")} />}
{audition && (

reads: “{audition.text}”

)}
candidates {candidates.map((spec) => ( {pretty(spec)} ))} 2–6 · Kokoro first: Orpheus pins ~8.5 GB and waits its turn
{heavy && an Orpheus candidate: the editor runs it through its heavy slot, after a render you are waiting for} {job && ( {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) ?? ""}`} )} {(audition?.candidates ?? []).some((c) => c.cached) && ( )}
{audition && (
c.cached).length}> {audition.reference && (
the real voice · {audition.speaker} a reference to compare with — never a target
)} {audition.candidates.map((c) => { const top = best !== null && c.score === best; return (
{pretty(c.spec)} {c.weight === "heavy" ? "Orpheus · heavy" : "fast"}
{c.cached ? (
); })}
)} {audition && !audition.speaker && (

no real voice named for {chosen.name}{" "}in this project (speakers.json — the walk's “Add to a voice”): the candidates are not scored

)} {reread && (
{reread.items.length ? ( <>

{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.

    {reread.items.map((x) => (
  • {x.id} — {x.reads.map((r) => `${r.role} ${pretty(r.reads)} → ${pretty(r.want)}`).join(", ")}
  • ))}
) : (

no picked read says {chosen.name} in another voice — nothing to re-read

)}
)} {queued && (

queued {queued.length} re-read{queued.length === 1 ? "" : "s"} ({queued.join(", ")}) —{" "} on Jobs

)}
)} {/* --- a recording made a character's read ------------------------------------------ */}

a recording, made a character's read

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

{/* --- the cast ----------------------------------------------------------------- */}

the cast · {view.cast.length} the same voice for a character in every project

{view.cast.length ? ( {view.cast.map((c) => ( ))}
{c.name} {(c.handles ?? []).map((h) => `@${h}`).join(" ")} {c.narrator && the narrator} {pretty(c.voice)} {typeof c.synthetic?.speed === "number" ? ` ×${c.synthetic.speed}` : ""} {c.convert ? `a recording → ${pretty(c.convert.voice ?? c.voice)}${c.convert.engine ? ` (${c.convert.engine})` : ""}` : ""} {pitchWords(c.convert) && ( `}> {` · pitch: ${pitchWords(c.convert)}`} )} {recordedWords({ ...c, recorded: { ...c.recorded, convert: undefined } }) ? ` · ${recordedWords({ ...c, recorded: { ...c.recorded, convert: undefined } })}` : ""} {c.speakers?.length ? ` · real voice: ${c.speakers.join(", ")}` : ""} {c.note ? ` · ${c.note}` : ""} {" "}
) : (

nobody yet — an audition's “Use everywhere” puts a character in it

)}
{status && (

{status}

)} {error && (

{error}

)}
); }