Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit cc952eb3e7237a8c5ee37cae414d6010a5958454
parent f3bd7644a8834e85710541ae6653488621a20b4d
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Tue, 17 Nov 2026 11:04:12 -0500

umtool review 1 (must 2; shoulds 4, 5, 7, 9; nits): a Read again that makes nothing says so, one press one read

- Finding 2: postThreadRead.mjs upToDate compares each piece's reading and tuning (never through the voices' set);
  a reading asked for a piece read from a take, a piece the read does not have, or a read with nothing synthesized
  is refused in a sentence; --events prints one result line (the take made, or none and why) and the bench's jobs
  read it -- only the take the job made is named, badged and played.
- Finding 4: one press at a time in the component (a synchronous flag) and on the server (the post's marker created
  exclusively BEFORE the editor is asked; a failed ask removes it and its .ask.json).
- Finding 5: a lost job (404, no state) fails, the bench out of reach five times running fails, on every mount.
- Finding 7: a line redacted drops its said-as (the bench and line.<n>.redact=on, said in the answer).
- Finding 9: one autoplay store for every mount.
- Nits: --no-pick says "not picked"; --tuned refuses an unknown role, --for/--tuned/the route take linked:<one
  digit>; Tune's takes is the settings' own unless given, an out-of-range field holds every read back; a failed
  read leaves no .ask.json; the thread panel's poll stops on unmount and a busy press keeps the running state; the
  narration view reads the readings once; tuneSig keys takes 3 as an untuned part's; spokenSaysHiddenErrors' choice
  said in a comment.

Co-Authored-By: Claude <noreply@anthropic.com>

Diffstat:
Mumtool/app/api/report/post-narration/route.ts | 44++++++++++++++++++++++++++++++++------------
Mumtool/components/projects/NarrationReview.tsx | 14+++++++++++---
Mumtool/components/projects/PostNarrationPanel.tsx | 28+++++++++++++++++++++++-----
Mumtool/components/projects/PostScreensPanel.tsx | 6+++++-
Mumtool/components/projects/PostThreadPanel.tsx | 63++++++++++++++++++++++++++++++++++++++++-----------------------
Mumtool/components/projects/ScreenLineVoice.tsx | 49+++++++++++++++++++++++++++++++++----------------
Mumtool/components/projects/read/ReadAgain.tsx | 46+++++++++++++++++++++++++++++++++-------------
Mumtool/lib/report/cardNarrationCli.mjs | 18++++++++++++------
Mumtool/lib/report/narration-review.mjs | 6++++--
Mumtool/lib/report/postNarrationCli.mjs | 8++++++--
Mumtool/lib/report/postScreensCli.mjs | 19+++++++++++++++----
Mumtool/lib/report/postThreadRead.mjs | 51+++++++++++++++++++++++++++++++++++++++++----------
Mumtool/lib/report/screenSaidAs.test.mjs | 8++++++++
Mumtool/lib/report/threadTuned.test.mjs | 4++++
Mumtool/report-to-video/post-thread.mjs | 2++
15 files changed, 269 insertions(+), 97 deletions(-)

