"use client"; import { useEffect, useRef, useState } from "react"; import { buttonVariants } from "@/components/ui/button"; import { cn } from "@/lib/utils"; import { ls } from "../useMic"; import { ORPHEUS_DEFAULT_TAKES, ORPHEUS_TUNING_DEFAULTS, TTS_TUNING_FIELDS, TTS_TUNING_RANGES, ttsTuningNameOf } from "yt-dlp-transcript-common/lib/ttsTuning.mjs"; import { asksSampler, characterTuneOf, keepAskOf, madeOwnOf as tuneMadeOwnOf, sameBaseline, tuneAskOf, tuneStartOf, unknownBaselineAskOf } from "@/lib/report/tuneAsk.mjs"; // --------------------------------------------------------------------------- // READ AGAIN (lane line-rerun, S3 of the Orpheus re-tune plan): one line's // re-read controls, the same wherever a synthetic voice reads a line -- a // post's script, a screen line, a thread read, a card's narration. // // Read again the same words, the next reading // Read edited text the words as edited (saved first), read // Tune ▾ the six numbers for this line only, prefilled from // how it was last made // play when ready the new read plays as it lands (remembered per browser) // // Every press is a form and a job: the caller's route runs the umtool command. // The read made joins the list unpicked; the caller's Pick makes it the one. // `keepForCharacter` is S2's seam (lane character-tuning): absent, no button. // --------------------------------------------------------------------------- export type Tuning = Partial>; /** S2's seam: keep these numbers for the character (its command: `umtool cast set --temperature …`). */ export type KeepForCharacter = (tuning: Tuning) => Promise; /** * THE TUNE's BASELINE (lane character-tuning, review 2): what a plain press reads this piece with NOW -- its * character's tuning (null: the defaults; no character: the defaults), unless its last read was the line's own * (`madeOwn`): then those numbers, and they stay the line's own. A press sends as the line's own only what differs * from the character's (all of it when the last read was the line's own); nothing changed on a character's line sends * none of the sampler, so the character's is asked as it is then. */ export type TuneBaseline = { character: { name: string; tuning: Tuning | null } | null; madeOwn: boolean; ownTakes?: number | null }; /** Was a read the line's own? (lib/report/tuneAsk.mjs: the one rule.) */ export const madeOwnOf = (tuning: Tuning | null | undefined, tuningAsked: unknown): boolean => tuneMadeOwnOf(tuning, tuningAsked); const NAMED: Record = { steady: "Steady", default: "Default", lively: "Lively", custom: "custom" }; const AUTOPLAY_KEY = "umtool.reads.autoplay"; const LABEL: Record = { temperature: "temperature", top_p: "top p", top_k: "top k", min_p: "min p", repeat_penalty: "repeat penalty", takes: "takes" }; // `takes` has no default here: empty is the editor's settings' own (tts.orpheus.takes), never a guessed 3. const DEFAULTS: Record = { ...ORPHEUS_TUNING_DEFAULTS }; void ORPHEUS_DEFAULT_TAKES; // ONE STORE for every mount (review 1, finding 9): a toggle on one line is the toggle on all of them, at once. const autoplayListeners = new Set<(on: boolean) => void>(); let autoplayNow: boolean | null = null; /** Whether a new read plays as it lands: on unless this browser said otherwise -- one value for every mount. */ export function useAutoPlay(): [boolean, (on: boolean) => void] { const [on, setOn] = useState(true); useEffect(() => { if (autoplayNow === null) autoplayNow = ls.get(AUTOPLAY_KEY) !== "off"; setOn(autoplayNow); autoplayListeners.add(setOn); return () => { autoplayListeners.delete(setOn); }; }, []); return [on, (v: boolean) => { autoplayNow = v; ls.set(AUTOPLAY_KEY, v ? "on" : "off"); for (const f of autoplayListeners) f(v); }]; } /** Play `url` now (a read that landed); a browser that refuses without a gesture is left silent. */ export function playNow(url: string) { try { void new Audio(url).play().catch(() => {}); } catch { // no audio here } } /** The numbers that differ from Orpheus's defaults, or null: what a read asks. */ export function tuningAsked(draft: Record): Tuning | null { const out: Tuning = {}; for (const k of TTS_TUNING_FIELDS as readonly (keyof Tuning)[]) { const v = Number(draft[k]); // `takes`: sent whenever one is given (the settings' may differ from 3); the sampler's: when not its default. if (draft[k] !== "" && Number.isFinite(v) && (k === "takes" || v !== DEFAULTS[k])) out[k] = v; } return Object.keys(out).length ? out : null; } /** A tuning and a reading as a short phrase: "reading 2 · temperature 0.7". Defaults are not said. */ export function madeWithText(t: { reading?: number | null; tuning?: Tuning | null }): string { const bits = [...(t.reading ? [`reading ${t.reading}`] : []), ...Object.entries(t.tuning ?? {}).filter(([k, v]) => k !== "takes" && v !== DEFAULTS[k]).map(([k, v]) => `${LABEL[k] ?? k} ${v}`)]; return bits.join(" · "); } export default function ReadAgain({ what = "", busy = false, waiting = null, canReadAgain = true, edited = false, onReadAgain, onReadEdited, madeWith = null, lineOwn = null, staleHref = null, baseline = undefined, madeOwn = false, refreshBaseline, baselineError = null, onRetryBaseline, character = null, keepForCharacter, error = null, note = null, autoplay, onAutoplay, }: { /** What is read, in the controls' names: "" (the post), "line 2", "the thread", "the card". */ what?: string; busy?: boolean; /** Said in place while the read waits (render mode holds the machine). */ waiting?: string | null; canReadAgain?: boolean; /** The words differ from what was last saved: Read edited text is offered. */ edited?: boolean; onReadAgain: (tuning: Tuning | null) => void; /** Absent: no edited text here (a thread read). */ onReadEdited?: (tuning: Tuning | null) => void; /** How the line was last made: the Tune numbers start from it (with no `baseline`, S3's rule). */ madeWith?: Tuning | null; /** * What a plain press reads it with now (lane character-tuning): the Tune starts there, and a press sends only what * differs. null: not known yet -- the presses wait for it (a press before would ask the last read's numbers as the * line's own); absent: S3's rule (the last read's numbers). */ baseline?: TuneBaseline | null; /** Its last read was the line's own (known before the baseline is: an untouched press while it is read). */ madeOwn?: boolean; /** * The values its last read's LINE owned (lib/report/tuneAsk.mjs lineOwnOf: the take's `tuningOwn`, else an older * take's every value when it asked true) -- a plain press passes back only these; the rest is resolved now. */ lineOwn?: Tuning | null; /** The Reads view at this character's stale reads (lane reads-find): linked beside a Keep that leaves reads stale. */ staleHref?: string | null; /** The baseline as it is NOW: a press asking a sampler value of its own checks it first (review 3 #1). */ refreshBaseline?: () => Promise; /** Why the baseline could not be read, and a retry: said in place. */ baselineError?: string | null; onRetryBaseline?: () => void; /** The character this line is read by, when known: S2 keeps a tuning for it. */ character?: { id: string; name: string; layer?: string } | null; keepForCharacter?: KeepForCharacter; error?: string | null; /** What the last press came to, said in place ("take 4 made, not picked", "nothing made -- …"). */ note?: string | null; /** Whether a new read plays as it lands (the caller's useAutoPlay: it plays it). */ autoplay: boolean; onAutoplay: (on: boolean) => void; }) { // The numbers a plain press would read with now: the line's own last numbers, else its character's, else the // defaults; the takes the line owned, else the character's, else the settings' (lib/report/tuneAsk.mjs). // "Use 's" (review 3 #3): the line back to its character -- the baseline as if its last read were the // character's, until a new read lands. const [fromCharacter, setFromCharacter] = useState(false); // The takes the line owns ride on the baseline (a press sends them back; a takes it did not own is resolved now). const own = fromCharacter ? null : lineOwn; const eff: TuneBaseline | null | undefined = baseline && fromCharacter ? (characterTuneOf(madeWith, baseline).baseline as TuneBaseline) : baseline ? { ...baseline, ownTakes: typeof own?.takes === "number" ? own.takes : null } : baseline; const start = (): Record => tuneStartOf({ madeWith, baseline: eff, own }) as Record; const [draft, setDraft] = useState>(start); const [kept, setKept] = useState(null); const [keeping, setKeeping] = useState(false); const keepingRef = useRef(false); // The takes field typed by the operator (a Keep pins takes only then: the draft's are the last read's recorded). const [takesTyped, setTakesTyped] = useState(false); // A field edited: the draft is the operator's -- a baseline read again does not replace it (it is said instead). const [dirty, setDirty] = useState(false); const [notice, setNotice] = useState(null); const pressing = useRef(false); useEffect(() => setFromCharacter(false), [JSON.stringify(madeWith)]); useEffect(() => { if (dirty) return; setDraft(start()); setTakesTyped(false); // eslint-disable-next-line react-hooks/exhaustive-deps }, [JSON.stringify(madeWith), JSON.stringify(eff), JSON.stringify(own)]); const edit = (next: Record) => { setDraft(next); setDirty(true); setNotice(null); }; /** * What a press asks as the line's own: with no character, S3's rule (what differs from the defaults); with one, * what differs from the character's tuning -- all of the sampler when the last read was the line's own -- and the * takes when given (S3's rule). */ const ask = (): Tuning | null => (eff?.character ? (tuneAskOf(draft, eff) as Tuning | null) : tuningAsked(draft)); // The baseline is not known (being read, or its read failed): an untouched press asks nothing of its own; an edited // one waits for it (review 3 #2). const loading = baseline === null; const waits = loading && dirty; const words = (b: TuneBaseline | null | undefined) => (!b ? "unknown" : b.madeOwn ? "this line's own" : b.character ? `${b.character.name}: ${NAMED[ttsTuningNameOf(b.character.tuning ?? {})] ?? "custom"}` : "defaults"); /** * A PRESS (review 3 #1): with the baseline unknown, the untouched ask; else the ask -- and one that names a sampler * value of its own is sent only if the baseline is still the one the draft was made against (read again first). If * it changed under the draft, nothing is sent: the new baseline is said, and the next press reads what is shown. */ const press = async (send: (t: Tuning | null) => void) => { if (pressing.current) return; if (loading) { const u = unknownBaselineAskOf(draft, { madeOwn, dirty }); if (!u.waits) { send(u.ask as Tuning | null); setDirty(false); } return; } const a = ask(); if (baseline && refreshBaseline && asksSampler(a)) { pressing.current = true; const fresh = await refreshBaseline().catch(() => null); pressing.current = false; if (fresh && !sameBaseline({ ...fresh, madeOwn: baseline.madeOwn }, baseline)) { setNotice(`it starts from ${words({ ...fresh, madeOwn: false })} now (it changed): press again to read with the numbers shown`); return; } } setNotice(null); setDirty(false); send(a); }; /** What a Keep keeps: the sampler as it stands, top k and min p when not their defaults, the takes only when typed. */ const keepAsk = (): Tuning => keepAskOf(draft, { takesTyped }) as Tuning; const baseWords = !eff ? null : words(eff); const btn = cn(buttonVariants({ variant: "outline", size: "sm" })); const bad = TTS_TUNING_FIELDS.some((k: string) => { const r = (TTS_TUNING_RANGES as Record)[k]; const v = Number(draft[k]); // Empty is only `takes`'s (the settings' own); any other empty or out-of-range field holds every read back. if (draft[k] === "") return k !== "takes"; return !Number.isFinite(v) || v < r.min || v > r.max || (r.integer && !Number.isInteger(v)); }); return (
{onReadEdited && ( )}
Tune ▾
this line only {baseWords && ( from {baseWords} )} {TTS_TUNING_FIELDS.map((k: string) => { const r = (TTS_TUNING_RANGES as Record)[k]; return ( ); })}
{baseline?.character && baseline.madeOwn && !fromCharacter && ( )} {keepForCharacter && character && ( )}
{kept && {kept}} {kept && staleHref && / made with other settings/.test(kept) && ( Re-read them )}
{busy && {waiting ?? "reading…"}} {notice && {notice}} {baselineError && ( the character's tuning could not be read ({baselineError}){waits ? ": an edited press waits for it" : ""}{" "} {onRetryBaseline && ( )} )} {!busy && note && {note}} {error && {error}}
); }