Archilyzer · Source

archilyzer

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

commit 8f7f9ef8a33a6f25eb27023e4d8905bf1844827f
parent c3ba0fed14d98a8295cf0bc51c2a26fea33ce22b
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Fri, 13 Nov 2026 01:19:11 -0500

umtool screens bench: Record / Stop / Keep a line in your voice, choose its take, Make the read

The post bench's screens section (components/projects/ScreenLineVoice.tsx, PostScreensPanel):
each read line shows what you read (the line as the read says it: GET /api/report/post-narration
?linePrompts=1, its masks, the redaction, an anonymous handle's shown name), Record / Stop / play
back / Discard / Keep -- Keep one umtool job running `posts screen <p> <item> record <id> <n>`
on the upload (POST multipart {line}; the upload removed when it ends) -- and a select CHOOSING
the take read in the line's place (the screen's lineTakes, saved with Save). "Make the read" is
`posts screen <p> <item> read` as a job (POST {op: "screen-read"}); either job is followed on GET
?screenJob=. Recording and the read are off while the draft is unsaved; a job's entry never
replaces edits made meanwhile. No model anywhere.

e2e (post-screens.spec.ts): the fake microphone's tone recorded, kept (converted by the stub
editor, none picked), chosen, saved, and played by the read in the line's place.

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

Diffstat:
Mumtool/app/api/report/post-narration/route.ts | 98+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/projects/PostBench.tsx | 12+++++++++++-
Mumtool/components/projects/PostScreensPanel.tsx | 83++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------
Aumtool/components/projects/ScreenLineVoice.tsx | 188+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/e2e/post-screens.spec.ts | 85+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
5 files changed, 454 insertions(+), 12 deletions(-)