diff --git a/umtool/app/api/report/post-narration/route.ts b/umtool/app/api/report/post-narration/route.ts @@ -168,7 +168,11 @@ export async function GET(request: Request) { const waiting = !st.done ? renderWaitSentence() : null; if (!st.done) return Response.json({ state: "running", status: st.status, ...(waiting ? { waiting } : {}) }, { headers: noStore }); await rm(pendingFileOf(r.project.dir, e), { force: true }); - if (st.status !== "done") return Response.json({ state: "failed", status: st.status, error: st.tail.slice(-3).join(" / ") }, { headers: noStore }); + if (st.status !== "done") { + // A read that failed leaves nothing behind (its .ask.json would count as a take number). + await rm(`${path.join(r.project.dir, ...rel.split("/"))}.ask.json`, { force: true }); + return Response.json({ state: "failed", status: st.status, error: st.tail.slice(-3).join(" / ") }, { headers: noStore }); + } const had = ((e.narration?.takes ?? []) as Array<{ file?: string }>).some((t) => t.file === rel); if (!had) { const abs = path.join(r.project.dir, ...rel.split("/")); @@ -317,7 +321,8 @@ async function postHere(request: Request) { } const withScreens = Array.isArray(e.screens) && (e.screens as unknown[]).length > 0; let argv: string[]; - if (body.op === "screen-read" || withScreens) argv = ["posts", "screen", r.project.id, id, "read", ...again, "--json"]; + // --events: one result line (the job's `result`, screenJobView) -- the take this job MADE, or none and why. + if (body.op === "screen-read" || withScreens) argv = ["posts", "screen", r.project.id, id, "read", ...again, "--events"]; else { // No screens: the thread read asked as the playing one was (castProject.mjs threadArgvOf), every piece anew. const t = pickedTake(e) as { read?: Record<string, unknown> } | null; @@ -326,10 +331,10 @@ async function postHere(request: Request) { // Its pieces' own readings (`--tuned`) give way to the new one: every piece is read anew. const asked = (threadArgvOf as (r: unknown, o: { takes: unknown }) => string[])(t.read, { takes: e.narration?.takes ?? [] }); const kept = asked.filter((x, i) => x !== "--tuned" && asked[i - 1] !== "--tuned"); - argv = ["posts", "narrate", r.project.id, id, "--take", "--thread", ...kept, ...again, "--json"]; + argv = ["posts", "narrate", r.project.id, id, "--take", "--thread", ...kept, ...again, "--events"]; } const label = body.op === "thread-read" ? `${id}: its thread read again` : body.for ? `${id}: ${String(body.for)} read again` : `${id}: its read made with its screens`; - const j = startUmtoolJob(screenJobKinds(r.project.id, id)[1], [{ label, argv: [process.execPath, cliPath(), ...argv], cwd: path.join(/* turbopackIgnore: true */ UMTOOL_DIR, ".."), env: {}, timeoutMs: 45 * 60 * 1000 }], { project: r.project.id }); + const j = startUmtoolJob(screenJobKinds(r.project.id, id)[1], [{ label, argv: [process.execPath, cliPath(), ...argv], cwd: path.join(/* turbopackIgnore: true */ UMTOOL_DIR, ".."), env: {}, ndjson: true, timeoutMs: 45 * 60 * 1000 }], { project: r.project.id }); return Response.json({ ok: true, job: { id: j.id, state: j.state } }, { headers: noStore }); } if (body.op === "undo") { @@ -354,11 +359,19 @@ async function postHere(request: Request) { const reading = body.reading === undefined || body.reading === null ? null : body.reading === "next" ? nextReadingOf(e.narration?.takes, script) : body.reading; const readingError = reading === null ? null : ttsReadingError(reading); if (readingError) return Response.json({ error: readingError }, { status: 400 }); - // ONE READ OF A POST AT A TIME: a second press while one is made is refused, never asked twice. - const pending = await readFile(pendingFileOf(r.project.dir, e), "utf8").then(JSON.parse, () => null) as { jobId?: string } | null; - if (pending?.jobId) { - const st = await jobState(pending.jobId).catch(() => null); - if (st && !st.done) return Response.json({ error: "a read of this post is being made: wait for it", busy: true }, { status: 409 }); + // ONE READ OF A POST AT A TIME: a second press while one is made is refused, never asked twice. The marker is + // TAKEN before the editor is asked (created exclusively: two presses at once cannot both take it; review 1, + // finding 4); a marker whose job ended, or one never given a job within two minutes, is stale and taken over. + const pendingFile = pendingFileOf(r.project.dir, e); + await mkdir(path.dirname(pendingFile), { recursive: true }); + const claim = () => writeFile(pendingFile, JSON.stringify({ starting: true, at: new Date().toISOString() }), { flag: "wx" }).then(() => true, () => false); + if (!(await claim())) { + const pending = (await readFile(pendingFile, "utf8").then(JSON.parse, () => null)) as { jobId?: string; at?: string } | null; + const st = pending?.jobId ? await jobState(pending.jobId).catch(() => null) : null; + const young = !pending?.jobId && Date.now() - Date.parse(String(pending?.at ?? "")) < 120_000; + if ((st && !st.done) || young) return Response.json({ error: "a read of this post is being made: wait for it", busy: true }, { status: 409 }); + await rm(pendingFile, { force: true }); + if (!(await claim())) return Response.json({ error: "a read of this post is being made: wait for it", busy: true }, { status: 409 }); } // The voice: the one asked for, the item's own character, the project's characters and voice map, the CAST, the // narrator's -- a single read's rule (readVoice.mjs). @@ -388,8 +401,15 @@ async function postHere(request: Request) { const keepPick = body.keepPick === true; if (speed || keepPick) await writeFile(`${out}.ask.json`, JSON.stringify({ ...(speed ? { speed, speedAsked: body.speed !== undefined && body.speed !== null ? true : (e.narration as { speed?: number } | undefined)?.speed != null ? "item" : "preset" } : {}), ...(keepPick ? { keepPick: true } : {}) })); const tuning = tuned?.ok && Object.keys(tuned.value).length ? tuned.value : null; - const jobId = await startJob("/api/ops/tts", { text: spoken, engine, voice, out, ...(speed ? { speed } : {}), ...(tuning ? { tuning } : {}), ...(reading !== null ? { reading } : {}) }); - await writeFile(pendingFileOf(r.project.dir, e), JSON.stringify({ jobId, file: rel, at: new Date().toISOString() })); + let jobId: string; + try { + jobId = await startJob("/api/ops/tts", { text: spoken, engine, voice, out, ...(speed ? { speed } : {}), ...(tuning ? { tuning } : {}), ...(reading !== null ? { reading } : {}) }); + } catch (err) { + await rm(pendingFile, { force: true }); + await rm(`${out}.ask.json`, { force: true }); + throw err; + } + await writeFile(pendingFile, JSON.stringify({ jobId, file: rel, at: new Date().toISOString() })); // Echoed only for the engine that takes them (Orpheus): Kokoro and eSpeak NG ignore them (the editor's result // says so in its `note`, which the GET below hands on), so the answer never claims a tuning that is not used. const tunes = engine === "orpheus"; @@ -562,7 +582,7 @@ const cliPath = () => path.join(/* turbopackIgnore: true */ UMTOOL_DIR, "bin", " const pendingFileOf = (dir: string, e: Entry) => path.join(dir, ...takesDirOf(postIdOf(e)).split("/"), ".reading.json"); const TUNING_FLAG_OF: Record<string, string> = { temperature: "--temperature", top_p: "--top-p", top_k: "--top-k", min_p: "--min-p", repeat_penalty: "--repeat-penalty", takes: "--chunk-takes" }; -const ROLE_RE = /^(post|quoted|parent:\d|linked:\d{1,2}|screen:[a-z0-9][a-z0-9-]{0,23}:\d{1,2})$/; +const ROLE_RE = /^(post|quoted|parent:\d|linked:\d|screen:[a-z0-9][a-z0-9-]{0,23}:\d{1,2})$/; /** A Read again's words for the CLI (lane line-rerun): `--for`, `--reading`, the tuning flags, `--no-pick`. */ function readAgainArgv(body: Record<string, unknown>): string[] { diff --git a/umtool/components/projects/NarrationReview.tsx b/umtool/components/projects/NarrationReview.tsx @@ -304,11 +304,19 @@ function NarrationCard({ if (!res.ok || !j.job) throw new Error(j.error ?? `HTTP ${res.status}`); setReading({ waiting: j.waiting ?? null }); try { + // A lost job (404, no state) failed; the bench out of reach is asked again, five times running at most + // (review 1, finding 5) -- nothing is played for a reading that did not end done. + let misses = 0; for (;;) { await new Promise((ok) => setTimeout(ok, 600)); - const p = await fetch(`/api/report/build?job=${encodeURIComponent(j.job.id)}`, { cache: "no-store" }); - if (!p.ok) continue; - const st = (await p.json()) as { state: string; error: string | null }; + const p = await fetch(`/api/report/build?job=${encodeURIComponent(j.job.id)}`, { cache: "no-store" }).catch(() => null); + if (!p) { + if ((misses += 1) >= 5) throw new Error("the bench did not answer"); + continue; + } + misses = 0; + const st = (await p.json().catch(() => ({}))) as { state?: string; error?: string | null }; + if (!p.ok || !st.state) throw new Error(st.error ?? `the job is gone (HTTP ${p.status})`); if (st.state === "running") continue; if (st.state !== "done") throw new Error(st.error ?? "the reading was not made"); break; diff --git a/umtool/components/projects/PostNarrationPanel.tsx b/umtool/components/projects/PostNarrationPanel.tsx @@ -249,11 +249,22 @@ export default function PostNarrationPanel({ // ---- READ AGAIN (lane line-rerun): the next reading, unpicked, played as it lands ------------------------------ const [autoplay, setAutoplay] = useAutoPlay(); const [landed, setLanded] = useState<string | null>(null); + // One press at a time, synchronously (review 1, finding 4): a second press before the first's answer is ignored. + const pressing = useRef(false); const readAgain = async (words: string, tuning: Tuning | null) => { const j = await post({ op: "take", script: words, reading: "next", keepPick: true, ...(tuning ? { tuning } : {}), voice: dir.voice || undefined }); if (!j) return; if (j.jobId && j.file) setJob({ id: j.jobId, file: j.file, note: "", script: words, state: "running", again: true }); }; + const press = async (fn: () => Promise<void>) => { + if (pressing.current || job?.state === "running") return; + pressing.current = true; + try { + await fn(); + } finally { + pressing.current = false; + } + }; const readEdited = async (tuning: Tuning | null) => { const saved = await post({ op: "set", patch: { script } }); if (saved) await readAgain(script, tuning); @@ -272,7 +283,13 @@ export default function PostNarrationPanel({ project, id: entry.id, job: job.id, file: job.file, script: job.script, ...(job.note ? { note: job.note } : {}), ...(job.derive ? { derive: String(job.derive.from), op: job.derive.op, ...(job.derive.engine ? { engine: job.derive.engine } : {}), ...(job.derive.voice ? { voice: job.derive.voice } : {}), ...(job.derive.pitch ? { pitch: job.derive.pitch } : {}), ...(typeof job.derive.semitones === "number" ? { semitones: String(job.derive.semitones) } : {}) } : {}), }); - const r = await fetch(`/api/report/post-narration?${q}`, { cache: "no-store" }); + // The bench out of reach: asked again, up to five times running; then failed (review 1, finding 5). + const r = await fetch(`/api/report/post-narration?${q}`, { cache: "no-store" }).catch(() => null); + if (!r) { + const misses = (job.polls ?? 0) + 1; + setJob(misses >= 5 ? { ...job, state: "failed", error: "the bench did not answer" } : { ...job, polls: misses }); + return; + } const j = (await r.json().catch(() => ({}))) as { state?: string; error?: string; entry?: Entry; token?: string; waiting?: string }; if (j.state === "done") { setJob({ ...job, state: "done", waiting: null }); @@ -284,8 +301,9 @@ export default function PostNarrationPanel({ if (j.entry) onEntry(j.entry, j.token ?? null); else window.location.reload(); } else if (j.state === "failed" || !r.ok) setJob({ ...job, state: "failed", error: j.error ?? `HTTP ${r.status}` }); - // Still queued or running on the editor (waiting for a render, it says so): ask again. - else setJob({ ...job, polls: (job.polls ?? 0) + 1, waiting: j.waiting ?? null }); + // Still queued or running on the editor (waiting for a render, it says so): ask again. No state: failed. + else if (j.state !== "running") setJob({ ...job, state: "failed", error: j.error ?? "the job is gone" }); + else setJob({ ...job, polls: 0, waiting: j.waiting ?? null }); }, 1500); return () => clearTimeout(t); // eslint-disable-next-line react-hooks/exhaustive-deps @@ -781,8 +799,8 @@ export default function PostNarrationPanel({ waiting={job?.state === "running" ? job.waiting ?? null : null} canReadAgain={!!(n.script ?? "").trim() && script === (n.script ?? "")} edited={!!script.trim() && script !== (n.script ?? "")} - onReadAgain={(t) => void readAgain(n.script ?? "", t)} - onReadEdited={(t) => void readEdited(t)} + onReadAgain={(t) => void press(() => readAgain(n.script ?? "", t))} + onReadEdited={(t) => void press(() => readEdited(t))} madeWith={madeWith} character={character} keepForCharacter={keepForCharacter} diff --git a/umtool/components/projects/PostScreensPanel.tsx b/umtool/components/projects/PostScreensPanel.tsx @@ -355,7 +355,11 @@ function ScreenEditor({ <input className="w-full" value={l.time ?? ""} onChange={(e) => setLine(n, { time: e.target.value || undefined })} data-post-screen-time={n} /> </td> <td> - <input type="checkbox" checked={!!l.redact} onChange={(e) => setLine(n, { redact: e.target.checked ? true : undefined })} data-post-screen-redact={n} aria-label={`redact line ${n}`} /> + <input type="checkbox" checked={!!l.redact} onChange={(e) => { + setLine(n, { redact: e.target.checked ? true : undefined }); + // A redacted line is never read: its said-as goes with it (review 1, finding 7). + if (e.target.checked) setSaidAs(n, ""); + }} data-post-screen-redact={n} aria-label={`redact line ${n}`} /> <button type="button" className="ink-link ml-1" onClick={() => setScreen((s) => { const { checked: _c, ...rest } = withoutLines(s, [n]) as Screen; void _c; return rest; })} title="remove the line (the read follows it)" data-post-screen-line-remove={n}> × </button> diff --git a/umtool/components/projects/PostThreadPanel.tsx b/umtool/components/projects/PostThreadPanel.tsx @@ -1,6 +1,6 @@ "use client"; -import { useMemo, useRef, useState } from "react"; +import { useEffect, useMemo, useRef, useState } from "react"; import ReadAgain, { playNow, useAutoPlay, type Tuning } from "./read/ReadAgain"; import { THREAD_DEFAULTS, THREAD_LIMITS, THREAD_MODES, partRoles, readPieces, threadKnobs, threadLayout, threadReadErrors } from "umtool-report-to-video/post-thread"; import { followKnobs } from "umtool-report-to-video/read-follow"; @@ -73,32 +73,48 @@ export default function PostThreadPanel({ // it lands -- `posts screen … read` / `posts narrate … --take --thread` as a umtool job (op thread-read). const playing = pickedTake(entry) as { read?: { kind?: string }; parts?: Array<{ reading?: number; tuning?: Tuning }> } | null; const [autoplay, setAutoplay] = useAutoPlay(); - const [again, setAgain] = useState<{ state: string; waiting?: string | null; error?: string | null } | null>(null); + const [again, setAgain] = useState<{ state: string; waiting?: string | null; error?: string | null; said?: string | null } | null>(null); const poll = useRef<ReturnType<typeof setTimeout> | null>(null); + const pressing = useRef(false); + useEffect(() => () => { + if (poll.current) clearTimeout(poll.current); + }, []); const readThreadAgain = async (tuning: Tuning | null) => { - if (!project || again?.state === "running") return; - const res = await fetch("/api/report/post-narration", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, op: "thread-read", id: entry.id, reading: "next", ...(tuning ? { tuning } : {}) }) }); - const j = (await res.json().catch(() => ({}))) as { job?: { id: string }; error?: string }; - if (!res.ok || !j.job) return setAgain({ state: "failed", error: j.error ?? `HTTP ${res.status}` }); - setAgain({ state: "running" }); - const jobId = j.job.id; - const tick = async () => { - const r = await fetch(`/api/report/post-narration?project=${encodeURIComponent(project)}&id=${encodeURIComponent(entry.id)}&screenJob=${encodeURIComponent(jobId)}`, { cache: "no-store" }).catch(() => null); - const v = r ? ((await r.json().catch(() => ({}))) as { state?: string; error?: string | null; waiting?: string; entry?: Entry | null; token?: string | null }) : {}; - if (!v.state || v.state === "running") { - setAgain({ state: "running", waiting: v.waiting ?? null }); - poll.current = setTimeout(tick, 1500); + if (!project || again?.state === "running" || pressing.current) return; + pressing.current = true; + try { + const res = await fetch("/api/report/post-narration", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, op: "thread-read", id: entry.id, reading: "next", ...(tuning ? { tuning } : {}) }) }).catch(() => null); + const j = res ? ((await res.json().catch(() => ({}))) as { job?: { id: string }; error?: string; busy?: boolean }) : { error: "the bench is out of reach" }; + if (!res?.ok || !j.job) { + // Busy: said, the running one's state kept. + if (j.busy) setAgain((a) => (a?.state === "running" ? a : { state: "idle", said: j.error ?? "busy" })); + else setAgain({ state: "failed", error: j.error ?? `HTTP ${res?.status ?? "?"}` }); return; } - setAgain({ state: v.state, error: v.error ?? null }); - if (v.state === "done" && v.entry) { - const takes = ((v.entry.narration as { takes?: Array<{ file?: string }> } | undefined)?.takes ?? []); - const file = takes.at(-1)?.file; - if (file && autoplay) playNow(`/api/report/file?project=${encodeURIComponent(project)}&path=${encodeURIComponent(file)}`); - onEntry?.(v.entry, v.token ?? null); - } - }; - poll.current = setTimeout(tick, 800); + setAgain({ state: "running" }); + const jobId = j.job.id; + let misses = 0; + const tick = async () => { + const r = await fetch(`/api/report/post-narration?project=${encodeURIComponent(project)}&id=${encodeURIComponent(entry.id)}&screenJob=${encodeURIComponent(jobId)}`, { cache: "no-store" }).catch(() => null); + const v = r ? ((await r.json().catch(() => ({}))) as { state?: string; error?: string | null; waiting?: string; entry?: Entry | null; token?: string | null; result?: { take?: { file: string; n: number } | null; why?: string } | null }) : null; + misses = r ? 0 : misses + 1; + // Still running; the bench out of reach (up to five times running) is asked again. A lost job (404, no state) failed. + if ((r && v?.state === "running") || (!r && misses < 5)) { + setAgain({ state: "running", waiting: v?.waiting ?? null }); + poll.current = setTimeout(tick, 1500); + return; + } + if (!r || !v?.state) return setAgain({ state: "failed", error: v?.error ?? `the job is gone${r ? ` (HTTP ${r.status})` : ""}` }); + const made = v.state === "done" ? v.result?.take ?? null : null; + setAgain({ state: v.state === "done" ? "done" : "failed", error: v.error ?? null, said: v.state === "done" ? (made ? `take ${made.n} made, not picked` : `nothing made -- ${v.result?.why ?? "the read already says this"}`) : null }); + // Only the take THIS job made plays (review 1, finding 2). + if (made && autoplay) playNow(`/api/report/file?project=${encodeURIComponent(project)}&path=${encodeURIComponent(made.file)}`); + if (v.entry) onEntry?.(v.entry, v.token ?? null); + }; + poll.current = setTimeout(tick, 800); + } finally { + pressing.current = false; + } }; const startOf = (part: number) => plan.follow?.blocks.find((b) => b.part === part)?.start ?? null; const setOwn = (patch: Thread) => @@ -155,6 +171,7 @@ export default function PostThreadPanel({ onReadAgain={(t) => void readThreadAgain(t)} madeWith={playing.parts?.find((p) => p.tuning)?.tuning ?? null} error={again?.state === "failed" ? again.error ?? "failed" : null} + note={again?.said ?? null} autoplay={autoplay} onAutoplay={setAutoplay} /> diff --git a/umtool/components/projects/ScreenLineVoice.tsx b/umtool/components/projects/ScreenLineVoice.tsx @@ -31,6 +31,9 @@ export function useScreenVoice({ project, id, onEntry, unsaved }: { project: str const [status, setStatus] = useState<string | null>(null); const [prompts, setPrompts] = useState<Record<string, string>>({}); const poll = useRef<ReturnType<typeof setTimeout> | null>(null); + const misses = useRef(0); + // One press at a time, synchronously (review 1, finding 4): a second press before the first's answer is ignored. + const pressing = useRef(false); useEffect(() => () => { if (poll.current) clearTimeout(poll.current); }, []); @@ -48,8 +51,11 @@ export function useScreenVoice({ project, id, onEntry, unsaved }: { project: str setJob(j); const tick = async () => { const r = await fetch(`/api/report/post-narration?project=${encodeURIComponent(project)}&id=${encodeURIComponent(id)}&screenJob=${encodeURIComponent(j.id)}`, { cache: "no-store" }).catch(() => null); - const v = r ? ((await r.json().catch(() => ({}))) as { state?: string; message?: string; error?: string; waiting?: string; entry?: VoiceEntry | null; token?: string | null; result?: { takes?: Array<{ n: number; step: string }>; notes?: string[] } | null }) : {}; - const state = v.state ?? (r ? "failed" : "running"); + const v = r ? ((await r.json().catch(() => ({}))) as { state?: string; message?: string; error?: string; waiting?: string; entry?: VoiceEntry | null; token?: string | null; result?: { takes?: Array<{ n: number; step: string }>; notes?: string[]; upToDate?: boolean; why?: string; take?: { file: string; n: number; parts?: Array<{ role: string | null; file: string | null }> } | null } | null }) : {}; + // A lost job (404, an answer with no state) has failed; the editor out of reach five times running too. + misses.current = r ? 0 : misses.current + 1; + const state = v.state ?? (r ? "failed" : misses.current >= 5 ? "failed" : "running"); + if (!v.state && r) v.error ??= `the job is gone (HTTP ${r.status})`; setJob({ ...j, state, message: v.message ?? null, error: v.error ?? null, waiting: v.waiting ?? null }); if (state === "running") { poll.current = setTimeout(tick, 1500); @@ -68,13 +74,17 @@ export function useScreenVoice({ project, id, onEntry, unsaved }: { project: str const made = v.result?.takes ?? []; setStatus(`${j.role}: ${made.map((x) => `take ${x.n} ${x.step}`).join(", ")} -- none picked; choose one for the line, Save, then make the read${(v.result?.notes ?? []).length ? ` (${(v.result?.notes ?? []).join("; ")})` : ""}`); } else if (j.what === "again" && j.role) { - // A LINE READ AGAIN (lane line-rerun): a new read, unpicked; its line's part plays as it lands. - const takes = ((v.entry?.narration as { takes?: TakeLike[] } | undefined)?.takes ?? []) as TakeLike[]; - const part = takes.at(-1)?.parts?.find((p) => p.role === j.role && p.file); - setLanded({ role: j.role, take: takes.length - 1 }); - if (part?.file && autoplayNow.current) playNow(fileUrl(project, part.file)); - setStatus(`${j.role}: read again -- take ${takes.length}, not picked; Pick makes it the one`); - } else setStatus("the read is made (picked)"); + // A LINE READ AGAIN (lane line-rerun): the take THIS JOB made (its result), unpicked; its line's part plays + // as it lands. None made: said, and nothing plays (review 1, finding 2). + const made = v.result?.take ?? null; + if (!made) setStatus(`${j.role}: nothing made -- ${v.result?.why ?? "the read already says this"}`); + else { + const part = made.parts?.find((p) => p.role === j.role && p.file); + setLanded({ role: j.role, take: made.n - 1 }); + if (part?.file && autoplayNow.current) playNow(fileUrl(project, part.file)); + setStatus(`${j.role}: read again -- take ${made.n}, not picked; Pick makes it the one`); + } + } else setStatus(v.result?.take ? `the read is made: take ${v.result.take.n} (picked)` : `nothing made -- ${v.result?.why ?? "the read already says this"}`); if (kept) setStatus((x) => `${x ?? ""} -- your unsaved edits are kept: Save, then reload the bench to see it`); void loadPrompts(); } @@ -130,15 +140,22 @@ export function useScreenVoice({ project, id, onEntry, unsaved }: { project: str autoplayNow.current = autoplay; const [landed, setLanded] = useState<{ role: string; take: number } | null>(null); const readLine = async (role: string, tuning: Tuning | null) => { - if (job?.state === "running") return; + if (job?.state === "running" || pressing.current) return; + pressing.current = true; setStatus(null); - const r = await fetch("/api/report/post-narration", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, op: "screen-read", id, for: role, reading: "next", keepPick: true, ...(tuning ? { tuning } : {}) }) }); - const j = (await r.json().catch(() => ({}))) as { job?: { id: string; state: string }; error?: string }; - if (!r.ok || !j.job) { - setJob({ id: "", what: "again", role, state: "failed", error: j.error ?? `HTTP ${r.status}` }); - return; + try { + const r = await fetch("/api/report/post-narration", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, op: "screen-read", id, for: role, reading: "next", keepPick: true, ...(tuning ? { tuning } : {}) }) }).catch(() => null); + const j = r ? ((await r.json().catch(() => ({}))) as { job?: { id: string; state: string }; error?: string; busy?: boolean }) : { error: "the bench is out of reach" }; + if (!r?.ok || !j.job) { + // Busy (another job runs): said, without taking the running one's place. + if (j.busy) setStatus(j.error ?? "busy"); + else setJob({ id: "", what: "again", role, state: "failed", error: j.error ?? `HTTP ${r?.status ?? "?"}` }); + return; + } + follow({ id: j.job.id, what: "again", role, state: j.job.state }); + } finally { + pressing.current = false; } - follow({ id: j.job.id, what: "again", role, state: j.job.state }); }; const pickTake = async (index: number) => { const r = await fetch("/api/report/post-narration", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, op: "set", id, patch: { pick: index } }) }); diff --git a/umtool/components/projects/read/ReadAgain.tsx b/umtool/components/projects/read/ReadAgain.tsx @@ -28,15 +28,29 @@ export type KeepForCharacter = (tuning: Tuning) => Promise<string | null>; const AUTOPLAY_KEY = "umtool.reads.autoplay"; const LABEL: Record<string, string> = { temperature: "temperature", top_p: "top p", top_k: "top k", min_p: "min p", repeat_penalty: "repeat penalty", takes: "takes" }; -const DEFAULTS: Record<string, number> = { ...ORPHEUS_TUNING_DEFAULTS, takes: ORPHEUS_DEFAULT_TAKES }; +// `takes` has no default here: empty is the editor's settings' own (tts.orpheus.takes), never a guessed 3. +const DEFAULTS: Record<string, number> = { ...ORPHEUS_TUNING_DEFAULTS }; +void ORPHEUS_DEFAULT_TAKES; -/** Whether a new read plays as it lands: on unless this browser said otherwise. */ +// 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(() => setOn(ls.get(AUTOPLAY_KEY) !== "off"), []); + useEffect(() => { + if (autoplayNow === null) autoplayNow = ls.get(AUTOPLAY_KEY) !== "off"; + setOn(autoplayNow); + autoplayListeners.add(setOn); + return () => { + autoplayListeners.delete(setOn); + }; + }, []); return [on, (v: boolean) => { - setOn(v); + autoplayNow = v; ls.set(AUTOPLAY_KEY, v ? "on" : "off"); + for (const f of autoplayListeners) f(v); }]; } @@ -54,19 +68,20 @@ export function tuningAsked(draft: Record<string, string>): Tuning | null { const out: Tuning = {}; for (const k of TTS_TUNING_FIELDS as readonly (keyof Tuning)[]) { const v = Number(draft[k]); - if (draft[k] !== "" && Number.isFinite(v) && v !== DEFAULTS[k]) out[k] = v; + // `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]) => v !== DEFAULTS[k]).map(([k, v]) => `${LABEL[k] ?? k} ${v}`)]; + 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, character = null, keepForCharacter, error = null, autoplay, onAutoplay, + what = "", busy = false, waiting = null, canReadAgain = true, edited = false, onReadAgain, onReadEdited, madeWith = null, 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; @@ -85,11 +100,13 @@ export default function ReadAgain({ 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; }) { - const start = (): Record<string, string> => Object.fromEntries(TTS_TUNING_FIELDS.map((k: string) => [k, String(madeWith?.[k as keyof Tuning] ?? DEFAULTS[k])])); + const start = (): Record<string, string> => Object.fromEntries(TTS_TUNING_FIELDS.map((k: string) => [k, madeWith?.[k as keyof Tuning] !== undefined ? String(madeWith[k as keyof Tuning]) : k in DEFAULTS ? String(DEFAULTS[k]) : ""])); const [draft, setDraft] = useState<Record<string, string>>(start); const [kept, setKept] = useState<string | null>(null); // eslint-disable-next-line react-hooks/exhaustive-deps @@ -98,15 +115,17 @@ export default function ReadAgain({ const bad = TTS_TUNING_FIELDS.some((k: string) => { const r = (TTS_TUNING_RANGES as Record<string, { min: number; max: number; integer: boolean }>)[k]; const v = Number(draft[k]); - return draft[k] === "" || !Number.isFinite(v) || v < r.min || v > r.max || (r.integer && !Number.isInteger(v)); + // 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 ( <div className="flex flex-wrap items-center gap-1.5" data-read-again={what || "post"}> - <button type="button" className={btn} disabled={busy || !canReadAgain} onClick={() => onReadAgain(tuningAsked(draft))} aria-label={what ? `Read ${what} again` : "Read again"} data-read-again-button=""> + <button type="button" className={btn} disabled={busy || bad || !canReadAgain} onClick={() => onReadAgain(tuningAsked(draft))} aria-label={what ? `Read ${what} again` : "Read again"} data-read-again-button=""> Read again </button> {onReadEdited && ( - <button type="button" className={btn} disabled={busy || !edited} onClick={() => onReadEdited(tuningAsked(draft))} aria-label={what ? `Read ${what} as edited` : "Read the edited text"} data-read-edited-button=""> + <button type="button" className={btn} disabled={busy || bad || !edited} onClick={() => onReadEdited(tuningAsked(draft))} aria-label={what ? `Read ${what} as edited` : "Read the edited text"} data-read-edited-button=""> Read edited text </button> )} @@ -121,7 +140,7 @@ export default function ReadAgain({ return ( <label key={k} className="flex items-center justify-between gap-2"> <span>{LABEL[k]}</span> - <input type="number" min={r.min} max={r.max} step={r.integer ? 1 : 0.01} value={draft[k]} onChange={(e) => setDraft({ ...draft, [k]: e.target.value })} className="w-20 rounded border border-seam bg-ground px-1 py-0.5" aria-label={`${LABEL[k]}, this line only`} data-read-tune-field={k} /> + <input type="number" min={r.min} max={r.max} step={r.integer ? 1 : 0.01} value={draft[k]} placeholder={k === "takes" ? "settings" : undefined} onChange={(e) => setDraft({ ...draft, [k]: e.target.value })} className="w-20 rounded border border-seam bg-ground px-1 py-0.5" aria-label={`${LABEL[k]}, this line only`} data-read-tune-field={k} /> </label> ); })} @@ -129,7 +148,7 @@ export default function ReadAgain({ <button type="button" className={btn} disabled={busy || bad || !canReadAgain} onClick={() => onReadAgain(tuningAsked(draft))} aria-label={what ? `Read ${what} again with this tuning` : "Read again with this tuning"} data-read-tune-read=""> Read with these </button> - <button type="button" className={btn} onClick={() => setDraft(Object.fromEntries(TTS_TUNING_FIELDS.map((k: string) => [k, String(DEFAULTS[k])])))} aria-label="Tuning back to the defaults" data-read-tune-defaults=""> + <button type="button" className={btn} onClick={() => setDraft(Object.fromEntries(TTS_TUNING_FIELDS.map((k: string) => [k, k in DEFAULTS ? String(DEFAULTS[k]) : ""])))} aria-label="Tuning back to the defaults" data-read-tune-defaults=""> Defaults </button> {keepForCharacter && character && ( @@ -146,6 +165,7 @@ export default function ReadAgain({ play when ready </label> {busy && <span className="text-text-2" data-read-busy="">{waiting ?? "reading…"}</span>} + {!busy && note && <span className="text-text-2" data-read-note="">{note}</span>} {error && <span className="text-[var(--color-blocking,#c33)]" data-read-error="">{error}</span>} </div> ); diff --git a/umtool/lib/report/cardNarrationCli.mjs b/umtool/lib/report/cardNarrationCli.mjs @@ -44,19 +44,25 @@ export const CARD_NARRATION_USAGE = [ const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); const spacing = (t) => String(t ?? "").replace(/\s+/g, " ").trim(); -/** Every reading kept for `cardId` beside the build (its record and its sound there), oldest first. */ -export async function cardReadings(projectDir, cardId) { +/** Every reading kept beside the build (its record and its sound there), by card id, each oldest first -- read once. */ +export async function allCardReadings(projectDir) { const dir = narrationDir(path.join(projectDir, "out")); const names = await readdir(dir).catch(() => []); - const out = []; + const out = new Map(); for (const f of names) { if (!/^[0-9a-f]{64}\.json$/.test(f)) continue; const rec = await readFile(path.join(dir, f), "utf8").then(JSON.parse, () => null); - if (!isObj(rec) || rec.id !== cardId || `${rec.key}.json` !== f) continue; + if (!isObj(rec) || typeof rec.id !== "string" || `${rec.key}.json` !== f) continue; if (!(await stat(narrationWavPath(dir, rec.key)).catch(() => null))?.isFile()) continue; - out.push(rec); + out.set(rec.id, [...(out.get(rec.id) ?? []), rec]); } - return out.sort((a, b) => String(a.createdAt ?? "").localeCompare(String(b.createdAt ?? ""))); + for (const list of out.values()) list.sort((a, b) => String(a.createdAt ?? "").localeCompare(String(b.createdAt ?? ""))); + return out; +} + +/** Every reading kept for `cardId` beside the build, oldest first. */ +export async function cardReadings(projectDir, cardId) { + return (await allCardReadings(projectDir)).get(cardId) ?? []; } /** One past the highest reading `text` was kept at (a record with none: 0), or 0 when it never was. */ diff --git a/umtool/lib/report/narration-review.mjs b/umtool/lib/report/narration-review.mjs @@ -13,7 +13,7 @@ import { stat } from "node:fs/promises"; import { estimatedNarratedCardSeconds, narrationWords } from "umtool-report-to-video/narration"; import { DRAFTS_REVIEW_FILE, readNarrationReview, reviewRows } from "umtool-report-to-video/narration-review"; import { narrationDir, narrationWavPath, readNarrationRecord } from "umtool-report-to-video/narration-store"; -import { cardReadings } from "./cardNarrationCli.mjs"; +import { allCardReadings } from "./cardNarrationCli.mjs"; /** * @param {string} projectDir @@ -24,6 +24,8 @@ export async function narrationReviewView(projectDir, manifest) { const dir = narrationDir(path.join(projectDir, "out")); const timeline = Array.isArray(manifest?.timeline) ? manifest.timeline : []; const rows = []; + // Every card's readings, the store read once for the view (review 1, a nit). + const kept = await allCardReadings(projectDir); for (const r of reviewRows(manifest, review)) { const at = timeline.findIndex((e) => e?.id === r.id); const e = timeline[at] ?? {}; @@ -59,7 +61,7 @@ export async function narrationReviewView(projectDir, manifest) { reading: Number.isInteger(e.narration?.reading) ? e.narration.reading : 0, tuning: e.narration?.tuning ?? null, madeWith: rec?.tuning ?? null, - readings: (await cardReadings(projectDir, r.id)).map((x) => ({ key: x.key, text: x.text, reading: Number.isInteger(x.reading) ? x.reading : 0, tuning: x.askedTuning ?? null, seconds: x.seconds, createdAt: x.createdAt ?? null })), + readings: (kept.get(r.id) ?? []).map((x) => ({ key: x.key, text: x.text, reading: Number.isInteger(x.reading) ? x.reading : 0, tuning: x.askedTuning ?? null, seconds: x.seconds, createdAt: x.createdAt ?? null })), }); } const counts = { approved: 0, rejected: 0, edited: 0, unreviewed: 0 }; diff --git a/umtool/lib/report/postNarrationCli.mjs b/umtool/lib/report/postNarrationCli.mjs @@ -514,6 +514,9 @@ export function tuningFlags(str) { return { tuning: Object.keys(tuning).length ? tuning : null, reading, flags }; } +/** A piece of a read, as a part's role names it (post-narration.mjs's part roles; `media:` is never synthesized). */ +const TUNED_ROLE_RE = /^(post|quoted|parent:\d|linked:\d|screen:[a-z0-9][a-z0-9-]{0,23}:\d{1,2})$/; + /** The fields `--tuned` names: the reading and the tuning's own (llama-server's names). */ const TUNED_FIELDS = new Set(["reading", ...TTS_TUNING_FIELDS]); @@ -525,7 +528,7 @@ const TUNED_FIELDS = new Set(["reading", ...TTS_TUNING_FIELDS]); export function threadTunedOf(tuned, { str, multi }) { const out = {}; const forRole = str("--for"); - if (forRole !== null && !/^(post|quoted|parent:\d|linked:\d{1,2}|screen:[a-z0-9][a-z0-9-]{0,23}:\d{1,2})$/.test(String(forRole))) { + if (forRole !== null && !TUNED_ROLE_RE.test(String(forRole))) { throw new NarrateError(`--for names one piece of the read: post, quoted, parent:<i>, linked:<i> or screen:<id>:<line> (got ${forRole})`); } if (forRole !== null && !tuned) throw new NarrateError("--for goes with --reading and the tuning flags: what that piece is read with"); @@ -533,6 +536,7 @@ export function threadTunedOf(tuned, { str, multi }) { for (const raw of multi("--tuned")) { const m = /^([^=]+)=(.+)$/.exec(String(raw).trim()); if (!m) throw new NarrateError(`--tuned takes <role>=reading:N,temperature:t,… (got ${raw})`); + if (m[1] !== "*" && !TUNED_ROLE_RE.test(m[1])) throw new NarrateError(`--tuned ${m[1]}: not a piece of a read (* or post, quoted, parent:<i>, linked:<i>, screen:<id>:<line>)`); const t = {}; let reading = null; for (const kv of m[2].split(",")) { @@ -832,7 +836,7 @@ export async function narrateCommand(project, words, flags, { json = false, dryR // ITS SCREENS (post-screens.mjs): read after his words unless --no-screens; a line from a take (--line-take). screens: !flags.has("--no-screens"), lineTakes: lineTakesOf(multi("--line-take")), // Its readings and tunings (lane line-rerun): the whole read's, one piece's (--for), each piece's (--tuned). - tuned: threadTunedOf(tuned, { str, multi }), keepPick: flags.has("--no-pick"), + tuned: threadTunedOf(tuned, { str, multi }), keepPick: flags.has("--no-pick"), events: flags.has("--events"), }); } if (str("--post-take") !== null) throw new NarrateError("--post-take is a thread read's (umtool posts narrate <p> <item> --take --thread --post-take <n>)"); diff --git a/umtool/lib/report/postScreensCli.mjs b/umtool/lib/report/postScreensCli.mjs @@ -57,7 +57,8 @@ export const SCREEN_USAGE = [ " set keys: kind= title=|off media= at=<a>,<b>|off unread= ref=|off read=all|none|<n>,… read.<n>=\"excerpt\"|on|off", " line.add=\"who: words\" line.<n>=off line.<n>.who=|off line.<n>.side=left|right|auto line.<n>.text=", " line.<n>.time=|off line.<n>.redact=on|off take.<n>=<take n>|off (the recording read in line n's place)", - " said.<n>=\"…\"|off (what the voice SAYS for line n -- an acronym spelled out, a typo said right; never drawn)", + " said.<n>=\"…\"|off (what the voice SAYS for line n -- an acronym spelled out, a typo said right; never drawn;", + " `off` or empty clears it, so the word \"off\" alone cannot be said: say it as \"Off.\"; line.<n>.redact=on drops it)", " check: the transcription read against the screenshot (by you, now); --undo takes it back. A screen not checked is a", " lint WARNING. An e-mail address, a phone number, an order or reference number in a line is masked whatever you do.", " read: the thread read with the screens (posts narrate <p> <item> --take --thread): his words from the take that plays", @@ -184,7 +185,15 @@ export function applyPairs(screen, pairs, { takeId = null } = {}) { else if (!SCREEN_SIDES.includes(v)) fail(`${key}= takes left, right or auto`); else l.side = v; } else if (f === "redact") { - if (v === "on") l.redact = true; + if (v === "on") { + l.redact = true; + // A redacted line is never read: its "said as" goes with it (review 1, finding 7). + const n = Number(m[1]); + if (isObj(sc.saidAs) && sc.saidAs[String(n)] !== undefined) { + delete sc.saidAs[String(n)]; + if (!Object.keys(sc.saidAs).length) delete sc.saidAs; + } + } else if (v === "off") delete l.redact; else fail(`${key}= takes on or off`); } else if (f === "text") l.text = v; @@ -369,7 +378,9 @@ export async function screenCommand(project, rest, { flags, str: flag, multi, js } }); // Words changed: what was checked is not what is there now. if (JSON.stringify(next.lines) !== JSON.stringify(sc.lines)) delete next.checked; - return write(screens.map((s) => (s.id === sc.id ? next : s)), `set screen ${sc.id}`); + // A line redacted drops its "said as": said in the answer. + const dropped = Object.keys(isObj(sc.saidAs) ? sc.saidAs : {}).filter((k) => !(isObj(next.saidAs) && k in next.saidAs) && next.lines?.[Number(k)]?.redact === true); + return write(screens.map((s) => (s.id === sc.id ? next : s)), `set screen ${sc.id}${dropped.length ? ` (line ${dropped.join(", ")} redacted: its said-as dropped -- a redacted line is never read)` : ""}`); } if (verb === "rm") { const sc = byId(words[0]); @@ -394,7 +405,7 @@ export async function screenCommand(project, rest, { flags, str: flag, multi, js postTake, lineTakes: { ...defaultLineTakes(e), ...chosenLineTakes(e), ...lineTakesOf(multi("--line-take")) }, // Its readings and tunings (lane line-rerun): the flags' (--reading, the tuning flags, --for, --tuned), over the // playing read's -- each piece's kept while it says the same words. - tuned: threadTunedOf(tuningFlags(flag), { str: flag, multi }), inherit: playingTuned(e), keepPick: flags.has("--no-pick"), + tuned: threadTunedOf(tuningFlags(flag), { str: flag, multi }), inherit: playingTuned(e), keepPick: flags.has("--no-pick"), events: flags.has("--events"), }); } if (verb === "record") { diff --git a/umtool/lib/report/postThreadRead.mjs b/umtool/lib/report/postThreadRead.mjs @@ -65,7 +65,7 @@ import { spokenRead, termsFor } from "umtool-report-to-video/post-redact"; import { readSpeedOf, resolvePieceVoice } from "umtool-report-to-video/post-say"; import { SCREEN_LINE_GAP, parseScreenRole, screenWho, screensOf, shapeSpans } from "umtool-report-to-video/post-screens"; import { readManifest } from "../projects/report.mjs"; -import { TTS_TUNING_FIELDS, normalizeTtsTuning } from "yt-dlp-transcript-common/lib/ttsTuning.mjs"; +import { ORPHEUS_DEFAULT_TAKES, TTS_TUNING_FIELDS, normalizeTtsTuning } from "yt-dlp-transcript-common/lib/ttsTuning.mjs"; import { withEditNotes } from "./edit-guard.mjs"; import { manifestToken, updatePostNarration } from "./manifest.mjs"; @@ -137,9 +137,13 @@ export function tuneSig(tune) { return `${r}${t ? `|t${JSON.stringify(t)}` : ""}`; } -/** A tuning with the sampler's defaults left out (takes kept as asked), in the fields' order; null when none is left. */ +/** + * A tuning with Orpheus's defaults left out, in the fields' order; null when none is left. `takes` equal to the code's + * default (3) is left out too (review 1, a nit): `--chunk-takes 3` keys as an untuned part does -- an untuned part's key + * never held the settings' takes either. + */ export function tuningOf(tuning) { - const n = normalizeTtsTuning(tuning); + const n = normalizeTtsTuning(tuning, { takes: ORPHEUS_DEFAULT_TAKES }); const out = Object.fromEntries(TTS_TUNING_FIELDS.filter((k) => n[k] !== undefined).map((k) => [k, n[k]])); return Object.keys(out).length ? out : null; } @@ -511,8 +515,17 @@ export function upToDate(e, plan) { if (JSON.stringify(Object.entries(lines).sort()) !== JSON.stringify(Object.entries(had).sort())) return false; // A take whose parts say their voices: each piece in the same engine and voice, at the same speed. const parts = Array.isArray(t.parts) ? t.parts.filter((p) => typeof p?.voice === "string") : []; - if (!parts.length) return !plan.pieces.some((p) => typeof p.speed === "number"); - return voiceSig(parts, t.engine ?? "orpheus") === voiceSig(plan.pieces, plan.engine); + if (!parts.length) return !plan.pieces.some((p) => typeof p.speed === "number" || p.reading || p.tuning); + if (voiceSig(parts, t.engine ?? "orpheus") !== voiceSig(plan.pieces, plan.engine)) return false; + // EACH PIECE's READING AND TUNING (review 1, finding 2): per piece, never through the voices' set -- two lines of one + // voice at readings 1 and 0 are not the same read as 0 and 1. + for (const pc of plan.pieces) { + if (pc.take) continue; + const mine = parts.filter((p) => p.role === pc.role && !p.take); + if (mine.length && mine.some((p) => tuneSig(p) !== tuneSig(pc))) return false; + if (!mine.length && (pc.reading || pc.tuning)) return false; + } + return true; } const fileThere = async (f) => !!(await stat(f).catch(() => null))?.isFile(); @@ -563,6 +576,17 @@ export async function threadTake(project, e, opts = {}) { const names = names0 !== undefined ? names0 : characterNames(L); const plan = threadReadPlan(manifest, e, { red, map, cast, item, overrides, parents, skip, quoted, linked, readSeen, voice, engine, speed, postTake, screens, names, lineTakes, tuned, inherit }); for (const [r, lt] of Object.entries(lineTakes)) lt.line = plan.pieces.find((pc) => pc.role === r)?.line; + // A READING OR TUNING ASKED FOR A PIECE (review 1, finding 2): of a piece the read has, synthesized -- a piece read + // from a take (a recording, his line from --post-take, a line's chosen or re-attached take) is never "read again". + for (const role of Object.keys(tuned ?? {})) { + if (role === "*") { + if (!plan.pieces.some((pc) => !pc.take)) throw new ThreadReadError(`${e.id}: every piece of this read is a take (a recording): there is nothing synthesized to read again -- record it again`); + continue; + } + const pc = plan.pieces.find((x) => x.role === role); + if (!pc) throw new ThreadReadError(`${e.id}: this read has no piece ${role} (its pieces: ${plan.pieces.map((x) => x.role).join(", ")})`); + if (pc.take) throw new ThreadReadError(`${e.id}: ${role} is read from take ${pc.take.n} (${pc.take.file}), not synthesized -- to read it again, record it again, or choose "synthesized" for it`); + } const parts = readParts(plan); const cacheDir = path.join(project.dir, ...PARTS_CACHE.split("/")); const wavOf = (p) => (p.take ? path.join(project.dir, ...p.file.split("/")) : path.join(cacheDir, `${p.key}.wav`)); @@ -699,18 +723,25 @@ async function guardOf(project, id) { /** `umtool posts narrate <p> <item> --take --thread …` (postNarrationCli.mjs routes it here). */ export async function threadCommand(project, e, o) { - const { json = false, out = (s) => console.log(s) } = o; - const say = (s) => !json && out(s); + const { json = false, events = false, out = (s) => console.log(s) } = o; + const say = (s) => !json && !events && out(s); let r; try { r = await threadTake(project, e, { ...o, signals: true, emit: (_ev, f) => f?.message && say(f.message) }); } catch (err) { - if (json && err instanceof ThreadReadError) { - out(JSON.stringify({ ok: false, id: e.id, error: err.message }, null, 2)); + if ((json || events) && err instanceof ThreadReadError) { + out(events ? JSON.stringify({ ev: "result", ok: false, id: e.id, error: err.message }) : JSON.stringify({ ok: false, id: e.id, error: err.message }, null, 2)); return 1; } throw err; } + // --events (the bench's Read again, review 1 finding 2): ONE line, the take MADE (its file and number) or none, and + // why -- the bench plays and names only the take this job made, never the list's last. + if (events) { + const n = r.take ? (r.result?.narration?.takes ?? []).findIndex((t) => t?.file === r.take.file) + 1 : null; + out(JSON.stringify({ ev: "result", ok: true, id: e.id, upToDate: !!r.upToDate, dryRun: !!r.dryRun, take: r.take ? { file: r.take.file, n, parts: (r.take.parts ?? []).map((p) => ({ role: p.role ?? null, file: p.file ?? null, reading: p.reading ?? 0 })) } : null, picked: r.take ? r.result?.narration?.pick === n - 1 : false, ...(r.upToDate ? { why: "the playing take already reads this, in these voices, at these readings" } : {}) })); + return 0; + } const pieces = r.plan.pieces.map((p) => ({ role: p.role, handle: p.handle, date: p.date, voice: p.voice, engine: p.engine, from: p.from, ...(p.take ? { take: p.take } : {}), ...(p.speed !== undefined ? { speed: p.speed } : {}), ...(p.character ? { character: p.character } : {}), words: p.text.split(/\s+/).filter(Boolean).length, ...(p.lexicon.length ? { lexicon: p.lexicon } : {}) })); const guard = r.take ? await guardOf(project, e.id) : null; // RECORDINGS OF ITS LINES NOBODY CHOSE (screenLine takes): said, never read in -- the operator chooses. @@ -738,7 +769,7 @@ export async function threadCommand(project, e, o) { return 0; } if (r.dryRun) return 0; - out(` ${r.take.file} ${r.take.seconds} s, ${r.fresh} part(s) synthesized${r.jobs.length ? ` (editor jobs ${r.jobs.join(", ")})` : ""}, picked`); + out(` ${r.take.file} ${r.take.seconds} s, ${r.fresh} part(s) synthesized${r.jobs.length ? ` (editor jobs ${r.jobs.join(", ")})` : ""}, ${o.keepPick ? "not picked (--pick to play it)" : "picked"}`); if (r.result.snapshot?.rel && !r.result.snapshot.skipped) out(` undo point: ${r.result.snapshot.rel} (umtool timeline ${project.id} undo)`); if (guard?.errors?.length) out(` the card would REFUSE it:\n${guard.errors.map((x) => ` ${x}`).join("\n")}\n (umtool posts roles ${project.id} ${e.id})`); for (const w of guard?.warnings ?? []) out(` warning: ${w}`); diff --git a/umtool/lib/report/screenSaidAs.test.mjs b/umtool/lib/report/screenSaidAs.test.mjs @@ -83,3 +83,11 @@ test("THE READING PIN with a said-as: a thread item's card draws as before", () e.screens[0].saidAs = { 0: "Are the tolls going up again, yes or no?" }; assert.deepEqual(drawn(e), PINNED_SHAS.thread); }); + +test("A LINE REDACTED drops its said-as (review 1, finding 7): line.<n>.redact=on is never refused for a said-as it had", () => { + const sc = applyPairs({ ...DM, saidAs: { 0: "Did the B R T plan pass?", 1: "Ask the clerk, room four." } }, ["line.1.redact=on"]); + assert.equal(sc.lines[1].redact, true); + assert.deepEqual(sc.saidAs, { 0: "Did the B R T plan pass?" }); + assert.deepEqual(validateScreens(item(sc)), []); + assert.equal("saidAs" in applyPairs({ ...DM, saidAs: { 1: "x" } }, ["line.1.redact=on"]), false); +}); diff --git a/umtool/lib/report/threadTuned.test.mjs b/umtool/lib/report/threadTuned.test.mjs @@ -63,6 +63,10 @@ test("--reading/--for/--tuned as a thread read's tuned map; refused in their own const c = flags({ "multi:--tuned": ["post=reading:3,top_p:0.9", "screen:s1:0=reading:1"] }); assert.deepEqual(threadTunedOf(null, c), { post: { reading: 3, tuning: { top_p: 0.9 } }, "screen:s1:0": { reading: 1 } }); assert.throws(() => threadTunedOf(null, flags({ "multi:--tuned": ["post=pitch:3"] })), /not one of reading, temperature/); + assert.throws(() => threadTunedOf(null, flags({ "multi:--tuned": ["bogus=reading:2"] })), /not a piece of a read/); + const ld = flags({ "--for": "linked:12", "--reading": "1" }); + assert.throws(() => threadTunedOf(tuningFlags(ld.str), ld), /--for names one piece/, "a part's role names one digit for linked"); + assert.equal(tuneSig({ tuning: { takes: 3, temperature: 0.7 } }), '|t{"temperature":0.7}', "takes 3 keys as an untuned part's"); assert.throws(() => threadTunedOf(null, flags({ "--for": "post" })), /--for goes with --reading/); const d = flags({ "--for": "nowhere", "--reading": "1" }); assert.throws(() => threadTunedOf(tuningFlags(d.str), d), /--for names one piece/); diff --git a/umtool/report-to-video/post-thread.mjs b/umtool/report-to-video/post-thread.mjs @@ -667,6 +667,8 @@ export function readSaysHiddenErrors(e) { * read's words -- the script saved for reading, a screen line's "said as" -- so a spoken edit the build would refuse is * refused when it is WRITTEN, and never reaches a take (whose refusal would drop the read from the preview). */ +// It judges the text as WRITTEN, not as spokenRead would say it (the lexicon, the redaction): refusing more is the safe +// side -- a word the lexicon would say another way is still refused if written as a masked shape (review 1: no change). export function spokenSaysHiddenErrors(e, text, where = "the read") { if (!str(text).trim() || !screensOfEntry(e).length) return []; const probe = { ...e, narration: { pick: 0, takes: [{ file: "narration/probe.wav", seconds: 1, script: str(text) }] } };