"use client"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { buttonVariants } from "@/components/ui/button"; import { cn } from "@/lib/utils"; import { postBenchHref, readsHref } from "@/lib/hrefs"; import { ORPHEUS_TUNING_NAMED, ORPHEUS_TUNING_NAMES, TTS_TUNING_RANGES, ttsTuningNameOf, type TtsTuningName } from "yt-dlp-transcript-common/lib/ttsTuning.mjs"; // --------------------------------------------------------------------------- // A CHARACTER's ORPHEUS TUNING, in its preset (lane character-tuning; components/projects/CharacterPresets.tsx; the // CLI is `umtool cast set --tuning … --temperature …`, `umtool cast try

…`, `umtool cast stale

`). // Works with the operator alone: every button a form and a job, every write the CLI's own command. // // the tuning Steady / Default / Lively fill the numbers, which are always shown and editable ("custom") // try it a line (its own in this project, or typed), Read it -> a job (the editor's tts) -> plays when // done; Another reading -> the same line and numbers, the next reading; the list of tries, each at // one loudness (-20 LUFS), with its numbers and reading; scratch (no take, nothing in the draft) // keep Keep these settings -> umtool cast set (the cast) / cast project

set (this video) // stale the reads by this character made with other settings than its tuning now (listed, never re-made) // --------------------------------------------------------------------------- export type TuningFields = { temperature?: number; top_p?: number; repeat_penalty?: number; takes?: number }; export type StaleRead = { id: string; role: string; character: string; reading: number; made: Record; want: Record }; type TuningView = { tuning: TuningFields | null; name: string; effective: Record; takesFrom: "character" | "setting" }; type TryRow = { key: string; character: string; layer?: string | null; voice: string; text: string; tuning: TuningFields; reading: number; rel: string; seconds: number | null; lufs: number | null; at: string }; type Tries = { character: { id: string; name: string; layer: string | null; voice: string | null; tuning: TuningView }; line: { text: string; from: string }; settingTakes: number; tries: TryRow[] }; type JobPoll = { id: string; state: "running" | "done" | "failed"; error: string | null; kind?: string; events?: { ev?: string; phase?: string; key?: string; reading?: number }[] }; type PostFn = (body: Record) => Promise | null>; const FIELDS = [ { k: "temperature", label: "temperature", step: 0.05 }, { k: "top_p", label: "top_p", step: 0.01 }, { k: "repeat_penalty", label: "repeat penalty", step: 0.05 }, { k: "takes", label: "takes", step: 1 }, ] as const; type Form = Record<(typeof FIELDS)[number]["k"], string>; const NAME_LABEL: Record = { steady: "Steady", default: "Default", lively: "Lively", custom: "custom" }; 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 fileUrl = (project: string, rel: string, v?: string) => `/api/report/file?project=${encodeURIComponent(project)}&path=${encodeURIComponent(rel)}${v ? `&v=${v}` : ""}`; const formOf = (t: TuningFields | null | undefined, eff?: Record): Form => ({ temperature: String(t?.temperature ?? eff?.temperature ?? ORPHEUS_TUNING_NAMED.default.temperature), top_p: String(t?.top_p ?? eff?.top_p ?? ORPHEUS_TUNING_NAMED.default.top_p), repeat_penalty: String(t?.repeat_penalty ?? eff?.repeat_penalty ?? ORPHEUS_TUNING_NAMED.default.repeat_penalty), takes: typeof t?.takes === "number" ? String(t.takes) : "", }); /** The form's numbers, or the field that is out of its range. */ function numbersOf(f: Form): { ok: true; t: TuningFields } | { ok: false; field: string } { const t: TuningFields = {}; for (const { k } of FIELDS) { const raw = f[k].trim(); if (!raw && k === "takes") continue; const n = Number(raw); const r = TTS_TUNING_RANGES[k]; if (!raw || !Number.isFinite(n) || n < r.min || n > r.max || (r.integer && !Number.isInteger(n))) return { ok: false, field: k }; t[k] = Math.round(n * 1000) / 1000; } return { ok: true, t }; } /** The form's numbers the same as the tuning KEPT: the sampler's three (unsaid: the default) and takes as stored (none: none). */ const sameAsStored = (a: TuningFields, stored: TuningFields) => (["temperature", "top_p", "repeat_penalty"] as const).every((k) => (a[k] ?? ORPHEUS_TUNING_NAMED.default[k]) === (stored[k] ?? ORPHEUS_TUNING_NAMED.default[k])) && (a.takes ?? null) === (stored.takes ?? null); const numbersWords = (t: TuningFields, settingTakes: number) => `temperature ${t.temperature ?? ORPHEUS_TUNING_NAMED.default.temperature} · top_p ${t.top_p ?? ORPHEUS_TUNING_NAMED.default.top_p} · repeat penalty ${t.repeat_penalty ?? ORPHEUS_TUNING_NAMED.default.repeat_penalty} · takes ${t.takes ?? settingTakes}`; export function CharacterTuning({ project, id, name, voice, scope, busy, post, onKept, stale, }: { project: string; id: string; name: string; voice: string; scope: "cast" | "project"; busy: boolean; post: PostFn; onKept: (what: string) => void; stale: StaleRead[]; }) { const orpheus = voice.startsWith("orpheus:"); const [data, setData] = useState(null); const [form, setForm] = useState

(null); const [text, setText] = useState(null); const [job, setJob] = useState(null); const [blocked, setBlocked] = useState(null); const [renderWait, setRenderWait] = useState(null); const [error, setError] = useState(null); const [status, setStatus] = useState(null); const [notes, setNotes] = useState([]); // A press sent and not answered yet: a second press waits (no second job, no second follow). const [pending, setPending] = useState(false); // The same, read synchronously: two clicks inside one render both see `pending` false. const pendingRef = useRef(false); const timer = useRef | null>(null); const audios = useRef>(new Map()); // The try a finished job made: it plays when the list is read again, and only it. const playKey = useRef(null); const load = useCallback(async () => { let r: Response; let j: (Tries & { error?: string }) | null = null; try { r = await fetch(`/api/report/voices?project=${encodeURIComponent(project)}&tries=${encodeURIComponent(id)}&scope=${scope}`, { cache: "no-store" }); j = (await r.json().catch(() => null)) as (Tries & { error?: string }) | null; } catch (e) { playKey.current = null; setError(`the tries could not be read: ${e instanceof Error ? e.message : String(e)}`); return; } if (!r.ok || !j) { playKey.current = null; setError(j?.error ?? `HTTP ${r.status}`); return; } setData(j); setForm((f) => f ?? formOf(j.character.tuning.tuning, j.character.tuning.effective)); setText((t) => t ?? j.line.text); }, [project, id, scope]); useEffect(() => { void load(); return () => { if (timer.current) clearTimeout(timer.current); }; }, [load]); // A new try plays when its job ends: the row of the key that job made, once the list is read again. useEffect(() => { const k = playKey.current; if (!k) return; playKey.current = null; void audios.current.get(k)?.play().catch(() => undefined); }, [data]); const settingTakes = data?.settingTakes ?? 3; const nums = form ? numbersOf(form) : null; const tuning = nums?.ok ? nums.t : null; const named = tuning ? ttsTuningNameOf(tuning) : "custom"; const kept = data?.character.tuning.tuning ?? {}; const isKept = !!tuning && sameAsStored(tuning, kept); const running = job?.state === "running"; const off = busy || running || pending || !!blocked || !orpheus; /** * Follow a job to its end; while it runs, say when render mode holds the machine. An answer that is not the job's * (umtool restarted: no such job) or a poll that cannot reach umtool ends it as failed -- never as made. */ const follow = useCallback((jobId: string, then: (j: JobPoll) => void) => { if (timer.current) clearTimeout(timer.current); const tick = async () => { let j: JobPoll; try { const r = await fetch(`/api/report/voices?job=${encodeURIComponent(jobId)}`, { cache: "no-store" }); const body = (await r.json().catch(() => null)) as (JobPoll & { error?: string }) | null; j = r.ok && body && typeof body.state === "string" ? body : { id: jobId, state: "failed", error: body?.error ?? `HTTP ${r.status}` }; } catch (e) { j = { id: jobId, state: "failed", error: `the job could not be followed: ${e instanceof Error ? e.message : String(e)}` }; } const rm = (await fetch("/api/render-mode", { cache: "no-store" }).then((x) => x.json()).catch(() => null)) as { held?: boolean; what?: string | null } | null; setRenderWait(j.state === "running" && rm?.held ? `Waiting for the render (${rm.what ?? "render mode is on"}): the read is made when it lets go.` : null); if (j.state === "running") { timer.current = setTimeout(() => void tick(), 1000); return; } then(j); }; void tick(); }, []); const read = async (ask: { reading: number } | { another: true }) => { if (!tuning || !text?.trim() || pendingRef.current) return; pendingRef.current = true; setPending(true); setError(null); setStatus(null); try { let r: Response; let j: { job?: JobPoll; error?: string; running?: JobPoll }; try { r = await fetch("/api/report/voices", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, op: "try", who: id, scope, text: text.trim(), tuning: { ...tuning, takes: tuning.takes ?? null }, ...ask }), }); j = (await r.json().catch(() => ({}))) as typeof j; } catch (e) { setError(`umtool could not be reached: ${e instanceof Error ? e.message : String(e)}`); return; } if (r.status === 409 && j.running) { // Another job holds umtool's runner: said here, the buttons open again when it ends. setBlocked(`Another job is running (${j.running.kind ?? "a job"}): Read it is open again when it ends.`); follow(j.running.id, () => setBlocked(null)); return; } if (!r.ok || !j.job) { setError(j.error ?? `HTTP ${r.status}`); return; } setJob(j.job); follow(j.job.id, (done) => { setJob(done); const made = (done.events ?? []).find((ev) => ev?.ev === "cast-try" && ev.phase === "done" && typeof ev.key === "string"); if (done.state !== "done" || !made) setError(`the read failed: ${done.error ?? "see the job's log on /jobs"}`); else { playKey.current = made.key ?? null; setStatus(`reading ${made.reading ?? 0} made`); } void load(); }); } finally { pendingRef.current = false; setPending(false); } }; const keep = async () => { if (!tuning) return; setNotes([]); const j = (await post({ op: "character-set", scope, id, tuning: { ...tuning, takes: tuning.takes ?? null } })) as { notes?: string[]; tuning?: TuningView } | null; if (j) { onKept(`${name}: Orpheus tuning kept (${NAME_LABEL[named]}) ${scope === "cast" ? "in the cast (every project)" : "for this video only"}`); // What the CLI said beside it (takes 3 not kept, a voice that ignores it), and the takes field as it is stored. setNotes(Array.isArray(j.notes) ? j.notes : []); const storedTakes = j.tuning?.tuning?.takes; setForm((f) => (f ? { ...f, takes: typeof storedTakes === "number" ? String(storedTakes) : "" } : f)); void load(); } }; const pick = (n: TtsTuningName) => setForm((f) => ({ ...(f ?? formOf(null)), temperature: String(ORPHEUS_TUNING_NAMED[n].temperature), top_p: String(ORPHEUS_TUNING_NAMED[n].top_p), repeat_penalty: String(ORPHEUS_TUNING_NAMED[n].repeat_penalty) })); const staleIds = useMemo(() => [...new Set(stale.map((s) => s.id))], [stale]); return (
Orpheus tuning {ORPHEUS_TUNING_NAMES.map((n) => { const t = ORPHEUS_TUNING_NAMED[n]; return ( ); })} {named === "custom" && custom} {!orpheus && {voice.split(":")[0] || "this voice"} ignores a tuning}
{FIELDS.map(({ k, label, step }) => { const r = TTS_TUNING_RANGES[k]; return ( ); })} {data ? (data.character.tuning.tuning ? `kept: ${NAME_LABEL[data.character.tuning.name] ?? data.character.tuning.name} · ${numbersWords(data.character.tuning.effective, settingTakes)}` : `kept: none (Default · takes ${settingTakes})`) : ""}