Archilyzer · Source

archilyzer

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

commit 33a7ba0a2aa440818a77cdfcdb2e2c0490962cda
parent d97a834c54d281f0885a2da03496b0fe7c5bf145
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Wed, 11 Nov 2026 21:50:49 -0500

umtool: review fixes for record -> filter -> preview -- a filtered Keep is refused unless the preview was made from the session's recording as it is now, a part saved drops the preview (server and page), and Keep waits for the recording to be read; Cancel stops the editor's job too (and says when it was not known yet); Keep, Again, a part's upload and dropping the preview answer 409 while the post's Filter runs; a held key is one press; the route clears the session only for a preview made from it; the read above the record button is the character's synthetic preset voice; an upload that is text (a playlist) is refused and ffmpeg opens local files only

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

Diffstat:
Meditor/CHANGELOG.md | 2+-
Mumtool/app/api/report/post-narration/record/route.ts | 53++++++++++++++++++++++++++++++++++++++---------------
Mumtool/components/projects/RecordFilter.tsx | 2++
Mumtool/components/projects/RecordSession.tsx | 39+++++++++++++++++++++++++++++----------
Mumtool/docs/knobs.md | 23++++++++++++++++-------
Mumtool/e2e/record-filter.spec.ts | 29+++++++++++++++++++++++++++++
Mumtool/lib/report/postNarrationCli.mjs | 7++++++-
Mumtool/lib/report/postRecord.mjs | 32+++++++++++++++++++++++++++++---
Mumtool/lib/report/postThreadRead.mjs | 1+
Mumtool/lib/report/recordPreview.mjs | 11+++++++----
Mumtool/lib/report/recordPreview.test.mjs | 55++++++++++++++++++++++++++++++++++++++++++++++++++++++-
11 files changed, 212 insertions(+), 42 deletions(-)

diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,7 +1,7 @@ # Changelog ## [Unreleased] -- **umtool: record, filter and listen before anything is kept.** On the record page a recording became a take the moment its last part was in, and hearing it in the character's voice meant importing it on the Voices page and waiting for three takes (operator, 11 Nov: "run the filter and preview it seamlessly in the record UI"). With **Filter before keeping** (on by itself for a post whose character has a stock voice to convert to) the post now waits. **Filter** (`f`) runs the character's recorded preset as one job: clean, cut, convert. Its result is a preview in `narration/.record-preview/<postId>.<label>/`, not a take. The page shows the three stages and the time it has run, and a wait at the editor's queue or the machine's heavy slot reads "waiting for memory … the gate working, not an error". **▶ Raw** and **▶ Filtered** play at one loudness. **Keep** (`Enter`) makes the recorded, cleaned and converted takes from the preview's files, converts nothing again, picks the last and opens the next post not recorded; **Again** (`Backspace` or `r`) drops the preview and records the part again. Each part's waveform carries two **cut marks** at the auto trim's answer; drag one, or press the arrow keys on it, to cut a keyboard click off the start or the end. **Pitch** and **semitones** (a Seed-VC convert) default to the preset's and re-run the convert alone; **Save to character** writes them back, and a post read as the narrator or as nobody offers **Keep in this video only**. Above the record button: the character, its direction line and **▶ <voice> reads it**, which plays the read kept from before when there is one and asks the editor only when pressed. Opened over http from the LAN the page says the microphone is off (a browser opens it only on localhost or https); **Use a sound file…** takes a recording made elsewhere, and Filter, the preview and Keep work there. From a terminal: `umtool posts narrate <p> <item> --recording <file> --preview [--out <file>] [--trim-span 0.4-3.1]` prints the paths and makes no take, `--keep-preview` keeps it, `--discard-preview` drops it. A "start on speech" trigger was not built: it would lose the start of the first word, and the auto trim already cuts the silence before it. ([knobs.md](../umtool/docs/knobs.md#record-filter-preview-on-the-record-page)) +- **umtool: record, filter and listen before anything is kept.** On the record page a recording became a take the moment its last part was in, and hearing it in the character's voice meant importing it on the Voices page and waiting for three takes (operator, 11 Nov: "run the filter and preview it seamlessly in the record UI"). With **Filter before keeping** (on by itself for a post whose character has a stock voice to convert to) the post now waits. **Filter** (`f`) runs the character's recorded preset as one job: clean, cut, convert. Its result is a preview in `narration/.record-preview/<postId>.<label>/`, not a take. The page shows the three stages and the time it has run, and a wait at the editor's queue or the machine's heavy slot reads "waiting for memory … the gate working, not an error". **▶ Raw** and **▶ Filtered** play at one loudness. **Keep** (`Enter`) makes the recorded, cleaned and converted takes from the preview's files, converts nothing again, picks the last and opens the next post not recorded; **Again** (`Backspace` or `r`) drops the preview and records the part again. Each part's waveform carries two **cut marks** at the auto trim's answer; drag one, or press the arrow keys on it, to cut a keyboard click off the start or the end. **Pitch** and **semitones** (a Seed-VC convert) default to the preset's and re-run the convert alone; **Save to character** writes them back, and a post read as the narrator or as nobody offers **Keep in this video only**. Above the record button: the character, its direction line and **▶ <voice> reads it** (its synthetic preset's voice), which plays the read kept from before when there is one and asks the editor only when pressed. Cancel stops the editor's job too. Opened over http from the LAN the page says the microphone is off (a browser opens it only on localhost or https); **Use a sound file…** takes a recording made elsewhere, and Filter, the preview and Keep work there. From a terminal: `umtool posts narrate <p> <item> --recording <file> --preview [--out <file>] [--trim-span 0.4-3.1]` prints the paths and makes no take, `--keep-preview` keeps it, `--discard-preview` drops it. A "start on speech" trigger was not built: it would lose the start of the first word, and the auto trim already cuts the silence before it. ([knobs.md](../umtool/docs/knobs.md#record-filter-preview-on-the-record-page)) - **umtool: a convert made from a take uses its character's voice, not the editor's default.** On 11 Nov `umtool posts narrate <p> <item> --derive <n> --op convert` with no flags made a take in the wrong voice: it asked the editor with nothing, and the editor used its own default target. A convert now takes its engine, stock voice, pitch and semitones from the recorded preset of the character the read is made as (`--as`, else the item's own, this video's for the author, the cast's, the narrator); a flag overrides its own key. With no character and no `--voice` it is refused in one sentence. The post bench's **run AI on take** does the same on the server. - **Lookouts: a saved set of channels and days, and a dry run that lists what it would read.** A lookout (lane/lookout) will read its channels' recent transcripts and answer with video ideas; this first part has no model. `settings.lookouts` holds the lookouts (off and empty by default; nothing in code names a channel), and `pnpm ops lookout-run --json '{"id":"…","dryRun":true}'` lists the week it would read: every video by its AIR date in the lookout's time zone (a stream that starts at 8:20 pm in New York is 3 Nov, not the 4 Nov of its UTC upload date), a recording uploaded twice read once with the other upload named beside it, a stream's cut-downs credited to the stream, the longest 40 read and every one left out listed with why. Over the pilot's week, read-only, it found all 6 of the pilot's duplicate uploads and all 18 of its stream cut-downs. `pnpm ops get lookouts` is the readout. Runs and verdicts will live in `transcripts/.lookouts/`, never published. - **umtool: a character is a preset, and a video can have characters of its own.** The operator wanted "a preset of voice and other settings" per character, applied to that author's posts, anonymous characters with their own profile per video, a pool reused across videos, and different presets for synthetic and recorded voices. A cast character now carries two presets. `synthetic` is the stock voice and its speed. `recorded` is what a recording of them is made into: the stock voice it is converted to, the engine, the pitch and semitones, whether it is cleaned first, whether its edges are trimmed and how much room is kept, and a one-line direction for the person reading, which is never sent to a model. An existing `cast.json` (`voice`, `convert`) reads as these presets, and the first write makes it version 2; `umtool cast undo` puts the old file back. A video's own characters live in `<project>/narration/characters.json`, for people who must not enter the pool. An anonymous one goes by a shown name, "Anon 1", "Anon 2" by default, on the Voices page, in `umtool cast project` and in a recording's note, and is refused the pool. `narration/voices.json` keeps working and is not rewritten. A post item can name its own character (`umtool posts character <p> <item> <id>`, `--clear`). One read asks, first hit wins: the command's flags, the item's character, the video's character for the author, the cast's, the narrator's, the default. `umtool cast project <p>` prints the answer and its source for each author. A thread read ignored `--speed`: each part is now asked at its character's speed, and `--speed` sets every part. A recording made a read (`posts narrate --recording`) applies its character's clean and trim settings; `--clean`, `--no-clean`, `--trim` and `--no-trim` override them for one read. The Voices page edits both presets, keeps the video's own characters, and has "Add to the pool" and "Keep in this video only"; none of it needs an agent. New: `umtool cast set <id> --speed --enhance --trim --trim-pad --direction`, `umtool cast project <p> add|set|rm|undo|pool|keep`. A convert target is still always a stock synthetic voice, and the disclosure line is unchanged. Not built yet: the on-screen card is not anonymised (a cut still shows the post's author for an anonymous character), and the record page does not show the direction (umtool/docs/knobs.md, "A character is a preset"). diff --git a/umtool/app/api/report/post-narration/record/route.ts b/umtool/app/api/report/post-narration/record/route.ts @@ -12,8 +12,8 @@ import { UMTOOL_DIR } from "@/lib/report/driver.mjs"; import { PARTS_CACHE, partKey } from "@/lib/report/postThreadRead.mjs"; import { projectRedaction } from "@/lib/report/postRedaction.mjs"; import { cancelJob, getJob, jobView, recentJobs, runningJob, startJob, type Job } from "@/lib/jobs"; -import { jobState, startJob as startEditorJob } from "@/lib/research/case-editor"; -import { CAST_PITCH_ENGINES, projectCharactersOf, recordedPresetOf, shownNameOf, voiceRefOf } from "umtool-report-to-video/cast"; +import { editorCall, jobState, startJob as startEditorJob } from "@/lib/research/case-editor"; +import { CAST_PITCH_ENGINES, characterSpeed, characterVoice, projectCharactersOf, recordedPresetOf, shownNameOf, voiceRefOf } from "umtool-report-to-video/cast"; import { spokenRead } from "umtool-report-to-video/post-redact"; export const dynamic = "force-dynamic"; @@ -45,14 +45,16 @@ export const dynamic = "force-dynamic"; // POST {project, op: "filter", id, spans?, pitch?, semitones?} THE CHAIN as one job (`umtool posts narrate <p> // <item> --preview --events`): clean, cut, convert -- a step whose inputs // stand is not run again (another pitch: the convert alone) -// POST {project, op: "cancel", id, job} stop that job +// POST {project, op: "cancel", id, job} stop that job AND the editor's job it waits on (its engine holds the +// heavy slot otherwise); `editor.note` when that one was not known yet +// keep, again, discard-preview, finish, discard and a part's upload answer 409 while the item's Filter runs // POST {project, op: "keep", id, filtered, spans?, script?} filtered: the preview's files made the takes // (recorded, cleaned, converted; the last picked) -- nothing converted // again; else the recorded take alone (finish). The session and the // scratch dir are cleared. // POST {project, op: "again", id, n?} the preview dropped (and part n, to record it again) // POST {project, op: "discard-preview", id} the scratch dir removed (the page is left; a beacon) -// POST {project, op: "stock", id, text} the character's STOCK voice reading the line: the cached read when there +// POST {project, op: "stock", id, text} the character's SYNTHETIC preset voice reading the line: the cached read when there // is one (narration/parts-cache/, a thread read's), else asked of the // editor's tts op (a job) -- only when a person asks @@ -75,8 +77,11 @@ const TYPES: Record<string, string> = { webm: "audio/webm", ogg: "audio/ogg", wa /** The Filter job of one post item (lib/jobs.ts: one job at a time, its log, Cancel). */ const filterKind = (project: string, id: string) => `record-filter ${project} ${id}`; +/** Is that item's Filter running now? Its scratch dir and its session are the job's until it ends. */ +const filterRunning = (project: string, id: string) => runningJob()?.kind === filterKind(project, id); +const busy = () => Response.json({ error: "its Filter is still running: wait for it, or Cancel it", busy: true }, { status: 409 }); -type Stage = { stage?: string; state?: string; message?: string; line?: string }; +type Stage = { stage?: string; state?: string; message?: string; line?: string; job?: string }; const WAITS = ["queued", "memory", "slot"]; /** * The Filter job as the record page reads it: its state, the STAGE it is at (the chain's last `stage` event: @@ -96,6 +101,8 @@ function filterJobView(job: Job) { // Every wait it went through, in order (said after the fact too: "waited for memory"). waited: [...new Set(stages.filter((x) => WAITS.includes(String(x.state))).map((x) => String(x.state)))], stages: last, + // The editor's job it waits on now (the clean, the convert): what Cancel stops there too. null: none known yet. + editorJob: job.state === "running" ? (stages.filter((x) => typeof x.job === "string").at(-1)?.job ?? null) : null, // A failure in the CLI's own words (its last line), not "exited 1". error: failed ? (job.log.filter((l) => !l.startsWith("**") && !l.startsWith("$ ") && !l.startsWith("---")).at(-1) ?? job.error) : null, }; @@ -113,6 +120,8 @@ async function whoOf(dir: string, e: Entry) { character: c ? { id: c.id as string, name: shownNameOf(c) as string, layer: who.layer as string, scope: own ? "project" : "cast" } : null, convert: preset ? preset.convert : null, recorded: preset ? { enhance: preset.enhance, trim: preset.trim, direction: preset.direction } : null, + // The voice it reads in when it is SYNTHESIZED (the synthetic preset: the cheap one to hear the line in). + synthetic: c && characterVoice(c) ? { voice: String(characterVoice(c)), speed: characterSpeed(c) as number | null } : null, pitchEngines: CAST_PITCH_ENGINES, }; } @@ -192,11 +201,14 @@ export async function POST(request: Request) { if (!e) return Response.json({ error: `no post item ${String(form.get("id"))}` }, { status: 404 }); const blob = form.get("part"); if (!blob || typeof blob === "string") return Response.json({ error: "no part" }, { status: 400 }); + if (filterRunning(r.project.id, e.id)) return busy(); try { const session = await savePart(r.project.dir, e, { n: Number(form.get("n")), count: Number(form.get("count")), text: String(form.get("text") ?? ""), para: Number(form.get("para")), bytes: new Uint8Array(await blob.arrayBuffer()), type: blob.type || "audio/webm", label: String(form.get("label") ?? "operator").toLowerCase(), }); + // Another recording than the one a preview was made from: that preview goes (it must never be kept for this one). + await discardPreview(r.project.dir, e, String(form.get("label") ?? "operator").toLowerCase()); return Response.json({ ok: true, session }, { headers: noStore }); } catch (err) { return fail(err); @@ -249,8 +261,17 @@ export async function POST(request: Request) { if (body.op === "cancel") { const job = getJob(String(body.job ?? "")); if (!job || job.kind !== filterKind(r.project.id, e.id)) return Response.json({ error: "no such job" }, { status: 404 }); - return Response.json({ ok: true, cancelled: cancelJob(job.id) }, { headers: noStore }); + // The editor's job too: its engine holds (or waits at) the heavy slot whether or not umtool still follows it. + const editorJob = filterJobView(job).editorJob; + const cancelled = cancelJob(job.id); + let editor: { job: string | null; cancelled: boolean; note?: string } = { job: editorJob, cancelled: false }; + if (editorJob) { + const a = await editorCall("/api/ops/job", { method: "POST", body: { verb: "cancel", ids: [editorJob] } }).catch((err: Error) => ({ ok: false, status: 502, body: { error: err.message } as Record<string, unknown> })); + editor = a.ok ? { job: editorJob, cancelled: true } : { job: editorJob, cancelled: false, note: `the editor's job ${editorJob} was not cancelled (${String(a.body.error ?? `HTTP ${a.status}`)}): cancel it on the editor's /jobs` }; + } else if (cancelled) editor = { job: null, cancelled: false, note: "the editor's job was not known yet: if one started, cancel it on the editor's /jobs" }; + return Response.json({ ok: true, cancelled, editor }, { headers: noStore }); } + if (["keep", "again", "discard-preview", "finish", "discard"].includes(String(body.op)) && filterRunning(r.project.id, e.id)) return busy(); if (body.op === "keep") { if (body.filtered === true) { // The preview's files made the takes: it must be OF this recording and these marks (nothing is converted here). @@ -260,8 +281,9 @@ export async function POST(request: Request) { if (spans && view.parts.some((p: { span: { from: number; to: number } | null }, k: number) => spans[k] && p.span && (Math.abs(p.span.from - spans[k]!.from) > 0.002 || Math.abs(p.span.to - spans[k]!.to) > 0.002))) { return Response.json({ error: "the cut marks moved since the Filter: Filter again, or keep the recording alone" }, { status: 409 }); } - const kept = await keepPreview(r.project, e, { label, script }); - await clearSession(r.project.dir, e, label); + // Of the session as it is NOW: a part recorded again since the Filter is another recording (409, nothing kept). + const kept = await keepPreview(r.project, e, { label, script, parts: doc?.session ? await sessionParts(r.project.dir, e, label) : null }); + if (kept.session) await clearSession(r.project.dir, e, label); return Response.json({ ok: true, takes: kept.takes, picked: kept.picked, notes: kept.notes, disclosure: kept.disclosure, entry: kept.entry, token: kept.token }, { headers: noStore }); } const kept = await finishSession(r.project, e, { label, manifest: r.manifest as Record<string, unknown>, script, spans }); @@ -280,20 +302,21 @@ export async function POST(request: Request) { if (body.op === "stock") { // The character's stock voice reading the line -- what the redaction, the slur filter and the lexicon leave of it. const who = await whoOf(r.project.dir, e); - const ref = voiceRefOf(who.convert?.voice ?? "") as { engine: string | null; voice: string } | null; - if (!ref?.engine) return Response.json({ error: "this post has no character with a stock voice to hear" }, { status: 400 }); + const ref = voiceRefOf(who.synthetic?.voice ?? "") as { engine: string | null; voice: string } | null; + const speed = ref?.engine && ref.engine !== "orpheus" && typeof who.synthetic?.speed === "number" ? who.synthetic.speed : null; + if (!ref?.engine) return Response.json({ error: "this post's character has no synthetic voice to hear" }, { status: 400 }); const text = String(body.text ?? "").trim(); if (!text) return Response.json({ error: "no line to read" }, { status: 400 }); const red = await projectRedaction(r.project.dir, r.manifest as Record<string, unknown>); const spoken = String(spokenRead(text, e, red, { voice: red?.slurs?.voice === "beep" ? "skip" : undefined }).text); - const key = partKey(ref.engine, ref.voice, spoken) as string; + const key = partKey(ref.engine, ref.voice, spoken, speed) as string; const abs = path.join(r.project.dir, ...stockRel(key).split("/")); - if ((await stat(abs).catch(() => null))?.isFile()) return Response.json({ ok: true, cached: true, file: stockRel(key), voice: who.convert?.voice }, { headers: noStore }); - if (body.cachedOnly === true) return Response.json({ ok: true, cached: false, voice: who.convert?.voice }, { headers: noStore }); + if ((await stat(abs).catch(() => null))?.isFile()) return Response.json({ ok: true, cached: true, file: stockRel(key), voice: who.synthetic?.voice }, { headers: noStore }); + if (body.cachedOnly === true) return Response.json({ ok: true, cached: false, voice: who.synthetic?.voice }, { headers: noStore }); await mkdir(path.dirname(abs), { recursive: true }); // The job writes BESIDE the cache; its poll renames it in (a half-written read is never a cached part). - const jobId = await startEditorJob("/api/ops/tts", { text: spoken, engine: ref.engine, voice: ref.voice, out: `${abs}.pending.tmp.wav` }); - return Response.json({ ok: true, cached: false, jobId, key, voice: who.convert?.voice }, { headers: noStore }); + const jobId = await startEditorJob("/api/ops/tts", { text: spoken, engine: ref.engine, voice: ref.voice, out: `${abs}.pending.tmp.wav`, ...(speed ? { speed } : {}) }); + return Response.json({ ok: true, cached: false, jobId, key, voice: who.synthetic?.voice }, { headers: noStore }); } return Response.json({ error: "op is discard, finish, prepare, filter, cancel, keep, again, discard-preview or stock" }, { status: 400 }); } catch (err) { diff --git a/umtool/components/projects/RecordFilter.tsx b/umtool/components/projects/RecordFilter.tsx @@ -30,6 +30,7 @@ export type Who = { character: { id: string; name: string; layer: string; scope: "project" | "cast" } | null; convert: { engine: string | null; voice: string | null; pitch?: string; semitones?: number } | null; recorded: { enhance: boolean; trim: { on: boolean; padMs: number | null }; direction: string | null } | null; + synthetic: { voice: string; speed: number | null } | null; pitchEngines: string[]; }; export type FilterJob = { @@ -42,6 +43,7 @@ export type FilterJob = { message: string | null; waiting: "queued" | "memory" | "slot" | null; waited: string[]; + editorJob?: string | null; stages: Record<string, { state?: string; message?: string }>; error: string | null; }; diff --git a/umtool/components/projects/RecordSession.tsx b/umtool/components/projects/RecordSession.tsx @@ -158,10 +158,15 @@ export default function RecordSession({ project, items: initial, start, box }: { setSpans(p.parts.map((x) => x.span ?? x.auto)); spanSource.current = p.source; }, []); + const dropPreview = useCallback(() => { + setPreview(null); + spanSource.current = null; + setFjob(null); + }, []); const loadWho = useCallback(async () => { const r = await fetch(`${RECORD_API}?project=${enc(project)}&id=${enc(item.id)}&preview`, { cache: "no-store" }); const j = (await r.json().catch(() => ({}))) as Partial<Who> & { preview?: Preview | null; job?: FilterJob | null }; - const w: Who = { character: j.character ?? null, convert: j.convert ?? null, recorded: j.recorded ?? null, pitchEngines: j.pitchEngines ?? [] }; + const w: Who = { character: j.character ?? null, convert: j.convert ?? null, recorded: j.recorded ?? null, synthetic: j.synthetic ?? null, pitchEngines: j.pitchEngines ?? [] }; setWho(w); setPitch(j.preview?.filtered?.asked?.pitch ?? w.convert?.pitch ?? "target"); setSemitones(String(j.preview?.filtered?.asked?.semitones ?? w.convert?.semitones ?? 0)); @@ -339,13 +344,15 @@ export default function RecordSession({ project, items: initial, start, box }: { setError(`part ${p.n} was NOT saved: ${j.error ?? `HTTP ${r.status}`} — record it again`); return; } + // Another recording than the one a preview was made from: that preview is gone (the server dropped it too). + dropPreview(); setSession(j.session); const s = j.session; const next = parts.findIndex((q) => !(s.parts[String(q.n)] && s.count === parts.length)); // The last part in: the take is made -- or, with "Filter before keeping", the post waits to be filtered and kept. if (next >= 0) setCur(next); else if (!(await waits())) await finish(); - }, [phase, mic, parts, cur, project, item.id, finish, waits]); + }, [phase, mic, parts, cur, project, item.id, finish, waits, dropPreview]); // A sound file for the current part (a recording made elsewhere: a phone's recorder, the LAN where the mic is off). const takeFile = useCallback( @@ -366,13 +373,14 @@ export default function RecordSession({ project, items: initial, start, box }: { const j = (await r.json().catch(() => ({}))) as { session?: Session; error?: string }; setPhase("idle"); if (!r.ok || !j.session) return setError(`part ${p.n} was NOT saved: ${j.error ?? `HTTP ${r.status}`}`); + dropPreview(); setSession(j.session); const sdoc = j.session; const next = parts.findIndex((q) => !(sdoc.parts[String(q.n)] && sdoc.count === parts.length)); if (next >= 0) setCur(next); else if (!(await waits())) await finish(); }, - [phase, parts, cur, project, item.id, finish, waits], + [phase, parts, cur, project, item.id, finish, waits, dropPreview], ); // FILTER: the character's recorded preset as one job -- clean, cut at the marks, convert -- into the scratch dir. @@ -387,7 +395,8 @@ export default function RecordSession({ project, items: initial, start, box }: { // KEEP: the preview's files made the takes (when it is of these marks and this pitch), else the recording alone. const keep = useCallback(async () => { - if (!reviewing || phase !== "idle" || fjob?.state === "running") return; + // No preview: the recording is still being read (a part just landed) -- there is nothing to judge or keep yet. + if (!reviewing || phase !== "idle" || fjob?.state === "running" || !preview) return; setError(null); setPhase("finishing"); const { ok, j } = await postOp({ op: "keep", filtered: current, spans, script: item.script }); @@ -405,7 +414,7 @@ export default function RecordSession({ project, items: initial, start, box }: { const next = order.find((i) => i > at && !items[i].recorded) ?? order.find((i) => !items[i].recorded); if (next === undefined) setStatus(`${said}. Every post is recorded.`); else setAt(next); - }, [reviewing, phase, fjob?.state, postOp, current, spans, item.script, item.id, item.n, items, at]); + }, [reviewing, phase, fjob?.state, preview, postOp, current, spans, item.script, item.id, item.n, items, at]); // The pitch asked here, written back to the character (the Voices page's own write: POST /api/report/voices). const voices = useCallback( @@ -490,6 +499,11 @@ export default function RecordSession({ project, items: initial, start, box }: { // A text box or a select keeps its keys; a checkbox (the count-in) does not -- Space still records. if (tgt?.closest("textarea, select, input:not([type=checkbox])")) return; if (ev.metaKey || ev.ctrlKey || ev.altKey) return; + // A key held down is one press: a held Space must not stop the recording it started, nor a held Enter keep twice. + if (ev.repeat) { + if ([" ", "Enter", "Backspace"].includes(ev.key) && !tgt?.closest("button, a, [role=slider]")) ev.preventDefault(); + return; + } // A button keeps its own Enter and Space (a cut mark keeps its arrows): the page's keys are for hands off it. const onButton = !!tgt?.closest("button, a, [role=slider]"); // While the Filter runs the recording it reads is not recorded over: the keys wait for it (n / p still walk). @@ -754,19 +768,19 @@ export default function RecordSession({ project, items: initial, start, box }: { “{who.recorded.direction}” </span> )} - {who.convert?.voice ? ( + {who.synthetic?.voice ? ( <button type="button" className={btn} disabled={stock.state === "asking" || !parts.length} onClick={() => void playStock()} - title="The stock voice reading this line: the read kept from before when there is one, else the editor is asked to synthesize it (Kokoro is quick; Orpheus is slow and takes the heavy slot)." + title="The character's synthetic voice reading this line (its synthetic preset; a recording is converted to its convert voice, which may be another): the read kept from before when there is one, else the editor is asked to synthesize it (Kokoro is quick; Orpheus is slow and takes the heavy slot)." data-record-stock={stock.state} > - {stock.state === "asking" ? "asking the editor…" : `▶ ${who.convert.voice} reads it`} + {stock.state === "asking" ? "asking the editor…" : `▶ ${who.synthetic.voice} reads it`} </button> ) : ( - <span className="text-text-2">no stock voice to convert to</span> + <span className="text-text-2">no synthetic voice to hear it in</span> )} {stock.state === "failed" && <span className="text-[var(--color-blocking,#c33)]" data-record-stock-error="">{stock.error}</span>} </> @@ -881,7 +895,12 @@ export default function RecordSession({ project, items: initial, start, box }: { <FilterProgress job={fjob} now={now} - onCancel={() => void postOp({ op: "cancel", job: fjob.id })} + onCancel={() => + void postOp({ op: "cancel", job: fjob.id }).then(({ j }) => { + const note = (j.editor as { note?: string } | undefined)?.note; + if (note) setError(note); + }) + } /> )} {preview?.raw && filtered && fjob?.state !== "running" && ( diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md @@ -1399,9 +1399,10 @@ umtool posts character quartering-diet <item> anon-1 # this one item rea The operator, 11 Nov 2026: "run the filter and preview it seamlessly in the record UI". On `/projects/<p>/narration/record`, above the record button: **who the post is read as** (the chain's character and -where it comes from), its **direction** line, and **▶ <voice> reads it** -- the character's stock voice reading the -part: the read kept from before when there is one (`narration/parts-cache/`, a thread read's), else asked of the -editor's tts op when the button is pressed, never before. +where it comes from), its **direction** line, and **▶ <voice> reads it** -- the character's SYNTHETIC preset voice +(`synthetic.voice`, at its speed: the cheap one to hear the line in -- the voice a recording is CONVERTED to is +`recorded.convert.voice`, which may be another) reading the part: the read kept from before when there is one +(`narration/parts-cache/`, a thread read's), else asked of the editor's tts op when the button is pressed, never before. **Filter before keeping** (a checkbox; on by itself for a post whose character has a stock voice to convert to, off otherwise -- the last part then makes the recorded take at once, as before): the last part in, the post WAITS. @@ -1419,7 +1420,9 @@ otherwise -- the last part then makes the recorded take at once, as before): the mark moved re-cuts the cleaned sound and converts; another pitch converts alone. **A wait is a state, not an error**: *queued* behind the editor's other voice jobs, *waiting for memory* or *for the heavy slot* at the machine's gate (the last line of the editor's job, `scripts/queue-lock.mjs`'s own) -- a short read takes two or three minutes. - umtool runs one job at a time: while another runs, Filter says so. + umtool runs one job at a time: while another runs, Filter says so. **Cancel** stops umtool's job AND the editor's + job it waits on (its engine holds, or waits at, the heavy slot otherwise); pressed before the editor's job is known, + the page says so. While a post's Filter runs, Keep, Again, a part's upload and dropping the preview answer 409. - **▶ Raw**, **▶ Filtered**, **▶ Raw, then filtered**: the two reads at ONE loudness (the louder turned down to the other's measured LUFS). With no clean engine and no character to convert to, it says nothing filtered it. - **Pitch** and **semitones** (a Seed-VC convert): default the preset's; **Save to character** writes them to the @@ -1430,7 +1433,13 @@ otherwise -- the last part then makes the recorded take at once, as before): the cleaned one, the converted one, the last PICKED and awaiting approval -- made FROM THE PREVIEW's FILES, nothing converted again; the page opens the next post not recorded yet. When the marks or the pitch moved since the Filter the button says **Keep the recording alone** and keeps one recorded take, cut at the marks. -- **Again** (**Backspace** or **r**): the preview dropped, the part recorded again. +- **Again** (**Backspace** or **r**): the preview dropped, the part recorded again. A part recorded over with Space + drops the preview too (page and server), and a filtered Keep is refused (409) unless the preview was made from the + session's recording as it is now -- the filtered read of an earlier recording is never kept. A held key is one press. +- A sound file chosen for a part (and `--recording <file>`) is an upload: one that is text (a playlist, a concat + script) is refused before ffmpeg opens it, and ffmpeg may open local files only (`-protocol_whitelist file`). +- Keep writes its takes one after another (an undo point each, as `--recording` does): a failure between them leaves + the takes already written, and the preview's files that were moved stay takes. - The scratch dir is removed on Keep, on Again, when the post or the page is left (unless its Filter is still running: it is there when you come back), when the recording it was made from changes, and a day after a crash left one. - **The microphone is a secure context's** (localhost, https): opened over http from the LAN the page says so and @@ -1441,13 +1450,13 @@ otherwise -- the last part then makes the recorded take at once, as before): the | Knob | In umtool | From a terminal | Route | |---|---|---|---| -| the preview -- the chain into the scratch dir, no take | **Filter** (f) | `umtool posts narrate <p> <item> --preview` (the page's session) · `--recording <file> --preview [--out <file>]` (a file; the filtered read copied to `--out`) · `--json` · `--events` (its progress, one JSON object a line) | `POST /api/report/post-narration/record {op: "filter", id, spans?, pitch?, semitones?}` → `{job}`; `GET ?project&id&job=<id>` → `{job: {state, stage, waiting, waited, stages, error}, preview?}`; `POST {op: "cancel", id, job}` | +| the preview -- the chain into the scratch dir, no take | **Filter** (f) | `umtool posts narrate <p> <item> --preview` (the page's session) · `--recording <file> --preview [--out <file>]` (a file; the filtered read copied to `--out`) · `--json` · `--events` (its progress, one JSON object a line) | `POST /api/report/post-narration/record {op: "filter", id, spans?, pitch?, semitones?}` → `{job}`; `GET ?project&id&job=<id>` → `{job: {state, stage, waiting, waited, stages, error}, preview?}`; `POST {op: "cancel", id, job}` → `{cancelled, editor: {job, cancelled, note?}}` | | the cut marks -- `[{from, to}]` per part | the waveform's two marks | `--trim-span 0.4-3.1` (the first part) · `--trim-span 2=0.2-4` | `spans` on `filter`, `keep`, `finish`; `POST {op: "prepare", id}` → each part's `seconds`, `peaks`, `auto` | | the pitch of this read | **pitch**, **semitones** | `--pitch target\|source\|contour` · `--semitones n` | `pitch`, `semitones` on `filter` | | the pitch kept on the character | **Save to character** · **Keep in this video only** | `umtool cast set <id> --convert-pitch … --convert-semitones n` · `umtool cast project <p> set <id> …` · `umtool cast project <p> keep @<handle>` | `POST /api/report/voices {op: "character-set" \| "character-keep"}` | | keep the preview -- its takes, the last picked | **Keep** (Enter) | `umtool posts narrate <p> <item> --keep-preview` | `POST … {op: "keep", id, filtered: true, spans?, script?}` (`filtered: false`: the recording alone) | | drop it | **Again** (Backspace, r), leaving the post | `umtool posts narrate <p> <item> --discard-preview` | `POST … {op: "again", id, n?}` · `{op: "discard-preview", id}` | -| the stock voice reading the line | **▶ <voice> reads it** | — | `POST … {op: "stock", id, text}` → `{file}` or `{jobId, key}`; `GET ?project&id&stock&job&key` | +| the character's synthetic voice reading the line | **▶ <voice> reads it** | — | `POST … {op: "stock", id, text}` → `{file}` or `{jobId, key}`; `GET ?project&id&stock&job&key` | | the preview's sounds | **▶ Raw**, **▶ Filtered**, **▶ what the marks keep** | the paths `--preview` prints | `GET ?project&id&preview&file=raw\|clean\|filtered\|part[&n]` · `GET ?project&id&preview` (who it is read as, the preview, the job) | ```sh diff --git a/umtool/e2e/record-filter.spec.ts b/umtool/e2e/record-filter.spec.ts @@ -295,3 +295,32 @@ test("opened over http from the LAN the microphone is off, and the page says so; expect(narr("p-2").takes).toHaveLength(1); expect(existsSync(path.join(NARRATION, ".record-preview", "2.operator"))).toBe(false); }); + +test("a part recorded again with Space (no Again) and Enter at once: the filtered read of the EARLIER recording is never kept", async ({ page }) => { + giveSavvy(); + await page.setViewportSize({ width: 1366, height: 1100 }); + await page.goto(urls.narrationRecordHref(P, { post: "p-1" })); + await expect(page.locator("[data-record-character]")).toHaveAttribute("data-record-character", "madam-savvy"); + await recordPart(page); + await expect(page.locator('[data-record-wave="1"]')).toBeVisible({ timeout: 20_000 }); + await page.locator("[data-record-filter]").click(); + await filterDone(page); + await expect(page.locator("[data-record-review-panel]")).toHaveAttribute("data-record-preview-current", "1"); + const before = converts().length; + // Space records over the part; Enter the moment it has landed. + await page.locator("[data-record-teleprompter]").click({ position: { x: 2, y: 2 } }); + await page.keyboard.press("Space"); + await expect(s(page)).toHaveAttribute("data-record-phase", "recording", { timeout: 15_000 }); + await page.waitForTimeout(1200); + await page.keyboard.press("Space"); + await page.keyboard.press("Enter"); + await expect(s(page)).toHaveAttribute("data-record-phase", "idle", { timeout: 15_000 }); + // The earlier preview is gone, on the page and on disk; whatever Enter did, no converted take was made. + await expect(page.locator("[data-record-compare]")).toHaveCount(0); + expect(existsSync(path.join(SCRATCH("1"), "filtered.wav"))).toBe(false); + expect((narr("p-1").takes ?? []).filter((t) => t.engine === "derived")).toHaveLength(0); + expect(converts()).toHaveLength(before); + // The server holds the line too: a filtered Keep with no preview of this recording is refused. + const r = await page.request.post("/api/report/post-narration/record", { data: { project: P, id: "p-1", op: "keep", filtered: true } }); + if ((narr("p-1").takes ?? []).length === 0) expect(r.status()).toBe(409); +}); diff --git a/umtool/lib/report/postNarrationCli.mjs b/umtool/lib/report/postNarrationCli.mjs @@ -560,7 +560,12 @@ export async function narrateCommand(project, words, flags, { json = false, dryR return 0; } if (flags.has("--keep-preview")) { - const r = await keepPreview(project, e, { label, note: str("--note"), script: str("--script") }); + // A preview of the record page's session is kept only while the session is still the recording it was made from. + const { readPreview } = await import("./recordPreview.mjs"); + const made = await readPreview(project.dir, e, label); + const parts = made?.session ? await (await import("./recordSession.mjs")).sessionParts(project.dir, e, label).catch(() => null) : null; + if (made?.session && !parts) throw new NarrateError(`${e.id}'s preview is of the record page's session, and that session is gone or not whole any more: --discard-preview, and Filter again`); + const r = await keepPreview(project, e, { label, note: str("--note"), script: str("--script"), parts }); // A preview of the record page's session: its parts are takes now, the session is over. if (r.session) await (await import("./recordSession.mjs")).clearSession(project.dir, e, label); if (json) out(JSON.stringify({ ok: true, id: e.id, takes: r.takes, picked: r.picked, notes: r.notes, disclosure: r.disclosure, character: r.character, token: r.token }, null, 2)); diff --git a/umtool/lib/report/postRecord.mjs b/umtool/lib/report/postRecord.mjs @@ -13,7 +13,7 @@ // project's synthesized takes (their measured loudness, else -21 LUFS) by one // gain under a -1 dBFS limiter. Nothing else: no cloning, no TTS, no effects. import { execFile } from "node:child_process"; -import { mkdir, readdir, rename, rm, stat } from "node:fs/promises"; +import { mkdir, open, readdir, rename, rm, stat } from "node:fs/promises"; import path from "node:path"; import { promisify } from "node:util"; import { detectSilence } from "umtool-report-to-video/cut-points"; @@ -64,9 +64,35 @@ export function explicitSpan(span, seconds) { return to - from >= 0.2 ? { from: r3(from), to: r3(to) } : null; } -/** One part as it was recorded (any sound ffmpeg reads) -> a 48 kHz mono wav, measured: `{ seconds, silences }`. */ +/** + * Is `file` TEXT where a sound should be -- a playlist, a concat script, an SDP, a manifest (m3u8, ffconcat, MPD …)? + * ffmpeg would follow one to OTHER files and addresses; a recording is a binary container, so its first bytes are + * never all text. An upload that is, is refused before ffmpeg sees it. + */ +export async function looksLikeText(file) { + const fh = await open(file, "r"); + try { + const buf = Buffer.alloc(2048); + const { bytesRead } = await fh.read(buf, 0, buf.length, 0); + if (!bytesRead) return false; + for (let i = 0; i < bytesRead; i += 1) { + const b = buf[i]; + if (b === 0 || (b < 9) || (b > 13 && b < 32)) return false; + } + return true; + } finally { + await fh.close(); + } +} + +/** + * One part as it was recorded (any sound ffmpeg reads) -> a 48 kHz mono wav, measured: `{ seconds, silences }`. The + * file is an UPLOAD: a text file (a playlist: looksLikeText) is refused, and ffmpeg may open local files only + * (`-protocol_whitelist file`: no http, no concat, no pipe). + */ export async function decodePart(src, out) { - await execFileP(FFMPEG(), ["-nostdin", "-v", "error", "-y", "-i", src, "-vn", "-ac", "1", "-ar", "48000", "-c:a", "pcm_s16le", out]); + if (await looksLikeText(src)) throw Object.assign(new Error("that is not a sound file: it is text (a playlist or a script), and a recording is refused one"), { status: 400 }); + await execFileP(FFMPEG(), ["-nostdin", "-v", "error", "-y", "-protocol_whitelist", "file", "-i", src, "-vn", "-ac", "1", "-ar", "48000", "-c:a", "pcm_s16le", out]); const { seconds } = await measureTake(out); const silences = await detectSilence(out, { silenceMinDur: 0.15 }).catch(() => []); return { seconds: r3(seconds ?? 0), silences }; diff --git a/umtool/lib/report/postThreadRead.mjs b/umtool/lib/report/postThreadRead.mjs @@ -109,6 +109,7 @@ export async function projectCastMap(dir) { * A part's cache key: sha1 of `voice|text` (an engine other than Orpheus: `engine|voice|text`), and of its SPEED when * it is read at one (`…|x1.1`: the same words at another speed are another part; none, or 1: the key as before). */ +/** @type {(engine: string, voice: string, text: string, speed?: number | null) => string} */ export const partKey = (engine, voice, text, speed = null) => createHash("sha1").update(`${engine === "orpheus" ? `${voice}|${text}` : `${engine}|${voice}|${text}`}${typeof speed === "number" && speed !== 1 ? `|x${speed}` : ""}`).digest("hex"); /** `--parents` as a selector: "0" (default), "all", "none", or a whole number n (parents 0..n). */ diff --git a/umtool/lib/report/recordPreview.mjs b/umtool/lib/report/recordPreview.mjs @@ -89,7 +89,7 @@ async function pruneStale(projectDir, keep, now = Date.now()) { } /** What a recording is, for the cache: its files, their sizes and times. */ -async function sourceKeyOf(parts) { +export async function sourceKeyOf(parts) { const rows = []; for (const p of parts) { const st = await stat(p.file).catch(() => null); @@ -364,15 +364,18 @@ export async function previewFile(projectDir, entry, which, { label = "operator" * original: trimmed, joined, levelled), the cleaned one (`steps: [{op: "enhance"}]`), the converted one (`steps: [{op: * "convert", engine, voice, pitch?, semitones?}]`) -- each a new take through the writer (an undo point each), the * last one PICKED (a pick takes the approval away: it awaits approval). Nothing is asked of the editor. The scratch dir - * is removed. Returns `{ takes: [{ step, file }], picked, notes, disclosure, character, session, entry, token }`. + * is removed. `parts`: the recording meant (the session's parts now) -- a preview of another is refused (409). Returns `{ takes: [{ step, file }], picked, notes, disclosure, character, session, entry, token }`. * * @param {{ id: string, dir: string }} project * @param {Record<string, any>} entry - * @param {{ label?: string, script?: string | null, note?: string | null }} [o] + * @param {{ label?: string, script?: string | null, note?: string | null, parts?: Array<{ file: string }> | null }} [o] */ -export async function keepPreview(project, entry, { label = "operator", script = null, note = null } = {}) { +export async function keepPreview(project, entry, { label = "operator", script = null, note = null, parts: meant = null } = {}) { const doc = await readPreview(project.dir, entry, label); if (!doc?.built) throw Object.assign(new NarrateError(`${entry.id} has no preview to keep (Filter it first: umtool posts narrate ${project.id} ${entry.id} --recording <file> --preview)`), { status: 409 }); + // The recording the caller means to keep (the record page's session, as it is NOW): a preview made from another + // one -- a part recorded again since the Filter -- is refused; its sound is not what was read last. + if (meant && (await sourceKeyOf(meant)) !== doc.source) throw Object.assign(new NarrateError(`${entry.id}'s preview is of an earlier recording (a part was recorded again since the Filter): Filter again, or keep the recording alone`), { status: 409 }); const dir = previewDirOf(project.dir, entry, label); const pid = postIdOf(entry); const takesDir = path.join(project.dir, ...takesDirOf(pid).split("/")); diff --git a/umtool/lib/report/recordPreview.test.mjs b/umtool/lib/report/recordPreview.test.mjs @@ -18,7 +18,7 @@ import { validatePostNarration } from "umtool-report-to-video/post-narration"; import { castCommand } from "./castCli.mjs"; import { measureTake, trimSpans } from "./postNarrationCli.mjs"; import { postsCommand } from "./postsCli.mjs"; -import { explicitSpan, keepRecording } from "./postRecord.mjs"; +import { decodePart, explicitSpan, keepRecording, looksLikeText } from "./postRecord.mjs"; import { PREVIEW_PEAKS, discardPreview, keepPreview, preparePreview, previewDirOf, previewFile, previewView, readPreview, runPreview } from "./recordPreview.mjs"; import { finishSession, savePart } from "./recordSession.mjs"; @@ -327,3 +327,56 @@ test("the CLI twin: --recording <file> --preview prints the paths and makes no t assert.notEqual(c.code, 0); assert.match(c.text(), /no preview to keep/); }); + +test("a preview is kept only for the recording it was made from: a part recorded again since the Filter is refused, nothing kept", async () => { + const e = await item("p-2"); + const a = path.join(ROOT, "again-a.wav"); + const b = path.join(ROOT, "again-b.wav"); + await wavOf(a, VOICE_B, 1.5, 0.4); + await wavOf(b, VOICE_B, 1.0, 0.4); + await savePart(DIR, e, { n: 1, count: 2, text: "A first paragraph.", para: 0, bytes: await readFile(a), type: "audio/wav" }); + await savePart(DIR, e, { n: 2, count: 2, text: "A second one.", para: 1, bytes: await readFile(b), type: "audio/wav" }); + const { sessionParts } = await import("./recordSession.mjs"); + const ed = editor(); + await runPreview(project, e, await sessionParts(DIR, e), { ask: ed.ask, session: true }); + const takes = (await item("p-2")).narration.takes.length; + // Part 2 recorded again (Space, with no Again): the session is another recording now. + await new Promise((res) => setTimeout(res, 20)); + await savePart(DIR, e, { n: 2, count: 2, text: "A second one.", para: 1, bytes: await readFile(a), type: "audio/wav" }); + await assert.rejects(keepPreview(project, await item("p-2"), { parts: await sessionParts(DIR, e) }), (err) => err.status === 409 && /preview is of an earlier recording/.test(err.message)); + assert.equal((await item("p-2")).narration.takes.length, takes, "nothing kept"); + assert.ok(existsSync(path.join(DIR, "narration", "posts", "2", ".recording-operator", "session.json")), "the new part is still there"); + // The terminal's --keep-preview asks the same. + const c = await posts(["narrate", "rec", "p-2", "--keep-preview"]); + assert.notEqual(c.code, 0); + assert.match(c.text(), /preview is of an earlier recording/); + // The same recording: kept. + await runPreview(project, await item("p-2"), await sessionParts(DIR, e), { ask: ed.ask, session: true }); + const k = await keepPreview(project, await item("p-2"), { parts: await sessionParts(DIR, e) }); + assert.equal(k.session, true); + const { clearSession } = await import("./recordSession.mjs"); + await clearSession(DIR, e); +}); + +test("an upload that is text (a playlist, a concat script) is refused before ffmpeg opens it; ffmpeg may open local files only", async () => { + const secret = path.join(ROOT, "secret.wav"); + await wavOf(secret, VOICE_A, 1, 0); + const lists = { + "list.m3u8": `#EXTM3U\n#EXT-X-TARGETDURATION:10\n#EXTINF:10,\n${secret}\n#EXT-X-ENDLIST\n`, + "list.wav": `#EXTM3U\n#EXTINF:10,\nhttp://127.0.0.1:9/x.ts\n`, + "script.ffconcat": `ffconcat version 1.0\nfile '${secret}'\n`, + }; + for (const [name, text] of Object.entries(lists)) { + const f = path.join(ROOT, name); + await writeFile(f, text); + assert.equal(await looksLikeText(f), true, name); + const out = path.join(ROOT, `${name}.out.wav`); + await assert.rejects(decodePart(f, out), (err) => err.status === 400 && /not a sound file: it is text/.test(err.message), name); + assert.equal(existsSync(out), false, `${name}: nothing decoded`); + await assert.rejects(keepRecording(project, await item("p-3"), [{ file: f }], { manifest: await manifest() }), /not a sound file/); + await assert.rejects(runPreview(project, await item("p-3"), [{ file: f }], { ask: editor().ask }), /not a sound file/); + } + assert.equal(await looksLikeText(secret), false, "a wav is binary"); + const ok = await decodePart(secret, path.join(ROOT, "secret.out.wav")); + assert.ok(ok.seconds > 0.9); +});