diff --git a/umtool/app/api/report/post-narration/route.ts b/umtool/app/api/report/post-narration/route.ts @@ -24,6 +24,8 @@ import { spokenRead } from "umtool-report-to-video/post-redact"; import { recordedPresetOf, shownNameOf } from "umtool-report-to-video/cast"; import { readLayers, recordedTrimFor } from "@/lib/report/characterLayers.mjs"; import { convertAskOf, derivePitchOf, deriveRefusalOf, stepPitchOf } from "@/lib/report/derivePitch.mjs"; +import { getJob, runningJob, startJob as startUmtoolJob, type Job } from "@/lib/jobs"; +import { UMTOOL_DIR } from "@/lib/report/driver.mjs"; export const dynamic = "force-dynamic"; @@ -67,6 +69,14 @@ const benchVoice = (red: { slurs?: { voice?: string } | null } | null) => (red?. // a reread, set or fit + inTake: <take> the same, scoped to the take's patch (takeScope.mjs, the CLI's // --in-take); every other op refuses inTake // POST {project, op: "undo"} the last structural write undone +// POST multipart {project, id, line: "screen:<id>:<n>", label?, part (audio)} +// ONE SCREEN LINE recorded (lib/report/screenLineRecord.mjs): a umtool +// job running `umtool posts screen <p> <item> record <id> <n> +// --recording <upload>` -- recorded, cleaned, converted to the +// speaker's character, none picked; the upload removed when it ends +// POST {project, op: "screen-read", id} MAKE THE READ with its screens: a umtool job running `umtool posts +// screen <p> <item> read` (the screens' chosen line takes in it) +// GET ?project&id&screenJob=<job> either job: its state, its result, and -- ended -- the entry as it is const noStore = { "cache-control": "no-store" }; type Entry = Record<string, unknown> & { id: string; type?: string; narration?: Record<string, unknown> }; @@ -88,6 +98,33 @@ export async function GET(request: Request) { const render = (m.render ?? {}) as Record<string, unknown>; const id = q.get("id"); const job = q.get("job"); + if (id && q.get("linePrompts") !== null) { + // What each read screen line says, as the read says it (screenLineRecord.mjs lineToRecord): the bench's prompt. + const e = postsOf(m).find((x) => x.id === id); + if (!e) return Response.json({ error: `no post item ${id}` }, { status: 404 }); + const { lineToRecord } = await import("@/lib/report/screenLineRecord.mjs"); + const { characterNames } = await import("@/lib/report/postThreadRead.mjs"); + const { screensOf, screenReadLines } = await import("umtool-report-to-video/post-screens"); + const red = await projectRedaction(r.project.dir, m); + const names = characterNames(await readLayers(r.project.dir).catch(() => null)); + const prompts: Record<string, string> = {}; + for (const sc of screensOf(e) as Array<{ id: string }>) { + for (const rl of screenReadLines(sc) as Array<{ n: number }>) { + const role = `screen:${sc.id}:${rl.n}`; + try { + prompts[role] = String(lineToRecord(e, role, { red, names: names as Record<string, string> }).prompt); + } catch { + // a line with nothing left to say: no prompt + } + } + } + return Response.json({ ok: true, prompts }, { headers: noStore }); + } + if (id && q.get("screenJob") !== null) { + const j = getJob(String(q.get("screenJob"))); + if (!j || !screenJobKinds(r.project.id, id).includes(j.kind)) return Response.json({ error: "no such job" }, { status: 404 }); + return Response.json(await screenJobView(r.project.dir, id, j), { headers: noStore }); + } if (id && !job && q.get("convert") !== null) { // What a convert of this post defaults to (`posts narrate --recording`'s rule: the author's character, else the narrator). const e = postsOf(m).find((x) => x.id === id); @@ -240,6 +277,15 @@ async function postHere(request: Request) { const id = String(body.id ?? ""); const token = body.token === undefined || body.token === null ? null : String(body.token); try { + if (body.op === "screen-read") { + // MAKE THE READ with the screens (the bench's button): the CLI's own command as a umtool job. + const e = postsOf(m).find((x) => x.id === id); + if (!e) return Response.json({ error: `no post item ${id}` }, { status: 404 }); + const running = runningJob(); + if (running) return Response.json({ error: `umtool is running another job (${running.kind}): make the read when it is done`, busy: true }, { status: 409 }); + const j = startUmtoolJob(screenJobKinds(r.project.id, id)[1], [{ label: `${id}: its read made with its screens`, argv: [process.execPath, cliPath(), "posts", "screen", r.project.id, id, "read", "--json"], cwd: path.join(/* turbopackIgnore: true */ UMTOOL_DIR, ".."), env: {}, 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") { const { result } = await withEditNotes(r.project, () => undoStructural(r.project.dir, { token })); return Response.json({ ok: true, ...result }, { headers: noStore }); @@ -414,6 +460,8 @@ async function record(request: Request) { if (!RECORD_LABEL_RE.test(label)) return Response.json({ error: `"${label}" is not a voice label (a-z, 0-9, - and _)` }, { status: 400 }); const blobs = form.getAll("part").filter((x): x is File => typeof x === "object" && x !== null && "arrayBuffer" in x); if (!blobs.length) return Response.json({ error: "nothing was recorded" }, { status: 400 }); + // ONE SCREEN LINE (the screens section's per-line Record): kept by the CLI's own command, as a umtool job. + if (form.get("line") !== null) return recordLine(r.project, e, String(form.get("line")), label, blobs[0]); const texts = form.getAll("text").map(String); const paras = form.getAll("para").map((x) => Number(x)); const up = path.join(r.project.dir, ...takesDirOf(postIdOf(e)).split("/"), `.upload-${Date.now()}`); @@ -439,3 +487,53 @@ async function record(request: Request) { await rm(up, { recursive: true, force: true }); } } + +/** The umtool CLI (bin/umtool.mjs). */ +const cliPath = () => path.join(/* turbopackIgnore: true */ UMTOOL_DIR, "bin", "umtool.mjs"); +/** The jobs of one post item's screens: a line recorded, its read made. */ +const screenJobKinds = (project: string, id: string) => [`screen-line ${project} ${id}`, `screen-read ${project} ${id}`]; + +/** A screens job as the bench reads it: its state, the CLI's result (its last word), and -- ended -- the entry. */ +async function screenJobView(dir: string, id: string, j: Job) { + const result = [...j.events].reverse().find((x) => x.ev === "result") ?? null; + const said = j.log.filter((l) => !l.startsWith("**") && !l.startsWith("$ ") && !l.startsWith("---")); + const ended = j.state !== "running"; + let entry: Entry | null = null; + let token: string | null = null; + if (ended) { + const m = (await readManifest(dir)) as Record<string, unknown> | null; + entry = m ? postsOf(m).find((x) => x.id === id) ?? null : null; + token = await manifestToken(dir); + } + const err = j.state === "failed" ? String((result as { error?: string } | null)?.error ?? said.at(-1) ?? j.error ?? "failed") : null; + return { ok: true, state: j.state, result, error: err, message: said.at(-1) ?? null, ...(ended ? { entry, token } : {}) }; +} + +/** + * ONE SCREEN LINE RECORDED (lib/report/screenLineRecord.mjs): the upload kept in a scratch dir beside the post's takes, + * `umtool posts screen <p> <item> record <id> <n> --recording <it> --events` run as a umtool job, the scratch dir + * removed when the job ends (whatever its state). + */ +async function recordLine(project: { id: string; dir: string }, e: Entry, role: string, label: string, blob: File) { + const m = /^screen:([a-z0-9][a-z0-9-]{0,23}):(\d{1,2})$/.exec(role); + if (!m) return Response.json({ error: "line must be screen:<id>:<n>" }, { status: 400 }); + if (blob.size > 200 * 1024 * 1024) return Response.json({ error: "the recording is larger than 200 MB" }, { status: 413 }); + const running = runningJob(); + if (running) return Response.json({ error: `umtool is running another job (${running.kind}): keep it when that is done`, busy: true }, { status: 409 }); + const up = path.join(project.dir, ...takesDirOf(postIdOf(e)).split("/"), `.line-upload-${Date.now()}`); + await mkdir(up, { recursive: true }); + const own = /\.(wav|mp3|m4a|aac|ogg|opus|flac|webm)$/i.exec(typeof blob.name === "string" ? blob.name : "")?.[1]?.toLowerCase(); + const file = path.join(up, `line.${own ?? (/ogg/.test(blob.type) ? "ogg" : /wav/.test(blob.type) ? "wav" : "webm")}`); + await writeFile(file, new Uint8Array(await blob.arrayBuffer())); + try { + const j = startUmtoolJob(screenJobKinds(project.id, e.id)[0], [{ + label: `${e.id}: line ${m[2]} of screen ${m[1]} recorded, cleaned, converted (none picked)`, + argv: [process.execPath, cliPath(), "posts", "screen", project.id, e.id, "record", m[1], m[2], "--recording", file, "--label", label, "--events"], + cwd: path.join(/* turbopackIgnore: true */ UMTOOL_DIR, ".."), env: {}, timeoutMs: 45 * 60 * 1000, ndjson: true, + }], { project: project.id, onEnd: () => rm(up, { recursive: true, force: true }) }); + return Response.json({ ok: true, job: { id: j.id, state: j.state } }, { headers: noStore }); + } catch (err) { + await rm(up, { recursive: true, force: true }); + return fail(err); + } +} diff --git a/umtool/components/projects/PostBench.tsx b/umtool/components/projects/PostBench.tsx @@ -431,7 +431,17 @@ export default function PostBench({ /> <PostFollowPanel entry={entry} plan={plan} render={render} s={s} setS={setS} setEntry={(f) => setEntry((e) => f(e) as Entry)} /> <PostThreadPanel project={project} entry={entry} plan={plan} render={render} before={before} scene={conversation} setS={setS} setEntry={(f) => setEntry((e) => f(e) as Entry)} /> - <PostScreensPanel project={project} entry={entry} setEntry={(f) => setEntry((e) => f(e) as Entry)} /> + <PostScreensPanel + project={project} + entry={entry} + saved={saved} + setEntry={(f) => setEntry((e) => f(e) as Entry)} + onEntry={(e, t) => { + setEntry(e as Entry); + setSaved(e as Entry); + setToken(t); + }} + /> <PostNarrationPanel project={project} entry={entry} diff --git a/umtool/components/projects/PostScreensPanel.tsx b/umtool/components/projects/PostScreensPanel.tsx @@ -4,8 +4,9 @@ import { useMemo, useRef, useState } from "react"; import { SCREEN_KINDS, lineOfText, screenFromRead, screenReadLines, screenWarnings, shapeSpans, validateScreens, withoutLines } from "umtool-report-to-video/post-screens"; import { isNarrated, pickedTake } from "umtool-report-to-video/post-narration"; import { ownPictureOnly } from "umtool-report-to-video/post-item"; -import { partRoles, threadReadErrors } from "umtool-report-to-video/post-thread"; +import { lineTakeWarnings, lineTakesOf, partRoles, threadReadErrors } from "umtool-report-to-video/post-thread"; import { postFileUrl } from "./review/PostItemPlayer"; +import { ScreenLineVoice, useScreenVoice, type LineTakeOption, type ScreenVoice, type VoiceEntry } from "./ScreenLineVoice"; // --------------------------------------------------------------------------- // A POST's SCREENS ON THE BENCH (report-to-video/post-screens.mjs; docs/report-video.md, "Screens"; operator, 12 Nov: @@ -14,12 +15,19 @@ import { postFileUrl } from "./review/PostItemPlayer"; // email, a post, text), its lines transcribed by hand (pasted as `who: words | time`), who says each and on which side, // which lines are read (a line's excerpt trimmed to the words read), and whether a person checked the transcription. // No model: everything here is typed. The bench's Save writes it (updatePostItem's `screens`); the read is made with -// `umtool posts screen <p> <item> read` (the line shown here). +// `umtool posts screen <p> <item> read` (the line shown here, and its button). A read line may be RECORDED in the +// operator's voice (ScreenLineVoice: `posts screen … record`) and that take CHOSEN for it (`lineTakes`). // --------------------------------------------------------------------------- type Line = { who?: string; side?: "left" | "right"; text: string; time?: string; redact?: true }; type Read = "all" | "none" | Array<{ line: number; text?: string }>; -type Screen = { id: string; media: number; at?: [number, number]; kind: string; title?: string; source?: string; checked?: { by: string; at: string }; ref?: string; unread?: "omit" | "dim"; lines: Line[]; read: Read }; +type Screen = { id: string; media: number; at?: [number, number]; kind: string; title?: string; source?: string; checked?: { by: string; at: string }; ref?: string; unread?: "omit" | "dim"; lines: Line[]; read: Read; lineTakes?: Record<string, string> }; +type LineRecs = Array<{ role: string; screen: string; n: number; takes: Array<{ n: number; id: string; take: { steps?: Array<{ op: string; voice?: string }>; engine?: string }; current: boolean; chosen: boolean }> }>; +/** A recording's step as the select says it: recorded, cleaned, converted to its voice. */ +const stepOf = (t: { steps?: Array<{ op: string; voice?: string }>; engine?: string }) => { + const st = t.steps?.[0]; + return st?.op === "convert" ? `converted to ${String(st.voice ?? "a stock voice").split(":").pop()}` : st?.op === "enhance" ? "cleaned" : "recorded"; +}; type Media = { src: string; kind: string; seconds?: number }; type Entry = Record<string, unknown> & { id: string; media?: Media[]; screens?: Screen[] }; @@ -28,8 +36,15 @@ const r2 = (v: number) => Math.round(v * 100) / 100; /** The read as a list of `{ line, text? }` (all: every line not redacted; none: none). */ const readList = (sc: Screen): Array<{ line: number; text?: string }> => (sc.read === "all" ? sc.lines.map((l, i) => (l.redact ? null : { line: i })).filter((x): x is { line: number } => !!x) : sc.read === "none" ? [] : sc.read); -export default function PostScreensPanel({ project, entry, setEntry }: { project: string; entry: Entry; setEntry: (f: (e: Entry) => Entry) => void }) { +export default function PostScreensPanel({ project, entry, saved, setEntry, onEntry }: { project: string; entry: Entry; saved: Entry; setEntry: (f: (e: Entry) => Entry) => void; onEntry: (e: Entry, token: string | null) => void }) { const screens = useMemo(() => (Array.isArray(entry.screens) ? entry.screens : []), [entry.screens]); + // THE OPERATOR's VOICE for a line: one mic, one job; a line is recorded as SAVED (the draft differing: Save first). + const dirty = JSON.stringify(entry) !== JSON.stringify(saved); + const dirtyNow = useRef(dirty); + dirtyNow.current = dirty; + const voice = useScreenVoice({ project, id: entry.id, onEntry: onEntry as (e: VoiceEntry, t: string | null) => void, unsaved: () => dirtyNow.current }); + const recs = useMemo(() => lineTakesOf(entry) as LineRecs, [entry]); + const lineWarnings = useMemo(() => lineTakeWarnings(entry) as string[], [entry]); const media = Array.isArray(entry.media) ? entry.media : []; const errors = useMemo(() => validateScreens(entry) as string[], [entry]); // The build's guard on the read as it is (post-thread.mjs): a line edited, removed or moved under a read is refused @@ -104,11 +119,35 @@ export default function PostScreensPanel({ project, entry, setEntry }: { project setScreen={(f) => setScreen(sc.id, f)} setLines={(f) => setLines(sc.id, f)} remove={() => setScreens((list) => list.filter((s) => s.id !== sc.id))} + voice={voice} + dirty={dirty} + recs={recs} /> ))} {screens.length > 0 && ( - <p className="m-0 mt-2 font-mono text-text-2" data-post-screens-read-cmd=""> - umtool posts screen {project} {entry.id} read + <div className="mt-2 flex flex-wrap items-center gap-2"> + <button type="button" className="ink-link disabled:opacity-40" disabled={dirty || voice.job?.state === "running" || !isNarrated(entry)} title={dirty ? "Save first" : "umtool posts screen … read, as a job"} onClick={() => void voice.makeRead()} data-post-screens-make-read=""> + Make the read + </button> + <span className="font-mono text-text-2" data-post-screens-read-cmd=""> + umtool posts screen {project} {entry.id} read + </span> + </div> + )} + {voice.job && ( + <p className={`m-0 mt-1 ${voice.job.state === "failed" ? "text-[var(--color-bad,#e5484d)]" : "text-text-2"}`} data-post-screens-job={voice.job.what} data-post-screens-job-state={voice.job.state}> + {voice.job.what === "line" ? `${voice.job.role}: ` : "the read: "} + {voice.job.state === "running" ? voice.job.message ?? "running…" : voice.job.state === "failed" ? voice.job.error ?? "failed" : "done"} + </p> + )} + {voice.status && ( + <p className="m-0 mt-1 text-text-2" data-post-screens-voice-status=""> + {voice.status} + </p> + )} + {voice.mic.error && ( + <p className="m-0 mt-1 text-[var(--color-bad,#e5484d)]" data-post-screens-mic-error=""> + {voice.mic.error} </p> )} {errors.length > 0 && ( @@ -125,9 +164,9 @@ export default function PostScreensPanel({ project, entry, setEntry }: { project ))} </ul> )} - {warnings.length > 0 && ( + {warnings.length + lineWarnings.length > 0 && ( <ul className="m-0 mt-1 list-disc pl-4 text-text-2" data-post-screens-warnings=""> - {warnings.map((w, i) => ( + {[...warnings, ...lineWarnings].map((w, i) => ( <li key={i}>{w}</li> ))} </ul> @@ -137,8 +176,11 @@ export default function PostScreensPanel({ project, entry, setEntry }: { project } function ScreenEditor({ - project, entry, sc, media, paste, setPaste, setScreen, setLines, remove, + project, entry, sc, media, paste, setPaste, setScreen, setLines, remove, voice, dirty, recs, }: { + voice: ScreenVoice; + dirty: boolean; + recs: LineRecs; project: string; entry: Entry; sc: Screen; @@ -263,6 +305,7 @@ function ScreenEditor({ <th>words (the excerpt read below, when trimmed)</th> <th className="w-20">time</th> <th className="w-14">redact</th> + <th className="w-48">your voice</th> </tr> </thead> <tbody> @@ -303,6 +346,28 @@ function ScreenEditor({ × </button> </td> + <td> + {d && !l.redact && ( + <ScreenLineVoice + role={`screen:${sc.id}:${n}`} + n={n} + voice={voice} + dirty={dirty} + options={(recs.find((x) => x.screen === sc.id && x.n === n)?.takes ?? []).map((x): LineTakeOption => ({ id: x.id, label: `take ${x.n} · ${stepOf(x.take)}`, current: x.current }))} + chosen={sc.lineTakes?.[String(n)]} + onChoose={(id) => + setScreen((s) => { + const lt = { ...(s.lineTakes ?? {}) }; + if (id) lt[String(n)] = id; + else delete lt[String(n)]; + const { lineTakes: _l, ...rest } = s; + void _l; + return Object.keys(lt).length ? { ...rest, lineTakes: lt } : rest; + }) + } + /> + )} + </td> </tr> ); })} diff --git a/umtool/components/projects/ScreenLineVoice.tsx b/umtool/components/projects/ScreenLineVoice.tsx @@ -0,0 +1,188 @@ +"use client"; + +import { useCallback, useEffect, useRef, useState } from "react"; +import { useMic, ls } from "./useMic"; + +// --------------------------------------------------------------------------- +// A SCREEN LINE IN THE OPERATOR's VOICE, on the post bench's screens section (lib/report/screenLineRecord.mjs; the +// CLI's `umtool posts screen <p> <item> record <id> <n> --recording <file>`): Record / Stop / play back / Redo / Keep +// per read line -- Keep one umtool JOB (recorded, cleaned, converted to the speaker's character's stock voice, none +// picked) -- and the select that CHOOSES which take, if any, is read in the line's place (the screen's `lineTakes`, +// saved with the bench's Save: `set <id> take.<n>=`). "Make the read" is `posts screen <p> <item> read`, as a job. +// Recording is off while the draft differs from what is saved: a line is recorded as it is SAVED. +// --------------------------------------------------------------------------- + +const LABEL_KEY = "umtool.post-narration.label"; + +type Job = { id: string; what: string; role?: string; state: string; message?: string | null; error?: string | null }; +export type VoiceEntry = Record<string, unknown> & { id: string }; + +/** The section's voice: one microphone, one take at a time, one job at a time. */ +export function useScreenVoice({ project, id, onEntry, unsaved }: { project: string; id: string; onEntry: (e: VoiceEntry, token: string | null) => void; unsaved: () => boolean }) { + const mic = useMic(); + const [at, setAt] = useState<string | null>(null); + const [phase, setPhase] = useState<"idle" | "recording">("idle"); + const [takes, setTakes] = useState<Record<string, { blob: Blob; url: string }>>({}); + const [job, setJob] = useState<Job | null>(null); + const [status, setStatus] = useState<string | null>(null); + const [prompts, setPrompts] = useState<Record<string, string>>({}); + const poll = useRef<ReturnType<typeof setTimeout> | null>(null); + useEffect(() => () => { + if (poll.current) clearTimeout(poll.current); + }, []); + // What each read line says, as the read says it (the server's: its masks, the redaction, an anonymous handle's shown name). + const loadPrompts = useCallback(async () => { + const r = await fetch(`/api/report/post-narration?project=${encodeURIComponent(project)}&id=${encodeURIComponent(id)}&linePrompts=1`, { cache: "no-store" }).catch(() => null); + const j = r && r.ok ? ((await r.json().catch(() => null)) as { prompts?: Record<string, string> } | null) : null; + setPrompts(j?.prompts ?? {}); + }, [project, id]); + useEffect(() => { + void loadPrompts(); + }, [loadPrompts]); + const follow = useCallback( + (j: Job) => { + 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; entry?: VoiceEntry | null; token?: string | null; result?: { takes?: Array<{ n: number; step: string }>; notes?: string[] } | null }) : {}; + const state = v.state ?? (r ? "failed" : "running"); + setJob({ ...j, state, message: v.message ?? null, error: v.error ?? null }); + if (state === "running") { + poll.current = setTimeout(tick, 1500); + return; + } + // The entry as the job left it -- never over edits made meanwhile (they are kept; Save, then reload to see it). + const kept = unsaved(); + if (v.entry && !kept) onEntry(v.entry, v.token ?? null); + if (state === "done") { + if (j.what === "line" && j.role) { + setTakes((t) => { + const { [j.role as string]: gone, ...rest } = t; + if (gone) URL.revokeObjectURL(gone.url); + return rest; + }); + 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 setStatus("the read is made (picked)"); + if (kept) setStatus((x) => `${x ?? ""} -- your unsaved edits are kept: Save, then reload the bench to see it`); + void loadPrompts(); + } + }; + poll.current = setTimeout(tick, 800); + }, + [project, id, onEntry, loadPrompts, unsaved], + ); + const record = async (role: string) => { + if (phase !== "idle" || job?.state === "running") return; + if (!(await mic.start())) return; + setAt(role); + setPhase("recording"); + }; + const stop = async () => { + if (phase !== "recording" || !at) return; + const blob = await mic.stop(); + setPhase("idle"); + if (!blob) return; + const role = at; + setTakes((t) => { + if (t[role]) URL.revokeObjectURL(t[role].url); + return { ...t, [role]: { blob, url: URL.createObjectURL(blob) } }; + }); + }; + const redo = (role: string) => + setTakes((t) => { + const { [role]: gone, ...rest } = t; + if (gone) URL.revokeObjectURL(gone.url); + return rest; + }); + const keep = async (role: string) => { + const t = takes[role]; + if (!t) return; + setStatus(null); + const fd = new FormData(); + fd.set("project", project); + fd.set("id", id); + fd.set("line", role); + fd.set("label", ls.get(LABEL_KEY) ?? "operator"); + fd.append("part", t.blob, `line${/ogg/.test(t.blob.type) ? ".ogg" : ".webm"}`); + const r = await fetch("/api/report/post-narration", { method: "POST", body: fd }); + const j = (await r.json().catch(() => ({}))) as { job?: { id: string; state: string }; error?: string }; + if (!r.ok || !j.job) { + setJob({ id: "", what: "line", role, state: "failed", error: j.error ?? `HTTP ${r.status}` }); + return; + } + follow({ id: j.job.id, what: "line", role, state: j.job.state }); + }; + const makeRead = async () => { + 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 }) }); + const j = (await r.json().catch(() => ({}))) as { job?: { id: string; state: string }; error?: string }; + if (!r.ok || !j.job) { + setJob({ id: "", what: "read", state: "failed", error: j.error ?? `HTTP ${r.status}` }); + return; + } + follow({ id: j.job.id, what: "read", state: j.job.state }); + }; + return { mic, at, phase, takes, job, status, prompts, record, stop, redo, keep, makeRead }; +} + +export type ScreenVoice = ReturnType<typeof useScreenVoice>; + +/** The recordings of one line, as the select offers them: `{ id, label, current }`. */ +export type LineTakeOption = { id: string; label: string; current: boolean }; + +/** ONE READ LINE's voice cell: Record / Stop / play back / Redo / Keep, and the take chosen for it. */ +export function ScreenLineVoice({ role, n, voice, dirty, options, chosen, onChoose }: { role: string; n: number; voice: ScreenVoice; dirty: boolean; options: LineTakeOption[]; chosen: string | undefined; onChoose: (id: string | undefined) => void }) { + const mine = voice.at === role && voice.phase === "recording"; + const t = voice.takes[role]; + const busy = voice.job?.state === "running"; + const other = voice.phase === "recording" && voice.at !== role; + const btn = "ink-link disabled:opacity-40"; + return ( + <div className="flex flex-col gap-0.5" data-post-screen-voice={n}> + {voice.prompts[role] && ( + <span className="text-text-2" title="what you read: the line as the read says it" data-post-screen-prompt={n}> + “{voice.prompts[role]}” + </span> + )} + <div className="flex flex-wrap items-center gap-1.5"> + {!mine ? ( + <button type="button" className={btn} disabled={dirty || busy || other} title={dirty ? "Save first: a line is recorded as it is saved" : "record this line in your voice"} onClick={() => void voice.record(role)} data-post-screen-record={n}> + {t ? "Redo" : "Record"} + </button> + ) : ( + <button type="button" className={btn} onClick={() => void voice.stop()} data-post-screen-record-stop={n}> + Stop + </button> + )} + {mine && <span className="text-[var(--color-bad,#e5484d)]" data-post-screen-recording={n}>● recording</span>} + {t && !mine && ( + <> + <audio src={t.url} controls className="h-6 w-36" data-post-screen-record-playback={n} /> + <button type="button" className={btn} disabled={busy} onClick={() => voice.redo(role)} data-post-screen-record-redo={n}> + Discard + </button> + <button type="button" className={btn} disabled={busy || dirty} onClick={() => void voice.keep(role)} data-post-screen-record-keep={n}> + Keep + </button> + </> + )} + {dirty && <span className="text-text-2" data-post-screen-record-save-first={n}>save first</span>} + </div> + {options.length > 0 && ( + <label className="flex items-center gap-1"> + reads + <select value={chosen ?? ""} onChange={(e) => onChoose(e.target.value || undefined)} data-post-screen-line-take={n}> + <option value="">synthesized</option> + {options.map((o) => ( + <option key={o.id} value={o.id}> + {o.label} + {o.current ? "" : " (line changed since)"} + </option> + ))} + </select> + </label> + )} + </div> + ); +} diff --git a/umtool/e2e/post-screens.spec.ts b/umtool/e2e/post-screens.spec.ts @@ -1,5 +1,6 @@ import { test, expect, type Page } from "@playwright/test"; -import { copyFileSync, existsSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { execFileSync } from "node:child_process"; +import { copyFileSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import path from "node:path"; import { fileURLToPath } from "node:url"; import * as urls from "./urls"; @@ -10,7 +11,11 @@ import * as urls from "./urls"; // - the bench's screens section adds a screen in the post's video, takes pasted lines, a line not read, an excerpt, // the transcription checked -- saved by the bench's Save through the item's one writer, no model anywhere; // - a narrated item whose read reads the screen draws it on the card after its words: typeset, its line being read -// lit, "· transcribed" in its header and on the card's badge while it is up. +// lit, "· transcribed" in its header and on the card's badge while it is up; +// - a read line RECORDED in the operator's voice (lane/screens-2; the fake microphone's tone, never a real voice): +// Record / Stop / play back / Keep (one job: recorded, then converted by the stub editor to the speaker's +// character's stock voice -- none picked), the take CHOSEN for the line in its select and saved, then "Make the +// read" (one job): the read plays the chosen take in the line's place. Recording is off while the draft is unsaved. // Fixture: e2e/fixtures/post-narration-fixture.mjs's p-11 (a 4 s video, a 2 s take), rewritten here. // // POST_SCREENS_SHOTS=<dir> screenshots there @@ -23,21 +28,37 @@ const MANIFEST = path.join(DIR, "video.manifest.json"); const PROJECT = "reports/post-narration-fixture"; const SHOTS = process.env.POST_SCREENS_SHOTS ?? null; +/** The fake microphone's voice: a 1 kHz tone, two seconds (never a real recording). */ +const MIC_WAV = path.join(HERE, "..", ".e2e-song", "post-screens-mic.wav"); +const CHARACTERS = path.join(DIR, "narration", "characters.json"); +if (!existsSync(MIC_WAV)) { + mkdirSync(path.dirname(MIC_WAV), { recursive: true }); + execFileSync("ffmpeg", ["-v", "error", "-y", "-f", "lavfi", "-i", "sine=frequency=1000:sample_rate=48000:duration=2", "-ac", "1", MIC_WAV]); +} +test.use({ launchOptions: { args: ["--use-fake-ui-for-media-stream", "--use-fake-device-for-media-stream", `--use-file-for-fake-audio-capture=${MIC_WAV}`, "--autoplay-policy=no-user-gesture-required"] } }); + type Line = { who?: string; side?: string; text: string; time?: string; redact?: boolean }; type Screen = { id: string; media: number; at?: number[]; kind: string; lines: Line[]; read: unknown; checked?: { by: string } }; const item = (id: string) => (JSON.parse(readFileSync(MANIFEST, "utf8")) as { timeline: Array<{ id: string; screens?: Screen[] }> }).timeline.find((e) => e.id === id); test.beforeAll(() => { if (!existsSync(`${MANIFEST}.pristine`)) copyFileSync(MANIFEST, `${MANIFEST}.pristine`); + if (existsSync(CHARACTERS) && !existsSync(`${CHARACTERS}.pristine`)) copyFileSync(CHARACTERS, `${CHARACTERS}.pristine`); }); +const restoreCharacters = () => { + if (existsSync(`${CHARACTERS}.pristine`)) copyFileSync(`${CHARACTERS}.pristine`, CHARACTERS); + else rmSync(CHARACTERS, { force: true }); +}; test.beforeEach(() => { test.setTimeout(120_000); copyFileSync(`${MANIFEST}.pristine`, MANIFEST); rmSync(path.join(DIR, "revisions"), { recursive: true, force: true }); rmSync(path.join(DIR, "notes.json"), { force: true }); + restoreCharacters(); }); test.afterAll(() => { if (existsSync(`${MANIFEST}.pristine`)) copyFileSync(`${MANIFEST}.pristine`, MANIFEST); + restoreCharacters(); }); const panel = (page: Page) => page.locator("[data-post-screens-panel]"); @@ -119,3 +140,63 @@ test("a read that reads the screen draws it on the card after its words: typeset await expect(frame.locator('[data-screen-line="0"] .sname')).toHaveText("TheQuartering"); if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "post-screens-card.png") }); }); + +type Take = { file: string; engine?: string; voice?: string; script?: string; steps?: Array<{ op: string; voice?: string }>; screenLine?: { screen: string; n: number; said: string; speaker: string }; parts?: Array<{ role?: string; take?: string }> }; +type Narr = { pick?: number; script?: string; takes: Take[] }; +const narrOf = (id: string) => (JSON.parse(readFileSync(MANIFEST, "utf8")) as { timeline: Array<{ id: string; narration: Narr; screens?: Array<Screen & { lineTakes?: Record<string, string> }> }> }).timeline.find((e) => e.id === id)!; +const idOf = (t: Take) => t.file.split("/").pop()!.replace(/\.wav$/, ""); + +test("a read line in your own voice: Record / Stop / Keep (one job, none picked), the take chosen for the line and saved, Make the read plays it in the line's place", async ({ page }) => { + test.setTimeout(180_000); + const m = JSON.parse(readFileSync(MANIFEST, "utf8")); + const e = m.timeline.find((x: { id: string }) => x.id === "p-11"); + e.screens = [{ id: "s1", media: 0, at: [0.5, 3.5], kind: "dm", read: "all", lines: [{ who: "TheQuartering", text: "hop on the scale fatso call 555 201 4477" }, { who: "narrsubject", text: "you first" }] }]; + writeFileSync(MANIFEST, JSON.stringify(m, null, 2) + "\n"); + // TheQuartering's character in this video: a stock voice to convert to. + mkdirSync(path.dirname(CHARACTERS), { recursive: true }); + writeFileSync(CHARACTERS, JSON.stringify({ format: "umtool-project-characters", version: 1, characters: [{ id: "tq", name: "Jeremy", handles: ["thequartering"], synthetic: { voice: "kokoro:am_michael" }, recorded: { convert: { engine: "openvoice", voice: "kokoro:am_michael" } } }] })); + const before = narrOf("p-11").narration; + await page.setViewportSize({ width: 1366, height: 1100 }); + await page.goto(urls.postBenchHref(PROJECT, "p-11")); + const sc = page.locator('[data-post-screen="s1"]'); + await expect(sc).toBeVisible({ timeout: 15_000 }); + // What you read: the line as the read says it -- the number masked out. + await expect(sc.locator('[data-post-screen-prompt="0"]')).toContainText("hop on the scale fatso call"); + await expect(sc.locator('[data-post-screen-prompt="0"]')).not.toContainText("555"); + // Unsaved: recording is off (a line is recorded as it is saved). + await sc.locator('[data-post-screen-time="1"]').fill("12:19 PM"); + await expect(sc.locator('[data-post-screen-record="0"]')).toBeDisabled(); + await expect(sc.locator('[data-post-screen-record-save-first="0"]')).toBeVisible(); + await sc.locator('[data-post-screen-time="1"]').fill(""); + await expect(sc.locator('[data-post-screen-record="0"]')).toBeEnabled(); + // Record, Stop, play back, Keep. + await sc.locator('[data-post-screen-record="0"]').click(); + await expect(sc.locator('[data-post-screen-recording="0"]')).toBeVisible(); + await page.waitForTimeout(1200); + await sc.locator('[data-post-screen-record-stop="0"]').click(); + await expect(sc.locator('[data-post-screen-record-playback="0"]')).toHaveCount(1); + await sc.locator('[data-post-screen-record-keep="0"]').click(); + await expect(panel(page).locator('[data-post-screens-job="line"]')).toHaveAttribute("data-post-screens-job-state", "done", { timeout: 90_000 }); + const n1 = narrOf("p-11").narration; + const made = n1.takes.slice(before.takes.length); + expect(made.length).toBeGreaterThanOrEqual(2); + expect(made.every((t) => t.screenLine?.screen === "s1" && t.screenLine?.n === 0 && t.screenLine?.speaker === "TheQuartering")).toBe(true); + expect(made.every((t) => !/555|4477/.test(String(t.script)))).toBe(true); + expect(made.at(-1)!.steps?.[0]?.op).toBe("convert"); + expect(n1.pick ?? 0).toBe(before.pick ?? 0); + await expect(panel(page).locator("[data-post-screens-voice-status]")).toContainText("none picked"); + // Not chosen: the lint says so; choose the converted take, Save. + await expect(panel(page).locator("[data-post-screens-warnings]")).toContainText("has a recording no read uses"); + const converted = idOf(made.at(-1)!); + await sc.locator('[data-post-screen-line-take="0"]').selectOption(converted); + await page.locator("[data-post-bench-save]").click(); + await expect.poll(() => narrOf("p-11").screens?.[0]?.lineTakes?.["0"] ?? null).toBe(converted); + if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "post-screens-voice.png"), fullPage: true }); + // Make the read: the chosen take in the line's place, the rest synthesized (the stub editor's tts). + await panel(page).locator("[data-post-screens-make-read]").click(); + await expect(panel(page).locator('[data-post-screens-job="read"]')).toHaveAttribute("data-post-screens-job-state", "done", { timeout: 120_000 }); + const n2 = narrOf("p-11").narration; + const playing = n2.takes[n2.pick ?? 0]; + expect(playing.parts?.find((p) => p.role === "screen:s1:0")?.take).toBe(converted); + expect(playing.parts?.some((p) => p.role === "screen:s1:1" && !p.take)).toBe(true); +});