Archilyzer · Source

archilyzer

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

commit e2e39454f607bec80f2efd1e4af04b3555b967b2
parent e3e4c75ef597477c43198f8bcef24972d5cdea8d
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Mon,  2 Nov 2026 22:56:10 -0500

umtool: recorded takes and the narration route -- a person's own read, part by part; parts; the bench's door

A take may be RECORDED (engine "recorded", a voice label, default "operator"):
POST /api/report/post-narration with the parts as audio (the browser's MediaRecorder),
each decoded to 48 kHz mono, its silence trimmed at either end (detectSilence), joined
with the parts' pauses (0.6 s between paragraphs, 0.25 s inside one) and brought to the
project's synthesized takes' level by one gain -- take-<n>.recorded-<label>.wav and its
.parts/, appended and picked. A take may be composed of PARTS ({n, para, text, file,
start, seconds, gapBefore}); --import reads take-<n>.parts.json beside a take.
scriptParts splits a script into its paragraphs (a paragraph over 60 words at its
sentence ends); drafted scripts keep the post's paragraphs. The same route: the
cut's reading progress, a synthesized take as the editor's tts job (kept when done),
set, fit and undo. The deck band's layout JSDoc back on deckLayout.

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

Diffstat:
Aumtool/app/api/report/post-narration/route.ts | 197+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/postRecord.mjs | 139+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/deck.mjs | 10+++++-----
Mumtool/report-to-video/post-item.mjs | 14++++++++++++--
Mumtool/report-to-video/post-narration.mjs | 86++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----------
Mumtool/report-to-video/post-narration.test.mjs | 3++-
6 files changed, 429 insertions(+), 20 deletions(-)

diff --git a/umtool/app/api/report/post-narration/route.ts b/umtool/app/api/report/post-narration/route.ts @@ -0,0 +1,197 @@ +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 { postItemPlan } from "umtool-report-to-video/post-item"; +import { jobState, resultLine, startJob } from "@/lib/research/case-editor"; +import { withEditNotes } from "@/lib/report/guard"; +import { StaleToken, StructureRefused, fitPostItems, manifestToken, undoStructural, updatePostNarration } from "@/lib/report/manifest.mjs"; +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 { keepRecording, RECORD_LABEL_RE } from "@/lib/report/postRecord.mjs"; +import { fitPostItem } from "@/lib/report/postFit.mjs"; + +export const dynamic = "force-dynamic"; + +// A NARRATED POST ITEM's bench (report-to-video/post-narration.mjs; knobs.md, +// "A narrated post item"): the recording session, the takes, the mix's knobs. +// +// GET ?project the cut's narration progress: each post item, +// what plays (recorded, synthesized, none), approved +// GET ?project&id&job&file[&note][&script] a synthesized take's job; once done, the take is +// kept (measured, appended and picked) +// POST multipart {project, id, label, script?, note?, part[] (audio), text[], para[]} +// a RECORDING, part by part: trimmed, joined, +// levelled, kept as take-<n>.recorded-<label>.wav +// POST {project, op: "set", id, patch, token} updatePostNarration (script, pick, approved, off, the mix) +// 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: "undo"} the last structural write undone + +const noStore = { "cache-control": "no-store" }; +type Entry = Record<string, unknown> & { id: string; type?: string; narration?: Record<string, unknown> }; + +const fail = (e: unknown) => { + if (e instanceof StaleToken) return Response.json({ error: e.message, stale: true }, { status: 409 }); + if (e instanceof StructureRefused) return Response.json({ error: e.message, errors: e.errors }, { status: 400 }); + const status = (e as { status?: number }).status ?? 400; + return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status }); +}; + +const postsOf = (m: Record<string, unknown>) => ((Array.isArray(m.timeline) ? m.timeline : []) as Entry[]).filter((e) => e?.type === "post"); + +export async function GET(request: Request) { + const q = new URL(request.url).searchParams; + const r = await resolveReport(q.get("project") ?? ""); + if ("error" in r) return Response.json({ error: r.error }, { status: r.status }); + const m = r.manifest as Record<string, unknown>; + const render = (m.render ?? {}) as Record<string, unknown>; + const id = q.get("id"); + const job = q.get("job"); + if (id && job) { + const e = postsOf(m).find((x) => x.id === id); + if (!e) return Response.json({ error: `no post item ${id}` }, { status: 404 }); + const rel = q.get("file") ?? ""; + if (!rel.startsWith(`${takesDirOf(postIdOf(e))}/take-`) || rel.includes("..") || !rel.endsWith(".wav")) return Response.json({ error: "not a take of this post" }, { status: 400 }); + try { + const st = await jobState(job); + if (!st.done) return Response.json({ state: "running", status: st.status }, { headers: noStore }); + if (st.status !== "done") return Response.json({ state: "failed", status: st.status, error: st.tail.slice(-3).join(" / ") }, { headers: noStore }); + const had = ((e.narration?.takes ?? []) as Array<{ file?: string }>).some((t) => t.file === rel); + if (!had) { + const abs = path.join(r.project.dir, ...rel.split("/")); + if (!(await stat(abs).catch(() => null))?.isFile()) { + const res = resultLine<{ wav?: string }>(st.tail, "@@tts-result "); + return Response.json({ state: "failed", error: `the job is done but ${rel} is not there (it wrote ${res?.wav ?? "nothing"})` }, { headers: noStore }); + } + const res = resultLine<{ engine?: string; voice?: string }>(st.tail, "@@tts-result ") ?? {}; + const meas = await measureTake(abs); + const note = q.get("note"); + const script = q.get("script") ?? String(e.narration?.script ?? ""); + const take = { + file: rel, engine: res.engine ?? q.get("engine") ?? "orpheus", voice: res.voice ?? q.get("voice") ?? "zac", seconds: meas.seconds, + script, at: new Date().toISOString(), jobId: job, ...(Number.isFinite(meas.lufs) ? { lufs: meas.lufs } : {}), ...(note ? { note } : {}), + }; + 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 }, { headers: noStore }); + } catch (err) { + return fail(err); + } + } + // The progress of the cut's reading: what each post item plays. + const items = postsOf(m).map((e, i) => { + const t = pickedTake(e); + return { + id: e.id, n: i + 1, postId: postIdOf(e), narrated: isNarrated(e), script: !!e.narration?.script, + plays: !t || !isNarrated(e) ? "none" : t.engine === "recorded" ? "recorded" : "synthesized", + approved: e.narration?.approved === true, takes: ((e.narration?.takes ?? []) as unknown[]).length, + seconds: postItemPlan(e, render).total, + }; + }); + return Response.json({ + ok: true, items, + counts: { posts: items.length, recorded: items.filter((x) => x.plays === "recorded").length, synthesized: items.filter((x) => x.plays === "synthesized").length, none: items.filter((x) => x.plays === "none").length, approved: items.filter((x) => x.approved).length }, + }, { headers: noStore }); +} + +export async function POST(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); + let body: Record<string, unknown>; + try { + body = await request.json(); + } catch { + return Response.json({ error: "expected JSON or a recording" }, { status: 400 }); + } + const r = await resolveReport(String(body.project ?? "")); + if ("error" in r) return Response.json({ error: r.error }, { status: r.status }); + const m = r.manifest as Record<string, unknown>; + const id = String(body.id ?? ""); + const token = body.token === undefined || body.token === null ? null : String(body.token); + try { + if (body.op === "undo") { + const { result } = await withEditNotes(r.project, () => undoStructural(r.project.dir, { token })); + return Response.json({ ok: true, ...result }, { headers: noStore }); + } + const e = postsOf(m).find((x) => x.id === id); + if (!e) return Response.json({ error: `no post item ${id}` }, { status: 404 }); + if (body.op === "set") { + const { result, editNotes } = await withEditNotes(r.project, () => updatePostNarration(r.project.dir, id, (body.patch ?? {}) as Record<string, unknown>, { token })); + return Response.json({ ok: true, entry: result.entry, token: result.token, editNotes }, { headers: noStore }); + } + if (body.op === "take") { + // The EDITOR synthesizes (its tts op, a job on its queue); the take is kept when the job is done (GET ?job). + const k = postNarrationKnobs(e, (m.render ?? {}) as Record<string, unknown>); + const script = String(body.script ?? e.narration?.script ?? "").trim(); + if (!script) return Response.json({ error: `${id} has no script to read` }, { status: 400 }); + const engine = String(body.engine ?? e.narration?.engine ?? k.engine); + const voice = String(body.voice ?? e.narration?.voice ?? k.voice); + const pid = postIdOf(e); + const dir = path.join(r.project.dir, ...takesDirOf(pid).split("/")); + await mkdir(dir, { recursive: true }); + const rel = takeFileOf(pid, nextTakeNumber(e, await readdir(dir).catch(() => [])), engine, voice); + const speed = body.speed === undefined || body.speed === null || engine === "orpheus" ? undefined : Number(body.speed); + 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 === "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 }); + if (!f || f.untouched || !f.window) return Response.json({ ok: true, untouched: true, why: !f ? "not narrated, clip=full, or no video" : "its video is no longer than the read" }, { headers: noStore }); + const { result } = await withEditNotes(r.project, async () => fitPostItems(r.project.dir, [{ id, media: f.media, window: f.window, ...(linger !== null ? { linger } : {}) }], { token: await manifestToken(r.project.dir) })); + const after = ((await readManifest(r.project.dir)) ?? {}) as Record<string, unknown>; + 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 }); + } catch (err) { + return fail(err); + } +} + +/** A recording, part by part: the uploads kept beside the post's takes until they are made into one. */ +async function record(request: Request) { + let form: FormData; + try { + form = await request.formData(); + } catch { + return Response.json({ error: "expected a multipart recording" }, { status: 400 }); + } + const r = await resolveReport(String(form.get("project") ?? "")); + if ("error" in r) return Response.json({ error: r.error }, { status: r.status }); + const m = r.manifest as Record<string, unknown>; + const id = String(form.get("id") ?? ""); + const e = postsOf(m).find((x) => x.id === id); + if (!e) return Response.json({ error: `no post item ${id}` }, { status: 404 }); + const label = String(form.get("label") ?? "operator").trim().toLowerCase() || "operator"; + if (!RECORD_LABEL_RE.test(label)) return Response.json({ error: `"${label}" is not a voice label (a-z, 0-9, - and _)` }, { status: 400 }); + const blobs = form.getAll("part").filter((x): x is File => typeof x === "object" && x !== null && "arrayBuffer" in x); + if (!blobs.length) return Response.json({ error: "nothing was recorded" }, { status: 400 }); + const texts = form.getAll("text").map(String); + const paras = form.getAll("para").map((x) => Number(x)); + const up = path.join(r.project.dir, ...takesDirOf(postIdOf(e)).split("/"), `.upload-${Date.now()}`); + await mkdir(up, { recursive: true }); + try { + const parts = []; + for (const [k, b] of blobs.entries()) { + if (b.size > 200 * 1024 * 1024) return Response.json({ error: "a part is larger than 200 MB" }, { status: 413 }); + const f = path.join(up, `p${k + 1}.${/ogg/.test(b.type) ? "ogg" : /wav/.test(b.type) ? "wav" : "webm"}`); + await writeFile(f, new Uint8Array(await b.arrayBuffer())); + parts.push({ file: f, text: texts[k] ?? "", para: Number.isInteger(paras[k]) ? paras[k] : k }); + } + const script = form.get("script"); + const note = form.get("note"); + const kept = await keepRecording(r.project, e, parts, { label, manifest: m, note: note ? String(note) : null, script: script === null ? null : String(script) }); + return Response.json({ ok: true, take: kept.take, gain: kept.gain, target: kept.target, token: kept.result.token, entry: kept.result.entry }, { headers: noStore }); + } catch (err) { + return fail(err); + } finally { + await rm(up, { recursive: true, force: true }); + } +} diff --git a/umtool/lib/report/postRecord.mjs b/umtool/lib/report/postRecord.mjs @@ -0,0 +1,139 @@ +// A RECORDED TAKE (operator, 2 Nov: "I think I'll record my voice"): a +// person's own reading of a post item's script, recorded on the post bench +// (the browser's MediaRecorder) PART BY PART for a long post, kept as a take +// like a synthesized one -- the render and Play treat it the same. +// +// narration/posts/<postId>/take-<n>.recorded-<label>.wav the joined read +// narration/posts/<postId>/take-<n>.recorded-<label>.parts/pNN.wav each part, trimmed +// +// Each part is decoded by ffmpeg to 48 kHz mono, its leading and trailing +// silence trimmed (detectSilence, cut-points.mjs) leaving a breath of room; +// the parts are joined with post-narration.mjs's pauses (0.6 s between +// paragraphs, 0.25 s inside one); the whole is brought to the level of the +// project's synthesized takes (their measured loudness, else -21 LUFS) by one +// gain under a -1 dBFS limiter. Nothing else: no cloning, no TTS, no effects. +import { execFile } from "node:child_process"; +import { mkdir, readdir, rename, rm, stat } from "node:fs/promises"; +import path from "node:path"; +import { promisify } from "node:util"; +import { detectSilence } from "umtool-report-to-video/cut-points"; +import { POST_NARRATION_DEFAULTS, nextTakeNumber, partGapBefore, postIdOf, takesDirOf } from "umtool-report-to-video/post-narration"; +import { withEditNotes } from "./edit-guard.mjs"; +import { manifestToken, updatePostNarration } from "./manifest.mjs"; +import { measureTake } from "./postNarrationCli.mjs"; + +const execFileP = promisify(execFile); +const FFMPEG = () => process.env.FFMPEG_BIN ?? "ffmpeg"; + +/** The room kept before and after a part's words when its silence is trimmed. */ +export const RECORD_ROOM = Object.freeze({ head: 0.08, tail: 0.15 }); +/** A recorded voice's label: `operator` unless a guest's. */ +export const RECORD_LABEL_RE = /^[a-z0-9][a-z0-9_-]{0,31}$/; + +const r3 = (v) => Math.round(v * 1000) / 1000; + +/** The span of a part worth keeping, from its silences: `[from, to]` inside `[0, seconds]`. */ +export function trimSpan(silences, seconds, room = RECORD_ROOM) { + let from = 0; + let to = seconds; + const lead = silences.find((x) => x.s <= 0.05); + if (lead && lead.e < seconds) from = Math.max(0, lead.e - room.head); + const tail = [...silences].reverse().find((x) => x.e >= seconds - 0.05); + if (tail && tail.s > from) to = Math.min(seconds, tail.s + room.tail); + if (to - from < 0.2) return { from: 0, to: seconds }; + return { from: r3(from), to: r3(to) }; +} + +/** The level the project's synthesized takes read at (their mean LUFS), else the default. */ +export function targetLufsOf(manifest) { + const v = []; + for (const e of manifest?.timeline ?? []) { + for (const t of e?.narration?.takes ?? []) if (t?.engine && t.engine !== "recorded" && Number.isFinite(t.lufs)) v.push(t.lufs); + } + return v.length ? Math.round((v.reduce((a, b) => a + b, 0) / v.length) * 10) / 10 : POST_NARRATION_DEFAULTS.lufs; +} + +/** + * KEEP A RECORDING: `parts` `[{ file (an uploaded blob, absolute), text, para }]` + * in reading order, made into take-<n>.recorded-<label>.wav and added to + * `entry`'s takes (picked) through the writer. Returns the take. + * + * @param {{ id: string, dir: string }} project + * @param {Record<string, any>} entry + * @param {Array<{ file: string, text?: string, para?: number }>} parts + * @param {{ label?: string, manifest?: Record<string, any>, note?: string | null, script?: string | null }} [o] + */ +export async function keepRecording(project, entry, parts, { label = "operator", manifest = null, note = null, script = null } = {}) { + if (!RECORD_LABEL_RE.test(label)) throw new Error(`"${label}" is not a voice label (a-z, 0-9, - and _)`); + if (!parts.length) throw new Error("nothing was recorded"); + const pid = postIdOf(entry); + const dir = path.join(project.dir, ...takesDirOf(pid).split("/")); + await mkdir(dir, { recursive: true }); + const n = nextTakeNumber(entry, await readdir(dir).catch(() => [])); + const base = `take-${n}.recorded-${label}`; + const rel = `${takesDirOf(pid)}/${base}.wav`; + const partsRel = `${takesDirOf(pid)}/${base}.parts`; + const partsDir = path.join(project.dir, ...partsRel.split("/")); + await mkdir(partsDir, { recursive: true }); + const ff = FFMPEG(); + // Each part: decoded, measured, trimmed of its silence at either end. + const made = []; + for (const [k, p] of parts.entries()) { + const raw = path.join(partsDir, `.p${String(k + 1).padStart(2, "0")}.raw.wav`); + await execFileP(ff, ["-nostdin", "-v", "error", "-y", "-i", p.file, "-vn", "-ac", "1", "-ar", "48000", "-c:a", "pcm_s16le", raw]); + const { seconds } = await measureTake(raw); + const sil = await detectSilence(raw, { silenceMinDur: 0.15 }).catch(() => []); + const span = trimSpan(sil, seconds ?? 0); + const out = path.join(partsDir, `p${String(k + 1).padStart(2, "0")}.wav`); + await execFileP(ff, ["-nostdin", "-v", "error", "-y", "-i", raw, "-af", `atrim=${span.from}:${span.to},asetpts=PTS-STARTPTS`, "-ar", "48000", "-ac", "1", "-c:a", "pcm_s16le", out]); + await rm(raw, { force: true }); + made.push({ out, seconds: r3(span.to - span.from), text: p.text, para: Number.isInteger(p.para) ? p.para : k }); + } + // Joined with the pauses, then brought to the synthesized takes' level. + const withPara = made.map((m) => ({ ...m })); + const inputs = []; + const chain = []; + let start = 0; + const partsOut = []; + withPara.forEach((m, k) => { + const gap = partGapBefore(withPara, k); + if (gap > 0) chain.push({ silence: gap }); + start += gap; + partsOut.push({ n: k + 1, para: m.para, ...(m.text ? { text: m.text } : {}), file: `${partsRel}/p${String(k + 1).padStart(2, "0")}.wav`, start: r3(start), seconds: m.seconds, gapBefore: gap }); + chain.push({ file: m.out }); + start += m.seconds; + }); + const filters = []; + const labels = []; + for (const [j, c] of chain.entries()) { + if (c.file) { + inputs.push("-i", c.file); + filters.push(`[${inputs.filter((x) => x === "-i").length - 1}:a]aformat=sample_rates=48000:channel_layouts=mono[s${j}]`); + } else { + inputs.push("-f", "lavfi", "-t", String(c.silence), "-i", "anullsrc=channel_layout=mono:sample_rate=48000"); + filters.push(`[${inputs.filter((x) => x === "-i").length - 1}:a]anull[s${j}]`); + } + labels.push(`[s${j}]`); + } + const joined = path.join(dir, `.${base}.joined.wav`); + await execFileP(ff, ["-nostdin", "-v", "error", "-y", ...inputs, "-filter_complex", `${filters.join(";")};${labels.join("")}concat=n=${labels.length}:v=0:a=1[a]`, "-map", "[a]", "-c:a", "pcm_s16le", joined]); + const measured = await measureTake(joined); + const target = targetLufsOf(manifest ?? {}); + const gain = Number.isFinite(measured.lufs) ? Math.max(-20, Math.min(30, target - measured.lufs)) : 0; + const tmp = path.join(dir, `.${base}.tmp.wav`); + await execFileP(ff, ["-nostdin", "-v", "error", "-y", "-i", joined, "-af", `volume=${gain.toFixed(2)}dB,alimiter=limit=0.891251:level=0:latency=1`, "-ar", "48000", "-ac", "1", "-c:a", "pcm_s16le", tmp]); + await rm(joined, { force: true }); + const abs = path.join(project.dir, ...rel.split("/")); + await rename(tmp, abs); + 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 ?? ""), + at: new Date().toISOString(), ...(Number.isFinite(m.lufs) ? { lufs: m.lufs } : {}), ...(note ? { note } : {}), + ...(partsOut.length > 1 ? { parts: partsOut } : {}), + }; + const { result, editNotes } = await withEditNotes(project, async () => + updatePostNarration(project.dir, entry.id, { addTake: take, ...(script !== null && script !== entry.narration?.script ? { script } : {}) }, { token: await manifestToken(project.dir) }), + ); + return { take, gain: Math.round(gain * 100) / 100, target, result, editNotes }; +} diff --git a/umtool/report-to-video/deck.mjs b/umtool/report-to-video/deck.mjs @@ -456,6 +456,11 @@ export function threadsGeometry(render) { }; } +/** The air the band keeps under its text block, px. */ +export const BAND_FOOT = 0; +/** In a crowded band, the share of the width the title and byline keep at the left (the section title stays out of it). */ +export const BAND_TEXT_RESERVE = 0.36; + /** * Where things sit INSIDE the deck region (region-local pixels). The * composition draws from this; umtool's preview frames the same rect. A @@ -472,11 +477,6 @@ export function threadsGeometry(render) { * * @param {{ tally?: string[] | null, schedule?: any }} [opts] */ -/** The air the band keeps under its text block, px. */ -export const BAND_FOOT = 0; -/** In a crowded band, the share of the width the title and byline keep at the left (the section title stays out of it). */ -export const BAND_TEXT_RESERVE = 0.36; - export function deckLayout(render, { tally = null, schedule = null } = {}) { const { W, deck: rect } = deckGeometry(render); const d = resolveDeck(render); diff --git a/umtool/report-to-video/post-item.mjs b/umtool/report-to-video/post-item.mjs @@ -166,12 +166,20 @@ export const POST_PICTURE_MIN = 1.5; /** The crossfade from one picture to the next, in seconds. */ export const POST_PICTURE_XFADE = 0.3; -/** The item's length by the rule, before `hold`. */ +/** + * The item's length by the rule, before `hold`. + * @param {Record<string, any>} entry + * @param {Record<string, any>} [render] + */ export function ruleSeconds(entry, render = undefined) { return planOf(entry, render, null).total; } -/** The item's length in the cut: `hold` when it is set, else the rule. `render` the cut's (its `postNarration` knobs). */ +/** + * The item's length in the cut: `hold` when it is set, else the rule. `render` the cut's (its `postNarration` knobs). + * @param {Record<string, any>} entry + * @param {Record<string, any>} [render] + */ export function postItemSeconds(entry, render = undefined) { if (fin(entry?.hold) && entry.hold > 0) return round3(entry.hold); return ruleSeconds(entry, render); @@ -187,6 +195,8 @@ export function postItemSeconds(entry, render = undefined) { * plan is cut (or extended) to it. A narrated item's plan carries its mix * (`narration`: narrationSchedule). The render and Play both play this plan. * + * @param {Record<string, any>} entry + * @param {Record<string, any>} [render] * @returns {{ reading: number, total: number, steps: Array<Record<string, any>>, held: number, narration?: Record<string, any> }} */ export function postItemPlan(entry, render = undefined) { diff --git a/umtool/report-to-video/post-narration.mjs b/umtool/report-to-video/post-narration.mjs @@ -290,7 +290,7 @@ export function postNarrationFilters({ media, voice, out, sch, gainDb = 0, audio * the operator's own edit. */ export function speakableText(text) { - return String(text ?? "") + const clean = String(text ?? "") .replace(/^RT @[A-Za-z0-9_]+:\s*/, "") .replace(/https?:\/\/\S+/g, " ") .replace(/(^|[\s(])@[A-Za-z0-9_]{1,30}\b/g, "$1") @@ -300,17 +300,24 @@ export function speakableText(text) { .replace(/(^|\s)w\/(?=\S)/gi, "$1with ") .replace(/\s&\s/g, " and ") .replace(/&amp;/g, "and") - .replace(/[ \t]+/g, " ") - .replace(/\s*\n\s*/g, "\n") - .split("\n") - .map((l) => l.trim()) - .filter(Boolean) - // A line break is a pause: a line that ends unpunctuated gets its full stop. - .map((l, i, all) => (i < all.length - 1 && !/[.!?…,;:—-]["')\]]*$/.test(l) ? `${l}.` : l)) - .join(" ") - .replace(/\s+([,.!?;:])/g, "$1") - .replace(/^[,.;:]\s*/, "") - .trim(); + .replace(/[ \t]+/g, " "); + // Its paragraphs (blank lines) stay paragraphs -- a long read is recorded and synthesized by them (scriptParts). + const paras = clean + .split(/\n[ \t]*\n/) + .map((para) => + para + .split("\n") + .map((l) => l.trim()) + .filter(Boolean) + // A line break is a pause: a line that ends unpunctuated gets its full stop. + .map((l, i, all) => (i < all.length - 1 && !/[.!?…,;:—-]["')\]]*$/.test(l) ? `${l}.` : l)) + .join(" ") + .replace(/\s+([,.!?;:])/g, "$1") + .replace(/^[,.;:]\s*/, "") + .trim(), + ) + .filter(Boolean); + return paras.map((p, i) => (i < paras.length - 1 && !/[.!?…,;:—-]["')\]]*$/.test(p) ? `${p}.` : p)).join("\n\n"); } /** @@ -451,3 +458,58 @@ export function postNarrationDisclosure(entry) { 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 ?? "?"})`; } + +// --------------------------------------------------------------------------- +// A long read, PART BY PART (operator, 2 Nov: "some of these massive posts +// will need to compose multiple read paragraphs and can't be one-shot"): the +// script split into parts -- its paragraphs (blank lines), a paragraph over +// POST_PART_WORDS words split at its sentence ends -- each synthesized or +// recorded on its own and joined with a pause between them. +// --------------------------------------------------------------------------- + +/** A part reads at most this many words (a paragraph longer than it is split at a sentence end). */ +export const POST_PART_WORDS = 60; +/** The pause the parts are joined with: between paragraphs, and inside one. */ +export const POST_PART_GAP = Object.freeze({ para: 0.6, inside: 0.25 }); + +const wordsOf = (t) => (String(t).trim() ? String(t).trim().split(/\s+/).length : 0); + +/** + * The script's PARTS, pure: `[{ n, para, text }]` (n from 1, para the + * paragraph's index from 0). A script of one short paragraph is one part. + */ +export function scriptParts(script, max = POST_PART_WORDS) { + const paras = String(script ?? "").split(/\n\s*\n/).map((p) => p.replace(/\s+/g, " ").trim()).filter(Boolean); + const out = []; + paras.forEach((p, para) => { + if (wordsOf(p) <= max) { + out.push({ para, text: p }); + return; + } + const sentences = p.match(/[^.!?…]+[.!?…]+["')\]]*\s*|[^.!?…]+$/g) ?? [p]; + let cur = ""; + for (const sen of sentences) { + if (cur && wordsOf(cur) + wordsOf(sen) > max) { + out.push({ para, text: cur.trim() }); + cur = ""; + } + cur += sen; + } + if (cur.trim()) out.push({ para, text: cur.trim() }); + }); + return out.map((p, i) => ({ n: i + 1, ...p })); +} + +/** The pause before part `k` of `parts` (0 before the first). */ +export const partGapBefore = (parts, k) => (k === 0 ? 0 : parts[k].para !== parts[k - 1].para ? POST_PART_GAP.para : POST_PART_GAP.inside); + +/** The part being read at item second `s` (the picked take's parts, on the item's clock), or null. */ +export function partAt(entry, sch, s) { + const t = pickedTake(entry); + const parts = Array.isArray(t?.parts) ? t.parts : []; + if (!parts.length || !sch) return null; + const local = s - sch.at; + let cur = null; + for (const p of parts) if (local >= p.start - 0.05) cur = p; + return cur; +} diff --git a/umtool/report-to-video/post-narration.test.mjs b/umtool/report-to-video/post-narration.test.mjs @@ -173,7 +173,8 @@ test("the segment's argv carries the take as an input and the mix after the item }); test("SCRIPTS ARE THE POST, VERBATIM: cleaned for pronunciation only, never an excerpt", () => { - assert.equal(speakableText("@KorriiNami Trust me & you w/ my plan(s) 😂 https://t.co/x\n\nI hate the weak"), "Trust me and you with my plans. I hate the weak"); + assert.equal(speakableText("@KorriiNami Trust me & you w/ my plan(s) 😂 https://t.co/x\n\nI hate the weak"), "Trust me and you with my plans.\n\nI hate the weak"); + assert.equal(speakableText("one\ntwo\n\nthree"), "one. two.\n\nthree"); const long = Array.from({ length: 150 }, (_, i) => `w${i}`).join(" ") + ". The end."; const d = draftScript(long); assert.equal(d.words, 152);