Archilyzer · Source

archilyzer

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

commit c91afb8f9c690855fd74d2414f3c78e6d16f99f1
parent 52425e315c573c872ab4e787a9f6dcedff860e31
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Thu,  5 Nov 2026 10:10:24 -0500

umtool: posts reread --pause -- silence put in after words of the approved read, no TTS

A derived take (steps: [{op: "pause", pauses}]) cut from the picked take's own
file just after each word named (<word>[#n]=<seconds>, 0.05-3; found in the
take's word timings as word-zoom matches: case and edge punctuation aside),
everything after moved on: the words by index, the parts after it (a part it
falls in grows), the take's length -- so zooms, captions, slams, beeps and the
read-follow keep their words. Absolute like a tempo: a paused take re-cuts
from the take before (=0 takes a pause away). --target counts one piece's
words; --dry-run, --json; refusals exit 1 (no word timings names posts narrate
--words), a malformed spec exit 2. The post bench's Options -> Re-join the read
(no TTS) gets a "pause after" field with Preview and Apply, on the cut's bench
and the take-only bench (?inTake=): POST /api/report/post-narration {op:
"reread", pause, target?, dryRun?, inTake?} -- a reread with inTake runs under
withTakeScope.

(operator, 5 Nov: "the "20 10 4 0" words @21:21 should have some spacing since
it's a countdown, though not necessarily real-time spacing")

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

Diffstat:
Mumtool/app/api/report/post-narration/route.ts | 42+++++++++++++++++++++++++++++++++++++++++-
Mumtool/components/projects/PostNarrationPanel.tsx | 66+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------
Aumtool/lib/report/postPause.mjs | 239+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/postPause.test.mjs | 165+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/postReread.mjs | 30+++++++++++++++++++++++++++++-
Mumtool/lib/report/postsCli.mjs | 6++++--
Mumtool/report-to-video/post-narration.mjs | 9++++++---
7 files changed, 543 insertions(+), 14 deletions(-)

diff --git a/umtool/app/api/report/post-narration/route.ts b/umtool/app/api/report/post-narration/route.ts @@ -12,6 +12,9 @@ import { readManifest } from "@/lib/projects/report.mjs"; import { refuseCaller } from "@/lib/report/caller"; import { deleteTake, measureTake } from "@/lib/report/postNarrationCli.mjs"; import { parseTempoSpec, rereadTake } from "@/lib/report/postReread.mjs"; +import { parsePauseSpec, pauseTake } from "@/lib/report/postPause.mjs"; +import { withTakeScope } from "@/lib/report/takeScope.mjs"; +import { isTakeId } from "@/lib/report/takes.mjs"; import { keepRecording, RECORD_LABEL_RE } from "@/lib/report/postRecord.mjs"; import { fitPostItem } from "@/lib/report/postFit.mjs"; import { projectRedaction } from "@/lib/report/postRedaction.mjs"; @@ -43,7 +46,11 @@ const benchVoice = (red: { slurs?: { voice?: string } | null } | null) => (red?. // POST {project, op: "delete", id, take} a take out of the list, its file to .trash/ (soft) // POST {project, op: "reread", id, without?, dropParts?, dropUrls?} the picked take RE-JOINED without a piece // POST {project, op: "reread", id, tempo: "4-16=1.35", stretch?} its parts RE-TIMED (no TTS); {…, yell: true, yellGain?, yellStyle?}: its caps raised +// POST {project, op: "reread", id, pause: "20=0.45,10=0.45", target?, dryRun?} SILENCE PUT IN after the words +// named (postPause.mjs); dryRun: the plan only, nothing written // (postReread.mjs: no TTS; a new take, picked, one undo point) +// any reread + 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 const noStore = { "cache-control": "no-store" }; @@ -144,7 +151,30 @@ export async function GET(request: Request) { }, { headers: noStore }); } +// "Edit this take only" (the bench's ?inTake=): a JSON reread naming `inTake` runs under takeScope.mjs withTakeScope -- +// the take's manifest read, the new take picked in its patch, the project's manifest untouched (the CLI's `--in-take`). +// The token is then the take's, so a client's project token is not checked. Only a reread: a TTS take is kept by a GET +// later (unscoped), so it is made on the cut's bench. export async function POST(request: Request) { + if ((request.headers.get("content-type") ?? "").startsWith("multipart/form-data")) return postHere(request); + const text = await request.text(); + let parsed: Record<string, unknown> | null = null; + try { + parsed = JSON.parse(text); + } catch { + parsed = null; + } + const take = parsed && typeof parsed.inTake === "string" && parsed.inTake ? parsed.inTake : null; + const again = (body: string) => new Request(request.url, { method: "POST", headers: request.headers, body }); + if (!take || !parsed) return postHere(again(text)); + if (!isTakeId(take)) return Response.json({ error: "inTake must be a take id" }, { status: 400 }); + if (parsed.op !== "reread") return Response.json({ error: `inTake: only a reread runs on a take's read here (${String(parsed.op ?? "no op")} is the cut bench's)` }, { status: 400 }); + const rr = await resolveReport(String(parsed.project ?? "")); + if ("error" in rr) return Response.json({ error: rr.error }, { status: rr.status }); + return withTakeScope(rr.project.dir, take, () => postHere(again(JSON.stringify({ ...parsed, token: null })))); +} + +async function postHere(request: Request) { const refused = refuseCaller(request, "/api/report/post-narration"); if (refused) return refused; if ((request.headers.get("content-type") ?? "").startsWith("multipart/form-data")) return record(request); @@ -233,12 +263,22 @@ export async function POST(request: Request) { const yy = await yellTake(r.project, e, { slurs: cutSlurs(m), ...(typeof body.yellGain === "number" ? { gain: body.yellGain } : {}), ...(typeof body.yellStyle === "string" ? { style: body.yellStyle } : {}) }); return Response.json({ ok: true, take: yy.take, spans: yy.plan.spans, entry: yy.result?.entry ?? null, token: yy.result?.token ?? null }, { headers: noStore }); } + // `pause`: "20=0.45,10=0.45" (postPause.mjs parsePauseSpec) -- silence put in after the words; `dryRun`: the plan only. + if (typeof body.pause === "string" && body.pause.trim()) { + const target = typeof body.target === "string" && body.target.trim() ? body.target.trim() : null; + const pp = await pauseTake(r.project, e, { pauses: parsePauseSpec(body.pause), target, dryRun: body.dryRun === true }); + const plan = pp.plan as { pauses: unknown[]; added: number; seconds: number; recut: boolean; fixedAt: number; picked: { seconds?: number }; take: Record<string, unknown> }; + return Response.json( + { ok: true, dryRun: body.dryRun === true, pauses: plan.pauses, added: plan.added, seconds: pp.take?.seconds ?? plan.seconds, was: plan.picked.seconds ?? null, recut: plan.recut, from: takeIdOf(plan.take), fixedAt: plan.fixedAt, take: pp.take ?? null, entry: pp.result?.entry ?? null, token: pp.result?.token ?? null }, + { headers: noStore }, + ); + } const pt = pickedTake(e) as { parts?: unknown[] } | null; const tempo = typeof body.tempo === "string" && body.tempo ? parseTempoSpec({ spec: body.tempo, count: Array.isArray(pt?.parts) ? pt.parts.length : 0 }) : null; const rr = await rereadTake(r.project, e, { without: list(body.without), dropParts: list(body.dropParts).map(Number), dropUrls: body.dropUrls === true, tempo, ...(body.stretch === "rubberband" ? { stretch: "rubberband" } : {}) }); return Response.json({ ok: true, take: rr.take, entry: rr.result?.entry ?? null, token: rr.result?.token ?? null }, { headers: noStore }); } catch (err) { - if ((err as Error)?.name === "RereadError" || (err as Error)?.name === "YellError") return Response.json({ error: (err as Error).message }, { status: 400 }); + if ((err as Error)?.name === "RereadError" || (err as Error)?.name === "YellError" || (err as Error)?.name === "PauseError") return Response.json({ error: (err as Error).message }, { status: 400 }); throw err; } } diff --git a/umtool/components/projects/PostNarrationPanel.tsx b/umtool/components/projects/PostNarrationPanel.tsx @@ -1,7 +1,7 @@ "use client"; import { Options } from "@/components/ui/disclosure"; -import { useInTake } from "./inTake"; +import { inTakeBody, useInTake } from "./inTake"; import Link from "next/link"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import Waveform from "@/components/Waveform"; @@ -37,7 +37,7 @@ import { wordZoomTimes, zoomSpan } from "umtool-report-to-video/word-zoom"; // --------------------------------------------------------------------------- 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 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 }>; words?: Array<{ w: string; start: number; end: number }> }; 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 } }; @@ -77,7 +77,7 @@ export default function PostNarrationPanel({ const post = useCallback( async (body: Record<string, unknown>) => { setError(null); - const res = await fetch("/api/report/post-narration", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, id: entry.id, token, ...body }) }); + const res = await fetch("/api/report/post-narration", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, id: entry.id, token, ...body, ...inTakeBody(inTake) }) }); const j = (await res.json().catch(() => ({}))) as { entry?: Entry; token?: string; error?: string; errors?: string[]; jobId?: string; file?: string; untouched?: boolean; why?: string; window?: Narration["window"] }; if (!res.ok) { setError(j.errors?.join("; ") ?? j.error ?? `HTTP ${res.status}`); @@ -86,7 +86,7 @@ export default function PostNarrationPanel({ if (j.entry) onEntry(j.entry, j.token ?? null); return j; }, - [project, entry.id, token, onEntry], + [project, entry.id, token, onEntry, inTake], ); const set = (patch: Record<string, unknown>) => post({ op: "set", patch }).then((j) => j && setStatus("saved")); @@ -336,11 +336,25 @@ export default function PostNarrationPanel({ ); // A take-scoped bench (?inTake): a read is made for the cut here; a take's own read is \`umtool posts narrate … --in-take <t>\`. + // Pauses in the picked read (postPause.mjs) are no TTS, so they are made here too, on the take's own read. if (inTake) return ( - <p className="m-0 text-[12px] text-muted" data-post-bench-in-take-note=""> - Narration is edited on the cut&apos;s bench (edits go to: the cut); take {inTake} keeps the reads it has. - </p> + <div className="space-y-2 text-[12.5px]" data-post-narration-in-take={inTake}> + <p className="m-0 text-[12px] text-muted" data-post-bench-in-take-note=""> + Narration is edited on the cut&apos;s bench (edits go to: the cut); take {inTake} keeps the reads it has. + </p> + {picked && ( + <Options id="post-reread" label="Re-join the read (no TTS)" hint="pauses after words"> + <PauseAfter post={post} hasWords={!!picked.words?.length} setStatus={setStatus} /> + </Options> + )} + {status && <p className="m-0 text-text-2" data-post-narration-status="">{status}</p>} + {error && ( + <p className="m-0 text-[var(--color-blocking,#c33)]" data-post-narration-error=""> + {error} + </p> + )} + </div> ); return ( <div className="space-y-3 text-[12.5px]" data-post-narration={entry.id} data-post-narration-plays={picked ? (picked.engine === "recorded" ? "recorded" : "synthesized") : "none"}> @@ -749,6 +763,7 @@ export default function PostNarrationPanel({ Raise the CAPS </button> </span> + <PauseAfter post={post} hasWords={!!picked.words?.length} setStatus={setStatus} /> </Options> )} {status && <p className="m-0 text-text-2" data-post-narration-status="">{status}</p>} @@ -760,3 +775,40 @@ export default function PostNarrationPanel({ </div> ); } + +type PausePlan = { pauses?: Array<{ word: number; w: string; at: number; seconds: number }>; added?: number; seconds?: number; was?: number | null; recut?: boolean; from?: string; fixedAt?: number; dryRun?: boolean }; + +/** + * PAUSES AFTER WORDS of the picked read, no TTS (lib/report/postPause.mjs; `umtool posts reread … --pause`): the + * words and their seconds (`20=0.45,10=0.45,4#2=0.6`), Preview (the dry run: where each cut lands) and Apply (a new + * take, picked). Needs the take's word timings. + */ +function PauseAfter({ post: send, hasWords, setStatus }: { post: (body: Record<string, unknown>) => Promise<unknown>; hasWords: boolean; setStatus: (s: string | null) => void }) { + const post = (b: Record<string, unknown>) => send(b) as Promise<PausePlan | null>; + const [spec, setSpec] = useState(""); + const [target, setTarget] = useState(""); + const [plan, setPlan] = useState<PausePlan | null>(null); + const btn = cn(buttonVariants({ variant: "outline", size: "sm" })); + const body = (dryRun: boolean) => ({ op: "reread", pause: spec.trim(), ...(target.trim() ? { target: target.trim() } : {}), ...(dryRun ? { dryRun: true } : {}) }); + const said = (j: PausePlan) => `${(j.pauses ?? []).map((p) => `after "${p.w}" (word ${p.word + 1}, ${p.at.toFixed(2)} s) +${p.seconds} s`).join(" · ")} -- ${Number(j.seconds).toFixed(2)} s (was ${Number(j.was ?? 0).toFixed(2)} s)${j.recut ? `, cut again from ${j.from}` : ""}${j.fixedAt ? ` · ${j.fixedAt} effect(s) with a set second do not move` : ""}`; + return ( + <span className="mt-1.5 flex flex-wrap items-center gap-1.5" data-post-reread-pause-row=""> + <label className="inline-flex items-center gap-1"> + pause after + <input value={spec} onChange={(e) => { setSpec(e.target.value); setPlan(null); }} placeholder="20=0.45,10=0.45,4#2=0.6" className="w-48 rounded border border-seam bg-ground px-1 py-0.5 font-mono text-[11px]" data-post-reread-pause="" /> + </label> + <label className="inline-flex items-center gap-1" title="count only the words of one piece of the read (post, parent:0, quoted, linked:0)"> + in + <input value={target} onChange={(e) => { setTarget(e.target.value); setPlan(null); }} placeholder="the whole read" className="w-24 rounded border border-seam bg-ground px-1 py-0.5 font-mono text-[11px]" data-post-reread-pause-target="" /> + </label> + <button type="button" className={btn} disabled={!spec.trim()} onClick={() => void post(body(true)).then((j) => { setPlan(j); if (j) setStatus(`would pause ${said(j)}`); })} data-post-reread-pause-preview=""> + Preview + </button> + <button type="button" className={btn} disabled={!spec.trim()} onClick={() => void post(body(false)).then((j) => { setPlan(null); if (j) setStatus(`paused ${said(j)}: a new take, picked`); })} data-post-reread-pause-go=""> + Apply + </button> + {!hasWords && <span className="text-muted" data-post-reread-pause-needs-words="">needs the take&apos;s word timings (Get word timings, or umtool posts narrate … --words)</span>} + {plan?.pauses && <span className="sr-only" data-post-reread-pause-plan={plan.pauses.length} />} + </span> + ); +} diff --git a/umtool/lib/report/postPause.mjs b/umtool/lib/report/postPause.mjs @@ -0,0 +1,239 @@ +// PAUSES IN AN APPROVED READ, no TTS (operator, 5 Nov, a Mr. Obvious cut: "the +// "20 10 4 0" words @21:21 should have some spacing since it's a countdown, +// though not necessarily real-time spacing" -- the read's delivery is liked, so +// it is never re-synthesized): the picked take cut just after each word named +// and that much silence put in, everything after it moved on by the same. +// +// umtool posts reread <p> <item> --pause "20=0.45,10=0.45,4=0.45" [--target linked:0] [--dry-run] [--json] [--in-take <t>] +// +// A word is named as word-zoom names one (word-zoom.mjs normWord: case and the +// punctuation at its edges aside; a phrase is its words in a row, the pause after +// its last): `<word>[#<n>]=<seconds>`, `#n` its n-th time in the read (default +// the first), seconds 0.05–3. It is found in the take's own word timings +// (`narration.takes[i].words`, the script's words as read: `umtool posts narrate +// <p> <item> --words` makes them), so a take without them is refused, naming +// that command. `--target <role>` (a piece role, post-thread.mjs partRoles: +// post, parent:0, quoted, linked:0 …) counts only the words of the parts reading +// that piece. +// +// THE CUT is just after the word's end: half way into the quiet before the next +// word, at most PAUSE_CUT_INTO_GAP past the end (never into the next word). What +// moves: every word after it (by its index -- a word's timing is the take's, +// shifted), every part starting after it (a part the cut falls inside grows by +// the pause), the take's length. Everything timed ON the read -- word zooms, +// captions, slams (their matched word's start), beeps (the slurs' words), the +// read-follow blocks (the parts' starts) -- reads those, so it stays on its words. +// An effect with a set second (`at`, the operator's nudge) is not moved: the plan +// names how many there are. +// +// A PAUSE IS ABSOLUTE, like a tempo: on a take whose last step is a pause the +// plan re-cuts from the take before it, the pauses it had kept and the ones named +// now set (a word named again takes the new seconds; `=0` takes a pause away). +// On any other take (a re-join, a re-time, a yell) it is cut from that take. +// The new take: `source: {kind: "take", from}`, `steps: [{op: "pause", pauses: +// [{word, w, at, seconds}]}]` (word: its index in the take's words; at: the cut, +// in the source take's seconds), picked in ONE write (one undo point). +// +// Plain ESM: the CLI runs it under bare node. +import { pickedTake, takeIdOf } from "umtool-report-to-video/post-narration"; +import { partRoles } from "umtool-report-to-video/post-thread"; +import { normWord } from "umtool-report-to-video/word-zoom"; +import { RereadError, lastLocalStep, writeDerivedTake } from "./postReread.mjs"; + +const fin = (v) => typeof v === "number" && Number.isFinite(v); +const r3 = (v) => Math.round(v * 1000) / 1000; + +/** A pause's length, seconds. */ +export const PAUSE_LIMITS = Object.freeze({ seconds: [0.05, 3] }); +/** The most pauses one take holds. */ +export const PAUSE_MAX = 40; +/** How far past a word's end the cut may go into the quiet before the next word, seconds. */ +export const PAUSE_CUT_INTO_GAP = 0.1; +const ROLE_RE = /^(post|quoted|parent:\d|media:\d|linked:\d)$/; + +/** A pause the plan cannot make (no word timings, the word not read, nothing to change): exit 1, not a usage error. */ +export class PauseError extends Error { + constructor(message) { + super(message); + this.name = "PauseError"; + } +} + +/** + * A PAUSE SPEC as the CLI writes it, pure: `"20=0.45,10=0.45,4#2=0.6"` -- + * `[{ match, occurrence, seconds }]`. `seconds` 0 takes a pause away (a re-cut); + * else 0.05–3. Refused (RereadError, a usage error): no `=`, no word, a bad + * occurrence or seconds. + * + * @param {string} spec + * @returns {Array<{ match: string, occurrence: number, seconds: number }>} + */ +export function parsePauseSpec(spec) { + const [lo, hi] = PAUSE_LIMITS.seconds; + const items = String(spec ?? "").split(",").map((x) => x.trim()).filter(Boolean); + if (!items.length) throw new RereadError(`--pause names the words and their pause: --pause "20=0.45,10=0.45" (<word>[#<n>]=<seconds>)`); + if (items.length > PAUSE_MAX) throw new RereadError(`--pause: at most ${PAUSE_MAX} pauses`); + return items.map((item) => { + const eq = item.lastIndexOf("="); + if (eq < 0) throw new RereadError(`--pause ${item}: <word>[#<n>]=<seconds>, e.g. 20=0.45 or 4#2=0.45`); + const left = item.slice(0, eq).trim(); + const right = item.slice(eq + 1).trim(); + const m = /^(.*?)(?:\s*#\s*(\d+))?$/.exec(left); + const match = (m?.[1] ?? "").trim(); + if (!match || !match.split(/\s+/).some((w) => normWord(w))) throw new RereadError(`--pause ${item}: name a word (or a phrase) the take reads`); + const occurrence = m?.[2] === undefined ? 1 : Number(m[2]); + if (!(Number.isInteger(occurrence) && occurrence >= 1 && occurrence <= 999)) throw new RereadError(`--pause ${item}: #<n> is its n-th time in the read, from 1`); + const seconds = /^\d*\.?\d+$/.test(right) ? Number(right) : NaN; + if (!(seconds === 0 || (fin(seconds) && seconds >= lo && seconds <= hi))) throw new RereadError(`--pause ${item}: a pause is ${lo}–${hi} seconds (0 takes one away)`); + return { match, occurrence, seconds }; + }); +} + +/** The word indices of `take` a target counts (null: all), by the parts reading that piece. */ +function targetWords(entry, take, target) { + if (!target) return null; + if (!ROLE_RE.test(target)) throw new RereadError(`--target ${target}: a piece of the read (post, parent:0, quoted, linked:0, media:0)`); + const parts = Array.isArray(take.parts) ? take.parts : []; + if (!parts.length || !parts.every((p) => fin(p?.start) && fin(p?.seconds))) throw new PauseError(`${entry.id}'s picked take was read in one go (no timed parts): there are no pieces to tell apart -- drop --target`); + const roles = partRoles(entry, take); + const spans = parts.map((p, k) => ({ role: roles[k]?.role ?? p.role ?? null, from: p.start - 0.05, to: p.start + p.seconds + 0.05 })).filter((s) => s.role === target); + if (!spans.length) throw new PauseError(`${entry.id}'s picked take reads no ${target} (its pieces: ${[...new Set(roles.map((r) => r?.role).filter(Boolean))].join(", ") || "none named"})`); + return take.words.map((w, i) => (spans.some((s) => w.start >= s.from && w.start < s.to) ? i : -1)).filter((i) => i >= 0); +} + +/** + * Where a named word is in `take`'s words: the index of its LAST word (a phrase's), or a PauseError naming how often it is there. + * @param {Record<string, any>} entry + * @param {Array<{ w: string }>} words + * @param {number[] | null} among the indices counted (a target's), or null for all + * @param {{ match: string, occurrence: number }} p + * @param {string | null} target + */ +export function findPauseWord(entry, words, among, { match, occurrence }, target = null) { + const want = match.split(/\s+/).map(normWord).filter(Boolean); + const idx = among ?? words.map((_, i) => i); + const hits = []; + for (let k = 0; k + want.length <= idx.length; k += 1) { + if (want.every((w, j) => normWord(words[idx[k + j]].w) === w)) hits.push(idx[k + want.length - 1]); + } + const where = `${entry.id}'s read${target ? ` (${target})` : ""}`; + if (!hits.length) throw new PauseError(`--pause "${match}": no such word in ${where} (it reads the script's words: ${JSON.stringify(words.slice(0, 8).map((w) => w.w).join(" "))}…)`); + if (occurrence > hits.length) throw new PauseError(`--pause "${match}#${occurrence}": "${match}" is in ${where} ${hits.length} time${hits.length === 1 ? "" : "s"}`); + return hits[occurrence - 1]; +} + +/** The cut after word `i` of `words`, take seconds: half way into the quiet before the next word, at most PAUSE_CUT_INTO_GAP past its end. */ +export function cutAfter(words, i, seconds = Infinity) { + const end = words[i].end; + const next = words[i + 1]?.start; + const room = fin(next) && next > end ? (next - end) / 2 : fin(next) ? 0 : PAUSE_CUT_INTO_GAP; + return r3(Math.min(end + Math.min(room, PAUSE_CUT_INTO_GAP), fin(seconds) ? seconds : Infinity)); +} + +/** + * THE PAUSE's PLAN, pure: the take it cuts (`take`: the picked one; on a take + * whose last step is a pause, the one before it), the pauses after (`pauses`, + * `[{ word, w, at, seconds }]` in order), the spans of the source cut between + * them (`spans: [{ from, to|null, gap }]`, `gap` the silence before the span), + * the words, parts and length moved on, and the steps. + * + * @param {Record<string, any>} entry + * @param {{ pauses: Array<{ match: string, occurrence: number, seconds: number }>, target?: string | null }} o + */ +export function pausePlan(entry, { pauses, target = null }) { + const picked = pickedTake(entry); + if (!picked) throw new PauseError(`${entry?.id ?? "?"} has no take to put a pause in`); + const noWords = (t) => !Array.isArray(t?.words) || !t.words.length; + if (noWords(picked)) throw new PauseError(`${entry.id}'s picked take (${takeIdOf(picked)}) has no word timings to find the words by: time its words first -- umtool posts narrate <p> ${entry.id} --words (+ --in-take <t> for a take's read; the bench's Get word timings) -- then pause`); + const takes = entry.narration.takes; + // A re-cut: the take before the pause step, when it is there with the same words. + const up = lastLocalStep(takes, picked, ["pause"]); + const recut = !!(up?.from && !noWords(up.from) && up.from.words.length === picked.words.length); + const take = recut ? { ...up.from, index: takes.indexOf(up.from) } : picked; + const words = take.words; + /** @type {Map<number, number>} word index -> seconds */ + const had = new Map(recut ? (Array.isArray(up.step.pauses) ? up.step.pauses : []).filter((p) => Number.isInteger(p?.word) && fin(p?.seconds) && p.word < words.length).map((p) => [p.word, p.seconds]) : []); + const among = targetWords(entry, take, target); + const named = new Map(); + for (const p of pauses) { + const i = findPauseWord(entry, words, among, p, target); + if (named.has(i) && named.get(i) !== p.seconds) throw new RereadError(`--pause: "${words[i].w}" (word ${i + 1}) is named twice`); + named.set(i, p.seconds); + } + const after = new Map(had); + for (const [i, s] of named) { + if (s === 0) after.delete(i); + else after.set(i, s); + } + const same = after.size === had.size && [...after].every(([i, s]) => had.get(i) === s); + if (same) throw new PauseError(`${entry.id}'s picked take has ${named.size === 1 ? "that pause" : "those pauses"} already: nothing to change`); + if (!after.size) throw new PauseError(`${entry.id}: that takes every pause away -- pick the take it was cut from (${takeIdOf(take)}) again: umtool posts narrate <p> ${entry.id} --pick ${take.index + 1}`); + if (after.size > PAUSE_MAX) throw new RereadError(`--pause: at most ${PAUSE_MAX} pauses in one take`); + const end = fin(take.seconds) ? take.seconds : Infinity; + const list = [...after].sort((a, b) => a[0] - b[0]).map(([i, s]) => ({ word: i, w: words[i].w, at: cutAfter(words, i, end), seconds: r3(s) })); + // The source cut at each pause, the silence before the span after it. + const spans = list.map((p, j) => ({ from: j === 0 ? 0 : list[j - 1].at, to: p.at, gap: j === 0 ? 0 : list[j - 1].seconds })); + spans.push({ from: list[list.length - 1].at, to: null, gap: list[list.length - 1].seconds }); + // What moves: a word after a pause by its index; a time at or after a cut by the pauses before it. + const before = (i) => list.reduce((acc, p) => (p.word < i ? acc + p.seconds : acc), 0); + const shiftAt = (v, strict = false) => list.reduce((acc, p) => ((strict ? p.at < v : p.at <= v) ? acc + p.seconds : acc), 0); + const newWords = words.map((w, i) => { + const d = before(i); + return { w: w.w, start: r3(w.start + d), end: r3(w.end + d) }; + }); + const parts = Array.isArray(take.parts) + ? take.parts.map((p) => { + if (!fin(p?.start) || !fin(p?.seconds)) return p; + const a = shiftAt(p.start); + const b = shiftAt(p.start + p.seconds, true); + const { file: _f, ...rest } = p; + // A part a pause falls inside grows by it (its own file, if it had one, no longer is it). + return { ...(b > a ? rest : p), start: r3(p.start + a), seconds: r3(p.seconds + Math.max(0, b - a)) }; + }) + : undefined; + const total = list.reduce((acc, p) => acc + p.seconds, 0); + const fixedAt = (Array.isArray(entry.fx) ? entry.fx : []).filter((fx) => fin(fx?.at)).length; + return { + take, picked, recut, target, pauses: list, named: [...named].map(([word, seconds]) => ({ word, w: words[word].w, seconds })), + was: had.size ? [...had].map(([word, seconds]) => ({ word, w: words[word].w, seconds })) : [], + spans, words: newWords, parts, script: typeof take.script === "string" ? take.script : entry.narration.script, + seconds: r3((fin(take.seconds) ? take.seconds : 0) + total), added: r3(total), fixedAt, + steps: [{ op: "pause", pauses: list, ranAt: new Date().toISOString() }], + }; +} + +/** The ffmpeg arguments that cut `src` at the plan's pauses and put each one's silence in (the source sample-exact between). */ +export function pauseArgs(src, out, plan, { rate = 48000, layout = "mono" } = {}) { + const chains = []; + const labels = []; + plan.spans.forEach((s, j) => { + if (s.gap > 0) { + chains.push(`anullsrc=r=${rate}:cl=${layout},atrim=end_sample=${Math.round(s.gap * rate)}[g${j}]`); + labels.push(`[g${j}]`); + } + const trim = `atrim=start_sample=${Math.round(s.from * rate)}${s.to === null ? "" : `:end_sample=${Math.round(s.to * rate)}`}`; + chains.push(`[0:a]aformat=sample_rates=${rate}:channel_layouts=${layout},${trim},asetpts=PTS-STARTPTS[a${j}]`); + labels.push(`[a${j}]`); + }); + chains.push(`${labels.join("")}concat=n=${labels.length}:v=0:a=1[out]`); + return ["-nostdin", "-hide_banner", "-loglevel", "error", "-y", "-i", src, "-filter_complex", chains.join(";"), "-map", "[out]", "-c:a", "pcm_s16le", out]; +} + +/** + * PAUSE post item `e`'s picked take (`pauses`, parsePauseSpec's): the file + * cut and the silences put in, measured, added and picked in one write. + * `dryRun`: the plan only. Returns `{ plan, take?, result? }`. + * + * @param {{ id: string, dir: string }} project + * @param {Record<string, any>} e + * @param {{ pauses: Array<{ match: string, occurrence: number, seconds: number }>, target?: string | null, dryRun?: boolean, measure?: (file: string) => Promise<{ seconds: number|null, lufs: number|null }> }} o + */ +export async function pauseTake(project, e, { pauses, target = null, dryRun = false, measure = undefined }) { + const plan = pausePlan(e, { pauses, target }); + if (dryRun) return { plan }; + const { take, result } = await writeDerivedTake(project, e, plan, { op: "pause", verb: "pause", measure, argsOf: (src, out, fmt) => pauseArgs(src, out, plan, fmt) }); + return { plan, take, result }; +} + +/** One pause as a line says it: `"20" (word 233, after 61.42 s) +0.45 s`. */ +export const pauseLine = (p) => `"${p.w}" (word ${p.word + 1}, after ${p.at.toFixed(2)} s) +${p.seconds} s`; diff --git a/umtool/lib/report/postPause.test.mjs b/umtool/lib/report/postPause.test.mjs @@ -0,0 +1,165 @@ +// postPause.mjs: PAUSES IN AN APPROVED READ, no TTS -- the spec, the word found +// (case and edge punctuation aside, #n its n-th time, a target's words only), +// the cut just after it, everything after moved on (words, parts, the fx that +// read them), the re-cut (absolute), the refusals; the file (ffmpeg, its +// length the source's plus the pauses) picked in ONE write, undoable; the CLI. +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { after, test } from "node:test"; +import { validatePostItem } from "umtool-report-to-video/post-item"; +import { wordZoomTimes } from "umtool-report-to-video/word-zoom"; +import { PauseError, cutAfter, parsePauseSpec, pauseArgs, pausePlan, pauseTake } from "./postPause.mjs"; +import { RereadError } from "./postReread.mjs"; +import { postsCommand } from "./postsCli.mjs"; +import { undoStructural } from "./manifest.mjs"; + +const ROOT = await mkdtemp(path.join(tmpdir(), "umtool-post-pause-")); +after(() => rm(ROOT, { recursive: true, force: true })); +const REPORTS = path.join(ROOT, "reports"); + +// "I'll give you 45 seconds. 20, 10, 4, 0. Alright." in two parts; then "Who are you? 4 more." +const TEXT = "I'll give you 45 seconds. 20, 10, 4, 0. Alright.\n\nWho are you? 4 more."; +const words = () => [ + { w: "I'll", start: 0.1, end: 0.3 }, { w: "give", start: 0.35, end: 0.55 }, { w: "you", start: 0.6, end: 0.7 }, { w: "45", start: 0.75, end: 1.2 }, { w: "seconds.", start: 1.25, end: 1.7 }, + { w: "20,", start: 2.0, end: 2.3 }, { w: "10,", start: 2.4, end: 2.6 }, { w: "4,", start: 2.62, end: 2.8 }, { w: "0.", start: 3.1, end: 3.4 }, { w: "Alright.", start: 3.6, end: 4.0 }, + { w: "Who", start: 4.6, end: 4.8 }, { w: "are", start: 4.85, end: 5.0 }, { w: "you?", start: 5.05, end: 5.3 }, { w: "4", start: 5.5, end: 5.7 }, { w: "more.", start: 5.75, end: 6.1 }, +]; +const parts = () => [ + { n: 1, para: 0, text: "I'll give you 45 seconds. 20, 10, 4, 0. Alright.", start: 0, seconds: 4.2, file: "narration/parts-cache/a.wav", role: "post" }, + { n: 2, para: 1, text: "Who are you? 4 more.", start: 4.5, seconds: 1.8, role: "post" }, +]; +const item = (o = {}) => ({ + type: "post", id: "p-1", post: "subj-x/1", platform: "x", author: "THE SUBJECT", handle: "Subject", date: "2026-10-30T10:00:00.000Z", text: TEXT, + narration: { script: TEXT, takes: [{ file: "narration/posts/1/take-2.orpheus-thread.wav", engine: "orpheus", voice: "leo+zac", seconds: 6.4, slurs: "said", words: words(), parts: parts() }], pick: 0 }, + ...o, +}); + +test("THE SPEC: words and their seconds, #n, a phrase; 0 takes one away; the refusals are usage errors", () => { + assert.deepEqual(parsePauseSpec("20=0.45, 10=0.45,4#2=0.6"), [{ match: "20", occurrence: 1, seconds: 0.45 }, { match: "10", occurrence: 1, seconds: 0.45 }, { match: "4", occurrence: 2, seconds: 0.6 }]); + assert.deepEqual(parsePauseSpec("who are you=1"), [{ match: "who are you", occurrence: 1, seconds: 1 }]); + assert.deepEqual(parsePauseSpec("20=0"), [{ match: "20", occurrence: 1, seconds: 0 }]); + for (const bad of ["", "20", "=0.4", "20=4", "20=0.01", "20=x", "20#0=0.4", "...=0.4"]) assert.throws(() => parsePauseSpec(bad), RereadError, bad); +}); + +test("THE WORD: case and edge punctuation aside, #n its n-th time, a phrase pauses after its last word; the cut half way into the quiet, at most 0.1 s", () => { + const p = pausePlan(item(), { pauses: parsePauseSpec("20=0.45,10=0.45,4=0.45") }); + assert.deepEqual(p.pauses.map((x) => [x.word, x.w, x.at, x.seconds]), [[5, "20,", 2.35, 0.45], [6, "10,", 2.61, 0.45], [7, "4,", 2.9, 0.45]]); + // "4" first is "4," of the countdown; #2 is the second part's. + assert.equal(pausePlan(item(), { pauses: parsePauseSpec("4#2=0.5") }).pauses[0].word, 13); + assert.equal(pausePlan(item(), { pauses: parsePauseSpec("WHO ARE YOU=0.5") }).pauses[0].word, 12); + // The cut: never into the next word (overlapping timings: at the end); the last word: 0.1 s past it, inside the take. + assert.equal(cutAfter([{ w: "a", start: 0, end: 1 }, { w: "b", start: 0.9, end: 2 }], 0), 1); + assert.equal(cutAfter([{ w: "a", start: 0, end: 1 }], 0, 1.05), 1.05); + assert.equal(cutAfter([{ w: "a", start: 0, end: 1 }, { w: "b", start: 1.5, end: 2 }], 0), 1.1); +}); + +test("WHAT MOVES: every word after a pause by the pauses before it, a part after it moved, a part it falls in grown (its own file dropped); the zooms read the words", () => { + const p = pausePlan(item(), { pauses: parsePauseSpec("20=0.45,4=0.3") }); + assert.equal(p.added, 0.75); + assert.equal(p.seconds, 7.15); + assert.deepEqual(p.words.slice(4, 9).map((w) => [w.w, w.start, w.end]), [["seconds.", 1.25, 1.7], ["20,", 2, 2.3], ["10,", 2.85, 3.05], ["4,", 3.07, 3.25], ["0.", 3.85, 4.15]]); + assert.deepEqual(p.words.at(-1), { w: "more.", start: 6.5, end: 6.85 }); + assert.equal(p.words.length, words().length, "one per script word still (the beeps find theirs)"); + assert.deepEqual(p.parts.map((x) => [x.n, x.start, x.seconds, x.file ?? null, x.role]), [[1, 0, 4.95, null, "post"], [2, 5.25, 1.8, null, "post"]]); + assert.deepEqual(p.spans, [{ from: 0, to: 2.35, gap: 0 }, { from: 2.35, to: 2.9, gap: 0.45 }, { from: 2.9, to: null, gap: 0.3 }]); + assert.deepEqual(p.steps.map((s) => [s.op, s.pauses.map((x) => [x.word, x.seconds])]), [["pause", [[5, 0.45], [7, 0.3]]]]); + // A word zoom on "0" is timed by the take's words: on the new take it lands 0.75 s later. + const e = item({ fx: [{ kind: "word-zoom", match: "0" }] }); + const before = wordZoomTimes(e)[0].t; + const t = { file: "narration/posts/1/take-3.pause-orpheus.wav", engine: "derived", voice: "leo+zac", seconds: p.seconds, source: { kind: "take", from: "take-2.orpheus-thread" }, steps: p.steps, words: p.words, parts: p.parts, slurs: "said" }; + const e2 = { ...e, narration: { ...e.narration, takes: [...e.narration.takes, t], pick: 1 } }; + assert.deepEqual(validatePostItem(e2), []); + assert.ok(Math.abs(wordZoomTimes(e2)[0].t - before - 0.75) < 0.01, `zoom ${before} -> ${wordZoomTimes(e2)[0].t}`); + // An effect with a set second is named, not moved. + assert.equal(pausePlan(item({ fx: [{ kind: "word-zoom", match: "0", at: 3 }] }), { pauses: parsePauseSpec("20=0.45") }).fixedAt, 1); + // The validator: a pause step's record. + const bad = { ...e2, narration: { ...e2.narration, takes: [e2.narration.takes[0], { ...t, steps: [{ op: "pause", pauses: [{ word: -1, at: 1, seconds: 9 }] }] }] } }; + assert.equal(validatePostItem(bad).filter((x) => /pauses/.test(x)).length, 1); +}); + +test("A RE-CUT: a pause on a paused take is cut from the take before it, the pauses it had kept, a word named again takes the new seconds, =0 takes one away", () => { + const e = item(); + const p1 = pausePlan(e, { pauses: parsePauseSpec("20=0.45,10=0.45") }); + const t1 = { file: "narration/posts/1/take-3.pause-orpheus.wav", engine: "derived", voice: "leo+zac", seconds: p1.seconds, source: { kind: "take", from: "take-2.orpheus-thread" }, steps: p1.steps, words: p1.words, parts: p1.parts }; + const e2 = { ...e, narration: { ...e.narration, takes: [...e.narration.takes, t1], pick: 1 } }; + const p2 = pausePlan(e2, { pauses: parsePauseSpec("10=0.8,4=0.3") }); + assert.equal(p2.recut, true); + assert.equal(p2.take.file, "narration/posts/1/take-2.orpheus-thread.wav", "cut from the first read"); + assert.deepEqual(p2.pauses.map((x) => [x.w, x.seconds]), [["20,", 0.45], ["10,", 0.8], ["4,", 0.3]]); + assert.equal(p2.seconds, 7.95); + assert.deepEqual(pausePlan(e2, { pauses: parsePauseSpec("20=0") }).pauses.map((x) => x.w), ["10,"]); + assert.throws(() => pausePlan(e2, { pauses: parsePauseSpec("20=0.45") }), /already: nothing to change/); + assert.throws(() => pausePlan(e2, { pauses: parsePauseSpec("20=0,10=0") }), /takes every pause away -- pick the take it was cut from \(take-2\.orpheus-thread\)/); +}); + +test("THE REFUSALS (exit 1): no word timings names posts narrate --words; a word not read; an occurrence not there; a target it does not read", () => { + const nw = item(); + delete nw.narration.takes[0].words; + assert.throws(() => pausePlan(nw, { pauses: parsePauseSpec("20=0.4") }), (err) => err instanceof PauseError && /no word timings.*umtool posts narrate <p> p-1 --words/.test(err.message)); + assert.throws(() => pausePlan(item(), { pauses: parsePauseSpec("twenty=0.4") }), (err) => err instanceof PauseError && /no such word/.test(err.message)); + assert.throws(() => pausePlan(item(), { pauses: parsePauseSpec("4#3=0.4") }), /is in p-1's read 2 times/); + assert.throws(() => pausePlan(item(), { pauses: parsePauseSpec("20=0.4"), target: "quoted" }), /reads no quoted/); + assert.throws(() => pausePlan(item(), { pauses: parsePauseSpec("20=0.4"), target: "nope" }), RereadError); + // A target counts only its parts' words: parts re-roled, "4" in the second part is its first. + const e = item(); + e.narration.takes[0].parts[1].role = "quoted"; + assert.equal(pausePlan(e, { pauses: parsePauseSpec("4=0.4"), target: "quoted" }).pauses[0].word, 13); +}); + +test("THE ffmpeg: the source cut sample-exact at each pause, the silence between, the last span to the end", () => { + const p = pausePlan(item(), { pauses: parsePauseSpec("20=0.45") }); + const fc = pauseArgs("/in.wav", "/o.wav", p, { rate: 24000, layout: "mono" })[8]; + assert.equal(fc, "[0:a]aformat=sample_rates=24000:channel_layouts=mono,atrim=start_sample=0:end_sample=56400,asetpts=PTS-STARTPTS[a0];anullsrc=r=24000:cl=mono,atrim=end_sample=10800[g1];[0:a]aformat=sample_rates=24000:channel_layouts=mono,atrim=start_sample=56400,asetpts=PTS-STARTPTS[a1];[a0][g1][a1]concat=n=3:v=0:a=1[out]"); +}); + +async function project(name, timeline) { + const dir = path.join(REPORTS, name); + await mkdir(path.join(dir, "narration", "posts", "1"), { recursive: true }); + execFileSync("ffmpeg", ["-nostdin", "-loglevel", "error", "-y", "-f", "lavfi", "-i", "sine=frequency=220:duration=6.4:sample_rate=24000", path.join(dir, "narration", "posts", "1", "take-2.orpheus-thread.wav")]); + await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify({ schemaVersion: 1, slug: name, title: name, provenance: { siteOrigin: "" }, render: { width: 1920, height: 1080, fps: 30 }, timeline }, null, 2)); + return { id: name, dir }; +} +const manifest = async (p) => JSON.parse(await readFile(path.join(p.dir, "video.manifest.json"), "utf8")); + +test("PAUSED: the file the source's length plus the pauses, a derived take (source, steps, words moved, slurs kept) picked in ONE write, undoable", async () => { + const p = await project("pause", [item()]); + const e = (await manifest(p)).timeline[0]; + const r = await pauseTake(p, e, { pauses: parsePauseSpec("20=0.45,10=0.45,4=0.45") }); + assert.match(r.take.file, /^narration\/posts\/1\/take-3\.pause-orpheus\.wav$/); + assert.ok(Math.abs(r.take.seconds - 7.75) < 0.02, `measured ${r.take.seconds}`); + const now = (await manifest(p)).timeline[0]; + assert.equal(now.narration.pick, 1); + const t = now.narration.takes[1]; + assert.deepEqual([t.engine, t.source, t.steps[0].op, t.slurs, t.words[8].start], ["derived", { kind: "take", from: "take-2.orpheus-thread" }, "pause", "said", 4.45]); + assert.deepEqual(validatePostItem(now), []); + await undoStructural(p.dir); + assert.equal((await manifest(p)).timeline[0].narration.takes.length, 1, "undone"); +}); + +test("THE CLI: posts reread --pause --dry-run writes nothing, --json the plan; applied, the take picked; a word not read is exit 1, a bad spec exit 2", async () => { + const p = await project("cli", [item()]); + const cli = async (args) => { + const lines = []; + const errs = []; + const code = await postsCommand(args, { root: REPORTS, out: (s) => lines.push(s), err: (s) => errs.push(s) }); + return { code, out: lines.join("\n"), err: errs.join("\n") }; + }; + const dry = await cli(["reread", "cli", "p-1", "--pause", "20=0.45,10=0.45", "--dry-run"]); + assert.equal(dry.code, 0, dry.err); + assert.match(dry.out, /would pause p-1's take \(take-2\.orpheus-thread\): 7\.30 s \(was 6\.40 s, \+0\.9 s of pauses\)/); + assert.match(dry.out, /after "20," \(word 6, after 2\.35 s\) \+0\.45 s/); + assert.equal((await manifest(p)).timeline[0].narration.takes.length, 1, "a dry run writes nothing"); + const js = await cli(["reread", "cli", "p-1", "--pause", "20=0.45", "--dry-run", "--json"]); + const doc = JSON.parse(js.out); + assert.deepEqual([doc.ok, doc.dryRun, doc.pauses.length, doc.added, doc.take], [true, true, 1, 0.45, null]); + const go = await cli(["reread", "cli", "p-1", "--pause", "20=0.45"]); + assert.equal(go.code, 0, go.err); + assert.match(go.out, /take-3\.pause-orpheus\.wav -- picked/); + assert.equal((await manifest(p)).timeline[0].narration.pick, 1); + assert.equal((await cli(["reread", "cli", "p-1", "--pause", "twenty=0.45"])).code, 1); + assert.equal((await cli(["reread", "cli", "p-1", "--pause", "20=9"])).code, 2); + assert.equal((await cli(["reread", "cli", "p-1", "--pause", "20=0.4", "--drop-urls"])).code, 2, "a pause goes alone"); +}); diff --git a/umtool/lib/report/postReread.mjs b/umtool/lib/report/postReread.mjs @@ -39,12 +39,17 @@ export const REREAD_USAGE = [ " umtool posts reread <project> <item> [--without parent:0|parent:1|quoted[,…]] [--drop-parts 3,4] [--drop-urls] [--dry-run] [--json]", " umtool posts reread <project> <item> --tempo-for \"4-16=1.35,21-25=1.3\" | --tempo 1.3 --parts 4-16,21-25 [--stretch atempo|rubberband] [--dry-run] [--json]", " umtool posts reread <project> <item> --yell-caps [--yell-gain 5.5] [--yell-style raise|shout|loud] [--dry-run] [--json]", + " umtool posts reread <project> <item> --pause \"20=0.45,10=0.45,4#2=0.6\" [--target post|parent:0|quoted|linked:0] [--dry-run] [--json]", " (any form, + --in-take <take> or --take <take>: the new take picked in a take's patch, the project's pick kept)", " A READ WITHOUT A PIECE, RE-JOINED (no TTS): the picked take's kept parts cut out of its own file and joined with", " the read's pauses, as a NEW take (source: the take; steps: rejoin) that is picked -- one write, undoable. --without", " drops the parts that read the post it answers (parent:0), that one's parent (parent:1) or the quoted post;", " --drop-parts the parts by number (as posts roles lists them); --drop-urls the parts that are nothing but a link.", " Its parts are re-timed (roles stored), its word timings moved with them, its slurs state kept.", + " --pause: SILENCE PUT IN after each word named (<word>[#<n>]=<seconds>, 0.05-3; #n its n-th time in the read; a", + " phrase pauses after its last word), found in the take's word timings (posts narrate --words makes them): the take", + " cut just after the word, everything after moved on (words, parts, so zooms, captions, slams, beeps keep their", + " words). On a paused take it re-cuts from the take before (=0 takes a pause away). --target counts one piece's words.", ].join("\n"); export class RereadError extends Error { @@ -370,7 +375,7 @@ export function piecesHidden(e, thread) { } /** `umtool posts reread <p> <item> …`: a re-join without a piece, a tempo (`tempoSpec`, tempoPlan's), or a yell (`yell`: postYell.mjs). */ -export async function rereadCommand(project, ref, { without = [], dropParts = [], dropUrls = false, tempoSpec = null, tempo = null, parts = null, stretch = "atempo", yell = null, dryRun = false, json = false, out = (s) => console.log(s) } = {}) { +export async function rereadCommand(project, ref, { without = [], dropParts = [], dropUrls = false, tempoSpec = null, tempo = null, parts = null, stretch = "atempo", yell = null, pause = null, target = null, dryRun = false, json = false, out = (s) => console.log(s) } = {}) { const manifest = await readManifest(project.dir); if (!manifest) throw new RereadError(`${project.id} has no manifest`); const e = (manifest.timeline ?? []).find((x) => x?.type === "post" && (x.id === ref || postIdOf(x) === ref || x.id === `p-${ref}`)); @@ -380,6 +385,11 @@ export async function rereadCommand(project, ref, { without = [], dropParts = [] const { yellCommand } = await import("./postYell.mjs"); return yellCommand(project, manifest, [e], { ...yell, dryRun, json, out }); } + if (pause !== null) { + if (tempoSpec !== null || tempo !== null || without.length || dropParts.length || dropUrls) throw new RereadError("--pause goes alone: re-join or re-time first, then pause that take (it is picked) -- or the other way round"); + return pauseCommand(project, e, { pause, target, dryRun, json, out }); + } + if (target !== null) throw new RereadError("--target names the piece --pause counts its words in"); const timed = tempoSpec !== null || tempo !== null; const t0 = pickedTake(e); const spec = timed ? parseTempoSpec({ spec: tempoSpec, tempo, parts, count: Array.isArray(t0?.parts) ? t0.parts.length : 0 }) : null; @@ -400,3 +410,21 @@ export async function rereadCommand(project, ref, { without = [], dropParts = [] if (r.take) out(` ${r.take.file} -- picked (one undo point: umtool timeline ${project.id} undo)`); return 0; } + +/** `umtool posts reread <p> <item> --pause …` (postPause.mjs): the dry run's plan, or the take made. */ +async function pauseCommand(project, e, { pause, target, dryRun, json, out }) { + const { parsePauseSpec, pauseLine, pauseTake } = await import("./postPause.mjs"); + const r = await pauseTake(project, e, { pauses: parsePauseSpec(pause), target, dryRun }); + const p = r.plan; + const was = Number(p.picked.seconds); + const secs = r.take?.seconds ?? p.seconds; + if (json) { + out(JSON.stringify({ ok: true, id: e.id, dryRun, from: takeIdOf(p.take), recut: p.recut, target: p.target, pauses: p.pauses, added: p.added, seconds: secs, was, fixedAt: p.fixedAt, take: r.take ?? null, token: r.result?.token ?? null }, null, 2)); + return 0; + } + out(`${dryRun ? "would pause" : "paused"} ${e.id}'s take${p.recut ? `, cut again from ${takeIdOf(p.take)} (each pause put in once)` : ` (${takeIdOf(p.take)})`}: ${secs.toFixed(2)} s (was ${was.toFixed(2)} s, +${p.added} s of pauses)`); + for (const x of p.pauses) out(` after ${pauseLine(x)}`); + if (p.fixedAt) out(` note: ${p.fixedAt} effect(s) of this item have a set second (at) -- they do not move with the words; check them`); + if (r.take) out(` ${r.take.file} -- picked (one undo point: umtool timeline ${project.id} undo)`); + return 0; +} diff --git a/umtool/lib/report/postsCli.mjs b/umtool/lib/report/postsCli.mjs @@ -179,7 +179,7 @@ export const POSTS_USAGE = [ " umtool posts scenes <project> [on|off] [--json] the MEDIA SCENES: neighbours with the same attachment", ].join("\n"); -const VALUED = new Set(["--in-take", "--set", "--attach", "--flag", "--author", "--id", "--crop", "--since", "--until", "--replies", "--order", "--limit", "--after", "--script", "--note", "--voice", "--engine", "--speed", "--pick", "--linger", "--derive", "--op", "--delete", "--match", "--target", "--occurrence", "--at", "--scale", "--hold", "--lead", "--ease", "--highlight", "--worker", "--without", "--drop-parts", "--text", "--place", "--rewind", "--zone", "--gap", "--from-scale", "--color", "--outline", "--outline-width", "--size", "--face", "--sfx", "--volume", "--bar", "--bar-style", "--tempo-for", "--tempo", "--parts", "--stretch", "--yell-gain", "--yell-style", "--parents", "--skip-parent", "--voice-for", "--item"]); +const VALUED = new Set(["--in-take", "--set", "--attach", "--flag", "--author", "--id", "--crop", "--since", "--until", "--replies", "--order", "--limit", "--after", "--script", "--note", "--voice", "--engine", "--speed", "--pick", "--linger", "--derive", "--op", "--delete", "--match", "--target", "--occurrence", "--at", "--scale", "--hold", "--lead", "--ease", "--highlight", "--worker", "--without", "--drop-parts", "--text", "--place", "--rewind", "--zone", "--gap", "--from-scale", "--color", "--outline", "--outline-width", "--size", "--face", "--sfx", "--volume", "--bar", "--bar-style", "--tempo-for", "--tempo", "--parts", "--stretch", "--yell-gain", "--yell-style", "--pause", "--parents", "--skip-parent", "--voice-for", "--item"]); /** The valued flags that may be given more than once (each value kept, in order). */ const MULTI = new Set(["--skip-parent", "--voice-for"]); const SLUG_RE = /^[A-Za-z0-9._-]+$/; @@ -484,8 +484,10 @@ export async function postsCommand(args, { root = REPORTS_ROOT, out = (s) => con return await rereadCommand(await projectOf(projectArg, root), ref, { without: list(flags.has("--without") ? str("--without") : null), dropParts, dropUrls: flags.has("--drop-urls"), tempoSpec: flags.has("--tempo-for") ? str("--tempo-for") : null, tempo: flags.has("--tempo") ? str("--tempo") : null, parts: flags.has("--parts") ? str("--parts") : null, - stretch: flags.has("--stretch") ? str("--stretch") : "atempo", yell, dryRun, json, out, + stretch: flags.has("--stretch") ? str("--stretch") : "atempo", yell, + pause: flags.has("--pause") ? str("--pause") : null, target: flags.has("--target") ? str("--target") : null, dryRun, json, out, }).catch((e) => { + // A pause the plan cannot make (PauseError: no word timings, the word not read) is exit 1; a malformed ask, 2. throw e?.name === "RereadError" || e?.name === "YellError" ? new CliError(e.message) : e; }); } diff --git a/umtool/report-to-video/post-narration.mjs b/umtool/report-to-video/post-narration.mjs @@ -61,9 +61,10 @@ export const POST_DERIVE_OPS = Object.freeze(["enhance", "convert"]); /** * The ops umtool runs itself on a take's own file (no editor job, no TTS): `rejoin` -- its kept parts cut out and * joined again; `tempo` -- named parts time-stretched, pitch kept (lib/report/postReread.mjs); `yell` -- the words - * he wrote in ALL CAPS raised, as a voice raised (lib/report/postYell.mjs). + * he wrote in ALL CAPS raised, as a voice raised (lib/report/postYell.mjs); `pause` -- silence put in after words named, + * everything after moved on (lib/report/postPause.mjs). */ -export const POST_LOCAL_OPS = Object.freeze(["rejoin", "tempo", "yell"]); +export const POST_LOCAL_OPS = Object.freeze(["rejoin", "tempo", "yell", "pause"]); /** The editor's op route for each. */ export const POST_DERIVE_ROUTES = Object.freeze({ enhance: "/api/ops/voice-enhance", convert: "/api/ops/voice-convert" }); @@ -188,7 +189,7 @@ const MIX_KEYS = ["lead", "tail", "ramp", "linger", "clip", "wet", "lowpassHz", const RENDER_KEYS = new Set([...MIX_KEYS.filter((k) => k !== "attach"), "engine", "voice", "follow", "thread"]); 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", "source", "steps", "words", "slurs", "lexicon", "read"]); -const STEP_KEYS = new Set(["op", "engine", "voice", "params", "ranAt", "job", "drop", "tempo", "spans"]); +const STEP_KEYS = new Set(["op", "engine", "voice", "params", "ranAt", "job", "drop", "tempo", "spans", "pauses"]); // `role` (post-thread.mjs): the text a part reads -- "post", "quoted", "parent:<i>", "media:<i>"; `voice`, `piece`: the batch's. // `tempo`: the part's reading speed in the take's file against its first read (a `tempo` step's; absent: 1). const PART_KEYS = new Set(["n", "para", "text", "file", "start", "seconds", "gapBefore", "note", "at", "jobId", "role", "voice", "piece", "tempo"]); @@ -658,6 +659,8 @@ export function validatePostNarration(e) { if (st.tempo !== undefined && !(isObj(st.tempo) && Object.keys(st.tempo).length <= 200 && Object.entries(st.tempo).every(([r, v]) => /^\d{1,3}(-\d{1,3})?$/.test(r) && numIn(v, POST_NARRATION_LIMITS.tempo)))) errors.push(`${tw}.steps[${k}].tempo must be {"<part>[-<part>]": ${POST_NARRATION_LIMITS.tempo.join("–")}}`); // A yell step's record: the take seconds it raised. if (st.spans !== undefined && !(Array.isArray(st.spans) && st.spans.length <= 500 && st.spans.every((x) => Array.isArray(x) && x.length === 2 && fin(x[0]) && fin(x[1]) && x[0] >= 0 && x[1] > x[0]))) errors.push(`${tw}.steps[${k}].spans must be a list of [from, to] (take seconds)`); + // A pause step's record: each pause, after word <word> (its index in the take's words), cut at <at> (the source take's seconds). + if (st.pauses !== undefined && !(Array.isArray(st.pauses) && st.pauses.length <= 200 && st.pauses.every((x) => isObj(x) && Number.isInteger(x.word) && x.word >= 0 && fin(x.at) && x.at >= 0 && numIn(x.seconds, [0.05, 3]) && (x.w === undefined || typeof x.w === "string")))) errors.push(`${tw}.steps[${k}].pauses must be a list of {word, w, at, seconds} (seconds 0.05–3)`); } }); }