Archilyzer · Source

archilyzer

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

commit bb1762931273bdfc882bd5e78cb8c54682d20334
parent 8cf29b6c3240565633f5a3c2ba87573764241516
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Mon,  2 Nov 2026 23:58:41 -0500

umtool: a take is a source and steps -- tts, recorded, or derived from another take by the editor's enhance / convert; the bench's take tree

A take carries `source` ({kind: "tts", engine, voice, script} | {kind: "recorded",
voice} | {kind: "take", from}) and, derived, its `steps` ({op, engine?, voice?,
ranAt, job}); takes of the older shape read as their source. `posts narrate <p>
<item> --derive <n> --op enhance|convert [--engine e] [--voice v]` asks the editor's
voice-enhance / voice-convert op (askEditorOp: any media op, a job) for a NEW take,
the original kept, a parted take part by part; an op the editor has no engine for
says "not installed" (the engines are a follow-up lane's). `--delete <n>` is soft:
the file to the post's .trash/. The bench lists the takes as a tree (each source,
its derived takes under it) with Pick, Re-run, Re-record (and "then re-run the
chain" after Keep), Delete, and "run AI on take #n". A converted take is disclosed
as a voice converted to a synthetic one; a recorded take as nothing synthetic.
A synthesized or derived take's job, when done, hands the bench the entry.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
Mumtool/app/api/report/post-narration/route.ts | 69+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
Mumtool/components/projects/PostNarrationPanel.tsx | 134++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------
Mumtool/docs/cli.md | 2+-
Mumtool/docs/knobs.md | 2++
Mumtool/docs/report-video.md | 16++++++++++++++++
Mumtool/e2e/post-narration.spec.ts | 12++++++++++++
Mumtool/lib/report/postNarration.test.mjs | 39+++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/postNarrationCli.mjs | 93+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Mumtool/lib/report/postRecord.mjs | 2+-
Mumtool/lib/report/postsCli.mjs | 2+-
Mumtool/report-to-video/narrate-via-editor.mjs | 50++++++++++++++++++++++++++++++++++++++++++++------
Mumtool/report-to-video/post-narration.mjs | 76+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
12 files changed, 467 insertions(+), 30 deletions(-)

diff --git a/umtool/app/api/report/post-narration/route.ts b/umtool/app/api/report/post-narration/route.ts @@ -1,6 +1,8 @@ import { mkdir, readdir, rm, stat, writeFile } from "node:fs/promises"; import path from "node:path"; -import { isNarrated, nextTakeNumber, pickedTake, postIdOf, postNarrationKnobs, takeFileOf, takesDirOf } from "umtool-report-to-video/post-narration"; +import { + POST_DERIVE_OPS, POST_DERIVE_ROUTES, derivedFileOf, isNarrated, nextTakeNumber, pickedTake, postIdOf, postNarrationKnobs, takeFileOf, takeIdOf, takesDirOf, +} from "umtool-report-to-video/post-narration"; import { postItemPlan } from "umtool-report-to-video/post-item"; import { jobState, resultLine, startJob } from "@/lib/research/case-editor"; import { withEditNotes } from "@/lib/report/guard"; @@ -8,7 +10,7 @@ import { StaleToken, StructureRefused, fitPostItems, manifestToken, undoStructur import { resolveReport } from "@/lib/report/serve.mjs"; import { readManifest } from "@/lib/projects/report.mjs"; import { refuseCaller } from "@/lib/report/caller"; -import { measureTake } from "@/lib/report/postNarrationCli.mjs"; +import { deleteTake, measureTake } from "@/lib/report/postNarrationCli.mjs"; import { keepRecording, RECORD_LABEL_RE } from "@/lib/report/postRecord.mjs"; import { fitPostItem } from "@/lib/report/postFit.mjs"; @@ -28,6 +30,11 @@ export const dynamic = "force-dynamic"; // POST {project, op: "take", id, note?, voice?, engine?, speed?, script?} // a new take asked of the EDITOR's tts op (a job) // POST {project, op: "fit", id, linger?} the attachment's best part for the read (posts fit) +// POST {project, op: "derive", id, from, op2: enhance|convert, engine?, voice?} +// a NEW take made from take `from` by the editor's voice op +// (a job; kept by GET ?job&derive=<from>); `installed: false` +// when the editor has no engine for it +// POST {project, op: "delete", id, take} a take out of the list, its file to .trash/ (soft) // POST {project, op: "undo"} the last structural write undone const noStore = { "cache-control": "no-store" }; @@ -70,13 +77,34 @@ export async function GET(request: Request) { const meas = await measureTake(abs); const note = q.get("note"); const script = q.get("script") ?? String(e.narration?.script ?? ""); + const derive = q.get("derive"); + if (derive !== null) { + // A derived take: source the take it came from, its step recorded, its parts (renamed) kept. + const takes = (e.narration?.takes ?? []) as Array<{ file: string; voice?: string; script?: string; parts?: Array<{ n: number }> }>; + const from = takes[Number(derive)]; + if (!from) return Response.json({ state: "failed", error: `no take ${derive}` }, { headers: noStore }); + const op = String(q.get("op") ?? ""); + const engine = q.get("engine"); + const voice = q.get("voice"); + const partsRel = rel.replace(/\.wav$/, ".parts"); + const derived = { + file: rel, engine: "derived", voice: voice ?? from.voice ?? "?", seconds: meas.seconds, source: { kind: "take", from: takeIdOf(from) }, + steps: [{ op, ...(engine ? { engine } : {}), ...(voice ? { voice } : {}), ranAt: new Date().toISOString(), job }], + script: from.script ?? script, at: new Date().toISOString(), jobId: job, ...(Number.isFinite(meas.lufs) ? { lufs: meas.lufs } : {}), + ...(Array.isArray(from.parts) ? { parts: from.parts.map((p) => ({ ...p, file: `${partsRel}/p${String(p.n).padStart(2, "0")}.wav` })) } : {}), + }; + const { result } = await withEditNotes(r.project, async () => updatePostNarration(r.project.dir, id, { addTake: derived }, { token: await manifestToken(r.project.dir) })); + return Response.json({ state: "done", file: rel, entry: result.entry, token: result.token }, { headers: noStore }); + } const take = { file: rel, engine: res.engine ?? q.get("engine") ?? "orpheus", voice: res.voice ?? q.get("voice") ?? "zac", seconds: meas.seconds, + source: { kind: "tts", engine: res.engine ?? q.get("engine") ?? "orpheus", voice: res.voice ?? q.get("voice") ?? "zac", script }, script, at: new Date().toISOString(), jobId: job, ...(Number.isFinite(meas.lufs) ? { lufs: meas.lufs } : {}), ...(note ? { note } : {}), }; - await withEditNotes(r.project, async () => + const { result } = await withEditNotes(r.project, async () => updatePostNarration(r.project.dir, id, { addTake: take, ...(script !== e.narration?.script ? { script } : {}) }, { token: await manifestToken(r.project.dir) }), ); + return Response.json({ state: "done", file: rel, entry: result.entry, token: result.token }, { headers: noStore }); } return Response.json({ state: "done", file: rel }, { headers: noStore }); } catch (err) { @@ -140,6 +168,39 @@ export async function POST(request: Request) { const jobId = await startJob("/api/ops/tts", { text: script, engine, voice, out: path.join(r.project.dir, ...rel.split("/")), ...(speed ? { speed } : {}) }); return Response.json({ ok: true, jobId, file: rel, engine, voice, script }, { headers: noStore }); } + if (body.op === "derive") { + const takes = (e.narration?.takes ?? []) as Array<{ file: string; parts?: Array<{ n: number; file?: string }> }>; + const from = Number(body.from); + const t = takes[from]; + if (!t) return Response.json({ error: `${id} has no take ${from + 1}` }, { status: 404 }); + const op = String(body.op2 ?? ""); + if (!(POST_DERIVE_OPS as readonly string[]).includes(op)) return Response.json({ error: `op2 is one of ${POST_DERIVE_OPS.join(", ")}` }, { status: 400 }); + const engine = body.engine ? String(body.engine) : null; + const voice = body.voice ? String(body.voice) : null; + const pid = postIdOf(e); + const dir = path.join(r.project.dir, ...takesDirOf(pid).split("/")); + await mkdir(dir, { recursive: true }); + const rel = derivedFileOf(pid, nextTakeNumber(e, await readdir(dir).catch(() => [])), op, engine ?? voice ?? "default"); + const abs = (x: string) => path.join(r.project.dir, ...x.split("/")); + const partsRel = rel.replace(/\.wav$/, ".parts"); + const parts = Array.isArray(t.parts) && t.parts.every((p) => typeof p.file === "string") + ? t.parts.map((p) => ({ file: abs(String(p.file)), out: abs(`${partsRel}/p${String(p.n).padStart(2, "0")}.wav`) })) + : null; + try { + const jobId = await startJob(POST_DERIVE_ROUTES[op as keyof typeof POST_DERIVE_ROUTES], { file: abs(t.file), out: abs(rel), ...(engine ? { engine } : {}), ...(voice ? { voice } : {}), ...(parts ? { parts } : {}) }); + return Response.json({ ok: true, jobId, file: rel, from, op: op, engine, voice }, { headers: noStore }); + } catch (err) { + const status = (err as { status?: number }).status ?? 502; + const msg = err instanceof Error ? err.message : String(err); + // The editor has no engine for it yet (a follow-up lane adds voice-enhance / voice-convert): say so, plainly. + if (status === 404 || /not installed|no engine|unknown|not found|404/i.test(msg)) return Response.json({ ok: false, installed: false, error: `the editor has no ${op} engine yet (not installed)` }, { status: 200, headers: noStore }); + return Response.json({ error: msg }, { status }); + } + } + if (body.op === "delete") { + const { result } = { result: await deleteTake(r.project, e, Number(body.take)) }; + return Response.json({ ok: true, entry: result.entry, token: result.token }, { headers: noStore }); + } if (body.op === "fit") { const linger = body.linger === undefined || body.linger === null ? null : Number(body.linger); const f = await fitPostItem(e, (m.render ?? {}) as Record<string, unknown>, r.project.dir, { linger }); @@ -149,7 +210,7 @@ export async function POST(request: Request) { const now = postsOf(after).find((x) => x.id === id); return Response.json({ ok: true, window: f.window, entry: now ?? null, token: result.token }, { headers: noStore }); } - return Response.json({ error: "op is set, take, fit or undo" }, { status: 400 }); + return Response.json({ error: "op is set, take, derive, delete, fit or undo" }, { status: 400 }); } catch (err) { return fail(err); } diff --git a/umtool/components/projects/PostNarrationPanel.tsx b/umtool/components/projects/PostNarrationPanel.tsx @@ -6,7 +6,7 @@ import Waveform from "@/components/Waveform"; import { buttonVariants } from "@/components/ui/button"; import { cn } from "@/lib/utils"; import { postBenchHref } from "@/lib/hrefs"; -import { POST_NARRATION_DEFAULTS, mixPhaseAt, pickedTake, postNarrationKnobs, scriptParts } from "umtool-report-to-video/post-narration"; +import { POST_DERIVE_OPS, POST_NARRATION_DEFAULTS, mixPhaseAt, pickedTake, postNarrationKnobs, scriptParts, takeIdOf, takeSourceOf } from "umtool-report-to-video/post-narration"; import { projectFileMedia } from "./bench/benchMedia"; import { usePeaks } from "./bench/usePeaks"; import { useNotes } from "@/lib/annotations/useNotes"; @@ -32,7 +32,8 @@ import type { PostPlan } from "./review/PostItemPlayer"; // `umtool posts narrate` runs; the bench takes the entry it returns. // --------------------------------------------------------------------------- -type Take = { file: string; engine?: string; voice?: string; seconds: number; note?: string; script?: string; label?: string; parts?: Array<{ n: number; para?: number; text?: string; start: number; seconds: number; file?: string }> }; +type Step = { op: string; engine?: string; voice?: string }; +type Take = { file: string; engine?: string; voice?: string; seconds: number; note?: string; script?: string; label?: string; source?: { kind: string; from?: string; voice?: string; engine?: string }; steps?: Step[]; parts?: Array<{ n: number; para?: number; text?: string; start: number; seconds: number; file?: string }> }; type Narration = { script?: string; takes?: Take[]; pick?: number; approved?: boolean; off?: boolean; window?: { media: number; start: number; end: number; score?: number; reason?: string } } & Record<string, unknown>; type Entry = Record<string, unknown> & { id: string; narration?: Narration; media?: Array<Record<string, unknown> & { src: string; kind: string; seconds?: number; start?: number; end?: number }> }; type Progress = { items: Array<{ id: string; n: number; plays: string; approved: boolean }>; counts: { posts: number; recorded: number; synthesized: number; none: number; approved: number } }; @@ -261,6 +262,13 @@ export default function PostNarrationPanel({ setBlobs([]); setPart(0); setStatus(`kept ${j.take?.file ?? "the recording"} (picked)`); + // Re-record, then re-run the chain: the steps the last recording's derived takes applied, on the new one. + if (rerunChain) { + const newIndex = (j.entry.narration?.takes ?? []).length - 1; + const lastRecorded = [...takes.keys()].reverse().find((i) => takeSourceOf(takes[i]).kind === "recorded"); + const steps = lastRecorded === undefined ? [] : (tree.kids.get(lastRecorded) ?? []).flatMap((k) => takes[k].steps ?? []); + if (steps.length) setChain(steps.map((step) => ({ from: newIndex, step }))); + } }; // R records, S stops (Space is the bench's play). useEffect(() => { @@ -281,7 +289,21 @@ export default function PostNarrationPanel({ // ---- a re-take with direction (the editor's tts op) -------------------------- const [dir, setDir] = useState({ note: "", voice: "", speed: "" }); - const [job, setJob] = useState<{ id: string; file: string; note: string; script: string; state: string; error?: string; polls?: number } | null>(null); + const [job, setJob] = useState<{ id: string; file: string; note: string; script: string; state: string; error?: string; polls?: number; derive?: { from: number; op: string; engine?: string | null; voice?: string | null } } | null>(null); + // Derived takes still to make after a re-record ("re-run the chain"), from the new take. + const [chain, setChain] = useState<Array<{ from: number; step: Step }>>([]); + const [rerunChain, setRerunChain] = useState(true); + const [notInstalled, setNotInstalled] = useState<string | null>(null); + const derive = async (from: number, step: Step) => { + setNotInstalled(null); + const j = (await post({ op: "derive", from, op2: step.op, engine: step.engine || undefined, voice: step.voice || undefined })) as ({ jobId?: string; file?: string; installed?: boolean; error?: string } & Record<string, unknown>) | null; + if (j && j.installed === false) { + setNotInstalled(j.error ?? `the editor has no ${step.op} engine yet`); + setChain([]); + return; + } + if (j?.jobId && j.file) setJob({ id: j.jobId, file: j.file, note: "", script, state: "running", derive: { from, op: step.op, engine: step.engine ?? null, voice: step.voice ?? null } }); + }; const retake = async () => { const j = await post({ op: "take", note: dir.note || undefined, voice: dir.voice || undefined, speed: dir.speed ? Number(dir.speed) : undefined, script }); if (j?.jobId && j.file) setJob({ id: j.jobId, file: j.file, note: dir.note, script, state: "running" }); @@ -289,13 +311,17 @@ export default function PostNarrationPanel({ useEffect(() => { if (!job || job.state !== "running") return; const t = setTimeout(async () => { - const q = new URLSearchParams({ project, id: entry.id, job: job.id, file: job.file, script: job.script, ...(job.note ? { note: job.note } : {}) }); + const q = new URLSearchParams({ + 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 } : {}) } : {}), + }); const r = await fetch(`/api/report/post-narration?${q}`, { cache: "no-store" }); - const j = (await r.json().catch(() => ({}))) as { state?: string; error?: string }; + const j = (await r.json().catch(() => ({}))) as { state?: string; error?: string; entry?: Entry; token?: string }; if (j.state === "done") { setJob({ ...job, state: "done" }); setStatus(`new take ${job.file} (picked)`); - window.location.reload(); + 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: ask again. else setJob({ ...job, polls: (job.polls ?? 0) + 1 }); @@ -303,6 +329,35 @@ export default function PostNarrationPanel({ return () => clearTimeout(t); }, [job, project, entry.id]); + useEffect(() => { + if (!chain.length || job?.state === "running") return; + const [first, ...rest] = chain; + setChain(rest); + void derive(first.from, first.step); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [chain, job?.state]); + + // The takes as a small tree: each source take (synthesized, recorded) with the takes derived from it under it. + const tree = useMemo(() => { + const byId = new Map(takes.map((t, i) => [takeIdOf(t), i])); + const kids = new Map<number, number[]>(); + const roots: number[] = []; + takes.forEach((t, i) => { + const src = takeSourceOf(t) as { kind: string; from?: string }; + const up = src.kind === "take" && src.from ? byId.get(src.from) : undefined; + if (up === undefined) roots.push(i); + else kids.set(up, [...(kids.get(up) ?? []), i]); + }); + const out: Array<{ i: number; depth: number }> = []; + const walk = (i: number, depth: number) => { + out.push({ i, depth }); + for (const k of kids.get(i) ?? []) walk(k, depth + 1); + }; + roots.forEach((i) => walk(i, 0)); + return { rows: out, kids }; + }, [takes]); + const [deriveDraft, setDeriveDraft] = useState<{ op: string; engine: string; voice: string }>({ op: "enhance", engine: "", voice: "" }); + // ---- the lanes ------------------------------------------------------------------ const vi = (entry.media ?? []).findIndex((m) => m.kind === "video"); const video = vi >= 0 ? entry.media![vi] : null; @@ -590,6 +645,10 @@ export default function PostNarrationPanel({ Discard </button> {phase === "recording" && <span className="text-red-400" data-post-recording="">● recording part {part + 1}</span>} + <label className="ml-auto flex items-center gap-1 text-text-2" title="after Keep, the steps the last recording's derived takes applied (enhance, convert) run again on the new one"> + <input type="checkbox" checked={rerunChain} onChange={(e) => setRerunChain(e.target.checked)} data-post-record-rerun-chain="" /> + then re-run the chain + </label> </div> </section> @@ -609,18 +668,44 @@ export default function PostNarrationPanel({ Undo last change </button> </div> - <ul className="m-0 list-none space-y-1 p-0"> - {takes.map((t, i) => ( - <li key={t.file} className={cn("rounded px-2 py-1", picked?.index === i && "bg-[var(--color-sel)]/15")} data-post-take={i + 1} data-post-take-picked={picked?.index === i ? "1" : undefined} data-post-take-engine={t.engine}> + <ul className="m-0 list-none space-y-1 p-0" data-post-take-tree=""> + {tree.rows.map(({ i, depth }) => { + const t = takes[i]; + const src = takeSourceOf(t) as { kind: string; voice?: string; engine?: string }; + const step = (t.steps ?? [])[0]; + return ( + <li key={t.file} className={cn("rounded px-2 py-1", picked?.index === i && "bg-[var(--color-sel)]/15")} style={{ marginLeft: depth * 20 }} data-post-take={i + 1} data-post-take-picked={picked?.index === i ? "1" : undefined} data-post-take-engine={t.engine} data-post-take-source={src.kind} data-post-take-depth={depth}> <div className="flex flex-wrap items-center gap-2"> - <span className="font-mono">#{i + 1}</span> - <span>{t.engine === "recorded" ? `recorded · ${t.voice ?? t.label ?? "?"}` : `${t.engine ?? "?"} · ${t.voice ?? "?"}`}</span> + <span className="font-mono">{depth ? "└ " : ""}#{i + 1}</span> + <span> + {src.kind === "recorded" ? `recorded · ${src.voice ?? t.voice ?? "?"}` : src.kind === "take" ? `${step?.op ?? "derived"}${step?.engine ? ` · ${step.engine}` : ""}${step?.voice ? ` → ${step.voice}` : ""}` : `${t.engine ?? "?"} · ${t.voice ?? "?"}`} + </span> <span className="tabular-nums">{Number(t.seconds).toFixed(1)} s</span> {/* eslint-disable-next-line jsx-a11y/media-has-caption */} <audio src={fileUrl(project, t.file)} controls preload="none" className="h-7" data-post-take-audio={i + 1} /> <button type="button" className={btn} disabled={picked?.index === i} onClick={() => void set({ pick: i })} data-post-take-pick={i + 1}> Pick </button> + {src.kind === "take" && step && ( + <button type="button" className={btn} disabled={job?.state === "running"} onClick={() => void derive(takes.findIndex((x) => takeIdOf(x) === (t.source as { from?: string }).from), step)} data-post-take-rerun={i + 1}> + Re-run + </button> + )} + {src.kind === "recorded" && ( + <button type="button" className={btn} onClick={() => document.querySelector("[data-post-record]")?.scrollIntoView({ behavior: "smooth" })} data-post-take-rerecord={i + 1}> + Re-record + </button> + )} + <button + type="button" + className={btn} + onClick={() => { + if (window.confirm(`Delete take #${i + 1}? Its file goes to the post's .trash/ folder.`)) void post({ op: "delete", take: i }); + }} + data-post-take-delete={i + 1} + > + Delete + </button> {t.note && <span className="text-text-2">“{t.note}”</span>} </div> {(t.parts?.length ?? 0) > 1 && ( @@ -639,9 +724,34 @@ export default function PostNarrationPanel({ </ol> )} </li> - ))} + ); + })} {!takes.length && <li className="text-text-2">no take yet: record one above, or ask the editor for a placeholder below</li>} </ul> + {picked && ( + <div className="flex flex-wrap items-center gap-1.5" data-post-derive=""> + <span className="micro">run AI on take #{picked.index + 1}</span> + <select value={deriveDraft.op} onChange={(e) => setDeriveDraft({ ...deriveDraft, op: e.target.value })} data-post-derive-op=""> + {POST_DERIVE_OPS.map((o) => ( + <option key={o} value={o}> + {o === "enhance" ? "enhance (denoise, level)" : "convert (to a stock synthetic voice)"} + </option> + ))} + </select> + <input value={deriveDraft.engine} onChange={(e) => setDeriveDraft({ ...deriveDraft, engine: e.target.value })} placeholder="engine" className="w-24 rounded border border-seam bg-ground px-1 py-0.5" data-post-derive-engine="" /> + {deriveDraft.op === "convert" && ( + <input value={deriveDraft.voice} onChange={(e) => setDeriveDraft({ ...deriveDraft, voice: e.target.value })} placeholder="stock voice" className="w-24 rounded border border-seam bg-ground px-1 py-0.5" data-post-derive-voice="" /> + )} + <button type="button" className={btn} disabled={job?.state === "running"} onClick={() => void derive(picked.index, { op: deriveDraft.op, ...(deriveDraft.engine ? { engine: deriveDraft.engine } : {}), ...(deriveDraft.voice ? { voice: deriveDraft.voice } : {}) })} data-post-derive-run=""> + Run → a new take + </button> + {notInstalled && ( + <span className="text-[var(--color-warn,#c80)]" data-post-derive-not-installed=""> + {notInstalled} + </span> + )} + </div> + )} <label className="block"> <span className="micro">script — the post, verbatim; add emotion with &lt;sigh&gt; &lt;laugh&gt; &lt;chuckle&gt; &lt;groan&gt; &lt;gasp&gt;</span> <textarea value={script} onChange={(e) => setScript(e.target.value)} rows={4} className="mt-1 w-full rounded border border-seam bg-ground px-2 py-1" data-post-script="" /> diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md @@ -83,7 +83,7 @@ Inbox cannot disagree about what is wrong with one. | `posts add <project> <archive-channel>/<postId> [--attach <clipId>] [--flag F] [--author A] [--id ID] [--thread] [--crop <px>] [--dry-run] [--json]` | a **post card** from the corpus's posts archive (`channels/<slug>/posts/*.jsonl`): its words, date, link and handle; id `x-<postId>` (`bsky-`, `post-`); the author an earlier post by the same handle carries in the cut, else the archive's. Its capture (`posts-media/<postId>/`: `shot.png`, `capture.json`, the post's pictures) is copied to the project's `posts-media/<slug>/<postId>/` — or used where it is, when that folder links the channel's captures; never copied through a link anywhere else. Then `upsertPost` (a post with the id is replaced, its `attachTo` kept). **Exit 1** with no screenshot, naming the `pnpm ops capture-posts` to run. `--thread`: the entry gets `thread: true` (a reply drawn with the post it answers; `shot-thread.png` is copied with the rest, and with none yet it prints the `"thread": true` capture to run). `--crop <px>`: the post's own crop (`shotMaxHeight`). A post that quotes another, reposts one or carries media is added with a `WARNING:` line (`--json`: `warnings`) — its screenshot shows them, by the post's own data. Play the cut's **Add post** runs this same write ([knobs.md](knobs.md#add-post-a-post-card-from-play-the-cut)) | | `posts reel <project> --channel <slug> [--channel <slug> …] [--since YYYY-MM-DD] [--until YYYY-MM-DD] [--own] [--with-media] [--replies include\|only\|exclude] [--order chrono\|reverse] [--limit N] [--after <id\|->] [--dry-run] [--json]` | **POST ITEMS** ([report-video.md](report-video.md#post-items-a-post-as-an-entry-of-the-cut)): each archived post an entry of the cut -- its card drawn from the archive row (snapshotted), its attachments copied into `posts-media/` and played in it. The channels are read as one archive, merged in time order, de-duplicated by post id (`--channel ObviousRises-x --channel ObviousRises-x-replies`); `--own` the accounts' own posts (their config's `socialHandle`, no reposts); `--with-media` only posts whose capture holds an attachment; `--replies` keeps, keeps only or drops replies (a reply carries the posts it answers from the archive, else the capture's thread shot, else a "Replying to" line). A post the cut already plays (by its id, a repost's original, a repost of it) is skipped, so a **re-run adds only what is new**; the rest goes in in ONE write (one undo point: `timeline <p> undo`), at the end unless `--after` | | `posts set-item <project> <item> [hold=<s>\|off] [layout=sequence\|grid] [redact=on\|off\|auto] [fit=read[:<linger>]] [media.<i>.start=<s>] [media.<i>.end=<s>] [media.<i>.trim=off] [media.<i>.mute=on\|off] [media.<i>.crop=x,y,w,h\|off] [media.<i>.push=on\|off] [--json]` | a **post item's knobs** (the post bench's writer, `updatePostItem`; [knobs.md](knobs.md#a-post-item-a-post-as-an-entry-of-the-cut)): `<item>` is its id or the post's id; refused in the build's words | -| `posts narrate <project> --import [--dry-run] [--json]` · `--list` · `<item> [--script "…"] [--pick <n>] [--approve\|--unapprove] [--off\|--on] [lead= tail= ramp= linger= clip=read\|full wet= lowpass= duck=on\|off short=hold\|loop attach=under\|after lufs=]` · `<item> --take [--note "…"] [--voice v] [--engine e] [--speed s] [--script "…"]` · `--all --draft-scripts [--force]` · `--all --take [--limit N]` · `--cut <k=v>…` | a **narrated post item** ([report-video.md](report-video.md#narrated-post-items), [knobs.md](knobs.md#a-narrated-post-item)): `--import` reads `narration/posts/index.json` (`[{id, entry, script, takes: [{file, engine, voice, seconds}], pick}]`, and a take's `take-<n>.parts.json`) into the cut in ONE write, measuring each take (length, loudness); a re-run adds only takes not there. `--take` asks the EDITOR for a new take (`POST /api/ops/tts`, its `out` the next `narration/posts/<postId>/take-<n>.<engine>-<voice>.wav`; a job, waited for; `ARCHILYZER_EDITOR_URL`, `WORKER_TOKEN`) and picks it, its `--note` kept with it; `--pick <n>` is the take's number as `--list` shows it. A new script or pick takes the approval away. `--all --draft-scripts` writes every post's words as its script, VERBATIM (cleaned only to be spoken: @handles, links, emoji dropped; `plan(s)` → plans, `w/` → with, `&` → and; paragraphs kept). `--cut` sets `render.postNarration`. Refused in the build's words (**exit 1**) | +| `posts narrate <project> --import [--dry-run] [--json]` · `--list` · `<item> [--script "…"] [--pick <n>] [--approve\|--unapprove] [--off\|--on] [lead= tail= ramp= linger= clip=read\|full wet= lowpass= duck=on\|off short=hold\|loop attach=under\|after lufs=]` · `<item> --take [--note "…"] [--voice v] [--engine e] [--speed s] [--script "…"]` · `<item> --derive <n> --op enhance\|convert [--engine e] [--voice v]` · `<item> --delete <n>` · `--all --draft-scripts [--force]` · `--all --take [--limit N]` · `--cut <k=v>…` | a **narrated post item** ([report-video.md](report-video.md#narrated-post-items), [knobs.md](knobs.md#a-narrated-post-item)): `--import` reads `narration/posts/index.json` (`[{id, entry, script, takes: [{file, engine, voice, seconds}], pick}]`, and a take's `take-<n>.parts.json`) into the cut in ONE write, measuring each take (length, loudness); a re-run adds only takes not there. `--take` asks the EDITOR for a new take (`POST /api/ops/tts`, its `out` the next `narration/posts/<postId>/take-<n>.<engine>-<voice>.wav`; a job, waited for; `ARCHILYZER_EDITOR_URL`, `WORKER_TOKEN`) and picks it, its `--note` kept with it; `--pick <n>` is the take's number as `--list` shows it. `--derive <n>` makes a NEW take from take n through the editor's `voice-enhance` / `voice-convert` op (a stock synthetic voice; "not installed" until the editor has the engine), the original kept; `--delete <n>` moves a take's file to the post's `.trash/`. A new script or pick takes the approval away. `--all --draft-scripts` writes every post's words as its script, VERBATIM (cleaned only to be spoken: @handles, links, emoji dropped; `plan(s)` → plans, `w/` → with, `&` → and; paragraphs kept). `--cut` sets `render.postNarration`. Refused in the build's words (**exit 1**) | | `posts fit <project> [--all \| <item> …] [--linger <s>] [--dry-run] [--json]` · `posts set-item <project> <item> fit=read[:<linger>]` | narrated posts' video attachments cut to their **best part** for the read (lead + take + tail + linger): a scored scan of the sound (loudness, its peaks), the speech (a transcript) and the scene cuts, the start snapped to a pause or a cut, recorded with why (`narration.window`) -- ONE write; each post's old and new length printed. A video no longer than the read is left as it is | | `posts avatar <project> [<handle> <image-file> \| <handle> off] [--json]` · `posts avatars <project> [--dry-run] [--json]` | the **authors' pictures** (`postAvatars`): `avatar` copies a picture into `posts-media/_avatars/` for every card that draws that handle (manual; never replaced by the archive's), `off` clears it, no handle lists them; `avatars` copies the archive's (the channels' `posts-media/_avatars/avatars.json`, capture-posts') for every author the cut's cards draw unblurred that it has none of. A blurred author never shows one | | `new <slug> --from-posts <channel> [--channel <more>…] [--since D] [--until D] [--own] [--with-media] [--replies …] [--order …] [--limit N]` | a **posts reel**: the scaffold with the deck on (no `siteOrigin`: each post's QR opens the post, `deck.qr.links: "original"`), then `posts reel` with the same filters | diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md @@ -673,6 +673,8 @@ the shape, the mix, recordings, parts, the best part). One writer for a post's n | `narration.script` — what is read: the post, verbatim; Orpheus's tags for emotion | post bench, **script**, **Save script** | `umtool posts narrate <p> <item> --script "…"` · every post's drafted: `--all --draft-scripts [--force]` | `op: "set", patch: {script}` | | a recorded take — your own read, part by part, kept as `take-<n>.recorded-<label>.wav`, picked | post bench, **record your read**: the mic, the level, **Record** (R) / **Stop** (S) / **Redo part** / **Next part**, **Keep** / **Discard**, **voice** (the label, default `operator`) | — | `POST` multipart `{project, id, label, script?, part[], text[], para[]}` | | a synthesized take — the editor's tts op, with direction | post bench, **Re-take with direction** (a note, a voice) | `umtool posts narrate <p> <item> --take [--note "…"] [--voice v] [--engine e] [--speed s]` · every missing one: `--all --take` | `op: "take"` → `{jobId, file}` · `GET ?project&id&job&file` keeps it when done | +| a derived take — a take run through the editor's `enhance` or `convert` (a stock synthetic voice) into a NEW take, the original kept; "not installed" until the editor has the engine | post bench, **run AI on take #n** (the op, an engine, a stock voice) → **Run → a new take**; a derived take's **Re-run**; a recording's **Re-record** with **then re-run the chain** | `umtool posts narrate <p> <item> --derive <n> --op enhance\|convert [--engine e] [--voice v]` | `op: "derive", from, op2, engine?, voice?` → `{jobId, file}` (or `{installed: false}`) · `GET ?project&id&job&file&derive=<from>&op=…` keeps it | +| delete a take (soft: its file to the post's `.trash/`) | post bench, the take's **Delete** | `--delete <n>` | `op: "delete", take` (an index) | | `narration.pick` — the take that plays | post bench, the take's **Pick** | `--pick <n>` (1 = the first, as `--list` shows) | `patch: {pick}` (an index) | | `narration.approved` — the picked take on this script, approved (a new script or pick takes it away) | post bench, **approved** | `--approve` · `--unapprove` | `patch: {approved: true \| null}` | | `narration.off` — keep it all, play un-narrated | post bench, **narrated** | `--off` · `--on` | `patch: {off: true \| null}` | diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md @@ -593,6 +593,22 @@ guest's voice another), picked. It plays, mixes and renders exactly as a synthes take. A recorded take carries no synthetic-voice disclosure; a synthesized one's is the cut's (`readCutDisclosure`). +**What a take is** (operator: "pure AI voice, record voice, and run AI on recorded voice, +and re-run or re-record"): a `source` and the `steps` applied to it — `{kind: "tts", engine, +voice, script}` (the editor's tts), `{kind: "recorded", voice}` (the bench's recording) or +`{kind: "take", from: <take id>}` (DERIVED: a new take made from another, `steps: [{op, +engine?, voice?, params?, ranAt, job}]`). A derived take never overwrites the one it came +from; a parted take is processed part by part (its parts kept). The ops are the editor's, +each a job like tts: `enhance` (denoise, level, de-reverb; `POST /api/ops/voice-enhance`) +and `convert` (voice conversion: the performance kept, the timbre swapped for a STOCK +synthetic voice, never a real person's; `/api/ops/voice-convert`, disclosed as "voice +converted to a synthetic voice"). The engines are a follow-up lane's: until the editor has +one, the bench and `posts narrate --derive` say "not installed" and write nothing. The +bench lists the takes as a tree (each source take, its derived takes under it) with +**Pick**, **Re-run** (the same step from the same source, a new take), **Re-record** (a +recording's: record again; **then re-run the chain** re-applies the steps its derived +takes had) and **Delete** (soft: the file to `narration/posts/<postId>/.trash/`). + **The best part of an attachment** (`umtool posts fit`, the bench's **Re-pick best**; `lib/report/postFit.mjs`): a video longer than the read is cut to a window of the read's length chosen by a scored scan — its sound's RMS (the window's mean and its diff --git a/umtool/e2e/post-narration.spec.ts b/umtool/e2e/post-narration.spec.ts @@ -48,6 +48,7 @@ test.beforeEach(() => { rmSync(path.join(DIR, "notes.json"), { force: true }); for (const f of ["take-2.orpheus-zac.wav", "take-2.recorded-operator.wav", "take-3.recorded-operator.wav"]) rmSync(path.join(DIR, "narration", "posts", "11", f), { force: true }); rmSync(path.join(DIR, "narration", "posts", "11", "take-2.recorded-operator.parts"), { recursive: true, force: true }); + rmSync(path.join(DIR, "narration", "posts", "11", ".trash"), { recursive: true, force: true }); }); const root = (page: Page) => page.locator("[data-play-cut]"); @@ -139,6 +140,17 @@ test("the post bench: the lanes, a re-take with direction (the editor's tts job) await page.locator('[data-post-mix="wet"]').fill("0.2"); await page.locator('[data-post-mix="wet"]').blur(); await expect.poll(() => (timeline().find((e) => e.id === "p-11")!.narration as Record<string, unknown>).wet).toBe(0.2); + // Run AI on a take: the stub editor has no voice ops -- "not installed", said plainly, nothing written. + await page.locator("[data-post-derive-op]").selectOption("enhance"); + await page.locator("[data-post-derive-run]").click(); + await expect(page.locator("[data-post-derive-not-installed]")).toContainText("not installed"); + expect(narr("p-11").takes).toHaveLength(2); + // Delete, softly: the take out of the list, its file in .trash/. + page.once("dialog", (d) => void d.accept()); + await page.locator('[data-post-take-delete="2"]').click(); + await expect(page.locator("[data-post-take]")).toHaveCount(1); + expect(existsSync(path.join(DIR, "narration", "posts", "11", "take-2.orpheus-zac.wav"))).toBe(false); + if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "post-narration-bench-takes.png"), fullPage: true }); }); test.describe("the recording session", () => { diff --git a/umtool/lib/report/postNarration.test.mjs b/umtool/lib/report/postNarration.test.mjs @@ -247,3 +247,42 @@ test("a RECORDING kept part by part: each trimmed of its silence, joined with th assert.equal(n.takes[1].voice, "operator"); assert.equal(postItemPlan((await manifest(p)).timeline[0]).narration.seconds, r.take.seconds); }); + +test("a DERIVED take: run through the editor's op into a new take, the original kept; not installed says so; delete is soft", async () => { + const { deriveTake, deleteTake } = await import("./postNarrationCli.mjs"); + const p = await project("der", [item("1")]); + await mkdir(path.join(p.dir, "narration", "posts", "1"), { recursive: true }); + wav(path.join(p.dir, "narration", "posts", "1", "take-1.recorded-operator.wav"), 1.5); + await updatePostNarration(p.dir, "p-1", { script: "x", addTake: { file: "narration/posts/1/take-1.recorded-operator.wav", engine: "recorded", voice: "operator", seconds: 1.5, source: { kind: "recorded", voice: "operator" } } }); + const asked = []; + const ask = async (route, body) => { + asked.push({ route, body }); + wav(body.out, 1.4); + return { jobId: "job-d", result: null }; + }; + const r = await deriveTake(p, (await manifest(p)).timeline[0], { from: 0, op: "convert", engine: "rvc", voice: "stock-a", ask }); + assert.equal(asked[0].route, "/api/ops/voice-convert"); + assert.ok(asked[0].body.file.endsWith("take-1.recorded-operator.wav")); + assert.equal(r.take.file, "narration/posts/1/take-2.convert-rvc.wav"); + assert.deepEqual(r.take.source, { kind: "take", from: "take-1.recorded-operator" }); + assert.equal(r.take.steps[0].op, "convert"); + const n = (await manifest(p)).timeline[0].narration; + assert.equal(n.takes.length, 2); + assert.equal(n.pick, 1); + const { postNarrationDisclosure, rootTakeOf } = await import("umtool-report-to-video/post-narration"); + assert.equal(rootTakeOf(n.takes, n.takes[1]), n.takes[0]); + assert.equal(postNarrationDisclosure((await manifest(p)).timeline[0]), "Narration: voice converted to a synthetic voice (rvc · stock-a)"); + // An op the editor has no engine for. + const { OpNotInstalled } = await import("umtool-report-to-video/narrate-via-editor"); + await assert.rejects( + deriveTake(p, (await manifest(p)).timeline[0], { from: 0, op: "enhance", ask: async (route) => { throw new OpNotInstalled(route, "no such op"); } }), + /no engine for \/api\/ops\/voice-enhance yet \(not installed/, + ); + // Delete, softly: moved to .trash, out of the list, the pick following. + await deleteTake(p, (await manifest(p)).timeline[0], 1); + const after = (await manifest(p)).timeline[0].narration; + assert.equal(after.takes.length, 1); + assert.equal(after.pick, 0); + const trash = await readdir(path.join(p.dir, "narration", "posts", "1", ".trash")); + assert.ok(trash.some((f) => f.endsWith("take-2.convert-rvc.wav"))); +}); diff --git a/umtool/lib/report/postNarrationCli.mjs b/umtool/lib/report/postNarrationCli.mjs @@ -18,11 +18,11 @@ // // Plain ESM: the CLI runs under bare node. import { execFile } from "node:child_process"; -import { mkdir, readFile, readdir, stat } from "node:fs/promises"; +import { mkdir, readFile, readdir, rename, stat } from "node:fs/promises"; import path from "node:path"; import { promisify } from "node:util"; import { - NARRATION_INDEX, draftScript, isNarrated, nextTakeNumber, pickedTake, postIdOf, postNarrationKnobs, takeFileOf, takesDirOf, + NARRATION_INDEX, POST_DERIVE_OPS, POST_DERIVE_ROUTES, derivedFileOf, draftScript, takeIdOf, isNarrated, nextTakeNumber, pickedTake, postIdOf, postNarrationKnobs, takeFileOf, takesDirOf, } from "umtool-report-to-video/post-narration"; import { postItemPlan } from "umtool-report-to-video/post-item"; import { readManifest } from "../projects/report.mjs"; @@ -48,6 +48,9 @@ export const NARRATE_USAGE = [ " <item>: the post item's id or its post's id. --pick <n>: the take's number as --list shows it (1 = the first).", " A new take is picked; a new script or pick takes the approval away. Scripts are the post VERBATIM (cleaned", " for pronunciation only); add emotion with Orpheus's tags <sigh> <laugh> <chuckle> <groan> <gasp> ….", + " --delete <n>: the take out of the list, its file moved to narration/posts/<postId>/.trash/ (soft).", + " --derive <n> --op enhance|convert [--engine e] [--voice v]: a NEW take made from take n by the editor's op", + " (enhance: denoise, level; convert: the performance kept, the timbre a STOCK synthetic voice) -- the original kept.", " A narrated post lasts lead + its read + tail + linger (1.8 s); a longer video is cut to that -- its best part,", " once `umtool posts fit` has scanned it (else from its in point). clip=full plays the attachments whole.", ].join("\n"); @@ -116,6 +119,7 @@ export async function importPatches(manifest, rows, measure) { file: t.file, engine: t.engine ?? "orpheus", voice: t.voice ?? "zac", + source: { kind: "tts", engine: t.engine ?? "orpheus", voice: t.voice ?? "zac", script: typeof t.script === "string" ? t.script : String(row.script ?? "") }, seconds: Number.isFinite(m.seconds) ? m.seconds : Number(t.seconds), script: typeof t.script === "string" ? t.script : String(row.script ?? ""), at: typeof t.at === "string" ? t.at : m.at ?? new Date().toISOString(), @@ -252,6 +256,7 @@ export async function makeTake(project, e, { script = null, note = null, engine const m = await measureTake(out); const take = { file: rel, engine: result?.engine ?? eng, voice: result?.voice ?? vox, seconds: m.seconds ?? Number(result?.seconds), + source: { kind: "tts", engine: result?.engine ?? eng, voice: result?.voice ?? vox, script: words }, script: words, at: new Date().toISOString(), ...(note ? { note } : {}), ...(spd !== null && eng !== "orpheus" ? { speed: spd } : {}), ...(Number.isFinite(m.lufs) ? { lufs: m.lufs } : {}), jobId, }; @@ -361,6 +366,27 @@ export async function narrateCommand(project, words, flags, { json = false, dryR const e = findPostItem(manifest, ref); if (!e) throw new NarrateError(`no post item ${ref} in ${project.id} (its id, or the post's id)`); + if (str("--delete") !== null) { + const k = Number(str("--delete")); + if (!Number.isInteger(k) || k < 1) throw new NarrateError("--delete takes a take's number as --list shows it (1 = the first)"); + const r = await deleteTake(project, e, k - 1); + out(json ? JSON.stringify({ ok: true, id: e.id, narration: r.narration, token: r.token }, null, 2) : `${e.id}: take ${k} moved to the post's .trash/ (out of the list)\n${narrationLines(r.entry, render).join("\n")}`); + return 0; + } + if (str("--derive") !== null) { + const k = Number(str("--derive")); + if (!Number.isInteger(k) || k < 1) throw new NarrateError("--derive takes a take's number as --list shows it (1 = the first)"); + const op = str("--op") ?? ""; + try { + const r = await deriveTake(project, e, { from: k - 1, op, engine: str("--engine"), voice: str("--voice"), emit: (_ev, f) => !json && f?.message && out(f.message) }); + if (json) out(JSON.stringify({ ok: true, id: e.id, take: r.take, token: r.result.token }, null, 2)); + else out(`${e.id}: take ${r.take.file} (${r.take.seconds} s), from take ${k} by ${op}, picked`); + return 0; + } catch (err) { + if (err?.name === "OpNotInstalled") throw new NarrateError(err.message); + throw err; + } + } if (flags.has("--take")) { const speedRaw = str("--speed"); const r = await makeTake(project, e, { @@ -444,3 +470,66 @@ export async function fitCommand(project, refs, { all = false, linger = null, js } return 0; } + +/** + * A DERIVED TAKE (post-narration.mjs: "run AI on recorded voice"): take + * `from` (an index) run through the editor's `op` (`enhance`, `convert`) into + * a NEW take -- source `{kind: "take", from: <its id>}`, its step recorded -- + * the original untouched; a parted take part by part (its parts kept). The + * editor's op is a job (`POST /api/ops/voice-enhance|voice-convert` with + * `{file, out, engine?, voice?, params?, parts?}`); one it has no engine for + * throws OpNotInstalled. + */ +export async function deriveTake(project, e, { from, op, engine = null, voice = null, params = null, emit = () => {}, editor = null, ask = null } = {}) { + const takes = e.narration?.takes ?? []; + const t = takes[from]; + if (!t) throw new NarrateError(`${e.id} has no take ${from + 1}`); + if (!POST_DERIVE_OPS.includes(op)) throw new NarrateError(`--op is one of ${POST_DERIVE_OPS.join(", ")}`); + const pid = postIdOf(e); + const dir = path.join(project.dir, ...takesDirOf(pid).split("/")); + await mkdir(dir, { recursive: true }); + const n = nextTakeNumber(e, await readdir(dir).catch(() => [])); + const rel = derivedFileOf(pid, n, op, engine ?? voice ?? "default"); + const abs = (r) => path.join(project.dir, ...r.split("/")); + const partsRel = rel.replace(/\.wav$/, ".parts"); + const parts = Array.isArray(t.parts) && t.parts.every((p) => typeof p.file === "string") + ? t.parts.map((p) => ({ ...p, file: `${partsRel}/p${String(p.n).padStart(2, "0")}.wav` })) + : null; + const body = { + file: abs(t.file), out: abs(rel), + ...(engine ? { engine } : {}), ...(voice ? { voice } : {}), ...(params ? { params } : {}), + ...(parts ? { parts: t.parts.map((p, k) => ({ file: abs(p.file), out: abs(parts[k].file) })) } : {}), + }; + const askOp = ask ?? (await import("umtool-report-to-video/narrate-via-editor")).askEditorOp; + const { jobId } = await askOp(POST_DERIVE_ROUTES[op], body, { ...(editor ? { editor } : {}), emit }); + if (!(await stat(abs(rel)).catch(() => null))?.isFile()) throw new NarrateError(`the editor's job ${jobId} finished but ${rel} is not there`); + const m = await measureTake(abs(rel)); + const take = { + file: rel, engine: "derived", voice: voice ?? t.voice ?? "?", seconds: m.seconds ?? t.seconds, + source: { kind: "take", from: takeIdOf(t) }, + steps: [{ op, ...(engine ? { engine } : {}), ...(voice ? { voice } : {}), ...(params ? { params } : {}), ranAt: new Date().toISOString(), job: jobId }], + script: t.script ?? e.narration?.script ?? "", at: new Date().toISOString(), jobId, + ...(Number.isFinite(m.lufs) ? { lufs: m.lufs } : {}), ...(parts ? { parts } : {}), + }; + const { result } = await withEditNotes(project, async () => updatePostNarration(project.dir, e.id, { addTake: take }, { token: await manifestToken(project.dir) })); + return { take, result }; +} + +/** + * DELETE A TAKE, SOFTLY: its file (and its parts) moved into the post's + * `narration/posts/<postId>/.trash/`, the take out of the list (the pick + * follows). Returns the write's result. + */ +export async function deleteTake(project, e, index) { + const t = (e.narration?.takes ?? [])[index]; + if (!t) throw new NarrateError(`${e.id} has no take ${index + 1}`); + const trash = path.join(project.dir, ...takesDirOf(postIdOf(e)).split("/"), ".trash"); + await mkdir(trash, { recursive: true }); + const stamp = new Date().toISOString().replace(/[:.]/g, "-"); + for (const rel of [t.file, String(t.file).replace(/\.wav$/, ".parts")]) { + const from = path.join(project.dir, ...String(rel).split("/")); + if (await stat(from).catch(() => null)) await rename(from, path.join(trash, `${stamp}-${path.basename(from)}`)); + } + const { result } = await withEditNotes(project, async () => updatePostNarration(project.dir, e.id, { dropTake: index }, { token: await manifestToken(project.dir) })); + return result; +} diff --git a/umtool/lib/report/postRecord.mjs b/umtool/lib/report/postRecord.mjs @@ -128,7 +128,7 @@ export async function keepRecording(project, entry, parts, { label = "operator", if (!(await stat(abs).catch(() => null))?.isFile()) throw new Error(`${rel} was not written`); const m = await measureTake(abs); const take = { - file: rel, engine: "recorded", voice: label, label, seconds: m.seconds, script: String(script ?? entry.narration?.script ?? ""), + file: rel, engine: "recorded", voice: label, label, seconds: m.seconds, source: { kind: "recorded", voice: label }, script: String(script ?? entry.narration?.script ?? ""), at: new Date().toISOString(), ...(Number.isFinite(m.lufs) ? { lufs: m.lufs } : {}), ...(note ? { note } : {}), ...(partsOut.length > 1 ? { parts: partsOut } : {}), }; diff --git a/umtool/lib/report/postsCli.mjs b/umtool/lib/report/postsCli.mjs @@ -73,7 +73,7 @@ export const POSTS_USAGE = [ " _avatars/, capture-posts') copied in where the cut has none; a manual one is never replaced.", ].join("\n"); -const VALUED = new Set(["--attach", "--flag", "--author", "--id", "--crop", "--since", "--until", "--replies", "--order", "--limit", "--after", "--script", "--note", "--voice", "--engine", "--speed", "--pick", "--linger"]); +const VALUED = new Set(["--attach", "--flag", "--author", "--id", "--crop", "--since", "--until", "--replies", "--order", "--limit", "--after", "--script", "--note", "--voice", "--engine", "--speed", "--pick", "--linger", "--derive", "--op", "--delete"]); const SLUG_RE = /^[A-Za-z0-9._-]+$/; const POST_ID_RE = /^[A-Za-z0-9_-]{1,64}$/; diff --git a/umtool/report-to-video/narrate-via-editor.mjs b/umtool/report-to-video/narrate-via-editor.mjs @@ -222,7 +222,44 @@ export async function narrateCut({ narrations, dir, editor = editorFromEnv(), em * @param {{ text: string, engine?: string, voice?: string, speed?: number, out?: string }} body * @param {{ editor?: { url: string, token: string }, emit?: (ev: string, f?: object) => void, pollMs?: number, onJob?: (id: string) => void }} [o] */ -export async function askEditorTts(body, { editor = editorFromEnv(), emit = () => {}, pollMs = POLL_MS, onJob = () => {} } = {}) { +export async function askEditorTts(body, o = {}) { + return askEditorOp("/api/ops/tts", body, o); +} + +/** The editor has no engine for an op (its route is missing, or it says the engine is not installed). */ +export class OpNotInstalled extends Error { + constructor(route, detail) { + super(`the editor has no engine for ${route} yet (not installed${detail ? `: ${detail}` : ""})`); + this.name = "OpNotInstalled"; + this.route = route; + } +} + +/** The result line of a voice op (`@@voice-result <json>`), else a tts one; null when none. */ +export function opResultIn(lines) { + let found = null; + for (const line of lines ?? []) { + for (const marker of ["@@voice-result ", TTS_RESULT_MARKER]) { + const at = String(line).indexOf(marker); + if (at < 0) continue; + try { + found = JSON.parse(String(line).slice(at + marker.length)); + } catch { + /* a mangled line */ + } + } + } + return found; +} + +/** + * ONE ASK OF ANY OF THE EDITOR's MEDIA OPS, waited for: `POST <route>` with + * `body` (its `out` the absolute file the result is written to), then its job + * followed to the end. Returns `{ jobId, result }` (result: the job's result + * line, null when the op writes none and `out` is given). An op the editor + * has no engine for throws OpNotInstalled. + */ +export async function askEditorOp(route, body, { editor = editorFromEnv(), emit = () => {}, pollMs = POLL_MS, onJob = () => {} } = {}) { const headers = { authorization: `Bearer ${editor.token}`, "content-type": "application/json" }; const reach = async (url, init) => { try { @@ -232,9 +269,10 @@ export async function askEditorTts(body, { editor = editorFromEnv(), emit = () = } }; const clean = Object.fromEntries(Object.entries(body).filter(([, v]) => v !== undefined && v !== null)); - const res = await reach(`${editor.url}/api/ops/tts`, { method: "POST", headers, body: JSON.stringify(clean) }); + const res = await reach(`${editor.url}${route}`, { method: "POST", headers, body: JSON.stringify(clean) }); const j = await res.json().catch(() => ({})); - if (!res.ok || !j.ok || typeof j.jobId !== "string") throw new Error(`the editor refused the take (HTTP ${res.status}): ${j.error ?? "no reason given"}`); + if (res.status === 404 || /not installed|no engine|unknown op/i.test(String(j.error ?? ""))) throw new OpNotInstalled(route, j.error ?? (res.status === 404 ? "no such op" : "")); + if (!res.ok || !j.ok || typeof j.jobId !== "string") throw new Error(`the editor refused it (${route}, HTTP ${res.status}): ${j.error ?? "no reason given"}`); const jobId = j.jobId; onJob(jobId); emit("note", { message: ` asked the editor as job ${jobId} (${clean.engine ?? "its default"} · ${clean.voice ?? "its default"})` }); @@ -271,12 +309,12 @@ export async function askEditorTts(body, { editor = editorFromEnv(), emit = () = for (let i = 0; i <= RESULT_RETRIES; i += 1) { const d = await reach(`${editor.url}/api/ops/job/${encodeURIComponent(jobId)}?tail=${TAIL_LINES}`, { headers }); tail = ((await d.json().catch(() => ({}))).tail ?? []); - if (status !== "done" || ttsResultIn(tail)) break; + if (status !== "done" || opResultIn(tail)) break; await sleep(Math.max(pollMs, 100)); } if (status !== "done") throw new Error(`editor job ${jobId} ${status}${tail.length ? ` — ${tail.slice(-3).join(" / ")}` : ""}`); - const result = ttsResultIn(tail); - if (!result) throw new Error(`editor job ${jobId} is done, but its log carries no ${TTS_RESULT_MARKER.trim()} line`); + const result = opResultIn(tail); + if (!result && !clean.out) throw new Error(`editor job ${jobId} is done, but its log carries no result line`); return { jobId, result }; } } diff --git a/umtool/report-to-video/post-narration.mjs b/umtool/report-to-video/post-narration.mjs @@ -33,7 +33,54 @@ /** The engines a post's narration may name (the editor's tts op). */ export const POST_NARRATION_ENGINES = Object.freeze(["orpheus", "kokoro", "espeak-ng"]); /** A take's engine: one of those, or `recorded` -- a person's own voice, recorded on the post bench (never synthesized). */ -export const POST_TAKE_ENGINES = Object.freeze([...POST_NARRATION_ENGINES, "recorded"]); +export const POST_TAKE_ENGINES = Object.freeze([...POST_NARRATION_ENGINES, "recorded", "derived"]); + +/** + * WHAT A TAKE IS (operator, 2 Nov: "pure AI voice, record voice, and run AI on + * recorded voice -- and re-run or re-record"): a `source` and the `steps` + * applied to it, and the file that came out -- + * + * source { kind: "tts", engine, voice, script } a stock voice, the editor's tts op + * { kind: "recorded", voice } a person's own read, recorded on the bench + * { kind: "take", from: <take id> } DERIVED: a new take made from another + * steps [{ op, engine?, params?, ranAt, job? }] the processing that made a derived take + * + * A derived take never overwrites the one it came from. Its ops are the + * editor's (each a job, like tts): `enhance` (denoise, level, de-reverb) and + * `convert` (voice conversion: the performance kept, the timbre swapped for a + * STOCK synthetic voice -- never a real person's). A take's id is its file's + * name without `.wav`. Takes from before this shape (engine and voice only) + * read as their source (takeSourceOf). + */ +export const POST_DERIVE_OPS = Object.freeze(["enhance", "convert"]); +/** The editor's op route for each. */ +export const POST_DERIVE_ROUTES = Object.freeze({ enhance: "/api/ops/voice-enhance", convert: "/api/ops/voice-convert" }); + +/** A take's id: its file's name without `.wav`. */ +export const takeIdOf = (t) => String(t?.file ?? "").split("/").pop().replace(/\.wav$/i, ""); + +/** A take's source, its own or read from the older shape. */ +export function takeSourceOf(t) { + if (isObj(t?.source)) return t.source; + if (t?.engine === "recorded") return { kind: "recorded", voice: t.voice ?? t.label ?? "operator" }; + return { kind: "tts", engine: t?.engine ?? "orpheus", voice: t?.voice ?? "zac", ...(typeof t?.script === "string" ? { script: t.script } : {}) }; +} + +/** The root of a take's chain (the source take a derived one came from, followed back), or the take itself. */ +export function rootTakeOf(takes, t) { + let cur = t; + for (let i = 0; i < 20; i += 1) { + const src = takeSourceOf(cur); + if (src.kind !== "take") return cur; + const up = takes.find((x) => takeIdOf(x) === src.from); + if (!up) return cur; + cur = up; + } + return cur; +} + +/** The file a derived take of post `postId` is written to: take-<n>.<op>-<engine>.wav. */ +export const derivedFileOf = (postId, n, op, engine) => `${takesDirOf(postId)}/take-${n}.${op}-${String(engine ?? "default").replace(/[^A-Za-z0-9_-]/g, "")}.wav`; /** * THE MIX's KNOBS and their defaults (`render.postNarration`, and the same @@ -106,7 +153,8 @@ const MIX_KEYS = ["lead", "tail", "ramp", "linger", "clip", "wet", "lowpassHz", // `attach` is one post's (it decides the card's layout, which is drawn from the entry alone). const RENDER_KEYS = new Set([...MIX_KEYS.filter((k) => k !== "attach"), "engine", "voice"]); const ITEM_KEYS = new Set([...MIX_KEYS, "script", "excerpt", "engine", "voice", "speed", "takes", "pick", "approved", "off", "window"]); -const TAKE_KEYS = new Set(["file", "engine", "voice", "seconds", "script", "at", "note", "speed", "lufs", "jobId", "parts", "label"]); +const TAKE_KEYS = new Set(["file", "engine", "voice", "seconds", "script", "at", "note", "speed", "lufs", "jobId", "parts", "label", "source", "steps"]); +const STEP_KEYS = new Set(["op", "engine", "voice", "params", "ranAt", "job"]); const PART_KEYS = new Set(["n", "para", "text", "file", "start", "seconds", "gapBefore", "note", "at", "jobId"]); const VOICE_RE = /^[A-Za-z0-9][A-Za-z0-9_.+-]{0,63}$/; /** Orpheus's expressive tags (narration.mjs NARRATION_TAGS, the editor's list). */ @@ -415,6 +463,22 @@ export function validatePostNarration(e) { if (t.lufs !== undefined && t.lufs !== null && !fin(t.lufs)) errors.push(`${tw}.lufs must be a number`); if (t.speed !== undefined && !numIn(t.speed, POST_NARRATION_LIMITS.speed)) errors.push(`${tw}.speed must be ${POST_NARRATION_LIMITS.speed.join("–")}`); if (t.label !== undefined && (typeof t.label !== "string" || !VOICE_RE.test(t.label))) errors.push(`${tw}.label must be a short name (a recorded voice's)`); + if (t.source !== undefined) { + const src = t.source; + const ok = isObj(src) && ( + (src.kind === "tts" && POST_NARRATION_ENGINES.includes(src.engine) && typeof src.voice === "string") || + (src.kind === "recorded" && typeof src.voice === "string" && VOICE_RE.test(src.voice)) || + (src.kind === "take" && typeof src.from === "string" && n.takes.some((x) => takeIdOf(x) === src.from && x !== t)) + ); + if (!ok) errors.push(`${tw}.source must be {kind: "tts", engine, voice}, {kind: "recorded", voice} or {kind: "take", from: <one of its takes' id>}`); + } + if (t.steps !== undefined) { + if (!Array.isArray(t.steps) || t.steps.length > 20) errors.push(`${tw}.steps must be a list (at most 20)`); + else t.steps.forEach((st, k) => { + if (!isObj(st) || !POST_DERIVE_OPS.includes(st.op)) errors.push(`${tw}.steps[${k}].op must be one of ${POST_DERIVE_OPS.join(", ")}`); + else for (const key of Object.keys(st)) if (!STEP_KEYS.has(key)) errors.push(`${tw}.steps[${k}].${key} is not a step key`); + }); + } if (t.parts !== undefined) { // A take COMPOSED OF PARTS (a long post read paragraph by paragraph): the joined file is the take's. if (!Array.isArray(t.parts) || t.parts.length > 200) errors.push(`${tw}.parts must be a list (at most 200)`); @@ -453,8 +517,14 @@ export function postNarrationFiles(entry) { export function postNarrationDisclosure(entry) { const t = pickedTake(entry); if (!t || !isNarrated(entry)) return null; + const takes = entry.narration.takes ?? []; + // A voice converted to a stock synthetic one says so; enhanced, the chain's root decides. + const convert = (t.steps ?? []).find((st) => st?.op === "convert"); + if (convert) return `Narration: voice converted to a synthetic voice (${convert.engine ?? "?"} · ${convert.voice ?? "?"})`; + const root = rootTakeOf(takes, t); // A recorded take is a person's own voice: nothing synthetic to disclose. - if (t.engine === "recorded") return null; + if (root.engine === "recorded" || takeSourceOf(root).kind === "recorded") return null; + if (root !== t) return postNarrationDisclosure({ ...entry, narration: { ...entry.narration, takes: [root], pick: 0 } }); const label = { orpheus: "Orpheus", kokoro: "Kokoro-82M", "espeak-ng": "eSpeak NG" }[t.engine] ?? t.engine ?? "a stock voice"; return `Narration: synthetic voice (${label} · ${t.voice ?? "?"})`; }