Archilyzer · Source

archilyzer

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

commit 7dad8de15309c5cf81b9c95ba20877b1b5352783
parent 2ba75e6cd84a9ea36a681f48694b4eb855d90352
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Wed,  4 Nov 2026 22:52:09 -0500

Merge main into lane/play-preload: join-continuity and voice-tools beside the preload -- PostItemPlayer keeps the join's clock (eased from the item before's place, faded in) and the readiness look after it

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

Diffstat:
Mumtool/app/api/report/post-item/route.ts | 14++++++--------
Mumtool/app/api/report/post-narration/route.ts | 8+++++---
Mumtool/bin/umtool.mjs | 13+++++++++++++
Mumtool/components/projects/review/PlayCut.tsx | 2+-
Mumtool/components/projects/review/PostItemPlayer.tsx | 78++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------------------
Mumtool/docs/cli.md | 6+++++-
Mumtool/docs/knobs.md | 59+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/docs/report-video.md | 60+++++++++++++++++++++++++++++++++++++++++++++++++++---------
Aumtool/lib/report/checkJoinsCli.mjs | 62++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/manifest.mjs | 2+-
Mumtool/lib/report/postNarrationCli.mjs | 37++++++++++++++++++++++++++++++++++---
Mumtool/lib/report/postRedaction.mjs | 14++++++++++----
Aumtool/lib/report/postSay.mjs | 317+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/postThreadRead.mjs | 434+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/postThreadRead.test.mjs | 346+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/postsCli.mjs | 54++++++++++++++++++++++++++++++++++++++++++++++--------
Mumtool/report-to-video/build-video.mjs | 10+++++++---
Aumtool/report-to-video/check-joins.mjs | 291++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/check-joins.test.mjs | 51+++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/package.json | 2++
Mumtool/report-to-video/post-item.mjs | 70++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------
Aumtool/report-to-video/post-join-continuity.test.mjs | 110+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/post-join.mjs | 63++++++++++++++++++++++++++++++++++++++++++++++++++-------------
Aumtool/report-to-video/post-media-enter.test.mjs | 81+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/post-narration.mjs | 10+++++++---
Mumtool/report-to-video/post-redact.mjs | 35+++++++++++++++++++++++++----------
Mumtool/report-to-video/post-render.mjs | 180+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------------------
Aumtool/report-to-video/post-say.mjs | 266+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/post-say.test.mjs | 136+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
29 files changed, 2677 insertions(+), 134 deletions(-)

diff --git a/umtool/app/api/report/post-item/route.ts b/umtool/app/api/report/post-item/route.ts @@ -1,6 +1,6 @@ import { readFile, realpath, stat } from "node:fs/promises"; import path from "node:path"; -import { cardWordsSize, panelEntry, postCardHtml, postItemPlan } from "umtool-report-to-video/post-item"; +import { joinCarryOf, panelEntry, postCardHtml, postItemPlan } from "umtool-report-to-video/post-item"; import { avatarUrls } from "umtool-report-to-video/post-avatars"; import { jobState, startJob } from "@/lib/research/case-editor"; import { withEditNotes } from "@/lib/report/guard"; @@ -63,12 +63,10 @@ async function itemOf(project: { dir: string }, manifest: Record<string, unknown return { item: at >= 0 ? tl[at] : null, prev: ctx.prev, ctx, prevCtx, manifest: m }; } -/** The size the item before draws its post's words at (post-item.mjs cardWordsSize; threaded when its plan is). */ -function joinWordsSize(prev: Entry, prevCtx: Record<string, unknown> | null, render: Record<string, unknown>, box: { width: number; height: number }) { +/** How the item before draws its post (post-item.mjs joinCarryOf), as the build draws the carried post alike. */ +function joinCarry(prev: Entry, prevCtx: Record<string, unknown> | null, render: Record<string, unknown>, box: { width: number; height: number }) { const pe = panelEntry(prev, render) as Entry; - const follow = followKnobs(pe, render).on; - const plan = postItemPlan(pe, render, (prevCtx ?? {}) as never) as { follow?: { thread?: unknown } }; - return cardWordsSize(pe, box, { follow, threaded: follow && !!plan.follow?.thread }); + return joinCarryOf(pe, postItemPlan(pe, render, (prevCtx ?? {}) as never) as never, box, render); } /** A project file under posts-media/, never outside it (its real path checked). */ @@ -185,7 +183,7 @@ export async function GET(request: Request) { let redaction = null; try { // uncensored=1: the slur filter off (post-slurs.mjs) -- Play's Uncensored; the redaction stays. - if (q.get("published") === "1") redaction = await projectRedaction(r.project.dir, found.manifest, { uncensored: q.get("uncensored") === "1" }); + if (q.get("published") === "1") redaction = await projectRedaction(r.project.dir, found.manifest, { uncensored: q.get("uncensored") === "1", say: false }); } catch (e) { return new Response(e instanceof Error ? e.message : String(e), { status: 500 }); } @@ -221,7 +219,7 @@ export async function GET(request: Request) { thread: followOn ? (scene ? sceneLayout(isNarrated(item) ? tlayout : null, item, scene) ?? tlayout : tlayout) : null, redaction, // THE JOIN (post-join.mjs): the post the item before ended on drawn as it drew its post (Play lays the morph). - join: followOn && found.ctx.join && found.prev?.type === "post" ? { size: joinWordsSize(found.prev as Entry, found.prevCtx, cutRender, { width: w, height: h }) } : null, + join: followOn && found.ctx.join && found.prev?.type === "post" ? joinCarry(found.prev as Entry, found.prevCtx, cutRender, { width: w, height: h }) : null, }); return new Response(html, { headers: { "content-type": "text/html; charset=utf-8", ...noStore } }); } diff --git a/umtool/app/api/report/post-narration/route.ts b/umtool/app/api/report/post-narration/route.ts @@ -109,9 +109,11 @@ export async function GET(request: Request) { } // What its audio does with the script's slurs (post-slurs.mjs): as the POST above asked for it. const red = await projectRedaction(r.project.dir, m); - const slurs = spokenRead(script, e, red, { voice: benchVoice(red) }).slurs; + const { slurs, lexicon } = spokenRead(script, e, red, { voice: benchVoice(red) }); const take = { ...(slurs ? { slurs } : {}), + // The pronunciation entries it said (post-say.mjs), as the POST above applied them. + ...(lexicon ? { lexicon } : {}), 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 } : {}), @@ -180,8 +182,8 @@ export async function POST(request: Request) { 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); - // What the voice SAYS: the script with every redacted term left out (post-redact.mjs) and each slur as the cut's - // filter has it (post-slurs.mjs); the script is kept as written. The bench cannot word-time a take as it is made, + // What the voice SAYS: the script with every redacted term left out (post-redact.mjs), each slur as the cut's + // filter has it (post-slurs.mjs) and the project's pronunciation lexicon applied (post-say.mjs); the script is kept as written. The bench cannot word-time a take as it is made, // so a beep falls back to skip here (the CLI's --take times it and beeps). const red = await projectRedaction(r.project.dir, m); const spoken = spokenRead(script, e, red, { voice: benchVoice(red) }).text; diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs @@ -16,6 +16,7 @@ // umtool check [<project> | --all] [--json] exit 1 on anything blocking // umtool links <project> [--json] [--fix] do the clip QRs open on their sites (out/links.json) // umtool speaker-check <project> [--clip <id> …] [--set 'Name=…'] [--list] which named voice each clip is (speaker-check.json) +// umtool check-joins <project> --take <id> [--json] [--all] do the post joins of a rendered take carry on, or jump // umtool link-policy <project> [--via <site>] [--direct a,b] [--clear] [--fix] cite via site X; these channels direct // umtool decisions [--json] // umtool inbox [--all] [--json] the decisions grouped as the inbox ranks them @@ -114,6 +115,8 @@ // reel <project> --channel <slug>… [--since/--until/--own/--with-media/--replies/--order/--limit] post items // set-item <project> <item> hold=… media.<i>.start=… a post item's knobs // narrate <project> [<item>] --import | --take | --script | --pick | --approve | k=v | --all … narration +// narrate <project> <item> --take --thread [--parents 0|all] … a thread read (postThreadRead.mjs) +// say <project> ls | add | remove | try | stale · voices <project> ls | set | remove lexicon, voice map // fit <project> --all | <item>… narrated posts' videos cut to their best part // avatar <project> <handle> <image> | avatars <project> the authors' pictures // redact <project> ls | add "<term>" [--substring] | remove <n> words blanked from what is published @@ -852,6 +855,8 @@ function usage() { " -> the shard's record; polite, cached; out/links.json, which check reads); exit 1 when one is dead", " umtool speaker-check <project> [--clip <id> …] [--json] which of the project's named voices (speakers.json) each", " clip is: TitaNet-small, local -> speaker-check.json; --set 'Name=<clip>,<channel>/<id>,channel:<slug>' / --remove / --list", + " umtool check-joins <project> --take <id> [--json] [--all] [--limit <n>] every boundary of the take's master where the", + " next post item draws a post the one before showed: its join, the SSIM across it, the largest jump", " umtool link-policy <project> [--via <site id|url>] [--direct a,b] [--clear] [--fix] [--json] the link policy", " (provenance.linkPolicy): cite via site X, these channels direct; --fix rewrites the clips that break it", " umtool patch-markers <project> [<file>.patch.json] [--fix] [--json] take patches whose deck markers name a", @@ -1041,6 +1046,12 @@ function usage() { " [media.<i>.end=<s>] [media.<i>.mute=on|off] [media.<i>.crop=x,y,w,h|off] [media.<i>.push=on|off] [--json]", " umtool posts narrate <project> [--import | --list | <item> [--script \"…\"] [--take [--note \"…\"]] [--pick n] [--approve] [k=v …]", " | --all --draft-scripts | --all --take | --cut k=v …] a post read aloud (its takes: the editor's tts or yours)", + " umtool posts narrate <project> <item> --take --thread [--parents 0|all] [--skip-parent <id>]… [--no-quoted]", + " [--voice-for <handle>=<voice>]… [--dry-run] [--json] a THREAD READ: its context and his words in date", + " order, each in its author's voice, parts cached, one take saved and picked (exit 0 / 1)", + " umtool posts say <project> ls | add <word> \"<spoken>\" [--case] [--item <id>] | remove <word> | try \"<text>\" | stale", + " the PRONUNCIATION LEXICON every synthesized read applies (stale: picked reads that say it the old way)", + " umtool posts voices <project> ls | set <handle|*> <voice> | remove <handle> the voice map a thread read uses", " umtool posts fit <project> [--all | <item> …] [--linger s] [--dry-run] narrated posts' videos cut to their best part", " umtool posts avatar <project> [<handle> <image>|off] · avatars <project> the authors' pictures on the cards", " umtool posts redact <project> ls | add \"<term>\" [--substring] [--note \"…\"] | remove <n> words blanked from", @@ -1113,6 +1124,8 @@ const COMMANDS = { links: async () => process.exit(await (await import("../lib/report/linksCli.mjs")).linksCommand(argv.slice(argv.indexOf("links") + 1))), // Which named voice each clip is (UI notes #15): lib/report/speakerCheck.mjs. "speaker-check": async () => process.exit(await (await import("../lib/report/speakerCheck.mjs")).speakerCheckCommand(argv.slice(argv.indexOf("speaker-check") + 1))), + // Do a rendered take's post joins carry on (operator, 4 Nov, mid-7): lib/report/checkJoinsCli.mjs. + "check-joins": async () => process.exit(await (await import("../lib/report/checkJoinsCli.mjs")).checkJoinsCommand(argv.slice(argv.indexOf("check-joins") + 1))), // The project's link policy (UI notes #10): lib/report/linksCli.mjs. "link-policy": async () => process.exit(await (await import("../lib/report/linksCli.mjs")).linkPolicyCommand(argv.slice(argv.indexOf("link-policy") + 1))), // A take patch's markers back on the cut (UI notes #6): lib/report/linksCli.mjs. diff --git a/umtool/components/projects/review/PlayCut.tsx b/umtool/components/projects/review/PlayCut.tsx @@ -944,7 +944,7 @@ export default function PlayCut({ joinFrom={(() => { // THE JOIN (post-join.mjs): the item before, so this one opens on it as it ended. const before = ui.cur > 0 ? entryOf.get(plan.items[ui.cur - 1]?.id ?? "") : null; - return postNow.entry.postPlan?.follow?.join && before?.type === "post" && before.post && before.postPlan ? { entry: before.post, plan: before.postPlan } : null; + return postNow.entry.postPlan?.follow?.join && before?.type === "post" && before.post && before.postPlan ? { entry: before.post, plan: before.postPlan, clock: before.postClock ?? null } : null; })()} /> ) : null; diff --git a/umtool/components/projects/review/PostItemPlayer.tsx b/umtool/components/projects/review/PostItemPlayer.tsx @@ -1,8 +1,8 @@ "use client"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; -import { POST_PUSH, mediaTimeAt, postLayout, stepAt, stepBoxes } from "umtool-report-to-video/post-item"; -import { applyJoinState, endMediaOf, joinFrameAt } from "umtool-report-to-video/post-join"; +import { POST_ENTER_FADE, POST_PUSH, mediaTimeAt, postLayout, stepAt, stepBoxes } from "umtool-report-to-video/post-item"; +import { applyJoinState, endMediaOf, joinClockOf, joinEase, joinFrameAt } from "umtool-report-to-video/post-join"; import { applyVisitState } from "umtool-report-to-video/post-link-visit"; import { applyMapState, mapHtml, mapPlace, mapSize } from "umtool-report-to-video/post-branch-map"; import { dryGainAt, mixPhaseAt, pickedTake, wetGainAt } from "umtool-report-to-video/post-narration"; @@ -131,6 +131,8 @@ export type PanelShow = { scope: string; media: Array<Record<string, unknown> & export type PostPlan = { panel?: { fade: number; shows: PanelShow[] }; + /** Its own attachments come in at this item second, with his own post (post-item.mjs ownMediaEnterAt). */ + enter?: number; reading: number; total: number; held: number; @@ -558,6 +560,9 @@ function JoinEnds({ project, ends, layout, box, op }: { project: string; ends: A ); } +/** A clock's plan (post-clock.mjs clockPlan). */ +type ClockPlan = { to: number; from: number | null; mode: "forward" | "rewind" | "none"; zone: string; gap: number; forced: boolean }; + export default function PostItemPlayer({ project, take = null, entry, plan, box, s, playing, cardKey = null, speed = 1, published = false, uncensored = false, scene = null, clock = null, joinFrom = null, progress = null, onReady, }: { @@ -586,9 +591,9 @@ export default function PostItemPlayer({ /** Its media scene (post-media-scene.mjs): which, and its place in it. */ scene?: { key: string; n: number; of: number } | null; /** Its clock (post-clock.mjs clockPlan, from the item before it), or none. */ - clock?: { to: number; from: number | null; mode: "forward" | "rewind" | "none"; zone: string; gap: number; forced: boolean } | null; - /** THE JOIN (post-join.mjs): the item before (its entry and plan) -- this one opens on it as it ended. */ - joinFrom?: { entry: Record<string, unknown> & { id: string }; plan: PostPlan } | null; + clock?: ClockPlan | null; + /** THE JOIN (post-join.mjs): the item before (its entry, plan and clock) -- this one opens on it as it ended. */ + joinFrom?: { entry: Record<string, unknown> & { id: string }; plan: PostPlan; clock?: ClockPlan | null } | null; /** Its progress bar (post-progress.mjs progressPlan), or none. */ progress?: ProgressPlan | null; }) { @@ -643,7 +648,11 @@ export default function PostItemPlayer({ const reading = s < plan.reading || !plan.steps.length; const current = stepAt(plan, s); // Beside the card, the first attachment is up (its first frame) while the words are read. - const shown = current ?? (layout.mode === "side" && plan.steps.length ? plan.steps[0] : null); + // ...unless it comes in with his own post (post-item.mjs ownMediaEnterAt: `plan.enter`): nothing of his until then. + const enterAt = plan.enter ?? 0; + const shown = current ?? (layout.mode === "side" && plan.steps.length && !(enterAt > 0) ? plan.steps[0] : null); + // Crossfaded in from that moment, as the build fades it (POST_ENTER_FADE). + const enterOp = enterAt > 0 && shown === plan.steps[0] ? Math.min(1, Math.max(0, (s - enterAt) / POST_ENTER_FADE)) : 1; const inStep = !!current && shown === current; const mediaPhase = layout.mode === "stack" && !reading; // A video's words, when it was transcribed (media[i].words): the cue at its source second. @@ -668,10 +677,12 @@ export default function PostItemPlayer({ const readFrame = useRef<HTMLIFrameElement | null>(null); // ---- THE JOIN, live (post-join.mjs): the item before's page in a frame of its own, at its last frame's state ---- const joinFrame = useRef<HTMLIFrameElement | null>(null); - const joinMeasure = useRef<{ A: Rect; anchor: number | null; slotA: Rect | null } | null>(null); + const joinMeasure = useRef<{ A: Rect; anchor: number | null; slotA: Rect | null; clock: { x: number; y: number; st: ReturnType<typeof clockStateAt> } | null } | null>(null); const [joinReady, setJoinReady] = useState(0); const joinSecs = plan.follow?.join?.seconds ?? 0; const joinOn = !!joinFrom && joinSecs > 0; + // It carries the post the item before ended on (post-thread.mjs: a carried parent, or the scene's post). + const carries = !!(plan.follow?.thread as { tiles?: Array<{ mode?: string; wasPost?: boolean }> } | undefined)?.tiles?.some((t) => t.mode === "carry" || (t.mode === "scene" && t.wasPost)); const onJoinLoad = useCallback(() => { let tries = 0; const tick = () => { @@ -681,16 +692,32 @@ export default function PostItemPlayer({ return; } const pf = joinFrom.plan.follow ?? null; - if (pf && doc.querySelector("[data-post-flow]")) { - const g = measureFollow(doc); - applyFollowState(followStateAt(pf, g ? followPath(pf, g) : null, Math.max(0, joinFrom.plan.total - 1 / 30)), doc); + const endS = Math.max(0, joinFrom.plan.total - 1 / 30); + const pl = postLayout(joinFrom.entry, box); + const route = pf && doc.querySelector("[data-post-flow]") ? followPath(pf, measureFollow(doc)) : null; + // ITS CLOCK as it ended (post-clock.mjs), placed as Play places this item's: the card at its read's end -- + // laid on its card when this item's does not carry on from it (joinClockOf), as the build's shot is. + const pc = joinFrom.clock && !(pl.mode === "stack" && joinFrom.plan.steps.length) ? joinFrom.clock : null; + let jclock: { x: number; y: number; st: ReturnType<typeof clockStateAt> } | null = null; + if (pc) { + const face = clockFace(pc.to, pc.zone); + const size = mountClock({ css: clockCss({ height: box.height, palette: paletteOfDoc(doc) }), html: clockHtml(), widest: { time: "12:58 PM", zone: face.zone, date: "Wed 30 Sep" } }, doc); + if (pf && route) applyFollowState(followStateAt(pf, route, joinFrom.plan.total), doc); + const at = size ? measureClockPlace({ size, inset: Math.round(22 * (box.height / 1080)) }, doc) : null; + if (at) jclock = { x: at.x, y: at.y, st: clockStateAt(pc, endS) }; + } + if (pf && route) { + const st = followStateAt(pf, route, endS); + applyFollowState(st, doc); + // A link visit's pointer, as it ended. + const visits = (pf as unknown as { visits?: unknown[] }).visits; + if (visits?.length) applyVisitState({ visits, st: st.visit ?? null }, doc); } const card = doc.querySelector("[data-post-card]"); if (!card) return; const c = card.getBoundingClientRect(); const post = doc.querySelector('[data-thread-slot="post"] .head') ?? card.querySelector(".head"); - const pl = postLayout(joinFrom.entry, box); - joinMeasure.current = { A: { x: c.left, y: c.top, width: c.width, height: c.height }, anchor: post ? post.getBoundingClientRect().top - c.top : null, slotA: pl.slot && pl.mode === "side" ? pl.slot : null }; + joinMeasure.current = { A: { x: c.left, y: c.top, width: c.width, height: c.height }, anchor: post ? post.getBoundingClientRect().top - c.top : null, slotA: pl.slot && pl.mode === "side" ? pl.slot : null, clock: jclock }; setJoinReady((n) => n + 1); }; tick(); @@ -930,13 +957,24 @@ export default function PostItemPlayer({ const jm = joinMeasure.current; if (!doc?.body || !jm) return; if (!doc.body.getAttribute("data-join")) { - doc.body.setAttribute("data-join", JSON.stringify({ A: jm.A, slotA: jm.slotA, slotB: layout.slot && layout.mode === "side" ? layout.slot : null, same: false })); const c = doc.querySelector("[data-post-card]")?.getBoundingClientRect(); + // The same content (the build's rule): the same width, the post it ended on carried in. + const same = !!c && Math.abs(jm.A.width - c.width) < 2 && carries; + doc.body.setAttribute("data-join", JSON.stringify({ A: jm.A, slotA: jm.slotA, slotB: layout.slot && layout.mode === "side" ? layout.slot : null, same })); if (c) setOwnBox({ x: c.left, y: c.top, width: c.width, height: c.height }); } applyJoinState(jp, doc); - }, [jp, joinReady, layout]); - const jframe = jp !== null && joinMeasure.current && ownBox ? joinFrameAt({ A: joinMeasure.current.A, B: ownBox, slotA: joinMeasure.current.slotA, slotB: layout.slot && layout.mode === "side" ? layout.slot : null, same: false }, jp) : null; + }, [jp, joinReady, layout, carries]); + const jframe = jp !== null && joinMeasure.current && ownBox ? joinFrameAt({ A: joinMeasure.current.A, B: ownBox, slotA: joinMeasure.current.slotA, slotB: layout.slot && layout.mode === "side" ? layout.slot : null, same: Math.abs(joinMeasure.current.A.width - ownBox.width) < 2 && carries }, jp) : null; + // THE CLOCK OVER THE JOIN (post-join.mjs joinClockOf): carried on from the item before's (moved the little way), + // or that one on its card as it ended, dissolving with it, and this one coming in. + const joinClock = useMemo(() => (joinOn && joinReady && joinMeasure.current ? joinClockOf({ from: joinMeasure.current.clock, own: clock ? clockAt : null, k: box.height / 1080 }) : null), [joinOn, joinReady, clock, clockAt, box.height]); + useEffect(() => { + const doc = joinFrame.current?.contentDocument; + const jm = joinMeasure.current; + if (!doc || !jm) return; + setClockState(joinClock?.bake && jm.clock?.st ? { x: jm.clock.x, y: jm.clock.y, st: jm.clock.st } : null, doc); + }, [joinClock, joinReady]); // THE BRANCH MAP (post-branch-map.mjs): its own layer over the attachments, where the build lays it. const branchMap = (follow?.thread as { map?: Record<string, unknown> } | undefined)?.map ?? null; const mapRef = useRef<HTMLDivElement | null>(null); @@ -1014,8 +1052,12 @@ export default function PostItemPlayer({ const doc = readFrame.current?.contentDocument; if (!doc) return; const until = layout.mode === "stack" && plan.steps.length ? plan.steps[0].at : Infinity; - setClockState(clockSt && clockAt && s < until ? { ...clockAt, st: clockSt } : null, doc); - }, [clockSt, clockAt, s, layout.mode, plan.steps]); + // Over the join: from the item before's place (eased as the card is), or coming in (as the build's fade). + const jc = joinClock && s < joinSecs ? joinClock : null; + const left = jc?.move ? 1 - joinEase(s / joinSecs) : 0; + const at = clockAt && jc?.move ? { x: clockAt.x + jc.move.dx * left, y: clockAt.y + jc.move.dy * left } : clockAt; + setClockState(clockSt && at && s < until ? { ...at, st: clockSt, ...(jc?.fadeIn ? { opacity: Math.max(0, s / joinSecs) } : {}) } : null, doc); + }, [clockSt, clockAt, s, layout.mode, plan.steps, joinClock, joinSecs]); // ---- READY (Play's clock waits for it): the card measured, the voice and the first attachment able to play ---- const onReadyRef = useRef(onReady); onReadyRef.current = onReady; @@ -1156,7 +1198,7 @@ export default function PostItemPlayer({ {shown && layout.slot && (layout.mode === "side" || mediaPhase) && ( <> {stepBoxes(shown, layout.slot).map((b: { x: number; y: number; width: number; height: number }, j: number) => ( - <MediaEl key={`${plan.steps.indexOf(shown)}:${j}`} joinOp={jframe && !(joinEnds.length === 1 && joinEnds[0].m.src === shown.items[j]?.src) ? Math.min(1, Math.max(0, (jframe.e - 0.35) / 0.65)) : 1} project={project} m={shown.items[j]} box={box} b={b} step={shown} s={s} playing={playing} inStep={inStep} mix={mix} speed={speed} /> + <MediaEl key={`${plan.steps.indexOf(shown)}:${j}`} joinOp={Math.min(enterOp, jframe && !(enterAt > 0) && !(joinEnds.length === 1 && joinEnds[0].m.src === shown.items[j]?.src) ? Math.min(1, Math.max(0, (jframe.e - 0.35) / 0.65)) : 1)} project={project} m={shown.items[j]} box={box} b={b} step={shown} s={s} playing={playing} inStep={inStep} mix={mix} speed={speed} /> ))} {cue && ( <div diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md @@ -72,6 +72,7 @@ Inbox cannot disagree about what is wrong with one. | `phrases "<phrase>" ["<phrase>" …] --channels a,b [--prefer c] [--exclude RE] [--words \| --regex] [--samples N] [--no-cache] [--json \| --full]` | the phrase finder's search ([tools.md](tools.md#the-phrase-finder-toolsphrases)): every phrase in one pass, each with its count once folded, by year, the preferred channel's share or Rumble's, speaker changes, sample contexts. Plain words become a tolerant pattern unless the phrase holds a regular expression's characters. `--json` the numbers, `--full` every instance; `--spec FILE --out FILE --progress` is the page's job form. **Exit 1** on a bad phrase | | `voice-match <project> [--reference auto\|rulings\|recordings] [--reference-video <channel>/<id> …] [--reference-channel <slug> …] [--instances FILE] [--span phrase\|cut] [--pad S] [--likely X --unlikely Y] [--out FILE] [--dry] [--json] [--progress ndjson]` | who is speaking, per montage clip: a local speaker-similarity score (TitaNet-small) against the host's voice → `<project>/voice-match.json` (the Cut tab's **Score the voices**); `--instances` also scores a phrase scan's instances not in the manifest; `--dry` prints the plan ([report-video.md](report-video.md#who-is-speaking-the-voice-match)) | | `speaker-check <project> [--clip <id> …] [--json] [--progress ndjson]` · `--set 'Name=<clip>,<channel>/<id>,channel:<slug>'` · `--remove <name>` · `--list` | which of the project's **named voices** (`speakers.json`) each clip is: TitaNet-small, local, against each voice's robust centroid → `<project>/speaker-check.json` (merged); the walk's **Speaker:** badge and **Check speaker** ([report-video.md](report-video.md#the-speaker-check-on-the-walk-which-of-several-voices)) | +| `check-joins <project> --take <id> [--json] [--all] [--limit <n>]` | do a rendered take's **post joins carry on**: every boundary of its master where the next post item draws a post the one before showed, its planned join, the SSIM across it and the largest frame-to-frame step (read-only, ffmpeg) -- worst first ([report-video.md](report-video.md#thread-scenes-whole-threads-the-join-manual-threads-wide-attachments-context-media-link-visits-the-branch-map)) | | `clips analyze <project> [--from <channel>/<id>] [--rescan] [--no-laughs] [--no-voices] [params] [--words FILE] [--progress ndjson] [--json]` · `clips propose <project> [--from <channel>/<id>] [--host N] [params] [--words FILE] [--dry] [--json]` · `clips show <project> [--json]` · `clips segments <project> [--json]` | the **clip finder** on a long recording ([report-video.md](report-video.md#highlights-the-clip-finder)): `analyze` runs the laugh scan (CED-mini) and a voice centroid per speaker on the recording's sound (cached in `<project>/scans/`), then proposes; `propose` proposes again from what is there (after a role flip, a param change, new words); `show` prints the speakers, laughs and the cut. Params `--target S` (600) `--laugh-min X` (0.25) `--merge-gap S` (6) `--setup-max S` (20) `--clip-max S` (75) and the scope `--scope FROM:TO` (either side may be empty; `all` clears it) or `--from S --to S` with numbers (a `--from` that is a `<channel>/<id>` names the recording), kept in `reactions.json`; `--host N` is your word on the host, kept. `--keep-cut` proposes without touching the cut (nothing moved, removed or added; the proposals are listed). **`--scope auto`** reads the narrated video auto-scope finds in the speaker turns (`--segment sN` names one, else the longest); `segments` lists them. A chat replay beside the recording (`live_chat.cues.json`) adds chat-burst moments and the log names the chat's lag. A channel on no site gets each clip linked to its platform page (`citeUrl`). A clip you edited, ruled, locked or added is never moved. **Exit 2** with no `diarization.json` (the message names the `archilyzer diarize backfill` to run) | | `timeline <project> [ls] [--json]` · `timeline <project> insert --after <id\|-> <channel>/<video>@<start>-<end> [--id ID] [--section N] [--lock] [--lock-end] [--title T] [--stream-title T] [--date YYYY-MM-DD] [--quote Q] [--cite S] [--cite-url U]` · `timeline <project> move <id> --to <index>` · `place <id>… --before <id\|-> [--section N]` · `remove <id>` · `reject <id> <why> [--note T]` · `wrong-speaker <id> [--correction T]` · `duplicate <id>` (`--at <index>` names one of an id's twins) · `post <json\|@file>` · `post-remove <id>` · `teaser <id> <patch-json\|@file>` · `undo` | the **structure** of the cut (the Cut tab's timeline, the On-screen section's teasers and posts) through the writers `POST /api/report/timeline` runs: `ls` prints index, id, type, video, start–end, date and title (`--json` adds the token and the posts); an insert's attribution is a second write through `window`'s writer, its date checked before anything is written; it is written in the manifest's own convention — under the deck `--title` is the deck's title (`onscreen.title`, `--stream-title` the stream's), a cut whose deck titles are dates gets `--date` as one in their format, and the clip takes the section of the clip it goes after (`--section N` names another) and, from the same recording, its deck title and its citation link. `place` is Play's drag on the reel strip: the entries land before that entry (`-`: the end), their clips joining section N (default: the section of the clip they land after), every other clip keeping its own and the markers following, an emptied section refused, each place its own undo point ([knobs.md](knobs.md#the-reel-strip-zoom-and-reorder)). A removal re-anchors what named the clip (a marker to the clip before, a chapter to the next in its section; a pair, a status reference or a deck claim dropped) and prints each `re-anchored:` line; `reject` rejects the clip for `<why>` — `not-matching` or `wrong-speaker` (fact errors: `incorrect`, the note its correction) or `irrelevant`, `repeats`, `weak`, `privacy`, `other` (`rejected`, never a correction) — and removes it, on record in `removed.json` with the reason and the note; `wrong-speaker <id>` is `reject <id> wrong-speaker`; `ls` marks a clip rejected but still in the cut (`[rejected — irrelevant]`) ([report-video.md](report-video.md#verdict--what-the-walk-said)). Every write snapshots the manifest first (`revisions/…-auto-before-<op>`), is refused only for what it breaks in the build's own words (**exit 1**), and on a generated manifest leaves an `edit` note ([report-video.md](report-video.md#structural-edits)) | | `timeline <project> insert (--to-section N \| --group G) <channel>/<video>@<start>-<end> [--id ID] [--lock] [--title T] [--stream-title T] [--date YYYY-MM-DD] [--quote Q] [--cite S] [--cite-url U]` | a clip at the **end of section N**, or **after group G's last clip and one of its clips** (the run stays together): one write, the marker that followed that last clip re-anchored after the new one, so the clip lands in the section and every other clip keeps its own; the attribution as `insert --after`'s. The Candidates panel's Insert is this ([knobs.md](knobs.md#the-candidates-inbox-proposed-clips-picked-by-a-press)) | @@ -83,7 +84,7 @@ Inbox cannot disagree about what is wrong with one. | `posts set <project> <post> thread=on\|off [hide=on\|off] [attach=<clipId>\|auto] [crop=<px>\|off] [--json]` | the Posts table's writer (`updatePosts`, `PUT /api/report/posts`) from a terminal: `<post>` is the manifest's id (`x-<postId>`) or the bare `<postId>`; `thread=on` draws a reply with the post it answers above it (`shot-thread.png` beside its `shot`, taken by `capture-posts` `"thread": true`; its own shot while there is none), `off` removes the key.; `crop=<px>` the post's own crop of its screenshot (`shotMaxHeight`, 120–1080: its top that tall, never panned; `off` removes it) ([knobs.md](knobs.md#add-post-a-post-card-from-play-the-cut)). Refused in the build's words (a post with no `shot`, an `attach` that is not a clip) — **exit 1** | | `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; the quoted post and the parent the archive lacks come from the capture's `context`, as `posts context` fills them). 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] [media.<i>.blur=on\|off] [media.<i>.blur.strength=1–10] [media.<i>.blur.label="…"\|off] [media.<i>.blur.boxes=x,y,w,h;…\|off] [quoted.paraphrase="…"\|off] [parent.<i>.paraphrase="…"\|off] [follow=on\|off\|auto] [follow.dim=<0.2-1>] [follow.ease=<s>] [thread.parent[.<i>]=auto\|full\|excerpt\|context\|carry\|hidden] [thread.quoted=…] [thread.carry=auto\|on\|off] [thread.reveal=on\|off] [thread.shrink=<0.3-1>] [thread.dim=<0.15-1>] [thread.seconds=<s>] [thread.pan=<s>] [thread=auto] [thread.group=<name>\|off] [thread.map=auto\|on\|off\|map\|label\|both] [panel=auto\|side\|top\|bottom] [media.add=<file>] [media.<i>=off] [parent.<i>=<json ref>\|@<file>\|off] [parent.<i>.media=<file>[,…]\|off] [link.add=<json ref>] [link.<i>=<json ref>\|off] [link.<i>.media=<file>\|off] [link.<i>.transcript="…"\|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. `quoted.paraphrase` / `parent.<i>.paraphrase`: your retelling of a long context post (≤ 600 characters), drawn in place of its words with a "paraphrased" label (its text kept); `off` or empty clears it. `follow=`: its read-follow ([knobs.md](knobs.md#read-follow-the-block-being-read-lit-the-card-panned-to-it)) -- `off`, `on`, `auto` (the cut's); `follow.dim=` / `follow.ease=` over the cut's. `thread.*`: its THREAD READ ([knobs.md](knobs.md#thread-reads-every-part-of-a-read-on-screen-while-it-is-said)) -- what each context post is on screen (`thread.parent.<i>` one parent, nearest first), the shrink, dim and their seconds, the pan's; `thread=auto` the cut's; a setting that would narrate a post the card hides is refused (**exit 1**). `media.<i>.blur…` CENSORS the attachment in the render (a real blur of the whole frame or of its boxes, labelled "Censored"; the file untouched; merged key by key, `blur=off` keeps the settings). THREAD SCENES ([knobs.md](knobs.md#thread-scenes-the-join-whole-threads-manual-threads-wide-attachments-context-media-link-visits-the-branch-map)): `parent.<i>=` an ancestor added / replaced / dropped (a whole-thread read), `parent.<i>.media=` its attachments, `media.add=` / `media.<i>=off` an attachment from a project file (measured), `link.add=` a post its words link to (a link visit) with its picture and transcript, `thread.group=` a manual thread, `thread.map=` the branch map, `panel=` where its attachments sit | +| `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] [media.<i>.enter=post\|item] [media.<i>.blur=on\|off] [media.<i>.blur.strength=1–10] [media.<i>.blur.label="…"\|off] [media.<i>.blur.boxes=x,y,w,h;…\|off] [quoted.paraphrase="…"\|off] [parent.<i>.paraphrase="…"\|off] [follow=on\|off\|auto] [follow.dim=<0.2-1>] [follow.ease=<s>] [thread.parent[.<i>]=auto\|full\|excerpt\|context\|carry\|hidden] [thread.quoted=…] [thread.carry=auto\|on\|off] [thread.reveal=on\|off] [thread.shrink=<0.3-1>] [thread.dim=<0.15-1>] [thread.seconds=<s>] [thread.pan=<s>] [thread=auto] [thread.group=<name>\|off] [thread.map=auto\|on\|off\|map\|label\|both] [panel=auto\|side\|top\|bottom] [media.add=<file>] [media.<i>=off] [parent.<i>=<json ref>\|@<file>\|off] [parent.<i>.media=<file>[,…]\|off] [link.add=<json ref>] [link.<i>=<json ref>\|off] [link.<i>.media=<file>\|off] [link.<i>.transcript="…"\|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. `quoted.paraphrase` / `parent.<i>.paraphrase`: your retelling of a long context post (≤ 600 characters), drawn in place of its words with a "paraphrased" label (its text kept); `off` or empty clears it. `follow=`: its read-follow ([knobs.md](knobs.md#read-follow-the-block-being-read-lit-the-card-panned-to-it)) -- `off`, `on`, `auto` (the cut's); `follow.dim=` / `follow.ease=` over the cut's. `thread.*`: its THREAD READ ([knobs.md](knobs.md#thread-reads-every-part-of-a-read-on-screen-while-it-is-said)) -- what each context post is on screen (`thread.parent.<i>` one parent, nearest first), the shrink, dim and their seconds, the pan's; `thread=auto` the cut's; a setting that would narrate a post the card hides is refused (**exit 1**). `media.<i>.blur…` CENSORS the attachment in the render (a real blur of the whole frame or of its boxes, labelled "Censored"; the file untouched; merged key by key, `blur=off` keeps the settings). THREAD SCENES ([knobs.md](knobs.md#thread-scenes-the-join-whole-threads-manual-threads-wide-attachments-context-media-link-visits-the-branch-map)): `parent.<i>=` an ancestor added / replaced / dropped (a whole-thread read), `parent.<i>.media=` its attachments, `media.add=` / `media.<i>=off` an attachment from a project file (measured), `link.add=` a post its words link to (a link visit) with its picture and transcript, `thread.group=` a manual thread, `thread.map=` the branch map, `panel=` where its attachments sit; `media.<i>.enter=` when its own attachment comes in -- with his own post's read (`post`, the default: a parent or a quote read first shows none of it) or with the item (`item`) | | `posts reread <project> <item> [--without parent:0\|parent:1\|quoted[,…]] [--drop-parts 3,4] [--drop-urls] [--dry-run] [--json]` | a narrated read **re-joined without a piece**, no TTS ([knobs.md](knobs.md#thread-reads-every-part-of-a-read-on-screen-while-it-is-said), [report-video.md](report-video.md#thread-reads)): the picked take's kept parts cut out of its own file (ffmpeg) and joined with the read's pauses, measured, added as a derived take (`steps: [{op: "rejoin", drop}]`, its parts re-timed with their roles, its word timings moved, its slurs state kept) and picked — ONE write (one undo point). `--without` drops the parts that read the post it answers (`parent:0`), its parent (`parent:1`) or the quoted post; `--drop-parts` by number; `--drop-urls` the parts that are nothing but a link. Nothing to drop, every part dropped or a take read in one go: **exit 1**. `posts set-item … thread.parent.<i>=context\|hidden` (or `thread.quoted=…`) on a piece the take reads runs it first (`--no-reread`: refused, as before) | | `posts reread <project> <item> --tempo-for "4-16=1.35,21-25=1.3" \| --tempo <x> --parts <runs> [--stretch atempo\|rubberband] [--dry-run] [--json]` | a narrated read's **parts re-timed**, no TTS ([knobs.md](knobs.md#thread-reads-every-part-of-a-read-on-screen-while-it-is-said), [report-video.md](report-video.md#a-long-read-sped-up-and-its-caps-yelled)): the parts named time-stretched (1–1.6, pitch kept), the rest untouched, joined with the read's pauses (each stretched part padded and trimmed to its length, sample-exact), its words scaled with their part, a derived take (`steps: [{op: "tempo", tempo, params: {stretch}}]`) picked in ONE write. A tempo is absolute: on a re-timed take it re-cuts from the take before. `posts set-item <p> <item> narration.tempo="4-16=1.35"` runs the same. A part outside the take, a tempo outside 1–1.6, nothing changed: **exit 1** | | `posts reread <project> <item> --yell-caps [--yell-gain 5.5] [--yell-style raise\|shout\|loud] [--dry-run] [--json]` · `posts yell <project> --all \| <item …> [--yell-gain …] [--yell-style …] [--dry-run] [--json]` | a narrated read's **caps yelled**, no TTS ([report-video.md](report-video.md#a-long-read-sped-up-and-its-caps-yelled), `lib/report/postYell.mjs`): his ALL-CAPS words found in the take's word timings and raised (the lift measured, its loudness within 1 LU), acronyms and masked slurs left flat, a derived take (`steps: [{op: "yell", spans, params}]`) picked (one undo point per item). No word timings: **exit 1** naming `posts narrate --words`; `posts yell --dry-run` lists every item's caps, the flat ones and why, and which need word timings | @@ -91,6 +92,9 @@ Inbox cannot disagree about what is wrong with one. | `timeline <project> threads [--json]` · `timeline <project> threads --write [--conversation <id>]` | **the cut's conversations** ([report-video.md](report-video.md#thread-reads), `post-conversation.mjs`): each tree of two post items or more — its root, its items' places, whether they play as one run (one scene) or are split by other entries, a reply placed before the post it answers, an item re-reading a post its run already read (with `posts set-item <p> <item> thread.parent.<i>=context`). `--write` gathers each (or the one holding `<id>`: its root, a post, an item, a `thread.group` name) at its first item's place in TREE order (a manual thread: in DATE order) — a post after what it answers, sibling branches by date, each depth first — in ONE write (one undo point); never across a section boundary (gathered within each section, and said) | | `posts roles <project> [<item> …] [--write] [--set <n>=<role>,…] [--json]` | a narrated read **piece by piece** ([knobs.md](knobs.md#thread-reads-every-part-of-a-read-on-screen-while-it-is-said), [report-video.md](report-video.md#thread-reads)): the text each part of the picked take reads -- `parent:<i>`, `quoted`, `post`, `media:<i>` -- stored or inferred, what the card shows for each, and the build's guard (a part read off a post the card hides is refused). `--write` stores the inferred roles on the picked takes' parts (one write; the import stores them for every new take); `<item> --set n=role,…` sets parts' roles by hand (`off`: inferred again); a part out of range or an unknown role is refused (**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= pace=fast\|normal]` · `<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` (and its read-follow: `follow=on\|off`, `follow.dim=`, `follow.ease=`; its thread reads: `thread.parent=`, `thread.quoted=`, `thread.carry=`, `thread.reveal=`, `thread.shrink=`, `thread.dim=`, `thread.seconds=`, `thread.pan=`). Refused in the build's words (**exit 1**) | +| `posts narrate <project> <item> --take --thread [--parents 0\|all\|none\|<n>] [--skip-parent <id\|parent:i>]… [--no-quoted] [--no-linked] [--read-seen] [--voice-for <handle>=<voice>]… [--voice v] [--engine e] [--note "…"] [--force] [--no-hold] [--dry-run] [--json]` | a **THREAD READ** as one command ([knobs.md](knobs.md#pronunciation-and-voices-the-lexicon-the-voice-map-a-thread-read), `lib/report/postThreadRead.mjs`): the post it answers (`--parents all`: every ancestor; `<n>`: parents 0..n; `none`), the post it quotes and the posts it links to, then his words, in DATE order, each in its author's voice (`--voice-for`, then the project's voice map, `posts voices`; his own: the narrator's), the redaction, the slur filter (a beep is skipped: a joined read is not word-timed) and the lexicon (`posts say`) applied. A parent or quoted post the item before already shows is not read again (`--read-seen`: it is). Each part is synthesized ONCE by the editor's tts op into `narration/parts-cache/<sha1(voice\|text)>.wav` (the transcription lane held meanwhile, only if it was not; `--no-hold`: left alone), joined (0.8 s between pieces, 0.6 between paragraphs, 0.25 inside one) into `take-<n>.<engine>-thread.wav` with `take-<n>.parts.json`, saved with its parts' roles, its lexicon and how it was asked (`read`) and PICKED — one write (one undo point). `--dry-run`: the pieces, voices and parts (cached or not), nothing asked. Already up to date (same words and voices): nothing done, **exit 0** (`--force`: again). A part not synthesized: **exit 1** (the parts made stay cached; run it again); `--json` prints `{ok: false, error}` too. A usage error: **exit 2** | +| `posts say <project> [ls] [--item <id>]` · `add <word\|phrase> "<spoken>" [--case] [--item <id>] [--note "…"]` · `remove <word\|n> [--item <id>]` · `try "<text>" [--item <id>]` · `stale` `[--json]` | **THE PRONUNCIATION LEXICON** ([knobs.md](knobs.md#pronunciation-and-voices-the-lexicon-the-voice-map-a-thread-read)): `narration/lexicon.json` in the project, a word or phrase said differently in EVERY synthesized read (a script's `--take`, each piece of a thread read, the bench's re-take); the scripts and cards keep their words. Whole words, without case unless `--case`, a phrase across any spaces, regex characters literal; `--item` for one item's reads (it wins over the project's). A masked slur and a redacted word are never replaced. `add` of a word already listed changes what is said. `try` prints what a voice would be asked to say. `stale` lists every picked read that still says an entry the old way, with the command that re-reads it. A bad entry or an unknown item: **exit 2** | +| `posts voices <project> [ls] \| set <handle\|*> <voice> \| remove <handle\|*> [--json]` | **THE VOICE MAP** (`narration/voices.json`): the stock voice a thread read gives each author (`*`: everyone it does not name; default `leo` on Orpheus); `ls` lists the map and every author the cut's items carry with the voice each would get. A bad handle or voice: **exit 2** | | `posts fx <project> <item> add caption --match "…" --text "…" [--target post\|quoted\|parent:<i>] [--occurrence n] [--at s] [--lead s] [--hold s] [--place below\|above\|side]` · `add clock [--rewind auto\|on\|off] [--off]` · `set <n> [--text …] [--place …] [--rewind …]` | a post item's **caption** ([report-video.md](report-video.md#a-caption), [knobs.md](knobs.md#a-caption-a-chip-explaining-a-phrase-as-it-is-read)): a chip explaining a phrase (any script: CJK drawn), up as it is read -- `--at`, else the take's word timings, else the reading estimate -- held `--hold` s, by the phrase and never over a word read while it is up; it waits for a word zoom. Its **clock** ([knobs.md](knobs.md#the-clock-each-posts-own-time-on-its-card-run-between-items)): the post's own time on the card, run from the clock item before it (forward; a REWIND when earlier: `--rewind`), `--off` not on this item. Through `updatePostFx`, refused in the build's words (**exit 1**); a zoom's knob on a caption, or a caption's on a zoom (**exit 1**) | | `posts clock <project> [on\|off\|default] [--zone <IANA zone>] [--json]` | the cut's **clock** default (`render.posts.clock`, `updatePostClock`); bare, which items show it and their times | | `posts fx <project> <item> add slam --text "不動心" [--match "…" \| --at s] [--whole \| --per-glyph] [--gap s] [--hold s] [--from-scale x] [--color #rrggbb] [--outline #rrggbb] [--outline-width px] [--place over-match\|center] [--size px] [--face jp\|sc\|tc\|kr] [--sfx trailer-hit\|off] [--volume x] [--swell \| --no-swell] [--bar "…" [--bar-style dark\|gold\|plain]]` · `set <n> [those flags; --bar off clears it]` | a post item's **slam** ([report-video.md](report-video.md#a-slam), [knobs.md](knobs.md#a-slam-a-trailer-style-title-slam-over-a-word-as-it-is-read)): a corny trailer title slam -- each glyph huge, shrinking onto the card just above the matched words' line and HITTING (a flash, dust, the frame's punch, a trailer hit's boom: the teaser's generator, `trailer-hits.mjs`), gold with a black outline; the hits spread evenly over the words' spoken span (`--gap` spaces them, `--at` moves the first), held `--hold` s; `--bar` lands the glyphs on a translation bar (rising in at the first hit, faded with them); a caption up with it waits for it. Through `updatePostFx`, refused in the build's words (**exit 1**); a slam's knob on another effect, or another's on a slam (**exit 2**) | diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md @@ -692,6 +692,7 @@ the shape, the mix, recordings, parts, the best part). One writer for a post's n | **the recording session** — the cut's posts read aloud in order, part by part, each part on disk as soon as it is kept (a reload resumes), the post's recorded take made and picked when its last part is in | `/projects/<p>/narration/record` (the Cut tab's **Record the narration**): the jump list (recorded / placeholder, n of N), the post's card and attachment, the teleprompter in its parts (the placeholder's `parts.json`, else the script split), the mic, the level, count-in; **Space** record / stop, **r** redo the part, **Enter** the next part (the post done: the next post), **n** / **p** posts; **Play it back**, **Play the placeholder** | — | `GET /api/report/post-narration/record?project&id[&n]` · `POST` multipart `{project, id, n, count, text, para, part}` · `POST {op: "discard", id, n}` · `POST {op: "finish", id}` | | 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 THREAD READ — the post it answers (or every ancestor), the post it quotes, the linked posts and his words, each in its author's voice, parts cached, one take picked ([below](#pronunciation-and-voices-the-lexicon-the-voice-map-a-thread-read)) | — | `umtool posts narrate <p> <item> --take --thread [--parents 0\|all] [--skip-parent <id>]… [--voice-for <handle>=<voice>]… [--dry-run] [--json]` | — | | a derived take — a take run through the editor's `enhance` or `convert` (a stock synthetic voice: `zac`, `leah`, `orpheus:zac`, never a recording) into a NEW take, the original kept; enhance engines `deepfilternet` · `rnnoise`, convert `openvoice` · `seed-vc` (unnamed: the editor's settings.voice, recorded on the take); "not installed" until `archilyzer voice setup --engine <id>` | 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) | @@ -776,6 +777,64 @@ snapshot and every script keep their words. | `render.posts.slurs.add` — the project's own words (always masked; a word, or `{word, forms?, mask?, say?}`) · `.except` — never masked here (a form, a slur's word or its id) | — | `umtool posts slurs <p> add <word>` · `except <word>` · `remove <word>` (one writer, `updatePostSlurs`) | — | | what the cut masks | — | `umtool posts slurs <p> ls [--json]`: per slur (its mask, never the word) and per post, and each read that needs word timings | — | +## Pronunciation and voices (the lexicon, the voice map, a thread read) + +Three plain commands do what hand-made scripts used to (operator, 4 Nov 2026: "we want the plain apps to do as much +heavy lifting as possible so cheaper models can more easily do these tasks without having to improvise shell scripts +and instead call real tools"). Run them; do not write a script that calls `pnpm ops tts`, ffmpeg or a regex file. + +**The lexicon** (`report-to-video/post-say.mjs`; the project's `narration/lexicon.json`, one writer, `lib/report/postSay.mjs` +`updateLexicon`): a word or phrase the VOICE says differently -- "tbh" said "T-B-H", "@grok" said "At grok", "atm" +said "A-T-M". It is applied where the words become what a voice is asked to say (`post-redact.mjs` `spokenRead`), so +EVERY synthesized read gets it: a script's take (`posts narrate --take`, `--all --take`), each piece of a thread read, +the bench's **Re-take with direction**. The script, the card and the archive keep their words. A match is a whole word +(no letter, digit or `_` either side; "can" is not the "can" of "can't"), without case unless `--case`, the words of a +phrase across any spaces; regex characters are literal (`C++`, `(sic)`, `$5`). `--item <id>`: that item's reads only, +winning over the project's entry for the same word; a longer match wins over a shorter one inside it; a replacement +is never matched again. **The slur filter and the redaction win**: a slur (whatever the filter's voice, on or off) and a +redacted word are never replaced, and a spoken form that says a slur or a blanked name is masked or dropped too. A take +records what it applied (`takes[i].lexicon: [{word, say, item?}]`), so `stale` knows a read SAID THE OLD WAY: an +entry its words hold that it did not apply with the same spoken form (a recording never is). It lives in the project, +not the manifest: changing it never re-renders a card, it makes new takes. Beep slurs: a take with a lexicon entry is +still word-timed against its script as written (the replaced words are placed between the words heard). + +**The voice map** (`narration/voices.json`, `updateVoiceMap`): `{"<handle>": "<voice>", "*": "<voice>"}` -- the stock +voice a thread read gives each author (handles without `@`, any case; `*` everyone it does not name, default `leo` on +Orpheus). The item's own author reads in the item's narrator voice (`narration.voice`, else the cut's) unless the map +names them; `--voice-for <handle>=<voice>` overrides it for one read, `--voice` sets his post's. + +**A thread read** (`lib/report/postThreadRead.mjs`): `posts narrate <p> <item> --take --thread` reads the post it +answers, the post it quotes, the posts its words link to and his words, in DATE order (`post-thread.mjs` +`chronoPieces`), each piece cleaned to be spoken (a context post's paraphrase when it has one), each in its author's +voice. Each part (a paragraph; a long one split at a sentence end) is synthesized ONCE through the editor's tts op (a +job on its queue, paced; the GPU and the heavy slot are the editor's) into `narration/parts-cache/<sha1(voice|text)>.wav` +and reused by every read after -- a re-read after one word changed asks for that part alone. The transcription lane is +held while parts are asked (only if it was not held; released after, on a failure, on Ctrl-C). The parts are joined +(0.8 s between pieces, 0.6 between paragraphs, 0.25 inside one) into `take-<n>.<engine>-thread.wav` with +`take-<n>.parts.json`, kept with each part's ROLE stored, and PICKED -- one write, one undo point +(`umtool timeline <p> undo`). Its exit code is the answer: 0 made or already up to date (`"upToDate": true`), 1 a part +was not synthesized (the parts made stay cached: run it again), 2 a usage error; `--json` for a queue step. + +| Knob | In umtool | From a terminal | Route | +|---|---|---|---| +| the lexicon -- `[{word, say, case?, item?, note?}]` (at most 500) | the bench's re-take applies it | `umtool posts say <p> add tbh "T-B-H"` · `add atm "at the moment" --item p-…` · `add US "U.S." --case` · `ls [--item <id>]` · `remove tbh [--item <id>]` (or its number) | — (`POST /api/report/post-narration {op: "take"}` applies it) | +| what a voice would be asked to say (the lexicon, the redaction, the slur filter) | — | `umtool posts say <p> try "tbh @grok atm" [--item <id>]` | — | +| the picked reads that say an entry the old way, each with the command that re-reads it | — | `umtool posts say <p> stale [--json]` | — | +| the voice map | — | `umtool posts voices <p> set kirscheverstahl tara` · `set '*' leo` · `remove <handle>` · `ls` (each author the cut carries, and the voice each gets) | — | +| a thread read -- `takes[i].read: {kind: "thread", parents, skip?, quoted?, linked?, seen?, voiceFor?, voice?}` | the post bench plays and picks it like any take | `umtool posts narrate <p> <item> --take --thread` (parent 0) · `--parents all` (every ancestor) · `--parents none` · `--skip-parent <id>` (repeat) · `--no-quoted` · `--no-linked` · `--read-seen` · `--voice-for Movail2=leah` · `--voice leo` · `--force` · `--dry-run` · `--json` | — | + +Recipes (copy them; `<p>` is the project, `<item>` the post item's id or its post's id): + +```sh +umtool posts say <p> add tbh "T-B-H" # every read says it so from now on +umtool posts say <p> stale # the reads that still say "tbh" -- and the line that fixes each +umtool posts voices <p> set kirscheverstahl tara # her words, in tara's voice +umtool posts narrate <p> <item> --take --thread --dry-run # what it will read, in which voices, what is cached +umtool posts narrate <p> <item> --take --thread --json # make it; exit 0 / 1 / 2 +umtool posts narrate <p> <item> --take --thread --parents all --skip-parent 2117733256955367748 # the whole chain but one +umtool posts roles <p> <item> # the guard: every part on screen while it is said +``` + ## A caption (a chip explaining a phrase as it is read) `fx: [{kind: "caption", match, text, …}]` on a post item ([report-video.md](report-video.md#a-caption): the shape, diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md @@ -552,6 +552,11 @@ the hand-made batch's list — `umtool posts narrate <p> --import` reads it into manifest in one undoable write. umtool never synthesizes: `posts narrate <p> <item> --take [--note "…"]` and the bench's **Re-take with direction** ask the editor's tts op (a job on its queue) to write the next take there, then measure it, append it and pick it. +What the voice is asked to say is the script with the redaction left out, the slur filter's +voice and the project's **pronunciation lexicon** applied (`umtool posts say`: "tbh" said +"T-B-H"); a **thread read** -- the post it answers, the quoted and linked posts and his words, +each in its author's voice, part by part from a cache -- is `posts narrate <p> <item> --take +--thread` ([knobs.md](knobs.md#pronunciation-and-voices-the-lexicon-the-voice-map-a-thread-read)). **The mix, inside the build's audio graph** (`postNarrationFilters`, frame-accurate, the item's true length — so the deck's rail and date run on with it, never frozen): @@ -1194,16 +1199,53 @@ Kirsche 17:45, his reply 19:03). A tile that does not answer the one drawn just **The join** (`report-to-video/post-join.mjs`; "I'd like a thread-like smooth transition here rather than a cut"). An item of a conversation run (or a manual thread) opens on the item before AS IT ENDED and morphs into its own -layout over its first `seconds` (0.6; the same content at the same width -- a carried post drawn alike -- switches -at the first frame, never a double image) -- a card beside an attachment to a card alone, another attachment, another +layout over its first `seconds` (0.6) -- a card beside an attachment to a card alone, another attachment, another width: the card's container eases from that item's box to its own (the words scaled with it, never re-flowed), that -item's card -- shot at its last frame in the build, its page in a second frame in Play -- rides the container and -fades as this one's comes in, the post it ended on (carried in, or the scene's) is drawn as that item drew its post -(its head, its words at their size) and framed where it sat (the anchor measured on both pages), the slot's well -fades in or out, and the attachment it ended on (its last frame) cross-fades into this one's -- the same one (a media -scene) is held. The read starts AFTER the join (`narrationSchedule`'s `pre`): an item in a run is the join longer. -`render.posts.join = { on, seconds }`; an item's `join: false` cuts. The build shoots the whole box while it joins -(the card and the slot's well move); `readInViewErrors` checks every read from its settle, after the join. +item's card -- shot at its last frame in the build, its page in a second frame in Play -- rides the container ON TOP +and dissolves into this one's, which is whole under it before it starts to go (`joinOpacities`: what both draw never +dims; the same content at the same width -- a carried post drawn alike -- is this card's from the first frame), the +post it ended on (carried in, or the scene's) is drawn as that item drew its post (its head -- a plain card's head at +the card's size, a threaded card's at its words box's, never this card's -- its words at their size and gap) and framed where it sat (the anchor measured on +both pages), the slot's well fades in or out, and the attachment it ended on (its last frame) cross-fades into this +one's -- the same one (a media scene) is held. The read starts AFTER the join (`narrationSchedule`'s `pre`): an item +in a run is the join longer. `render.posts.join = { on, seconds }`; an item's `join: false` cuts. The build shoots the +whole box while it joins (the card and the slot's well move); `readInViewErrors` checks every read from its settle, +after the join. + +**The join opens EXACTLY on the item before's last frame** (operator, 4 Nov, on mid-7 at 2357 s: "the transition from +some posts hard cutting into the same post with children should be addressed. If one post is visible in the next +scene, there should be a transition"). Its shot is that item's page in its read-follow's LAST state, with what its +segment lays over the card: its parent's shot, a link visit's pointer, and its CLOCK, placed as its own segment placed +it. The clock (`joinClockOf`): within 24 px (at 1080) of where this item's sits, this one opens there and moves the +little way with the card; further apart a move would cross the card's words, so the item before's is laid in its shot +(dissolving with it) and this one comes in over the join; none before, this one comes in; none now, that one dissolves. +Before this, a carried post switched to this card at the second frame and everything only the item before drew -- its +counts, its quote, its clock -- vanished at once, and the carried head (the words' size, not a card's) moved the words +down 12-18 px. A joined segment's key carries `jv` (the join's drawing, `POST_JOIN_DRAW_V`) and the clock the item +before ran, so a changed join rebuilds; an item with no join keeps its key. + +**His own attachment comes in with his own post** (`ownMediaEnterAt`, post-item.mjs; operator, 4 Nov, mid-11 at +~15:58: "I think the mr. obvious gif should come in when his post does rather than during the strawb megathread +reading"). In a threaded read that reads a parent, a quote or a linked post BEFORE his words, the item's own +attachments enter at his post's first part: until then the slot shows the piece being read's context media +(`panelSchedule`) or nothing; there his attachment crossfades in (`POST_ENTER_FADE`, 0.3 s) -- a video STARTS there +(its offset and its sound counted from that moment), its trim fitted to what is left of the read, pictures sharing +what is left. An item that reads only its post, and one past the first of a media scene (the item before ended on the +same attachment: held through), is as before. `posts set-item … media.<i>.enter=item` (the first attachment's) puts it +back with the item. Only an item that enters later carries `enter` in its segment key; Play and the bench lay it the +same (`plan.enter`). + +**Checking it** (`umtool check-joins <project> --take <id> [--json] [--all] [--limit <n>]`, +`report-to-video/check-joins.mjs`, read-only): every boundary of a rendered take's master where the next post item +draws a post the one before showed (its post, a parent, the quote, a linked post, a scene tile), its relation +(self-reply, reply to it, quotes it, manual thread, same thread…), its planned join, and over the post box (the deck +strip left out) its EDGE -- the largest frame-to-frame change (mean absolute difference, 0-255, grey) into the item +before's last frame and this one's first two, over what was already moving in the item before's six frames before +them (a video playing): a join's ease starts flat, so anything there is a cut -- with the SSIM +across the boundary and the largest step of the join after it shown beside; worst first. `JUMPS` is a planned join +whose edge is over 2.5 (`JOIN_CHECK`): mid-7's 2357 s boundary is 10.4 on main, 0.1 with the dissolve. The boundary is +found where the concat put it: the segments' file lengths as the concat demuxer reads them (a file's longest stream: +an audio a few ms longer than its video moves every later segment -- 0.33 s by the end of mid-7), not the schedule's. **A manual thread** (`thread.group`; "basically do all of them chronologically as if a thread, maybe subtly indicate the original relations"). Consecutive items with the same `thread.group` are one run even when X does not link them diff --git a/umtool/lib/report/checkJoinsCli.mjs b/umtool/lib/report/checkJoinsCli.mjs @@ -0,0 +1,62 @@ +// `umtool check-joins <project> --take <id> [--json] [--all] [--limit <n>]` -- the measured check of a rendered +// take's joins (report-to-video/check-joins.mjs): every boundary where the next post item draws a post the one before +// showed, its planned join, and how alike the master's frames are across it. Read-only. + +import { existsSync } from "node:fs"; +import path from "node:path"; + +import { checkJoins, joinsTable } from "umtool-report-to-video/check-joins"; +import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs"; +import { takesDirOf } from "./takes.mjs"; + +class CliError extends Error {} + +export const CHECK_JOINS_USAGE = [ + "usage: umtool check-joins <project> --take <id> [--json] [--all] [--limit <n>]", + " Every boundary of the take's master where the next post item draws a post the one before showed (its post, a", + " parent, the quote, a scene tile, a manual thread's stack): its planned join, the SSIM of the last frame before", + " against the first after (over the post box), and the largest frame-to-frame change across it and its join.", + " Worst first. --all: every post-to-post boundary. Read-only (ffmpeg reads the master).", +].join("\n"); + +export async function checkJoinsCommand(args, { reportsRoot = REPORTS_ROOT, log = console.log, err = console.error } = {}) { + try { + const words = []; + const flags = {}; + for (let i = 0; i < args.length; i += 1) { + const a = args[i]; + if (["--take", "--limit"].includes(a)) { + if (i + 1 >= args.length) throw new CliError(`${a} needs a value`); + flags[a] = args[++i]; + } else if (["--json", "--all", "--help"].includes(a)) flags[a] = true; + else if (a.startsWith("--")) throw new CliError(`unknown flag ${a}`); + else words.push(a); + } + if (flags["--help"] || !words.length || !flags["--take"]) { + log(CHECK_JOINS_USAGE); + return flags["--help"] ? 0 : 2; + } + const r = await resolveProject(words[0], reportsRoot); + if (r.ambiguous) throw new CliError(`"${words[0]}" is the name of ${r.ambiguous.length} projects — pass its id`); + if (!r.project) throw new CliError(`no project matches "${words[0]}"`); + const takeDir = path.join(takesDirOf(r.project.dir), String(flags["--take"])); + if (!existsSync(path.join(takeDir, "out", "sourced", "schedule.json"))) throw new CliError(`${flags["--take"]}: no rendered take at ${takeDir} (out/sourced/schedule.json)`); + const limit = flags["--limit"] ? Number(flags["--limit"]) : Infinity; + if (!(limit > 0)) throw new CliError("--limit takes a positive number"); + const got = await checkJoins(takeDir, { all: !!flags["--all"], onRow: flags["--json"] ? () => {} : (row) => err(` ${row.t.toFixed(2)} ${row.from} → ${row.to}: ssim ${row.ssim?.toFixed(3) ?? "-"}, jump ${row.jump}`) }); + const rows = got.rows.slice(0, limit); + if (flags["--json"]) { + log(JSON.stringify({ take: flags["--take"], master: got.master, drift: got.offsets, rows }, null, 2)); + return 0; + } + log(`${flags["--take"]}: ${got.rows.length} boundar${got.rows.length === 1 ? "y" : "ies"} where the next post item draws a post the one before showed${flags["--all"] ? " (--all: every post-to-post boundary)" : ""}, worst first`); + if (got.offsets) log(` (the master's segments sit ${got.offsets.toFixed(3)} s after the schedule's by the end: the concat demuxer's file lengths)`); + log(joinsTable(rows)); + const bad = got.rows.filter((x) => x.verdict === "JUMPS" || x.verdict === "cut"); + log(`${bad.length} jump or cut where a post stays on screen`); + return 0; + } catch (e) { + err(e instanceof CliError ? `umtool check-joins: ${e.message}` : `umtool check-joins: ${e?.stack ?? e}`); + return 1; + } +} diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs @@ -2358,7 +2358,7 @@ export async function insertEntries(dir, afterId, specs, { token = null, op = "i /** The knobs of a post item a write may set (post-item.mjs; knobs.md, "A post item"). */ export const POST_ITEM_KNOBS = Object.freeze(["hold", "mediaLayout", "panel", "redact", "follow", "thread", "scene", "progress"]); /** A post item attachment's knobs: its trim, its sound, its crop, the push-in, its transcript, its censoring blur. */ -export const POST_MEDIA_KNOBS = Object.freeze(["start", "end", "mute", "crop", "push", "words", "blur"]); +export const POST_MEDIA_KNOBS = Object.freeze(["start", "end", "mute", "crop", "push", "words", "blur", "enter"]); /** A context post's knobs (`quoted`, `parents[i]`): the operator's paraphrase of its words. */ export const POST_CONTEXT_KNOBS = Object.freeze(["paraphrase", "ref", "media", "transcript"]); /** The fields a context post (a parent, a linked post) is given by hand (`parent.<i>=<ref>`, post-item.mjs refErrors). */ diff --git a/umtool/lib/report/postNarrationCli.mjs b/umtool/lib/report/postNarrationCli.mjs @@ -16,6 +16,7 @@ // umtool posts narrate <p> --all --take [--limit N] every missing take, one at a time (resumable) // umtool posts narrate <p> --cut k=v … the cut's mix (render.postNarration) // umtool posts narrate <p> <item> --words [--worker <id>] its take's word timings (the editor's transcription, aligned; postFxCli.mjs) +// umtool posts narrate <p> <item> --take --thread [...] a THREAD READ, each piece in its author's voice (postThreadRead.mjs) // // Plain ESM: the CLI runs under bare node. import { execFile } from "node:child_process"; @@ -43,6 +44,8 @@ export const NARRATE_USAGE = [ " umtool posts narrate <project> <item> [--script \"…\"] [--take [--note \"…\"] [--voice v] [--engine e] [--speed s]]", " [--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=… rate=… pace=fast|normal] [--json]", + " umtool posts narrate <project> <item> --take --thread [--parents 0|all|none|<n>] [--skip-parent <id>]… [--no-quoted]", + " [--no-linked] [--read-seen] [--voice-for <handle>=<voice>]… [--voice v] [--force] [--dry-run]", " umtool posts narrate <project> --all --draft-scripts [--force] | --all --take [--limit N]", " umtool posts narrate <project> --cut lead=… tail=… ramp=… linger=… clip=read|full wet=… lowpass=… duck=on|off short=hold|loop lufs=… rate=… pace=fast|normal engine=… voice=… follow=on|off follow.dim=… follow.ease=…", " --cut thread.parent=auto|full|excerpt|context|carry|hidden thread.quoted=… thread.carry=auto|on|off thread.reveal=on|off thread.shrink=… thread.dim=… thread.seconds=… thread.pan=…", @@ -51,6 +54,11 @@ export const NARRATE_USAGE = [ " writes (`pnpm ops tts`, a job on its tts queue; ARCHILYZER_EDITOR_URL + WORKER_TOKEN) -- umtool never synthesizes.", " --import reads narration/posts/index.json ([{id, entry, script, takes: [{file, engine, voice, seconds}], pick}]).", " <item>: the post item's id or its post's id. --pick <n>: the take's number as --list shows it (1 = the first).", + " Every synthesized read says the project's PRONUNCIATION LEXICON's words its way (umtool posts say <p> --help).", + " --take --thread: a THREAD READ -- the post it answers (--parents all: every ancestor), the post it quotes, the", + " posts it links to and his words in date order, each in its author's voice (umtool posts voices), each part", + " synthesized once into narration/parts-cache/, joined, saved and picked in one write (exit 0 also when it is", + " already up to date; 1 when a part could not be synthesized). --dry-run lists the pieces and parts, asks nothing.", " 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).", @@ -295,8 +303,9 @@ export async function makeTake(project, e, { script = null, note = null, engine const rel = takeFileOf(pid, n, eng, vox); const out = path.join(project.dir, ...rel.split("/")); const askTts = ask ?? (await import("umtool-report-to-video/narrate-via-editor")).askEditorTts; - // What the voice SAYS: the script with every redacted term left out (post-redact.mjs), and each slur as the - // cut's filter has it (post-slurs.mjs: skipped, its stand-in, or said for a beep) -- the script itself is kept as written. + // What the voice SAYS: the script with every redacted term left out (post-redact.mjs), each slur as the cut's + // filter has it (post-slurs.mjs: skipped, its stand-in, or said for a beep), and each word of the project's + // pronunciation lexicon said its way (post-say.mjs) -- the script itself is kept as written. const red = redaction !== undefined ? redaction : await projectRedaction(project.dir, (await readManifest(project.dir)) ?? {}); const said = spokenRead(words, e, red); const ttsBody = (text) => ({ text, engine: eng, voice: vox, out, ...(spd !== null && eng !== "orpheus" ? { speed: spd } : {}) }); @@ -323,6 +332,8 @@ export async function makeTake(project, e, { script = null, note = null, engine ...(Number.isFinite(m.lufs) ? { lufs: m.lufs } : {}), jobId, // What its audio does with the slurs the script holds (post-slurs.mjs), and its words when timed for a beep. ...(slurs ? { slurs } : {}), ...(timed ? { words: timed } : {}), + // The pronunciation entries it said (post-say.mjs; `umtool posts say <p> stale` reads them). + ...(said.lexicon ? { lexicon: said.lexicon } : {}), }; const patch = { addTake: take, ...(script !== null && script !== e.narration?.script ? { script: words } : {}) }; const { result: wrote, editNotes } = await withEditNotes(project, async () => updatePostNarration(project.dir, e.id, patch, { token: await manifestToken(project.dir) })); @@ -349,7 +360,7 @@ async function timeTakeWords(project, rel, script, { askOp = null, emit = () => } /** `umtool posts narrate …` (postsCli.mjs routes it here). */ -export async function narrateCommand(project, words, flags, { json = false, dryRun = false, out = (s) => console.log(s), str }) { +export async function narrateCommand(project, words, flags, { json = false, dryRun = false, out = (s) => console.log(s), str, multi = () => [] }) { const manifest = await readManifest(project.dir); if (!manifest) throw new NarrateError(`${project.id} has no manifest`); const render = manifest.render ?? {}; @@ -427,6 +438,7 @@ export async function narrateCommand(project, words, flags, { json = false, dryR return 0; } if (flags.has("--take")) { + if (flags.has("--thread")) throw new NarrateError("--take --thread reads one item: name it (umtool posts narrate <p> <item> --take --thread)"); const limitRaw = str("--limit"); const limit = limitRaw === null ? Infinity : Number(limitRaw); const todo = tl.filter((e) => e.narration?.script && !(e.narration.takes ?? []).length); @@ -480,6 +492,25 @@ export async function narrateCommand(project, words, flags, { json = false, dryR } return 0; } + if (flags.has("--take") && flags.has("--thread")) { + // A THREAD READ (postThreadRead.mjs): its context and his words, each in its author's voice, one take picked. + const { threadCommand, parentsSelector } = await import("./postThreadRead.mjs"); + const { voiceOverridesOf } = await import("umtool-report-to-video/post-say"); + let overrides; + let parents; + try { + overrides = voiceOverridesOf(multi("--voice-for")); + parents = parentsSelector(str("--parents")); + } catch (err) { + throw new NarrateError(err instanceof Error ? err.message : String(err)); + } + return threadCommand(project, e, { + manifest, json, out, overrides, parents, skip: multi("--skip-parent").flatMap((x) => x.split(",")).map((x) => x.trim()).filter(Boolean), + quoted: !flags.has("--no-quoted"), linked: !flags.has("--no-linked"), readSeen: flags.has("--read-seen"), + voice: str("--voice"), engine: str("--engine"), note: str("--note"), force: flags.has("--force"), hold: !flags.has("--no-hold"), dryRun, + }); + } + if (flags.has("--thread")) throw new NarrateError("--thread goes with --take (umtool posts narrate <p> <item> --take --thread)"); if (flags.has("--take")) { const speedRaw = str("--speed"); const r = await makeTake(project, e, { diff --git a/umtool/lib/report/postRedaction.mjs b/umtool/lib/report/postRedaction.mjs @@ -1,16 +1,22 @@ // A PROJECT's REDACTION (umtool-report-to-video/post-redact.mjs): the corpus's // terms, its channels' post markup and the project's own `render.posts.redact`, // read from the channels tree the project's clip bench reads. What a take's -// synthesized read, Play's "As published" and the post item route blank. +// synthesized read, Play's "As published" and the post item route blank -- +// and, for a read only, the project's pronunciation lexicon (`say`). import { readPostRedaction } from "umtool-report-to-video/post-redact-files"; import { channelsDirFor, hasShadowChannels } from "../projects/report.mjs"; +import { readLexicon } from "./postSay.mjs"; /** * @param {string} dir the project's folder * @param {Record<string, any>} manifest - * @param {{ uncensored?: boolean }} [o] the slur filter off (post-slurs.mjs), the redaction kept + * @param {{ uncensored?: boolean, say?: boolean }} [o] the slur filter off (post-slurs.mjs), the redaction kept; `say: false` + * leaves the lexicon out (a view of the card, which never reads it) */ -export async function projectRedaction(dir, manifest, { uncensored = false } = {}) { +export async function projectRedaction(dir, manifest, { uncensored = false, say: withSay = true } = {}) { const channelsDir = channelsDirFor(dir, manifest, { shadowExists: await hasShadowChannels(dir) }); - return readPostRedaction(channelsDir, manifest, { uncensored }); + const red = await readPostRedaction(channelsDir, manifest, { uncensored }); + // The project's pronunciation lexicon (postSay.mjs): what spokenRead says in a word's place -- a read's only. + const say = withSay ? await readLexicon(dir) : []; + return say.length ? { ...red, say } : red; } diff --git a/umtool/lib/report/postSay.mjs b/umtool/lib/report/postSay.mjs @@ -0,0 +1,317 @@ +// A PROJECT's PRONUNCIATION LEXICON and VOICE MAP (umtool-report-to-video/post-say.mjs; +// umtool/docs/knobs.md, "Pronunciation and voices"): the files, their one writer +// each, and the CLI. +// +// umtool posts say <p> [ls] [--item <id>] [--json] +// umtool posts say <p> add <word|phrase> "<spoken>" [--case] [--item <id>] [--note "…"] [--json] +// umtool posts say <p> remove <word|n> [--item <id>] [--json] +// umtool posts say <p> try "<text>" [--item <id>] [--json] what a voice would be asked to say +// umtool posts say <p> stale [--json] picked reads that say an entry the old way +// umtool posts voices <p> [ls] | set <handle|*> <voice> | remove <handle|*> [--json] +// +// The files are the project's own (`narration/lexicon.json`, `narration/voices.json`), written +// atomically (a temp file renamed over), refused whole in post-say.mjs's words. They are NOT in the +// manifest: a narrated segment's cache key carries render.postNarration, and what a voice says is a +// new take's business, never a re-render's. +// +// Plain ESM: the CLI runs under bare node. +import { mkdir, readFile, rename, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { + LEXICON_FILE, VOICES_FILE, VOICE_MAP_OTHER, handleKey, lexiconFor, lexiconKey, staleLexicon, validateLexicon, validateVoiceMap, +} from "umtool-report-to-video/post-say"; +import { isNarrated, pickedTake } from "umtool-report-to-video/post-narration"; +import { readManifest } from "../projects/report.mjs"; + +export class SayError extends Error { + constructor(message) { + super(message); + this.name = "SayError"; + } +} + +export const SAY_USAGE = [ + "usage: umtool posts say <project> [ls] [--item <id>] [--json]", + " umtool posts say <project> add <word|phrase> \"<spoken>\" [--case] [--item <id>] [--note \"…\"] [--json]", + " umtool posts say <project> remove <word|n> [--item <id>] [--json]", + " umtool posts say <project> try \"<text>\" [--item <id>] [--json]", + " umtool posts say <project> stale [--json]", + " THE PRONUNCIATION LEXICON (narration/lexicon.json): a word or phrase the voice says differently -- \"tbh\" said", + " \"T-B-H\", \"@grok\" said \"At grok\" -- in EVERY synthesized read (a script's take, each piece of a thread read,", + " the bench's re-take); the scripts and the cards keep their words. A whole-word match without case (--case: with", + " it), a phrase across any spaces, regex characters literal; --item: that post item's reads only (it wins over the", + " project's). A slur the filter masks and a redacted word are never replaced (the filter and the redaction win).", + " add of a word already on the list changes what is said for it. try: what a voice would be asked to say for the", + " text. stale: each picked read that still says an entry the old way, with the command that re-reads it.", +].join("\n"); + +export const VOICES_USAGE = [ + "usage: umtool posts voices <project> [ls] [--json]", + " umtool posts voices <project> set <handle|*> <voice> [--json]", + " umtool posts voices <project> remove <handle|*> [--json]", + " THE VOICE MAP (narration/voices.json): the stock voice each author's words are read in by a thread read", + " (umtool posts narrate <p> <item> --take --thread) -- set kirscheverstahl tara; `*` is everyone it does not name", + " (default leo on Orpheus). The item's own author reads in the item's narrator voice unless the map names them.", + " ls: the map, and every author the cut's post items carry with the voice each would get.", +].join("\n"); + +const abs = (project, rel) => path.join(project.dir, ...rel.split("/")); + +async function readJson(file) { + let text; + try { + text = await readFile(file, "utf8"); + } catch (e) { + if (e?.code === "ENOENT") return undefined; + throw e; + } + try { + return JSON.parse(text); + } catch (e) { + throw new SayError(`${file} is not JSON: ${e instanceof Error ? e.message : e}`); + } +} + +async function writeJsonAtomic(file, value) { + await mkdir(path.dirname(file), { recursive: true }); + const tmp = `${file}.${process.pid}.${Date.now()}.tmp`; + await writeFile(tmp, `${JSON.stringify(value, null, 1)}\n`); + await rename(tmp, file); +} + +/** The project's lexicon as its file holds it (`[]` with none); a broken file throws. */ +export async function readLexicon(dir) { + const doc = await readJson(path.join(dir, ...LEXICON_FILE.split("/"))); + if (doc === undefined) return []; + const errors = validateLexicon(doc); + if (errors.length) throw new SayError(`${LEXICON_FILE} is refused: ${errors.join("; ")}`); + return doc; +} + +/** The project's voice map (`{}` with none); a broken file throws. */ +export async function readVoiceMap(dir) { + const doc = await readJson(path.join(dir, ...VOICES_FILE.split("/"))); + if (doc === undefined) return {}; + const errors = validateVoiceMap(doc); + if (errors.length) throw new SayError(`${VOICES_FILE} is refused: ${errors.join("; ")}`); + return doc; +} + +/** + * CHANGE THE LEXICON (its one writer): `{ add: {word, say, case?, item?, note?} }` -- an entry with the same + * word (and case, and item) is REPLACED -- or `{ remove: {word, item?} | <index> }`. Refused whole. + * Returns `{ lexicon, changed: "added" | "updated" | "removed", entry }`. + */ +export async function updateLexicon(dir, change) { + const list = [...(await readLexicon(dir))]; + let changed; + let entry; + if (change?.add) { + const a = change.add; + entry = { + word: String(a.word ?? "").replace(/\s+/g, " ").trim(), say: String(a.say ?? "").trim(), + ...(a.case === true ? { case: true } : {}), ...(a.item ? { item: String(a.item) } : {}), ...(a.note ? { note: String(a.note) } : {}), + }; + const k = list.findIndex((x) => lexiconKey(x) === lexiconKey(entry)); + if (k >= 0) { + list[k] = entry; + changed = "updated"; + } else { + list.push(entry); + changed = "added"; + } + } else if (change?.remove !== undefined) { + const r = change.remove; + let k = -1; + if (Number.isInteger(r)) k = r >= 0 && r < list.length ? r : -1; + else { + const w = String(r?.word ?? "").replace(/\s+/g, " ").trim().toLowerCase(); + const it = r?.item ? String(r.item) : null; + const hits = list.map((x, i) => ({ x, i })).filter(({ x }) => String(x.word).replace(/\s+/g, " ").trim().toLowerCase() === w && (x.item ?? null) === it); + if (hits.length > 1) throw new SayError(`"${r.word}" is on the list ${hits.length} times (with and without --case): remove it by its number, as ls shows it`); + k = hits[0]?.i ?? -1; + } + if (k < 0) throw new SayError(`no entry ${Number.isInteger(r) ? r + 1 : `"${r?.word}"${r?.item ? ` for ${r.item}` : ""}`} on the lexicon (umtool posts say <p> ls)`); + [entry] = list.splice(k, 1); + changed = "removed"; + } else throw new SayError("a lexicon change is {add} or {remove}"); + const errors = validateLexicon(list); + if (errors.length) throw new SayError(`refused: ${errors.join("; ")}`); + await writeJsonAtomic(path.join(dir, ...LEXICON_FILE.split("/")), list); + return { lexicon: list, changed, entry }; +} + +/** CHANGE THE VOICE MAP (its one writer): `{ set: {handle, voice} }` or `{ remove: handle }`. */ +export async function updateVoiceMap(dir, change) { + const map = { ...(await readVoiceMap(dir)) }; + if (change?.set) { + const h = handleKey(change.set.handle); + if (!h) throw new SayError("posts voices set takes a handle (or *) and a voice"); + map[h] = String(change.set.voice ?? ""); + } else if (change?.remove !== undefined) { + const h = handleKey(change.remove); + if (!(h in map)) throw new SayError(`${h} is not on the voice map`); + delete map[h]; + } else throw new SayError("a voice map change is {set} or {remove}"); + const errors = validateVoiceMap(map); + if (errors.length) throw new SayError(`refused: ${errors.join("; ")}`); + await writeJsonAtomic(path.join(dir, ...VOICES_FILE.split("/")), map); + return { voices: map }; +} + +/** The post item `ref` names (its id, its post's id, p-<id>), or null. */ +function itemOf(manifest, ref) { + const r = String(ref ?? ""); + return (manifest?.timeline ?? []).find((e) => e?.type === "post" && (e.id === r || String(e.post ?? "").split("/")[1] === r || e.id === `p-${r}`)) ?? null; +} + +/** + * THE PICKED READS THAT SAY AN ENTRY THE OLD WAY, pure: `[{ id, take, thread, entries: [{word, say, item?, was?}], + * fix }]` -- every narrated post item whose picked take is synthesized and matches an entry it did not apply. + */ +export function staleReads(manifest, lexicon, project = "<p>") { + const out = []; + for (const e of manifest?.timeline ?? []) { + if (e?.type !== "post" || !isNarrated(e)) continue; + const t = pickedTake(e); + if (!t) continue; + const entries = staleLexicon(e, t, lexicon); + if (!entries.length) continue; + const thread = t.read?.kind === "thread" || /-thread\.wav$/.test(String(t.file ?? "")) || (Array.isArray(t.parts) && new Set(t.parts.map((p) => p?.voice).filter(Boolean)).size > 1); + out.push({ id: e.id, take: t.file, thread, entries, fix: `umtool posts narrate ${project} ${e.id} --take${thread ? ` --thread${threadArgsOf(t.read)}` : ""}` }); + } + return out; +} + +/** A thread take's `read` record as the flags that ask for it again. */ +export function threadArgsOf(read) { + if (!read || read.kind !== "thread") return ""; + const q = (s) => (/^[A-Za-z0-9_.:=+-]+$/.test(s) ? s : `'${String(s).replace(/'/g, "'\\''")}'`); + const a = []; + if (read.parents !== undefined && String(read.parents) !== "0") a.push(`--parents ${read.parents}`); + for (const s of read.skip ?? []) a.push(`--skip-parent ${q(s)}`); + if (read.quoted === false) a.push("--no-quoted"); + if (read.linked === false) a.push("--no-linked"); + if (read.seen === true) a.push("--read-seen"); + for (const [h, v] of Object.entries(read.voiceFor ?? {})) a.push(`--voice-for ${q(`${h}=${v}`)}`); + if (read.voice) a.push(`--voice ${q(read.voice)}`); + return a.length ? ` ${a.join(" ")}` : ""; +} + +/** `umtool posts say …` (postsCli.mjs routes it here). */ +export async function sayCommand(project, rest, { flags, str, json = false, out = (s) => console.log(s) }) { + const [sub = "ls", ...args] = rest; + const manifest = (await readManifest(project.dir)) ?? {}; + const itemRef = flags.has("--item") ? str("--item") : null; + const item = itemRef === null ? null : itemOf(manifest, itemRef); + if (itemRef !== null && !item) throw new SayError(`no post item ${itemRef} in ${project.id} (its id, or the post's id)`); + const line = (x, i) => ` ${i + 1}. ${JSON.stringify(x.word)} -> ${JSON.stringify(x.say)}${x.case ? " (with case)" : ""}${x.item ? ` (${x.item} only)` : ""}${x.note ? ` -- ${x.note}` : ""}`; + + if (sub === "add") { + const [word, say] = args; + if (!word || say === undefined) throw new SayError('posts say add takes the word and what to say: add tbh "T-B-H"'); + const r = await updateLexicon(project.dir, { add: { word, say, case: flags.has("--case"), item: item?.id ?? null, note: flags.has("--note") ? str("--note") : null } }); + if (json) out(JSON.stringify({ ok: true, changed: r.changed, entry: r.entry, lexicon: r.lexicon }, null, 2)); + else { + out(`${r.changed} ${JSON.stringify(r.entry.word)} -> ${JSON.stringify(r.entry.say)}${r.entry.item ? ` for ${r.entry.item}` : ""}; ${project.id}'s lexicon holds ${r.lexicon.length} entr${r.lexicon.length === 1 ? "y" : "ies"}`); + const n = staleReads(manifest, r.lexicon, project.id).length; + if (n) out(` ${n} picked read(s) say an entry the old way: umtool posts say ${project.id} stale`); + } + return 0; + } + if (sub === "remove") { + const [w] = args; + if (!w) throw new SayError("posts say remove takes the word (or its number, as ls shows it)"); + const list = await readLexicon(project.dir); + const byNumber = /^\d+$/.test(w) && !list.some((x) => String(x.word).toLowerCase() === w.toLowerCase()); + const r = await updateLexicon(project.dir, { remove: byNumber ? Number(w) - 1 : { word: w, item: item?.id ?? null } }); + out(json ? JSON.stringify({ ok: true, changed: r.changed, entry: r.entry, lexicon: r.lexicon }, null, 2) : `removed ${JSON.stringify(r.entry.word)}${r.entry.item ? ` (${r.entry.item})` : ""}; ${r.lexicon.length} left`); + return 0; + } + if (sub === "try") { + const [text] = args; + if (text === undefined) throw new SayError('posts say try takes the text: try "tbh atm"'); + const { projectRedaction } = await import("./postRedaction.mjs"); + const { spokenRead } = await import("umtool-report-to-video/post-redact"); + const red = await projectRedaction(project.dir, manifest); + const said = spokenRead(text, item ?? { id: null }, red); + out(json ? JSON.stringify({ ok: true, text, said: said.text, lexicon: said.lexicon ?? [], slurs: said.slurs }, null, 2) : `${said.text}${said.lexicon?.length ? `\n (${said.lexicon.map((x) => `${x.word} -> ${x.say}`).join(", ")})` : ""}`); + return 0; + } + if (sub === "stale") { + const list = await readLexicon(project.dir); + const rows = staleReads(manifest, list, project.id); + if (json) out(JSON.stringify({ ok: true, stale: rows.length, reads: rows }, null, 2)); + else { + out(rows.length ? `${rows.length} picked read(s) say a lexicon entry the old way:` : `no picked read says a lexicon entry the old way (${list.length} entr${list.length === 1 ? "y" : "ies"})`); + for (const r of rows) { + out(` ${r.id} ${r.take}`); + out(` ${r.entries.map((x) => `${JSON.stringify(x.word)} (now ${JSON.stringify(x.say)}${x.was ? `, was ${JSON.stringify(x.was)}` : ""})`).join(", ")}`); + out(` ${r.fix}`); + } + } + return 0; + } + if (sub !== "ls") throw new SayError(`posts say: ls, add, remove, try or stale (not ${sub})`); + const list = await readLexicon(project.dir); + const shown = item ? lexiconFor(list, item.id).map((x) => list.find((y) => lexiconKey(y) === lexiconKey(x))).filter(Boolean) : list; + if (json) out(JSON.stringify({ ok: true, file: LEXICON_FILE, lexicon: shown }, null, 2)); + else { + out(`${project.id}: ${shown.length} lexicon entr${shown.length === 1 ? "y" : "ies"}${item ? ` that apply to ${item.id}` : ""} (${LEXICON_FILE})${shown.length ? "" : ` -- umtool posts say ${project.id} add tbh "T-B-H"`}`); + shown.forEach((x) => out(line(x, list.indexOf(x)))); + } + return 0; +} + +/** `umtool posts voices …` (postsCli.mjs routes it here). */ +export async function voicesCommand(project, rest, { json = false, out = (s) => console.log(s) }) { + const [sub = "ls", ...args] = rest; + if (sub === "set") { + const [h, v] = args; + if (!h || !v) throw new SayError("posts voices set takes a handle (or *) and a voice: set kirscheverstahl tara"); + const r = await updateVoiceMap(project.dir, { set: { handle: h, voice: v } }); + out(json ? JSON.stringify({ ok: true, voices: r.voices }, null, 2) : `${handleKey(h) === VOICE_MAP_OTHER ? "everyone else" : `@${handleKey(h)}`} reads in ${v}`); + return 0; + } + if (sub === "remove") { + const [h] = args; + if (!h) throw new SayError("posts voices remove takes a handle (or *)"); + const r = await updateVoiceMap(project.dir, { remove: h }); + out(json ? JSON.stringify({ ok: true, voices: r.voices }, null, 2) : `${handleKey(h)} off the voice map`); + return 0; + } + if (sub !== "ls") throw new SayError(`posts voices: ls, set or remove (not ${sub})`); + const map = await readVoiceMap(project.dir); + const manifest = (await readManifest(project.dir)) ?? {}; + const { voiceForPiece } = await import("umtool-report-to-video/post-say"); + const { postNarrationKnobs } = await import("umtool-report-to-video/post-narration"); + const k = postNarrationKnobs({}, manifest.render ?? {}); + // Every author a thread read could voice: the items' own, their parents', quoted and linked posts'. + const authors = new Map(); + const count = (h, own) => { + const key = handleKey(h); + if (!key) return; + const a = authors.get(key) ?? { handle: key, items: 0, context: 0 }; + if (own) a.items += 1; + else a.context += 1; + authors.set(key, a); + }; + for (const e of manifest.timeline ?? []) { + if (e?.type !== "post") continue; + count(e.handle, true); + for (const p of Array.isArray(e.parents) ? e.parents : []) count(p?.handle, false); + if (e.quoted) count(e.quoted.handle, false); + for (const l of Array.isArray(e.links) ? e.links : []) count(l?.handle, false); + } + const rows = [...authors.values()].sort((a, b) => b.items + b.context - (a.items + a.context)).map((a) => ({ + ...a, voice: voiceForPiece({ handle: a.handle, role: "parent:0" }, { map, narrator: k.voice, engine: k.engine }), mapped: a.handle in map, + })); + if (json) out(JSON.stringify({ ok: true, file: VOICES_FILE, voices: map, narrator: k.voice, engine: k.engine, authors: rows }, null, 2)); + else { + out(`${project.id}: ${Object.keys(map).length} voice(s) on the map (${VOICES_FILE}); the narrator ${k.engine} · ${k.voice}`); + for (const [h, v] of Object.entries(map)) out(` ${h === VOICE_MAP_OTHER ? "* (everyone else)" : `@${h}`} -> ${v}`); + if (rows.length) out(" the cut's authors, as a context post (their own items read in the narrator's voice unless mapped):"); + for (const r of rows) out(` @${r.handle} ${r.voice}${r.mapped ? "" : " (default)"} -- ${r.items} item(s), ${r.context} context post(s)`); + } + return 0; +} diff --git a/umtool/lib/report/postThreadRead.mjs b/umtool/lib/report/postThreadRead.mjs @@ -0,0 +1,434 @@ +// A THREAD READ AS A REAL COMMAND (operator, 4 Nov 2026: "we want the plain +// apps to do as much heavy lifting as possible so cheaper models can more +// easily do these tasks without having to improvise shell scripts and instead +// call real tools"): a post item read WITH ITS CONTEXT -- the post it answers +// (or every ancestor), the post it quotes, the posts its words link to, and +// his words -- each piece in its author's voice, in date order, made into one +// take, saved and picked in ONE write (one undo point). +// +// umtool posts narrate <p> <item> --take --thread [--parents 0|all|none|<n>] [--skip-parent <id|parent:i>]… +// [--no-quoted] [--no-linked] [--read-seen] [--voice-for <handle>=<voice>]… [--voice v] [--engine e] +// [--note "…"] [--force] [--no-hold] [--dry-run] [--json] +// +// THE PIECES (post-thread.mjs chronoPieces): every context post the card draws with words, and his post, oldest +// first (each at its own date; without dates: the parents oldest first, the quoted post, the linked posts, his). +// --parents 0 (default) the post it answers only; all: every ancestor; <n>: parents 0..n; none: no parent +// --skip-parent <id> leave one ancestor out (its post id, or its role parent:<i>); repeatable +// --no-quoted / --no-linked leave the quoted post / the linked posts out +// a parent or quoted post ON SCREEN FROM THE ITEM BEFORE (the item before in the cut, its parents, the scene its +// run leaves) is not read again -- --read-seen reads it anyway (a read for another cut, whose item before differs) +// A context piece reads its paraphrase when it has one, else its words, cleaned to be spoken (draftScript); his +// piece reads his script (drafted from his words, and set, when he has none). Every piece is what a voice SAYS +// (post-redact.mjs spokenRead): the redaction left out, the slur filter's voice (a beep cannot be timed on a joined +// read: such a slur is skipped), the project's pronunciation lexicon applied (post-say.mjs, `umtool posts say`). +// +// THE VOICES (post-say.mjs voiceForPiece): --voice-for, --voice (his post), the project's voice map +// (`umtool posts voices`), the narrator's for the item's own author, the map's "*", leo (Orpheus). +// +// THE PARTS: each piece split as a long read is (post-narration.mjs scriptParts: its paragraphs, a paragraph over +// 60 words at a sentence end), each part synthesized ONCE and kept in the project's PARTS CACHE -- +// narration/parts-cache/<sha1(voice|text)>.wav (another engine than Orpheus: sha1(engine|voice|text)) -- so a part +// read once is never asked again, in this read or any other. A part not in the cache is asked of the EDITOR's tts op +// (askEditorTts: `POST /api/ops/tts`, a job on its tts queue; the GPU and the heavy slot are its to arbitrate), one +// at a time; the transcription lane is held while they are asked (only when it was not held; released after, on a +// failure and on a signal too; --no-hold: left alone). +// +// THE TAKE: the parts joined with the pauses (POST_PART_GAP: 0.8 s between pieces, 0.6 between paragraphs, 0.25 +// inside one) by ffmpeg into narration/posts/<postId>/take-<n>.<engine>-thread.wav, its parts meta beside it +// (take-<n>.parts.json: each part's text, voice, role, piece, file, start, seconds, gap), measured, and added with +// its parts (each part's ROLE stored), the lexicon it applied, its slur state and how it was asked (`read`) -- +// picked, in one write. A read whose words and voices are what the picked take already says is left alone +// (--force makes it again). +// +// Exit codes: 0 made (or already up to date, `upToDate: true`); 1 a part could not be synthesized, the join +// failed or the write was refused (`--json`: `{ok: false, error}` on stdout too); 2 a usage error. +// +// Plain ESM: the CLI runs it under bare node. +import { execFile } from "node:child_process"; +import { createHash } from "node:crypto"; +import { mkdir, readdir, stat, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { promisify } from "node:util"; +import { POST_PART_GAP, draftScript, nextTakeNumber, pickedTake, postIdOf, postNarrationKnobs, scriptParts, takeFileOf, takesDirOf } from "umtool-report-to-video/post-narration"; +import { chronoPieces } from "umtool-report-to-video/post-thread"; +import { cardText, parentsOf } from "umtool-report-to-video/post-item"; +import { planContext } from "umtool-report-to-video/post-conversation"; +import { spokenRead } from "umtool-report-to-video/post-redact"; +import { voiceForPiece } from "umtool-report-to-video/post-say"; +import { readManifest } from "../projects/report.mjs"; +import { withEditNotes } from "./edit-guard.mjs"; +import { manifestToken, updatePostNarration } from "./manifest.mjs"; + +const execFileP = promisify(execFile); +const FFMPEG = () => process.env.FFMPEG_BIN ?? "ffmpeg"; +const r3 = (v) => Math.round(v * 1000) / 1000; +const str = (v) => (typeof v === "string" ? v : ""); +const norm = (t) => str(t).replace(/\s+/g, " ").trim(); + +/** The project's parts cache (relative to its folder). */ +export const PARTS_CACHE = "narration/parts-cache"; +/** The rate the parts are joined at (the editor's tts cache: 48 kHz mono). */ +const JOIN_RATE = 48000; + +export class ThreadReadError extends Error { + constructor(message) { + super(message); + this.name = "ThreadReadError"; + } +} + +export const THREAD_READ_USAGE = [ + " umtool posts narrate <project> <item> --take --thread [--parents 0|all|none|<n>] [--skip-parent <id|parent:i>]…", + " [--no-quoted] [--no-linked] [--read-seen] [--voice-for <handle>=<voice>]… [--voice v] [--engine e]", + " [--note \"…\"] [--force] [--no-hold] [--dry-run] [--json]", + " A THREAD READ: the post it answers (--parents all: every ancestor; none: no parent), the post it quotes, the posts", + " its words link to and his words, in DATE order, each in its author's voice (the project's voice map, umtool posts", + " voices; --voice-for handle=voice for this read), the redaction, the slur filter and the pronunciation lexicon", + " (umtool posts say) applied. A parent or quoted post the item before already shows is not read again (--read-seen:", + " it is). Each part is synthesized once by the editor (its tts op, a job) into narration/parts-cache/ and reused by", + " every read after; the take (take-<n>.<engine>-thread.wav + take-<n>.parts.json) is saved with its parts' roles and", + " PICKED in one write (one undo point). --dry-run: the pieces, voices and parts (cached or to synthesize), nothing", + " asked. Up to date already (same words, same voices): left alone, exit 0 (--force: made again). Exit 1: a part", + " could not be synthesized (the parts already made stay cached: run it again).", +].join("\n"); + +/** A part's cache key: sha1 of `voice|text` (an engine other than Orpheus: `engine|voice|text`). */ +export const partKey = (engine, voice, text) => createHash("sha1").update(engine === "orpheus" ? `${voice}|${text}` : `${engine}|${voice}|${text}`).digest("hex"); + +/** `--parents` as a selector: "0" (default), "all", "none", or a whole number n (parents 0..n). */ +export function parentsSelector(v) { + const s = v === null || v === undefined || v === "" ? "0" : String(v).trim().toLowerCase(); + if (s === "all" || s === "none") return s; + if (/^\d$/.test(s)) return s; + throw new ThreadReadError(`--parents takes 0, all, none or a parent's index (0-7) (got ${v})`); +} + +/** The ids of the posts already on screen as item `e` opens (the item before, its parents, its run's scene). */ +export function seenIds(manifest, e) { + const tl = Array.isArray(manifest?.timeline) ? manifest.timeline : []; + const i = tl.findIndex((x) => x?.id === e?.id); + if (i <= 0) return new Set(); + const { prev, scene } = planContext(tl, i, manifest?.render ?? {}); + const out = new Set(); + if (prev?.type === "post") { + for (const id of [postIdOf(prev), str(prev.originalId)]) if (id) out.add(id); + for (const p of parentsOf(prev)) if (str(p.id)) out.add(str(p.id)); + } + for (const t of Array.isArray(scene?.tiles) ? scene.tiles : []) if (str(t?.id)) out.add(str(t.id)); + return out; +} + +/** + * THE READ, PIECE BY PIECE, pure: `{ engine, narrator, pieces: [{ role, handle, date, voice, written, text, + * lexicon, slurs }], skipped: [{ role, id?, why }], want, voice, script, lexicon, slurs }` -- `text` what the voice + * says (spokenRead), `want` the whole read (pieces joined by a blank line), `voice` the take's label (its voices + * joined by "+"), `script` his script when he had none (set with the take). + * + * @param {Record<string, any>} manifest + * @param {Record<string, any>} e the post item + * @param {{ red?: any, map?: Record<string, string>, overrides?: Record<string, string>, parents?: string, + * skip?: string[], quoted?: boolean, linked?: boolean, readSeen?: boolean, voice?: string | null, engine?: string | null }} [o] + */ +export function threadReadPlan(manifest, e, { red = null, map = {}, overrides = {}, parents = "0", skip = [], quoted = true, linked = true, readSeen = false, voice = null, engine = null } = {}) { + const render = manifest?.render ?? {}; + const k = postNarrationKnobs(e, render); + const eng = engine ?? e.narration?.engine ?? k.engine; + const narrator = e.narration?.voice ?? k.voice; + const sel = parentsSelector(parents); + const seen = readSeen ? new Set() : seenIds(manifest, e); + const skips = new Set((skip ?? []).map((s) => String(s).trim()).filter(Boolean)); + const ps = parentsOf(e); + // A beep needs the slur's time in the take; a joined read is not word-timed as it is made -- skip it there. + const slurVoice = red?.slurs?.voice === "beep" ? "skip" : undefined; + const own = str(e.narration?.script).trim(); + const script = own ? null : draftScript(cardText(e)).script || null; + const pieces = []; + const skipped = []; + for (const p of chronoPieces(e)) { + const m = /^parent:(\d)$/.exec(p.role); + if (m) { + const at = Number(m[1]); + const id = str(ps[at]?.id); + if (sel === "none" || (sel !== "all" && at > Number(sel))) { + skipped.push({ role: p.role, ...(id ? { id } : {}), why: `--parents ${sel}` }); + continue; + } + if (skips.has(p.role) || (id && skips.has(id))) { + skipped.push({ role: p.role, ...(id ? { id } : {}), why: "--skip-parent" }); + continue; + } + if (id && seen.has(id)) { + skipped.push({ role: p.role, id, why: "on screen from the item before (--read-seen reads it)" }); + continue; + } + } + if (p.role === "quoted") { + const id = str(e.quoted?.id); + if (!quoted) { + skipped.push({ role: p.role, ...(id ? { id } : {}), why: "--no-quoted" }); + continue; + } + if (id && seen.has(id)) { + skipped.push({ role: p.role, id, why: "on screen from the item before (--read-seen reads it)" }); + continue; + } + } + if (p.role.startsWith("linked:") && !linked) { + skipped.push({ role: p.role, why: "--no-linked" }); + continue; + } + const written = p.role === "post" ? own || script || "" : draftScript(p.text).script; + if (!norm(written)) { + skipped.push({ role: p.role, why: "no words to read" }); + continue; + } + const said = spokenRead(written, e, red, { voice: slurVoice }); + if (!norm(said.text)) { + skipped.push({ role: p.role, why: "nothing left to say (all of it redacted)" }); + continue; + } + const v = voiceForPiece({ handle: p.handle, role: p.role }, { map, overrides, self: str(e.handle), voice, narrator, engine: eng }); + pieces.push({ role: p.role, handle: p.handle, date: p.date, voice: v, written, text: said.text.trim(), lexicon: said.lexicon ?? [], slurs: said.slurs }); + } + if (!pieces.some((p) => p.role === "post")) throw new ThreadReadError(`${e.id} has no words of his own to read (--script "…" first)`); + const lexicon = [...new Map(pieces.flatMap((p) => p.lexicon).map((x) => [`${x.word.toLowerCase()}|${x.item ?? ""}`, x])).values()]; + const states = pieces.map((p) => p.slurs).filter(Boolean); + return { + engine: eng, narrator, pieces, skipped, script, + want: pieces.map((p) => p.text).join("\n\n"), + voice: [...new Set(pieces.map((p) => p.voice))].join("+"), + lexicon, slurs: states.includes("said") ? "said" : states[0] ?? null, + }; +} + +/** The read's PARTS, pure: each piece's parts (scriptParts) with its voice, role and cache key, in order. */ +export function readParts(plan) { + return plan.pieces.flatMap((pc, piece) => + scriptParts(pc.text).map((q) => ({ piece, para: q.para, role: pc.role, voice: pc.voice, text: q.text, key: partKey(plan.engine, pc.voice, q.text) })), + ); +} + +/** + * THE JOIN's TIMES, pure: each part's start in the take, its length, the gap before it (POST_PART_GAP: a new piece, + * a new paragraph, inside one) -- the parts meta as `take-<n>.parts.json` holds it -- and the take's length. + * `para` is the piece × 100 + the paragraph (post-thread.mjs reads a piece as `para` div 100). + */ +export function joinTimes(parts, seconds, { fileOf = (p) => `${PARTS_CACHE}/${p.key}.wav` } = {}) { + let t = 0; + const meta = parts.map((p, i) => { + const prev = i > 0 ? parts[i - 1] : null; + const gap = !prev ? 0 : p.piece !== prev.piece ? POST_PART_GAP.piece : p.para !== prev.para ? POST_PART_GAP.para : POST_PART_GAP.inside; + t += gap; + const s = Number(seconds[i]); + const row = { n: i + 1, para: p.piece * 100 + p.para, text: p.text, voice: p.voice, role: p.role, piece: p.piece, file: fileOf(p), start: r3(t), seconds: r3(s), gapBefore: gap }; + t += s; + return row; + }); + return { meta, seconds: r3(t) }; +} + +/** The `read` record of a take: how it was asked for (only what differs from the defaults). */ +export function readRecordOf({ parents = "0", skip = [], quoted = true, linked = true, readSeen = false, overrides = {}, voice = null }) { + return { + kind: "thread", parents: parentsSelector(parents), + ...(skip?.length ? { skip: [...skip] } : {}), ...(quoted ? {} : { quoted: false }), ...(linked ? {} : { linked: false }), + ...(readSeen ? { seen: true } : {}), ...(Object.keys(overrides ?? {}).length ? { voiceFor: { ...overrides } } : {}), ...(voice ? { voice } : {}), + }; +} + +/** Is the picked take this read already (the same words, voices and engine)? */ +export function upToDate(e, plan) { + const t = pickedTake(e); + return !!t && norm(t.script) === norm(plan.want) && str(t.voice) === plan.voice && (t.engine ?? "orpheus") === plan.engine; +} + +const fileThere = async (f) => !!(await stat(f).catch(() => null))?.isFile(); + +/** A file's length, seconds (ffprobe). */ +async function durationOf(file) { + const { stdout } = await execFileP(process.env.FFPROBE_BIN ?? "ffprobe", ["-v", "error", "-show_entries", "format=duration", "-of", "default=noprint_wrappers=1:nokey=1", file]).catch(() => ({ stdout: "" })); + const s = Number(String(stdout).trim()); + if (!(s > 0)) throw new ThreadReadError(`${file} has no length (not a sound file?) -- delete it from ${PARTS_CACHE}/ and run it again`); + return s; +} + +/** + * MAKE A THREAD READ of post item `e` and keep it, picked: see the head of this file. `ask` (askEditorTts's shape: + * `(body, { emit }) => { jobId, result }`, writing `body.out`) and `lanes` (renderMode.mjs editorLanes' shape, or + * null: none held) are the tests' to stub. Returns `{ upToDate, plan, parts, take?, result?, fresh, cached, jobs, + * lane, dryRun }`. + */ +export async function threadTake(project, e, opts = {}) { + const { + manifest: m0 = null, red: red0 = undefined, map: map0 = undefined, overrides = {}, parents = "0", skip = [], quoted = true, linked = true, + readSeen = false, voice = null, engine = null, note = null, force = false, hold = true, dryRun = false, + ask = null, lanes: lanes0 = undefined, emit = () => {}, editor = null, signals = false, + } = opts; + const manifest = m0 ?? (await readManifest(project.dir)); + if (!manifest) throw new ThreadReadError(`${project.id} has no manifest`); + const red = red0 !== undefined ? red0 : await (await import("./postRedaction.mjs")).projectRedaction(project.dir, manifest); + const map = map0 !== undefined ? map0 : await (await import("./postSay.mjs")).readVoiceMap(project.dir); + const plan = threadReadPlan(manifest, e, { red, map, overrides, parents, skip, quoted, linked, readSeen, voice, engine }); + const parts = readParts(plan); + const cacheDir = path.join(project.dir, ...PARTS_CACHE.split("/")); + const wavOf = (p) => path.join(cacheDir, `${p.key}.wav`); + const have = await Promise.all(parts.map((p) => fileThere(wavOf(p)))); + const base = { plan, parts: parts.map((p, i) => ({ ...p, cached: have[i] })), fresh: 0, cached: have.filter(Boolean).length, jobs: [], lane: null, dryRun }; + if (!force && upToDate(e, plan)) return { ...base, upToDate: true }; + if (dryRun) return { ...base, upToDate: false }; + + // The parts not in the cache, asked of the editor one at a time -- the transcription lane held meanwhile. + await mkdir(cacheDir, { recursive: true }); + const todo = parts.map((p, i) => ({ p, i })).filter(({ i }) => !have[i]); + const jobs = []; + let fresh = 0; + let lane = todo.length ? "not held" : null; + let release = async () => {}; + const off = []; + if (todo.length && hold) { + let lanes = lanes0; + if (lanes === undefined) { + const { editorLanes } = await import("./renderMode.mjs"); + const { editorConfig } = await import("./fetchWindows.mjs"); + lanes = editorLanes(editorConfig(process.env)); + } + if (!lanes) lane = "not held (no editor token to ask with)"; + else { + try { + if (await lanes.isHeld("transcription")) lane = "already held (left alone)"; + else { + await lanes.hold("transcription"); + lane = "held, released after"; + let done = false; + release = async () => { + if (done) return; + done = true; + try { + await lanes.release("transcription"); + } catch (err) { + emit("note", { message: `the transcription lane could NOT be released (${err instanceof Error ? err.message : err}): pnpm ops lane --json '{"lane":"transcription","held":false}'` }); + } + }; + if (signals) { + for (const sig of ["SIGINT", "SIGTERM"]) { + const h = () => { + release().finally(() => process.exit(sig === "SIGINT" ? 130 : 143)); + }; + process.once(sig, h); + off.push(() => process.removeListener(sig, h)); + } + } + } + } catch (err) { + lane = `not held (${err instanceof Error ? err.message : err})`; + } + } + emit("note", { message: `the transcription lane: ${lane}` }); + } + try { + const askTts = ask ?? (await import("umtool-report-to-video/narrate-via-editor")).askEditorTts; + for (const [n, { p }] of todo.entries()) { + emit("note", { message: `part ${n + 1}/${todo.length} (${p.role}, ${p.voice}): asking the editor…` }); + await writeFile(path.join(cacheDir, `${p.key}.txt`), p.text); + try { + const { jobId } = await askTts({ text: p.text, engine: plan.engine, voice: p.voice, out: wavOf(p) }, { ...(editor ? { editor } : {}), emit }); + if (jobId) jobs.push(jobId); + } catch (err) { + throw new ThreadReadError(`part ${p.role} "${p.text.slice(0, 60)}${p.text.length > 60 ? "…" : ""}" (${p.voice}) was not synthesized: ${err instanceof Error ? err.message : err} -- the ${fresh + base.cached} part(s) made are cached; run it again`); + } + if (!(await fileThere(wavOf(p)))) throw new ThreadReadError(`the editor's job ${jobs.at(-1) ?? "?"} finished but ${PARTS_CACHE}/${p.key}.wav is not there`); + fresh += 1; + } + } finally { + await release(); + for (const f of off) f(); + } + + // The join: each part resampled to one rate, the gap before it laid in as silence, all concatenated. + const seconds = []; + for (const p of parts) seconds.push(await durationOf(wavOf(p))); + const { meta, seconds: total } = joinTimes(parts, seconds); + 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 = takeFileOf(pid, n, plan.engine, "thread"); + const out = path.join(project.dir, ...rel.split("/")); + const inputs = parts.flatMap((p) => ["-i", wavOf(p)]); + const filt = meta.map((row, i) => `[${i}:a]aresample=${JOIN_RATE},aformat=channel_layouts=mono,adelay=${Math.round(row.gapBefore * 1000)}:all=1[a${i}]`); + filt.push(`${meta.map((_, i) => `[a${i}]`).join("")}concat=n=${meta.length}:v=0:a=1[out]`); + try { + await execFileP(FFMPEG(), ["-nostdin", "-v", "error", "-y", ...inputs, "-filter_complex", filt.join(";"), "-map", "[out]", "-ar", String(JOIN_RATE), "-ac", "1", out], { maxBuffer: 1 << 24 }); + } catch (err) { + throw new ThreadReadError(`the join failed: ${String(err?.stderr || err?.message || err).trim().split("\n").slice(-2).join(" | ")}`); + } + // Beside it, as the importer and the recording page read a take's parts (postNarrationCli.mjs partsFileOf). + const { measureTake, partsFileOf } = await import("./postNarrationCli.mjs"); + await writeFile(path.join(project.dir, ...partsFileOf(rel).split("/")), `${JSON.stringify(meta, null, 1)}\n`); + const mt = await measureTake(out); + const take = { + file: rel, engine: plan.engine, voice: plan.voice, seconds: mt.seconds ?? total, + source: { kind: "tts", engine: plan.engine, voice: plan.voice, script: plan.want }, + script: plan.want, at: new Date().toISOString(), + note: note ?? `thread read: ${plan.pieces.map((p) => `${p.role} (${p.voice})`).join(" + ")}`, + ...(Number.isFinite(mt.lufs) ? { lufs: mt.lufs } : {}), + parts: meta, + ...(plan.slurs ? { slurs: plan.slurs } : {}), + ...(plan.lexicon.length ? { lexicon: plan.lexicon } : {}), + read: readRecordOf({ parents, skip, quoted, linked, readSeen, overrides, voice }), + }; + const patch = { addTake: take, ...(plan.script ? { script: plan.script } : {}) }; + const { result, editNotes } = await withEditNotes(project, async () => updatePostNarration(project.dir, e.id, patch, { token: await manifestToken(project.dir) })); + return { ...base, upToDate: false, fresh, jobs, lane, take, result, editNotes }; +} + +/** The guard on the item as it is now (postThreadCli.mjs readListing): what the card would refuse, and its warnings. */ +async function guardOf(project, id) { + const { readListing } = await import("./postThreadCli.mjs"); + const manifest = await readManifest(project.dir); + const tl = manifest?.timeline ?? []; + const i = tl.findIndex((x) => x?.id === id); + if (i < 0) return { errors: [], warnings: [] }; + const L = readListing(tl[i], manifest.render ?? {}, planContext(tl, i, manifest.render ?? {})); + return { errors: L.errors ?? [], warnings: L.warnings ?? [], pieces: L.pieces }; +} + +/** `umtool posts narrate <p> <item> --take --thread …` (postNarrationCli.mjs routes it here). */ +export async function threadCommand(project, e, o) { + const { json = false, out = (s) => console.log(s) } = o; + const say = (s) => !json && out(s); + let r; + try { + r = await threadTake(project, e, { ...o, signals: true, emit: (_ev, f) => f?.message && say(f.message) }); + } catch (err) { + if (json && err instanceof ThreadReadError) { + out(JSON.stringify({ ok: false, id: e.id, error: err.message }, null, 2)); + return 1; + } + throw err; + } + const pieces = r.plan.pieces.map((p) => ({ role: p.role, handle: p.handle, date: p.date, voice: p.voice, words: p.text.split(/\s+/).filter(Boolean).length, ...(p.lexicon.length ? { lexicon: p.lexicon } : {}) })); + const guard = r.take ? await guardOf(project, e.id) : null; + if (json) { + out(JSON.stringify({ + ok: true, id: e.id, upToDate: r.upToDate, dryRun: r.dryRun, engine: r.plan.engine, voice: r.plan.voice, pieces, skipped: r.plan.skipped, + parts: r.parts.map((p) => ({ role: p.role, voice: p.voice, key: p.key, cached: p.cached, text: p.text })), + fresh: r.fresh, cached: r.cached, jobs: r.jobs, lane: r.lane, + ...(r.take ? { take: r.take, pick: r.result.narration?.pick ?? null, token: r.result.token, snapshot: r.result.snapshot ?? null, guard } : {}), + }, null, 2)); + return 0; + } + out(`${e.id}: a thread read of ${pieces.length} piece(s), ${r.parts.length} part(s) (${r.cached} cached${r.dryRun ? `, ${r.parts.length - r.cached} to synthesize` : ""})`); + for (const p of pieces) out(` ${p.role.padEnd(9)} ${p.voice.padEnd(6)} ${p.handle ? `@${p.handle}` : ""}${p.date ? ` ${p.date.slice(0, 16)}` : ""} ${p.words} words${p.lexicon ? ` (said: ${p.lexicon.map((x) => `${x.word} -> ${x.say}`).join(", ")})` : ""}`); + for (const s of r.plan.skipped) out(` (not read: ${s.role}${s.id ? ` ${s.id}` : ""} -- ${s.why})`); + if (r.upToDate) { + out(` up to date: the picked take already reads this, in these voices (--force makes it again)`); + return 0; + } + if (r.dryRun) return 0; + out(` ${r.take.file} ${r.take.seconds} s, ${r.fresh} part(s) synthesized${r.jobs.length ? ` (editor jobs ${r.jobs.join(", ")})` : ""}, picked`); + if (r.result.snapshot?.rel && !r.result.snapshot.skipped) out(` undo point: ${r.result.snapshot.rel} (umtool timeline ${project.id} undo)`); + if (guard?.errors?.length) out(` the card would REFUSE it:\n${guard.errors.map((x) => ` ${x}`).join("\n")}\n (umtool posts roles ${project.id} ${e.id})`); + for (const w of guard?.warnings ?? []) out(` warning: ${w}`); + return 0; +} diff --git a/umtool/lib/report/postThreadRead.test.mjs b/umtool/lib/report/postThreadRead.test.mjs @@ -0,0 +1,346 @@ +// A thread read as a command (postThreadRead.mjs): the pieces in date order, what is +// skipped (--parents, --skip-parent, a post the item before shows), the voices (the +// map, --voice-for), the parts cache and its keys, the join's times, the take +// (its parts meta, roles, lexicon, read record; picked in one write), up to date, +// a failure; the lexicon and the voice map through the CLI; and a re-take through +// the CLI against a stub editor (no real editor: ARCHILYZER_EDITOR_URL points at +// a server this test runs). +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { createHash } from "node:crypto"; +import { createServer } from "node:http"; +import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises"; +import { existsSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { after, before, test } from "node:test"; +import { joinTimes, partKey, readParts, seenIds, threadReadPlan, threadTake, upToDate } from "./postThreadRead.mjs"; +import { staleReads, threadArgsOf, updateLexicon } from "./postSay.mjs"; +import { postsCommand } from "./postsCli.mjs"; +import { partRoles } from "umtool-report-to-video/post-thread"; + +const ROOT = await mkdtemp(path.join(tmpdir(), "umtool-thread-read-")); +after(() => rm(ROOT, { recursive: true, force: true })); +const REPORTS = path.join(ROOT, "reports"); +const CH = path.join(ROOT, "channels"); +const ff = (args) => execFileSync("ffmpeg", ["-v", "error", "-y", ...args]); +/** A part: `secs` of a tone. */ +const tone = (f, secs = 0.5) => ff(["-f", "lavfi", "-i", `sine=f=220:d=${secs}`, "-ar", "48000", "-ac", "1", f]); + +const KIRSCHE = { id: "101", handle: "KirscheVerstahl", author: "Kirsche", date: "2026-10-30T09:00:00.000Z", text: "parent zero words, honestly" }; +const GRAND = { id: "100", handle: "Someone", author: "Someone", date: "2026-10-30T08:00:00.000Z", text: "the grandparent's words" }; +const QUOTED = { id: "102", handle: "Movail2", author: "Mo", date: "2026-10-30T09:30:00.000Z", text: "quoted words tbh" }; +const item = (id, o = {}) => ({ + type: "post", id: `p-${id}`, post: `subj-x/${id}`, platform: "x", author: "THE SUBJECT", handle: "ObviousRises", date: "2026-10-30T10:00:00.000Z", + text: `his words ${id}`, ...o, +}); +const threaded = (id, o = {}) => item(id, { parents: [KIRSCHE, GRAND], quoted: QUOTED, narration: { script: "his words tbh, atm" }, ...o }); + +async function project(name, timeline) { + const dir = path.join(REPORTS, name); + await mkdir(dir, { recursive: true }); + await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify({ + schemaVersion: 1, slug: name, title: name, provenance: { siteOrigin: "", channelSlug: "subj-x", channelsDir: CH }, + render: { width: 1920, height: 1080, fps: 30, palette: { bg: "#000000", fg: "#ffffff", muted: "#888888", accent: "#c8752a" } }, + timeline, + }, null, 2)); + return { id: name, dir }; +} +const manifest = async (p) => JSON.parse(await readFile(path.join(p.dir, "video.manifest.json"), "utf8")); +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") }; +}; +/** A stubbed tts: each ask recorded and its `out` written as a tone. */ +const stubAsk = (asked) => async (body) => { + asked.push(body); + tone(body.out, 0.4 + (asked.length % 3) * 0.1); + return { jobId: `job-${asked.length}`, result: { wav: body.out, engine: body.engine, voice: body.voice } }; +}; +const stubLanes = (log, { held = false } = {}) => ({ + isHeld: async () => held, + hold: async (l) => log.push(`hold ${l}`), + release: async (l) => log.push(`release ${l}`), +}); +const NO_RED = { terms: [], markup: {}, slurs: null }; + +test("the plan: his context in DATE order, parent 0 by default; every ancestor with --parents all; voices by author", () => { + const e = threaded("1"); + const m = { render: {}, timeline: [e] }; + const plan = threadReadPlan(m, e, { red: NO_RED, map: { kirscheverstahl: "tara" } }); + assert.deepEqual(plan.pieces.map((p) => [p.role, p.voice]), [["parent:0", "tara"], ["quoted", "leo"], ["post", "zac"]]); + assert.deepEqual(plan.skipped.map((s) => [s.role, s.why]), [["parent:1", "--parents 0"]]); + assert.equal(plan.voice, "tara+leo+zac"); + assert.equal(plan.want, "parent zero words, honestly\n\nquoted words tbh\n\nhis words tbh, atm"); + const all = threadReadPlan(m, e, { red: NO_RED, parents: "all" }); + assert.deepEqual(all.pieces.map((p) => p.role), ["parent:1", "parent:0", "quoted", "post"]); + assert.deepEqual(threadReadPlan(m, e, { red: NO_RED, parents: "none" }).pieces.map((p) => p.role), ["quoted", "post"]); + assert.deepEqual(threadReadPlan(m, e, { red: NO_RED, parents: "1" }).pieces.map((p) => p.role), ["parent:1", "parent:0", "quoted", "post"]); + // --skip-parent by its id or its role; --no-quoted; --voice-for; --voice for his post. + const sk = threadReadPlan(m, e, { red: NO_RED, parents: "all", skip: ["101"], quoted: false, overrides: { someone: "dan" }, voice: "leah" }); + assert.deepEqual(sk.pieces.map((p) => [p.role, p.voice]), [["parent:1", "dan"], ["post", "leah"]]); + assert.deepEqual(sk.skipped.map((s) => s.why), ["--skip-parent", "--no-quoted"]); + assert.deepEqual(threadReadPlan(m, e, { red: NO_RED, parents: "all", skip: ["parent:1"] }).skipped.map((s) => s.role), ["parent:1"]); + assert.throws(() => threadReadPlan(m, e, { parents: "some" }), /--parents takes/); + // No dates: the parents oldest first, the quoted post, his. + const nd = threaded("2", { date: undefined, parents: [{ ...KIRSCHE, date: undefined }, { ...GRAND, date: undefined }], quoted: { ...QUOTED, date: undefined } }); + assert.deepEqual(threadReadPlan({ timeline: [nd] }, nd, { red: NO_RED, parents: "all" }).pieces.map((p) => p.role), ["parent:1", "parent:0", "quoted", "post"]); +}); + +test("a post the item before already shows is not read again (its post, its parents); --read-seen reads it", () => { + const before = item("101", { parents: [GRAND] }); + const e = threaded("3"); + const m = { render: {}, timeline: [before, e] }; + assert.ok(seenIds(m, e).has("101")); + const plan = threadReadPlan(m, e, { red: NO_RED, parents: "all" }); + assert.deepEqual(plan.pieces.map((p) => p.role), ["quoted", "post"]); + assert.match(plan.skipped.map((s) => s.why).join(), /on screen from the item before/); + assert.deepEqual(threadReadPlan(m, e, { red: NO_RED, parents: "all", readSeen: true }).pieces.map((p) => p.role), ["parent:1", "parent:0", "quoted", "post"]); +}); + +test("the lexicon and the redaction are applied to every piece; a beep is skipped on a joined read; parts, keys and times", () => { + const e = threaded("4", { parents: [{ ...KIRSCHE, text: "Quentin said tbh. ".repeat(1) + "x ".repeat(70) }] }); + const red = { terms: [{ term: "Quentin" }], markup: {}, slurs: null, say: [{ word: "tbh", say: "T-B-H" }, { word: "atm", say: "A-T-M", item: "p-4" }] }; + const plan = threadReadPlan({ timeline: [e] }, e, { red }); + assert.match(plan.pieces[0].text, /^said T-B-H\./); + assert.equal(plan.pieces[1].text, "quoted words T-B-H"); + assert.equal(plan.pieces[2].text, "his words T-B-H, A-T-M"); + assert.deepEqual(plan.lexicon, [{ word: "tbh", say: "T-B-H" }, { word: "atm", say: "A-T-M", item: "p-4" }]); + const parts = readParts(plan); + // The parent's 70+ words split at its sentence end: two parts of piece 0. + assert.deepEqual(parts.map((p) => [p.piece, p.para]), [[0, 0], [0, 0], [1, 0], [2, 0]]); + assert.equal(parts[2].key, createHash("sha1").update("leo|quoted words T-B-H").digest("hex"), "the cache key: sha1(voice|text)"); + assert.equal(partKey("kokoro", "af_heart", "hi"), createHash("sha1").update("kokoro|af_heart|hi").digest("hex")); + const { meta, seconds } = joinTimes(parts, [1, 1, 2, 3]); + assert.deepEqual(meta.map((r) => r.gapBefore), [0, 0.25, 0.8, 0.8]); + assert.deepEqual(meta.map((r) => r.start), [0, 1.25, 3.05, 5.85]); + assert.deepEqual(meta.map((r) => r.para), [0, 0, 100, 200]); + assert.deepEqual(meta.map((r) => r.role), ["parent:0", "parent:0", "quoted", "post"]); + assert.equal(seconds, 8.85); +}); + +test("threadTake: the parts asked once into the cache (the lane held, then released), joined, saved and PICKED with roles in one write; again: up to date", async () => { + const p = await project("tr", [item("0"), threaded("5")]); + const m = await manifest(p); + const asked = []; + const lanes = []; + const r = await threadTake(p, m.timeline[1], { red: { ...NO_RED, say: [{ word: "tbh", say: "T-B-H" }] }, map: { kirscheverstahl: "tara" }, ask: stubAsk(asked), lanes: stubLanes(lanes) }); + assert.equal(asked.length, 3); + assert.deepEqual(asked.map((a) => [a.voice, a.engine]), [["tara", "orpheus"], ["leo", "orpheus"], ["zac", "orpheus"]]); + assert.equal(asked[1].text, "quoted words T-B-H"); + assert.ok(asked[0].out.startsWith(path.join(p.dir, "narration", "parts-cache"))); + assert.deepEqual(lanes, ["hold transcription", "release transcription"]); + assert.equal(r.lane, "held, released after"); + assert.equal(r.take.file, "narration/posts/5/take-1.orpheus-thread.wav"); + assert.ok(existsSync(path.join(p.dir, r.take.file))); + const meta = JSON.parse(await readFile(path.join(p.dir, "narration/posts/5/take-1.parts.json"), "utf8")); + assert.deepEqual(meta.map((x) => [x.role, x.voice, x.piece]), [["parent:0", "tara", 0], ["quoted", "leo", 1], ["post", "zac", 2]]); + assert.ok(meta.every((x) => x.file.startsWith("narration/parts-cache/") && existsSync(path.join(p.dir, x.file)))); + const n = (await manifest(p)).timeline[1].narration; + assert.equal(n.takes.length, 1); + assert.equal(n.pick, 0); + const t = n.takes[0]; + assert.equal(t.voice, "tara+leo+zac"); + assert.deepEqual(t.lexicon, [{ word: "tbh", say: "T-B-H" }]); + assert.deepEqual(t.read, { kind: "thread", parents: "0" }); + assert.deepEqual(t.parts.map((x) => x.role), ["parent:0", "quoted", "post"]); + assert.deepEqual(partRoles((await manifest(p)).timeline[1]).map((x) => [x.role, x.source]), [["parent:0", "stored"], ["quoted", "stored"], ["post", "stored"]]); + assert.ok(Math.abs(t.seconds - (meta.at(-1).start + meta.at(-1).seconds)) < 0.06, "the take's length is the join's"); + const revs = await readdir(path.join(p.dir, "revisions")); + assert.equal(revs.filter((f) => f.includes("post-narration")).length, 1, "one undo point"); + // Again: the picked take already reads it -- nothing asked, nothing written. + const again = await threadTake(p, (await manifest(p)).timeline[1], { red: { ...NO_RED, say: [{ word: "tbh", say: "T-B-H" }] }, map: { kirscheverstahl: "tara" }, ask: stubAsk(asked), lanes: stubLanes(lanes) }); + assert.equal(again.upToDate, true); + assert.equal(asked.length, 3); + // --force: made again from the cache (no ask, no lane), a second take picked. + const forced = await threadTake(p, (await manifest(p)).timeline[1], { red: { ...NO_RED, say: [{ word: "tbh", say: "T-B-H" }] }, map: { kirscheverstahl: "tara" }, ask: stubAsk(asked), lanes: stubLanes(lanes), force: true }); + assert.equal(asked.length, 3); + assert.equal(forced.fresh, 0); + assert.equal(forced.cached, 3); + assert.equal(lanes.length, 2, "nothing to synthesize: the lane is not touched"); + assert.equal(forced.take.file, "narration/posts/5/take-2.orpheus-thread.wav"); + assert.equal((await manifest(p)).timeline[1].narration.pick, 1); + // Another voice for one author: only that piece is asked; the rest come from the cache. + const v2 = await threadTake(p, (await manifest(p)).timeline[1], { red: { ...NO_RED, say: [{ word: "tbh", say: "T-B-H" }] }, map: { kirscheverstahl: "mia" }, ask: stubAsk(asked), lanes: stubLanes(lanes, { held: true }) }); + assert.deepEqual(asked.slice(3).map((a) => a.voice), ["mia"]); + assert.equal(v2.lane, "already held (left alone)"); + assert.ok(!lanes.slice(2).includes("release transcription"), "a lane it did not hold is never released"); +}); + +test("threadTake: a part that fails is a ThreadReadError, the lane released, the parts made kept in the cache; --dry-run asks nothing", async () => { + const p = await project("trf", [threaded("6")]); + const m = await manifest(p); + const dry = await threadTake(p, m.timeline[0], { red: NO_RED, map: {}, ask: async () => assert.fail("asked"), lanes: stubLanes([]), dryRun: true }); + assert.equal(dry.dryRun, true); + assert.equal(dry.parts.length, 3); + assert.ok(dry.parts.every((x) => !x.cached)); + const asked = []; + const lanes = []; + const ok = stubAsk(asked); + const ask = async (body) => { + if (asked.length === 1) throw new Error("editor job job-2 failed — out of memory"); + return ok(body); + }; + await assert.rejects(threadTake(p, m.timeline[0], { red: NO_RED, map: {}, ask, lanes: stubLanes(lanes) }), (err) => err.name === "ThreadReadError" && /was not synthesized: editor job job-2 failed/.test(err.message)); + assert.deepEqual(lanes, ["hold transcription", "release transcription"]); + assert.equal((await manifest(p)).timeline[0].narration.takes, undefined, "nothing written"); + const cached = (await readdir(path.join(p.dir, "narration", "parts-cache"))).filter((f) => f.endsWith(".wav")); + assert.equal(cached.length, 1); + // Run again: the cached part is not asked again. + const r = await threadTake(p, m.timeline[0], { red: NO_RED, map: {}, ask: ok, lanes: stubLanes(lanes) }); + assert.equal(r.fresh, 2); + assert.equal(r.cached, 1); + assert.equal(upToDate((await manifest(p)).timeline[0], r.plan), true); +}); + +test("posts say: add (and update), ls, try, remove; an item's own entry; posts voices set / ls; refusals are usage errors", async () => { + const p = await project("say", [threaded("7"), item("8", { narration: { script: "tbh hi" } })]); + let r = await cli(["say", "say", "add", "tbh", "T-B-H"]); + assert.equal(r.code, 0, r.err); + assert.match(r.out, /added "tbh" -> "T-B-H"/); + r = await cli(["say", "say", "add", "tbh", "tee bee aitch"]); + assert.match(r.out, /updated "tbh"/); + r = await cli(["say", "say", "add", "atm", "at the moment", "--item", "7"]); + assert.equal(r.code, 0, r.err); + const lex = JSON.parse(await readFile(path.join(p.dir, "narration", "lexicon.json"), "utf8")); + assert.deepEqual(lex, [{ word: "tbh", say: "tee bee aitch" }, { word: "atm", say: "at the moment", item: "p-7" }]); + r = await cli(["say", "say", "try", "tbh, atm", "--item", "p-7", "--json"]); + assert.equal(JSON.parse(r.out).said, "tee bee aitch, at the moment"); + r = await cli(["say", "say", "try", "tbh, atm"]); + assert.match(r.out, /^tee bee aitch, atm/); + r = await cli(["say", "say", "ls", "--item", "p-8"]); + assert.match(r.out, /1 lexicon entry that apply to p-8/); + r = await cli(["say", "say", "remove", "atm"]); + assert.equal(r.code, 2, "atm is p-7's: name the item"); + r = await cli(["say", "say", "remove", "atm", "--item", "p-7"]); + assert.equal(r.code, 0, r.err); + assert.equal((await cli(["say", "say", "add", "!!", "x"])).code, 2); + assert.equal((await cli(["say", "say", "add", "x", "<b>"])).code, 2); + assert.equal((await cli(["say", "say", "add", "x", "y", "--item", "p-nope"])).code, 2); + // The voice map. + r = await cli(["voices", "say", "set", "@KirscheVerstahl", "tara"]); + assert.equal(r.code, 0, r.err); + r = await cli(["voices", "say", "set", "*", "dan"]); + assert.equal(r.code, 0, r.err); + assert.deepEqual(JSON.parse(await readFile(path.join(p.dir, "narration", "voices.json"), "utf8")), { kirscheverstahl: "tara", "*": "dan" }); + r = await cli(["voices", "say", "ls", "--json"]); + const j = JSON.parse(r.out); + assert.equal(j.authors.find((a) => a.handle === "kirscheverstahl").voice, "tara"); + assert.equal(j.authors.find((a) => a.handle === "movail2").voice, "dan"); + assert.equal((await cli(["voices", "say", "set", "x", "not a voice"])).code, 2); + assert.equal((await cli(["voices", "say", "remove", "nobody"])).code, 2); +}); + +test("posts say stale: the picked reads that say an entry the old way, with the command that re-reads each", async () => { + const p = await project("stale", [ + item("9", { narration: { script: "tbh one", takes: [{ file: "narration/posts/9/take-1.orpheus-zac.wav", seconds: 1, script: "tbh one" }], pick: 0 } }), + item("10", { narration: { script: "tbh two", takes: [{ file: "narration/posts/10/take-1.orpheus-zac.wav", seconds: 1, script: "tbh two", lexicon: [{ word: "tbh", say: "T-B-H" }] }], pick: 0 } }), + item("11", { narration: { script: "T-B-H three", takes: [{ file: "narration/posts/11/take-1.orpheus-thread.wav", seconds: 1, voice: "leo+zac", script: "tbh x\n\nT-B-H three", read: { kind: "thread", parents: "all", skip: ["5"], voiceFor: { a: "dan" } } }], pick: 0 } }), + item("12", { narration: { script: "tbh", takes: [{ file: "narration/posts/12/take-1.recorded-operator.wav", engine: "recorded", seconds: 1, script: "tbh" }], pick: 0 } }), + ]); + await updateLexicon(p.dir, { add: { word: "tbh", say: "T-B-H" } }); + const r = await cli(["say", "stale", "stale", "--json"]); + assert.equal(r.code, 0, r.err); + const j = JSON.parse(r.out); + assert.deepEqual(j.reads.map((x) => x.id), ["p-9", "p-11"]); + assert.equal(j.reads[0].fix, "umtool posts narrate stale p-9 --take"); + assert.equal(j.reads[1].fix, "umtool posts narrate stale p-11 --take --thread --parents all --skip-parent 5 --voice-for a=dan"); + assert.equal(threadArgsOf({ kind: "thread", parents: "0", quoted: false, seen: true }), " --no-quoted --read-seen"); + assert.equal(staleReads(await manifest(p), [], "stale").length, 0); +}); + +// --------------------------------------------------------------------------- +// Through the CLI, against a stub editor: the re-take applies the lexicon. +// --------------------------------------------------------------------------- + +const stub = { asks: [], lanes: [], held: false, server: null, url: "" }; +before(async () => { + let next = 1; + const jobs = new Map(); + stub.server = createServer(async (req, res) => { + const json = (code, v) => { + res.writeHead(code, { "content-type": "application/json" }); + res.end(JSON.stringify(v)); + }; + const url = new URL(req.url, "http://x"); + let body = ""; + for await (const c of req) body += c; + const b = body ? JSON.parse(body) : null; + if (req.headers.authorization !== "Bearer test-token") return json(401, { ok: false, error: "no" }); + if (req.method === "POST" && url.pathname === "/api/ops/tts") { + stub.asks.push(b); + const id = `stub-${next++}`; + tone(b.out, 0.6); + jobs.set(id, { wav: b.out, engine: b.engine, voice: b.voice, seconds: 0.6 }); + return json(200, { ok: true, jobId: id }); + } + const m = /^\/api\/ops\/job\/(.+)$/.exec(url.pathname); + if (req.method === "GET" && m && jobs.has(m[1])) return json(200, { ok: true, job: { id: m[1], status: "done" }, tail: [`@@tts-result ${JSON.stringify(jobs.get(m[1]))}`] }); + if (req.method === "GET" && url.pathname === "/api/ops/settings") return json(200, { ok: true, value: { transcription: { held: stub.held } } }); + if (req.method === "POST" && url.pathname === "/api/ops/lane") { + stub.lanes.push(`${b.lane}:${b.held}`); + return json(200, { ok: true }); + } + return json(404, { ok: false, error: `no ${url.pathname}` }); + }); + await new Promise((r) => stub.server.listen(0, "127.0.0.1", r)); + stub.url = `http://127.0.0.1:${stub.server.address().port}`; + process.env.ARCHILYZER_EDITOR_URL = stub.url; + process.env.WORKER_TOKEN = "test-token"; + process.env.NARRATE_VIA_EDITOR_POLL_MS = "20"; +}); +after(() => new Promise((r) => (stub.server ? stub.server.close(r) : r()))); + +test("CLI: `posts narrate --take` asks the editor to SAY the lexicon's words, records them, and the read is no longer stale", async () => { + const p = await project("cli-take", [item("20", { narration: { script: "tbh, @grok is this true" } })]); + assert.equal((await cli(["say", "cli-take", "add", "tbh", "T-B-H"])).code, 0); + assert.equal((await cli(["say", "cli-take", "add", "@grok", "At grok"])).code, 0); + stub.asks.length = 0; + const r = await cli(["narrate", "cli-take", "p-20", "--take", "--json"]); + assert.equal(r.code, 0, r.err); + assert.equal(stub.asks.length, 1); + assert.equal(stub.asks[0].text, "T-B-H, At grok is this true"); + const t = (await manifest(p)).timeline[0].narration.takes[0]; + assert.equal(t.script, "tbh, @grok is this true", "the script is kept as written"); + assert.deepEqual(t.lexicon, [{ word: "tbh", say: "T-B-H" }, { word: "@grok", say: "At grok" }]); + assert.equal(JSON.parse((await cli(["say", "cli-take", "stale", "--json"])).out).stale, 0); + // The spoken form changed: the read is stale (said the old way), and says what it said. + assert.equal((await cli(["say", "cli-take", "add", "tbh", "to be honest"])).code, 0); + const st = JSON.parse((await cli(["say", "cli-take", "stale", "--json"])).out); + assert.deepEqual(st.reads[0].entries, [{ word: "tbh", say: "to be honest", was: "T-B-H" }]); +}); + +test("CLI: `posts narrate --take --thread --json` -- a thread read through the editor, the lane held and released, a clear JSON result", async () => { + const p = await project("cli-thread", [threaded("21")]); + assert.equal((await cli(["voices", "cli-thread", "set", "kirscheverstahl", "tara"])).code, 0); + assert.equal((await cli(["say", "cli-thread", "add", "tbh", "T-B-H"])).code, 0); + stub.asks.length = 0; + stub.lanes.length = 0; + const dry = await cli(["narrate", "cli-thread", "p-21", "--take", "--thread", "--parents", "all", "--dry-run", "--json"]); + assert.equal(dry.code, 0, dry.err); + assert.equal(JSON.parse(dry.out).parts.length, 4); + assert.equal(stub.asks.length, 0); + const r = await cli(["narrate", "cli-thread", "p-21", "--take", "--thread", "--parents", "all", "--skip-parent", "100", "--voice-for", "Movail2=leah", "--json"]); + assert.equal(r.code, 0, r.err); + const j = JSON.parse(r.out); + assert.equal(j.ok, true); + assert.equal(j.upToDate, false); + assert.deepEqual(j.pieces.map((x) => [x.role, x.voice]), [["parent:0", "tara"], ["quoted", "leah"], ["post", "zac"]]); + assert.deepEqual(stub.asks.map((a) => a.text), ["parent zero words, honestly", "quoted words T-B-H", "his words T-B-H, atm"]); + assert.deepEqual(stub.lanes, ["transcription:true", "transcription:false"]); + assert.equal(j.take.file, "narration/posts/21/take-1.orpheus-thread.wav"); + assert.deepEqual(j.take.read, { kind: "thread", parents: "all", skip: ["100"], voiceFor: { movail2: "leah" } }); + assert.equal(j.pick, 0); + assert.deepEqual(j.guard.errors, []); + // Again: up to date, exit 0, nothing asked. + const again = await cli(["narrate", "cli-thread", "p-21", "--take", "--thread", "--parents", "all", "--skip-parent", "100", "--voice-for", "Movail2=leah", "--json"]); + assert.equal(again.code, 0); + assert.equal(JSON.parse(again.out).upToDate, true); + assert.equal(stub.asks.length, 3); + // Usage errors are exit 2. + assert.equal((await cli(["narrate", "cli-thread", "p-21", "--thread"])).code, 2); + assert.equal((await cli(["narrate", "cli-thread", "p-21", "--take", "--thread", "--parents", "most"])).code, 2); + assert.equal((await cli(["narrate", "cli-thread", "p-21", "--take", "--thread", "--voice-for", "tara"])).code, 2); +}); diff --git a/umtool/lib/report/postsCli.mjs b/umtool/lib/report/postsCli.mjs @@ -66,6 +66,17 @@ const SLURS_USAGE_LINES = [ " only), off or `umtool take … --uncensored` is the uncensored cut. umtool posts slurs --help: the whole story.", ]; +// `umtool posts say` / `posts voices` (postSay.mjs SAY_USAGE, VOICES_USAGE): its lines, kept here so the usage is one block. +const SAY_LINES = [ + " umtool posts say <project> [ls] | add <word|phrase> \"<spoken>\" [--case] [--item <id>] [--note \"…\"] | remove <word|n>", + " | try \"<text>\" [--item <id>] | stale [--json]", + " THE PRONUNCIATION LEXICON (narration/lexicon.json): \"tbh\" said \"T-B-H\" in every synthesized read (a take, a thread", + " read's pieces, the bench's re-take) -- whole words, without case unless --case, --item for one item's reads; a", + " masked slur and a redacted word are never replaced. stale: the picked reads that still say one the old way.", + " umtool posts voices <project> [ls] | set <handle|*> <voice> | remove <handle|*> [--json]", + " THE VOICE MAP (narration/voices.json): the voice a thread read gives each author (* everyone else; default leo).", +]; + export const POSTS_USAGE = [ "usage: umtool posts add <project> <archive-channel>/<postId> [--attach <clipId>] [--flag F] [--author A] [--id ID]", " [--thread] [--crop <px>] [--dry-run] [--json]", @@ -91,7 +102,7 @@ export const POSTS_USAGE = [ " [thread.carry=auto|on|off] [thread.reveal=on|off] [thread.shrink=<0.3-1>] [thread.dim=<0.15-1>]", " [thread.seconds=<0-3>] [thread.pan=<0.1-3>] [thread=auto]", " [media.<i>.start=<s>] [media.<i>.end=<s>] [media.<i>.mute=on|off] [media.<i>.crop=x,y,w,h|off]", - " [media.<i>.push=on|off] [media.<i>.trim=off] [quoted.paraphrase=\"…\"|off]", + " [media.<i>.push=on|off] [media.<i>.trim=off] [media.<i>.enter=post|item] [quoted.paraphrase=\"…\"|off]", " [media.<i>.blur=on|off] [media.<i>.blur.strength=1–10] [media.<i>.blur.label=\"…\"|off]", " [media.<i>.blur.boxes=x,y,w,h;…|off] [media.<i>.blur.band=below:<f>|above:<f>|between:<a>,<b>[:left:<f>|:right:<f>]|off]", " [media.<i>.blur.style=blur|black|pixelate|off] [media.<i>.censor=<edge>:<f>[:<style>][:<strength>]|off]", @@ -128,8 +139,8 @@ export const POSTS_USAGE = [ " panel=: where the attachments sit -- beside the card, or at full width above (top) or below it (a wide one: auto).", ...ROLES_LINES, ...REREAD_LINES, - " umtool posts narrate <project> … a post item's narration: script, takes (the editor's tts), pick, approve, mix", - " (umtool posts narrate --help)", + " umtool posts narrate <project> … a post item's narration: script, takes (the editor's tts), pick, approve, mix,", + " a thread read (--take --thread) (umtool posts narrate --help)", " umtool posts fit <project> [--all|<item> …] [--linger s] [--dry-run] narrated posts' videos cut to their best part", " umtool posts fx <project> <item> [ls] | add word-zoom --match \"…\" [--at s] … | add caption --match \"…\" --text \"…\" | set <n> … | remove <n>", " a WORD ZOOM (the card pushed in on a word) or a CAPTION (a chip explaining a phrase) as it is read,", @@ -150,6 +161,7 @@ export const POSTS_USAGE = [ " never rewritten; Play's \"As published\" shows the bars. `ls` lists the project's terms (n as `remove` takes it)", " and counts the corpus's (transcripts/redactions.json, channels/<slug>/posts-markup.json).", ...SLURS_USAGE_LINES, + ...SAY_LINES, " umtool posts context <project> [--dry-run] [--json]", " every post item's CONTEXT from its capture (capture.json's `context`: the post it quotes, the post it answers, as", " its page showed them) where the archive row lacks it -- one write (one undo point). A post whose capture read", @@ -160,7 +172,9 @@ 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(["--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"]); +const VALUED = new Set(["--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"]); +/** 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._-]+$/; const POST_ID_RE = /^[A-Za-z0-9_-]{1,64}$/; @@ -410,6 +424,7 @@ export async function addPostFromArchive(project, { slug, postId, attach = null, export async function postsCommand(args, { root = REPORTS_ROOT, out = (s) => console.log(s), err = (s) => console.error(s) } = {}) { const words = []; const flags = new Map(); + const multis = new Map(); const channels = []; for (let i = 0; i < args.length; i += 1) { const a = args[i]; @@ -418,6 +433,7 @@ export async function postsCommand(args, { root = REPORTS_ROOT, out = (s) => con i += 1; } else if (VALUED.has(a)) { flags.set(a, args[i + 1] ?? ""); + if (MULTI.has(a)) multis.set(a, [...(multis.get(a) ?? []), args[i + 1] ?? ""]); i += 1; } else if (a.startsWith("--")) flags.set(a, true); else words.push(a); @@ -430,6 +446,11 @@ export async function postsCommand(args, { root = REPORTS_ROOT, out = (s) => con if (v === true || v === "") throw new CliError(`${name} needs a value`); return String(v); }; + const multi = (name) => { + const vs = multis.get(name) ?? []; + if (vs.some((v) => v === "")) throw new CliError(`${name} needs a value`); + return vs.map(String); + }; try { const [verb, projectArg, ref] = words; if (verb === "reel" && projectArg && !flags.has("--help")) return await reelCommand(projectArg, { channels, flags, str, root, json, dryRun, out }); @@ -469,7 +490,7 @@ export async function postsCommand(args, { root = REPORTS_ROOT, out = (s) => con err(NARRATE_USAGE); return 2; } - return await narrateCommand(await projectOf(projectArg, root), words.slice(2), flags, { json, dryRun, out, str }); + return await narrateCommand(await projectOf(projectArg, root), words.slice(2), flags, { json, dryRun, out, str, multi }); } if (verb === "fx") { const { FX_USAGE, fxCommand } = await import("./postFxCli.mjs"); @@ -518,6 +539,19 @@ export async function postsCommand(args, { root = REPORTS_ROOT, out = (s) => con }); } if (verb === "redact" && projectArg && !flags.has("--help")) return await redactCommand(projectArg, words.slice(2), { root, json, out, flags, str }); + if (verb === "say" || verb === "voices") { + // The pronunciation lexicon and the voice map (postSay.mjs): a refusal in its words is a usage error. + const { SAY_USAGE, VOICES_USAGE, sayCommand, voicesCommand } = await import("./postSay.mjs"); + if (!projectArg || flags.has("--help")) { + err(verb === "say" ? SAY_USAGE : VOICES_USAGE); + return 2; + } + const project = await projectOf(projectArg, root); + const run = verb === "say" ? sayCommand(project, words.slice(2), { flags, str, json, out }) : voicesCommand(project, words.slice(2), { json, out }); + return await run.catch((e) => { + throw e?.name === "SayError" ? new CliError(e.message) : e; + }); + } if (verb === "slurs") { // The slur filter (postSlursCli.mjs): its own words refused as a usage error. const { SLURS_USAGE, slursCommand } = await import("./postSlursCli.mjs"); @@ -841,13 +875,17 @@ export function postItemPatchOf(pairs) { Object.assign(blur, { on: true, ...c }); } } else { - const m = /^media\.(\d+)\.(start|end|mute|crop|push|trim)$/.exec(k); - if (!m) throw new CliError(`${pair}: not a post item knob (hold=, layout=, panel=, redact=, scene=, follow=, follow.dim|ease=, thread=, thread.parent|quoted|carry|reveal|shrink|dim|seconds|pan|group|map=, media.add=, media.<i>=off, media.<i>.start|end|mute|crop|push|trim=, media.<i>.blur[.strength|.label|.boxes|.band|.style]=, media.<i>.censor=, quoted.paraphrase=, parent.<i>=<ref>|off, parent.<i>.media=, parent.<i>.paraphrase=, link.add=, link.<i>=<ref>|off, link.<i>.media=, link.<i>.transcript=)`); + const m = /^media\.(\d+)\.(start|end|mute|crop|push|trim|enter)$/.exec(k); + if (!m) throw new CliError(`${pair}: not a post item knob (hold=, layout=, panel=, redact=, scene=, follow=, follow.dim|ease=, thread=, thread.parent|quoted|carry|reveal|shrink|dim|seconds|pan|group|map=, media.add=, media.<i>=off, media.<i>.start|end|mute|crop|push|trim|enter=, media.<i>.blur[.strength|.label|.boxes|.band|.style]=, media.<i>.censor=, quoted.paraphrase=, parent.<i>=<ref>|off, parent.<i>.media=, parent.<i>.paraphrase=, link.add=, link.<i>=<ref>|off, link.<i>.media=, link.<i>.transcript=)`); const media = (out.media ??= {}); const one = (media[m[1]] ??= {}); if (m[2] === "start" || m[2] === "end") one[m[2]] = OFF.has(v) || v === "" ? null : Number(raw); else if (m[2] === "mute" || m[2] === "push") one[m[2]] = onOff(v, k) || null; - else if (m[2] === "trim") { + else if (m[2] === "enter") { + // When it comes in (post-item.mjs ownMediaEnterAt): with his own post (the default) or with the item. + if (!["post", "item", ...OFF].includes(v)) throw new CliError(`${k}= takes post (with his own post's read, the default), item (with the item) or off`); + one.enter = v === "item" ? "item" : v === "post" ? "post" : null; + } else if (m[2] === "trim") { if (!OFF.has(v)) throw new CliError(`${k}= takes off (the whole attachment)`); one.start = null; one.end = null; diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs @@ -219,13 +219,17 @@ import { buildPostSegment } from "./post-render.mjs"; import { TRAILER_AUDIO, trailerHitsGraph } from "./trailer-hits.mjs"; import { planContext, planContextOf } from "./post-conversation.mjs"; -/** The item before post item `id` with its own context (post-join.mjs: what the item opens on), or null. */ -function postJoinFrom(timeline, id, render, groups) { +/** + * The item before post item `id` with its own context (post-join.mjs: what the item opens on), or null -- and, when + * that one joins the item before IT, that item too (`before`: how its segment drew the post it carried in). + */ +function postJoinFrom(timeline, id, render, groups, depth = 0) { const tl = Array.isArray(timeline) ? timeline : []; const i = tl.findIndex((e) => e?.id === id); const prev = i > 0 ? tl[i - 1] : null; if (prev?.type !== "post") return null; - return { entry: prev, ...planContext(tl, i - 1, render), mediaScene: mediaSceneById(tl, prev.id, groups, render) }; + const ctx = planContext(tl, i - 1, render); + return { entry: prev, ...ctx, mediaScene: mediaSceneById(tl, prev.id, groups, render), ...(depth === 0 && ctx.join ? { before: postJoinFrom(tl, prev.id, render, groups, 1) } : {}) }; } import { readPostRedaction } from "./post-redact-files.mjs"; import { dropMarks, redactEntry } from "./post-redact.mjs"; diff --git a/umtool/report-to-video/check-joins.mjs b/umtool/report-to-video/check-joins.mjs @@ -0,0 +1,291 @@ +// CHECK JOINS (umtool/docs/report-video.md, "The join"; operator, 4 Nov, on mid-7: "the transition from some posts +// hard cutting into the same post with children should be addressed. If one post is visible in the next scene, +// there should be a transition"). A MEASURED check of a rendered take: for every boundary between two post items +// where the next one draws a post the one before showed (its post, a parent, the quote, a scene tile, a manual +// thread's stack), the master's last frame of the item before and the first frames of the next are read back +// (ffmpeg, read-only) and scored over the two items' CARDS as laid out (cardRegion) -- the deck strip, the chrome and +// the attachments' slots left out: +// +// edge THE VERDICT: the largest frame-to-frame change (the mean absolute difference, 0-255, of the box in +// grey) into the frames around the boundary (the item before's last, this one's first and second) -- a +// join's first frames barely move (its ease starts flat: 0.07 % of the way at its second frame), so +// anything seen there over what was already moving (the item before's last frames: a video playing) is +// a cut +// ssim the item before's last frame against the next item's second (1: the same picture; dark flat cards make +// it touchy -- a clock coming in faintly costs 0.07 -- so it is shown, not judged) +// jump how far the largest frame-to-frame change across the boundary and the join after it (the mean +// absolute difference, 0-255, of the box in grey) stands above its neighbours: a cut is one big step +// alone, a morph or a dissolve many small ones alike +// +// The boundary's place in the master is where the concat put it: each segment starts at the sum of the files +// before it AS THE CONCAT DEMUXER READS THEM (a file's length is its longest stream's: an audio stream a few ms +// longer than the video moves every later segment, measured 0.33 s by the end of mid-7), else the schedule's. +// +// umtool check-joins <project> --take <id> [--json] [--all] [--limit <n>] +// +// Pure helpers first (tested), then the ffmpeg reads. + +import { execFile } from "node:child_process"; +import { readFile } from "node:fs/promises"; +import path from "node:path"; +import { promisify } from "node:util"; + +import { chainOf, planContext } from "./post-conversation.mjs"; +import { linksOf, panelEntry, parentsOf, postLayout } from "./post-item.mjs"; +import { groupOf, shownIdOf } from "./post-thread.mjs"; + +const execFileP = promisify(execFile); +const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); +const str = (v) => (typeof v === "string" ? v : ""); +const fin = (v) => typeof v === "number" && Number.isFinite(v); +const r3 = (v) => Math.round(v * 1000) / 1000; + +/** A cut whose boundary scores below this SSIM, or jumps above this, is called a CUT (a join's frames move little). */ +export const JOIN_CHECK = Object.freeze({ edge: 2.5 }); + +/** + * The posts item `e` draws (its own, the posts it answers, its quote, the posts it links, the scene its run left on + * screen): `Map<id, what>` -- `what` "post", "parent", "quoted", "linked", "scene". + * @param {Record<string, any>} e + * @param {{ scene?: { tiles?: Array<Record<string, any>> } | null }} [ctx] + */ +export function postsDrawnBy(e, { scene = null } = {}) { + const out = new Map(); + const add = (id, what) => { + if (str(id) && !out.has(str(id))) out.set(str(id), what); + }; + add(shownIdOf(e), "post"); + for (const p of parentsOf(e)) add(p?.id, "parent"); + if (isObj(e?.quoted)) add(e.quoted.id, "quoted"); + for (const l of linksOf(e)) add(l?.id, "linked"); + for (const t of Array.isArray(scene?.tiles) ? scene.tiles : []) add(t?.id, "scene"); + return out; +} + +/** How item `b` relates to `a`, the item before it (the check's words). */ +export function joinRelation(a, b) { + const ida = shownIdOf(a); + const pb = parentsOf(b); + if (groupOf(a) && groupOf(a) === groupOf(b)) return "manual thread"; + if (ida && str(pb[0]?.id) === ida) return str(a?.handle) && str(a?.handle).toLowerCase() === str(b?.handle).toLowerCase() ? "self-reply" : "reply to it"; + if (ida && isObj(b?.quoted) && str(b.quoted.id) === ida) return "quotes it"; + if (ida && pb.some((p) => str(p?.id) === ida)) return "a later reply"; + if (ida && ida === shownIdOf(b)) return "the same post"; + const ca = new Set(chainOf(a).filter(Boolean)); + if (chainOf(b).some((id) => id && ca.has(id))) return "same thread"; + return "shares a post"; +} + +/** + * THE BOUNDARIES, pure: each post-to-post boundary of the schedule (`schedule.segments`, by id into the timeline) + * with what the two items share -- `{ i, from, to, at, shared: [id], relation, join, seconds }` (`join` the + * planned join's seconds, or null: a cut). `all`: every post-to-post boundary, sharing or not. + */ +export function joinBoundaries(timeline, schedule, render = undefined, { all = false } = {}) { + const tl = Array.isArray(timeline) ? timeline : []; + const byId = new Map(tl.map((e, k) => [str(e?.id), k])); + const segs = Array.isArray(schedule?.segments) ? schedule.segments : []; + const out = []; + for (let i = 1; i < segs.length; i += 1) { + const sa = segs[i - 1]; + const sb = segs[i]; + if (sa?.type !== "post" || sb?.type !== "post") continue; + const ka = byId.get(str(sa.id)); + const kb = byId.get(str(sb.id)); + if (ka === undefined || kb === undefined) continue; + const a = tl[ka]; + const b = tl[kb]; + const ctxA = planContext(tl, ka, render); + const ctxB = planContext(tl, kb, render); + const drawnA = postsDrawnBy(a, ctxA); + const drawnB = postsDrawnBy(b, ctxB); + const shared = [...drawnB.keys()].filter((id) => drawnA.has(id)); + if (!shared.length && !all) continue; + out.push({ + i, from: str(a.id), to: str(b.id), at: fin(sb.start) ? sb.start : null, + shared, relation: shared.length ? joinRelation(a, b) : "none", + join: ctxB.join && fin(ctxB.join.seconds) && kb === ka + 1 ? ctxB.join.seconds : null, + }); + } + return out; +} + +/** + * Where each segment starts in the master: the sum of the files before it as the concat demuxer reads them + * (`durations[i]`: segment i's file length, its longest stream's), else the schedule's start. + * @param {{ segments: Array<{ start?: number }> }} schedule + * @param {Array<number | null>} [durations] + */ +export function masterStarts(schedule, durations = []) { + const segs = schedule?.segments ?? []; + const usable = durations.length === segs.length && durations.every(fin); + let acc = 0; + return segs.map((s, i) => { + const t = usable ? acc : fin(s.start) ? s.start : acc; + if (usable) acc += durations[i]; + return r3(t); + }); +} + +/** ffmpeg's `metadata=print:file=-` lines → `[{ t, v }]` (the frame's pts time, the key's value). */ +export function parseFrameMeta(text, key) { + const out = []; + let t = null; + for (const line of String(text).split(/\r?\n/)) { + const m = /pts_time:([-\d.]+)/.exec(line); + if (m) t = Number(m[1]); + const v = new RegExp(`${key.replace(/\./g, "\\.")}=([-\\d.e]+)`).exec(line); + if (v && t !== null) out.push({ t, v: Number(v[1]) }); + } + return out; +} + +/** The verdict of one measured boundary: "join" (it moved on smoothly), "cut" (a step), "planned cut". */ +export function joinVerdict(row) { + const bad = fin(row.edge) && row.edge > JOIN_CHECK.edge; + if (!bad) return row.join ? "join" : "smooth"; + return row.join ? "JUMPS" : "cut"; +} + +/** Worst first: the biggest edge, then the lowest SSIM. */ +export function rankJoins(rows) { + const score = (r) => -(fin(r.edge) ? r.edge : 0) + (fin(r.ssim) ? r.ssim : 1) / 1000; + return [...rows].sort((a, b) => score(a) - score(b)); +} + +/** The table a person reads. */ +export function joinsTable(rows) { + const head = ["at (master)", "from → to", "relation", "shared", "join", "edge", "ssim", "jump", "verdict"]; + const lines = rows.map((r) => [ + fin(r.t) ? r.t.toFixed(2) : "?", + `${r.from} → ${r.to}`, + r.relation, + String(r.shared.length), + r.join ? `${r.join}s` : "cut", + fin(r.edge) ? r.edge.toFixed(1) : "-", + fin(r.ssim) ? r.ssim.toFixed(3) : "-", + fin(r.jump) ? r.jump.toFixed(1) : "-", + joinVerdict(r), + ]); + const w = head.map((h, k) => Math.max(h.length, ...lines.map((l) => l[k].length))); + const fmt = (l) => l.map((c, k) => c.padEnd(w[k])).join(" ").trimEnd(); + return [fmt(head), fmt(w.map((n) => "-".repeat(n))), ...lines.map(fmt)].join("\n"); +} + +// --------------------------------------------------------------------------- +// The reads (ffmpeg / ffprobe, read-only). +// --------------------------------------------------------------------------- + +/** + * THE CARDS' REGION in the master, pure: the union of the items' cards as laid out (post-item.mjs postLayout, the + * cut's panel rule on) in the post box `box` (the deck's, where the segment lays its box), even-sized for ffmpeg. + */ +export function cardRegion(entries, box, render = undefined) { + const cards = entries.filter(Boolean).map((e) => postLayout(panelEntry(e, render), { width: box.width, height: box.height }).card).filter((c) => c && [c.x, c.y, c.width, c.height].every(fin)); + if (!cards.length) return box; + const x0 = Math.max(0, Math.floor(Math.min(...cards.map((c) => c.x)))); + const y0 = Math.max(0, Math.floor(Math.min(...cards.map((c) => c.y)))); + const x1 = Math.min(box.width, Math.ceil(Math.max(...cards.map((c) => c.x + c.width)))); + const y1 = Math.min(box.height, Math.ceil(Math.max(...cards.map((c) => c.y + c.height)))); + const w = x1 - x0 - ((x1 - x0) % 2); + const h = y1 - y0 - ((y1 - y0) % 2); + return w > 8 && h > 8 ? { x: box.x + x0, y: box.y + y0, width: w, height: h } : box; +} + +/** A file's length as the concat demuxer reads it (its format duration), or null. */ +async function fileSeconds(file, ffprobe) { + try { + const { stdout } = await execFileP(ffprobe, ["-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", file]); + const v = Number(String(stdout).trim()); + return fin(v) ? v : null; + } catch { + return null; + } +} + +/** The files concat.txt lists, in order. */ +export function concatFiles(text) { + return String(text).split(/\r?\n/).map((l) => /^file\s+'(.*)'\s*$/.exec(l.trim())).filter(Boolean).map((m) => m[1].replace(/'\\''/g, "'")); +} + +/** + * Measure boundary `row` in `master` at `t` (where segment `to` starts): the SSIM of the frame 1.5 frames before + * against the one 1.5 frames after, and the largest frame-to-frame change from 3 frames before to the join's end + * (+0.4 s), over `box` scaled to half, in grey. + */ +export async function measureBoundary(master, t, { box, fps = 30, join = null, ffmpeg = "ffmpeg" }) { + const crop = `crop=${box.width}:${box.height}:${box.x}:${box.y},scale=${Math.round(box.width / 2)}:-2,format=gray`; + const ta = Math.max(0, t - 1.5 / fps); + const tb = t + 1.5 / fps; + const ss = await execFileP(ffmpeg, ["-nostdin", "-v", "info", "-ss", ta.toFixed(4), "-i", master, "-ss", tb.toFixed(4), "-i", master, "-frames:v", "1", "-lavfi", `[0:v]${crop}[a];[1:v]${crop}[b];[a][b]ssim`, "-f", "null", "-"], { maxBuffer: 1 << 24 }); + const m = /All:([\d.]+)/.exec(String(ss.stderr)); + const from = Math.max(0, t - 3 / fps); + const span = (fin(join) ? join : 0) + 0.4 + 3 / fps; + const d = await execFileP(ffmpeg, ["-nostdin", "-v", "error", "-ss", from.toFixed(4), "-i", master, "-t", span.toFixed(4), "-vf", `${crop},tblend=all_mode=difference,signalstats,metadata=print:key=lavfi.signalstats.YAVG:file=-`, "-f", "null", "-"], { maxBuffer: 1 << 24 }); + const diffs = parseFrameMeta(String(d.stdout) + String(d.stderr), "lavfi.signalstats.YAVG"); + const j = jumpOf(diffs); + return { edge: r3(edgeOf(diffs.map((x) => ({ t: from + x.t, v: x.v })), t, fps)), ssim: m ? Number(m[1]) : null, jump: r3(j.jump), jumpAt: r3(from + j.t), peak: r3(j.peak) }; +} + +/** + * THE EDGE, pure: the largest change into the frames around the boundary -- the item before's last, this one's first + * and second -- over the largest among the item before's six frames before them (what was already moving: a video + * playing, a pan) (`diffs` on + * the master's clock, each the change INTO its frame; `t` where this item starts). + */ +export function edgeOf(diffs, t, fps = 30) { + const max = (a, b) => diffs.filter((x) => x.t > a && x.t <= b).reduce((m, x) => Math.max(m, x.v), 0); + // Over what was already moving: a video playing in the slot, a pan -- the item before's last frames' own change. + return Math.max(0, max(t - 1.5 / fps, t + 1.5 / fps) - max(t - 7.5 / fps, t - 1.5 / fps)); +} + +/** + * THE JUMP in a run of frame-to-frame changes (`[{ t, v }]`), pure: how far one step stands above the larger of its + * neighbours -- a cut is one step (big, its neighbours still), a morph or a dissolve many alike (small) -- `{ jump, + * t, peak }` (`peak` the largest step itself). + */ +export function jumpOf(diffs) { + let out = { jump: 0, t: 0, peak: 0 }; + diffs.forEach((x, i) => { + const near = Math.max(diffs[i - 1]?.v ?? 0, diffs[i + 1]?.v ?? 0); + const j = Math.max(0, x.v - near); + if (j > out.jump) out = { ...out, jump: j, t: x.t }; + if (x.v > out.peak) out.peak = x.v; + }); + return out; +} + +/** + * CHECK A TAKE: `{ rows, master, offsets }` -- each boundary (joinBoundaries) measured in the take's master. + * `takeDir` the take's folder (its video.manifest.json, out/<slug>.mp4, out/sourced/{schedule.json,concat.txt}). + */ +export async function checkJoins(takeDir, { all = false, ffmpeg = "ffmpeg", ffprobe = "ffprobe", onRow = () => {} } = {}) { + const manifest = JSON.parse(await readFile(path.join(takeDir, "video.manifest.json"), "utf8")); + const out = path.join(takeDir, "out"); + const sourced = path.join(out, "sourced"); + const schedule = JSON.parse(await readFile(path.join(sourced, "schedule.json"), "utf8")); + const master = path.join(out, `${str(manifest.slug)}.mp4`); + const fps = fin(schedule.fps) ? schedule.fps : manifest.render?.fps ?? 30; + const files = concatFiles(await readFile(path.join(sourced, "concat.txt"), "utf8").catch(() => "")); + const durations = files.length === schedule.segments.length ? await Promise.all(files.map((f) => fileSeconds(f, ffprobe))) : []; + const starts = masterStarts(schedule, durations); + const rows = joinBoundaries(manifest.timeline, schedule, manifest.render, { all }); + const measured = []; + for (const r of rows) { + const seg = schedule.segments[r.i]; + const cut = JSON.parse(await readFile(path.join(sourced, "segments", `${seg.id}.cut.json`), "utf8").catch(() => "null")); + const fb = cut?.framing?.box; + const box = isObj(fb) && [fb.x, fb.y, fb.width, fb.height].every(fin) ? { x: Math.round(fb.x), y: Math.round(fb.y), width: Math.round(fb.width) - (Math.round(fb.width) % 2), height: Math.round(fb.height) - (Math.round(fb.height) % 2) } : { x: 0, y: 0, width: 1920, height: 880 }; + const t = starts[r.i]; + // Over the CARDS (the item before's and this one's, as laid out), never their attachments' slots: a video playing + // through the boundary, or one cross-fading into another, is not the join's step. + const byId = new Map(manifest.timeline.map((e) => [e?.id, e])); + const region = cardRegion([byId.get(r.from), byId.get(r.to)], box, manifest.render); + const m = await measureBoundary(master, t, { box: region, fps, join: r.join, ffmpeg }); + const row = { ...r, t, box: region, ...m }; + row.verdict = joinVerdict(row); + measured.push(row); + onRow(row); + } + return { rows: rankJoins(measured), master, offsets: durations.length ? r3(starts[starts.length - 1] - (schedule.segments.at(-1)?.start ?? 0)) : 0 }; +} diff --git a/umtool/report-to-video/check-joins.test.mjs b/umtool/report-to-video/check-joins.test.mjs @@ -0,0 +1,51 @@ +// CHECK JOINS (check-joins.mjs): the measured check of a rendered take's joins -- its pure parts. +import assert from "node:assert/strict"; +import { test } from "node:test"; + +import { cardRegion, concatFiles, edgeOf, joinBoundaries, jumpOf, joinRelation, joinVerdict, joinsTable, masterStarts, parseFrameMeta, postsDrawnBy, rankJoins } from "./check-joins.mjs"; + +const at = (h) => `2026-11-04T${String(h).padStart(2, "0")}:00:00.000Z`; +const narrate = (e, parts) => ({ ...e, narration: { takes: [{ file: `narration/${e.id}.wav`, seconds: 6, parts: parts.map((p) => ({ text: p.join(" ") })) }], picked: 0 } }); +const post = (id, text, h, extra = {}) => ({ type: "post", id: `p-${id}`, post: `ObviousRises-x/${id}`, platform: "x", author: "MR. OBVIOUS", handle: "ObviousRises", date: at(h), text, url: `https://x.com/ObviousRises/status/${id}`, ...extra }); +const ref = (id, text, h) => ({ id, author: "MR. OBVIOUS", handle: "ObviousRises", date: at(h), text }); + +test("CHECK JOINS: the boundaries where the next item draws a post the one before showed, their relation and planned join; the master's starts from the files as the concat reads them; worst first", () => { + const a = narrate(post("10", "mercy", 7), [["mercy"]]); + const b = narrate(post("11", "notice", 8, { parents: [ref("10", "mercy", 7)] }), [["notice"]]); + const c = narrate(post("99", "unrelated", 9), [["unrelated"]]); + const tl = [a, b, c]; + assert.deepEqual([...postsDrawnBy(b).entries()], [["11", "post"], ["10", "parent"]]); + assert.equal(joinRelation(a, b), "self-reply"); + assert.equal(joinRelation(a, { ...b, handle: "Other" }), "reply to it"); + assert.equal(joinRelation(a, { ...c, quoted: { id: "10", text: "mercy" } }), "quotes it"); + const schedule = { fps: 30, segments: [{ id: "p-10", type: "post", start: 0, duration: 15.9 }, { id: "p-11", type: "post", start: 15.9, duration: 10 }, { id: "p-99", type: "post", start: 25.9, duration: 5 }] }; + const rows = joinBoundaries(tl, schedule); + assert.deepEqual(rows.map((r) => [r.from, r.to, r.shared, r.relation, r.join]), [["p-10", "p-11", ["10"], "self-reply", 0.6]]); + assert.equal(joinBoundaries(tl, schedule, undefined, { all: true }).length, 2); + // The audio a few ms longer than the video: every later segment later than the schedule says. + assert.deepEqual(masterStarts(schedule, [15.905, 10.003, 5]), [0, 15.905, 25.908]); + assert.deepEqual(masterStarts(schedule, []), [0, 15.9, 25.9]); + assert.deepEqual(concatFiles("ffconcat version 1.0\nfile '/a/b.mp4'\nfile '/a/it'\\''s.mp4'\n"), ["/a/b.mp4", "/a/it's.mp4"]); + assert.deepEqual(parseFrameMeta("frame:0 pts:512 pts_time:0.0333\nlavfi.signalstats.YAVG=0.5\nframe:1 pts:1024 pts_time:0.0667\nlavfi.signalstats.YAVG=9.25\n", "lavfi.signalstats.YAVG"), [{ t: 0.0333, v: 0.5 }, { t: 0.0667, v: 9.25 }]); + // A cut: one step alone; a dissolve: many alike. + assert.equal(jumpOf([{ t: 0, v: 0 }, { t: 1, v: 9 }, { t: 2, v: 0.2 }]).jump, 8.8); + assert.ok(jumpOf([{ t: 0, v: 2 }, { t: 1, v: 2.5 }, { t: 2, v: 2.2 }, { t: 3, v: 1.9 }]).jump < 0.5); + // Over the cards, not the slots: a card beside a video is its own column. + const box = { x: 173, y: 2, width: 1574, height: 886 }; + const withVideo = { ...a, media: [{ src: "v.mp4", kind: "video", width: 1280, height: 720, seconds: 10 }] }; + const reg = cardRegion([withVideo], box); + assert.ok(reg.width < box.width * 0.6 && reg.x >= box.x && reg.width % 2 === 0 && reg.height % 2 === 0); + assert.deepEqual(cardRegion([], box), box); + // THE EDGE: mid-7's 2357 boundary on main (the carried post switching at frame 1) against the lane's dissolve. + const series = (vals, t0 = 692.1) => vals.map((v, k) => ({ t: t0 + k / 30, v })); + assert.equal(edgeOf(series([0, 0, 0.4, 10.4, 3.6, 0, 4.7]), 692.153), 10.4); + assert.equal(edgeOf(series([0, 0, 0.1, 0, 3.9, 0, 5.3]), 692.153), 0.1); + // A video playing across the boundary: its own change is not the join's. + assert.ok(edgeOf(series([4, 3.8, 0, 4.1, 3.9, 4.2, 0, 4.0, 4.1], 692.0), 692.153) < 0.5); + const measured = [{ from: "a", to: "b", shared: ["1"], relation: "self-reply", join: 0.6, t: 1, edge: 10.4, ssim: 0.79, jump: 10.7 }, { from: "c", to: "d", shared: ["2"], relation: "manual thread", join: 0.6, t: 2, edge: 0.1, ssim: 0.998, jump: 1.2 }]; + assert.deepEqual(rankJoins(measured).map((r) => r.from), ["a", "c"]); + assert.equal(joinVerdict(measured[0]), "JUMPS"); + assert.equal(joinVerdict(measured[1]), "join"); + assert.equal(joinVerdict({ ...measured[0], join: null }), "cut"); + assert.match(joinsTable(measured), /a → b\s+self-reply\s+1\s+0\.6s\s+10\.4\s+0\.790\s+10\.7\s+JUMPS/); +}); diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json @@ -23,6 +23,7 @@ "./brand-ids": "./brand-ids.mjs", "./build-video": "./build-video.mjs", "./check-availability": "./check-availability.mjs", + "./check-joins": "./check-joins.mjs", "./chunked-encode": "./chunked-encode.mjs", "./claims": "./claims.mjs", "./clip-audio": "./clip-audio.mjs", @@ -71,6 +72,7 @@ "./post-censor": "./post-censor.mjs", "./post-media-scene": "./post-media-scene.mjs", "./post-redact": "./post-redact.mjs", + "./post-say": "./post-say.mjs", "./post-redact-files": "./post-redact-files.mjs", "./post-slurs": "./post-slurs.mjs", "./post-thread": "./post-thread.mjs", diff --git a/umtool/report-to-video/post-item.mjs b/umtool/report-to-video/post-item.mjs @@ -35,7 +35,7 @@ import { import { BAR_CSS, barsHtml, hasMarks, projectRedactOf, redactEntry, redactSceneRef, redactionOn, validatePostsRender } from "./post-redact.mjs"; import { blurErrors } from "./post-censor.mjs"; import { WORD_ZOOM_HIGHLIGHT_ALPHA, cardTokens, cardWordsOf, findMatch, targetTextOf, validatePostFx } from "./word-zoom.mjs"; -import { FOLLOW_MIN_SIZE, followBlocks, followSchedule, scopeBlocks, validatePostFollow } from "./read-follow.mjs"; +import { FOLLOW_MIN_SIZE, followBlocks, followKnobs, followSchedule, scopeBlocks, validatePostFollow } from "./read-follow.mjs"; import { panelSchedule, validatePostThread } from "./post-thread.mjs"; import { joinLayerHtml, validatePostJoin, validatePostJoinRender } from "./post-join.mjs"; import { validatePostLinkVisit, validatePostLinkVisitRender, visitsEnd } from "./post-link-visit.mjs"; @@ -292,6 +292,10 @@ function planOf(entry, render, hold, prev = null, scene = null, mediaScene = nul return { ...plan, reading: round3(Math.min(voiceOnly, total)), total, ...extra, ...(panel ? { panel } : {}) }; } const span = sch ? round3(sch.at + sch.seconds + k.tail + k.linger) : readingSeconds(entry); + // ITS OWN ATTACHMENTS come in with ITS OWN POST (ownMediaEnterAt): a thread read's parents and quotes first, his + // attachment when his words begin -- a video starts there, its sound too, its trim fitted to what is left. + const enter = ownMediaEnterAt(entry, follow, { mediaScene }); + const avail = round3(Math.max(0, span - enter)); const all = mediaSteps(entry).map((s) => { if (s.kind !== "video" || k.clip === "full") return s; // An out point the operator set is kept: that span is the choice. One `posts fit` set (it is the @@ -299,16 +303,16 @@ function planOf(entry, render, hold, prev = null, scene = null, mediaScene = nul const m = s.items[0]; const w = entry?.narration?.window; const fitEnd = sch && isObj(w) && w.media === m.i && fin(w.end) && Math.abs(w.end - m.end) < 0.011; - return fin(m.end) && !fitEnd ? s : { ...s, seconds: round3(Math.min(s.seconds, span)) }; + return fin(m.end) && !fitEnd ? s : { ...s, seconds: round3(Math.min(s.seconds, avail)) }; }); const videos = all.filter((s) => s.kind === "video").reduce((n, s) => n + s.seconds, 0); const pics = all.filter((s) => s.kind !== "video"); - const share = pics.length ? Math.max(POST_PICTURE_MIN, (span - videos) / pics.length) : 0; + const share = pics.length ? Math.max(POST_PICTURE_MIN, (avail - videos) / pics.length) : 0; const steps = all.map((s) => (s.kind === "video" ? s : { ...s, seconds: round3(share) })); const media = round3(steps.reduce((n, s) => n + s.seconds, 0)); // A LINK VISIT (post-link-visit.mjs) lit after the read runs on its hold: the item holds it. - const total = hold ?? round3(Math.max(span, media, follow?.visits ? visitsEnd(follow.visits) : 0)); - const plan = planSteps(steps, 0, total); + const total = hold ?? round3(Math.max(span, enter + media, follow?.visits ? visitsEnd(follow.visits) : 0)); + const plan = planSteps(steps, enter, total); // A video shorter than the read: looped to the end, or (the default) its last frame held. const last = plan.steps[plan.steps.length - 1]; if (k.short === "loop" && last?.kind === "video" && plan.held > 0.05) { @@ -318,7 +322,35 @@ function planOf(entry, render, hold, prev = null, scene = null, mediaScene = nul } // A CONTEXT POST's attachment (post-thread.mjs panelSchedule): over the slot while it is on screen. const panel = follow ? panelSchedule(entry, follow, total) : null; - return { ...plan, reading: 0, total, ...extra, ...(panel ? { panel } : {}) }; + return { ...plan, reading: 0, total, ...extra, ...(panel ? { panel } : {}), ...(enter > 0 && plan.steps.length ? { enter } : {}) }; +} + +/** Where an item's own attachments may come in (`media[0].enter`): with its own post (the default), or with the item. */ +export const POST_MEDIA_ENTERS = Object.freeze(["post", "item"]); +/** Their crossfade in, seconds, from the moment his own words begin. */ +export const POST_ENTER_FADE = 0.3; + +/** + * WHEN AN ITEM's OWN ATTACHMENTS COME IN, pure (operator, 4 Nov, mid-11 at ~15:58: "the mr. obvious gif should come in + * when his post does rather than during the strawb megathread reading"): the item second its OWN POST's read begins + * (its first block of scope `post`) when a threaded read reads something else before it (a parent, a quote, a linked + * post) -- else 0, as before: an item that reads only its post, one not threaded, one in a media scene after its + * first (the item before ended on the same attachment: held through), or one whose first attachment says + * `enter: "item"`. Until then the slot shows that + * piece's context media (panelSchedule), or nothing. + * @param {Record<string, any>} entry + * @param {{ thread?: any, blocks?: Array<{ scope?: string, start: number | null }> } | null} follow + */ +export function ownMediaEnterAt(entry, follow, { mediaScene = null } = {}) { + const media = Array.isArray(entry?.media) ? entry.media : []; + // In a media scene past its first item the item before ended on this same attachment: held through, as before. + if (!media.length || !follow?.thread || (mediaScene && (mediaScene.n ?? 0) > 0)) return 0; + if (media[0]?.enter === "item") return 0; + const blocks = (follow.blocks ?? []).filter((b) => fin(b.start)); + const post = blocks.filter((b) => b.scope === "post"); + if (!post.length) return 0; + const at = Math.min(...post.map((b) => b.start)); + return blocks.some((b) => b.scope !== "post" && b.start < at - 1e-6) ? round3(at) : 0; } /** Steps placed from `at0`, cut at `total` (postItemPlan's walk). */ @@ -576,6 +608,7 @@ function mediaErrors(m, where) { } if (timed && fin(m.start) && fin(m.end) && m.end - m.start < POST_MEDIA_MIN_SPAN) errors.push(`${where}: end must be at least ${POST_MEDIA_MIN_SPAN} s after start`); for (const k of ["mute", "push", "audio"]) if (m[k] !== undefined && typeof m[k] !== "boolean") errors.push(`${where}.${k} must be true or false`); + if (m.enter !== undefined && !POST_MEDIA_ENTERS.includes(m.enter)) errors.push(`${where}.enter must be ${POST_MEDIA_ENTERS.join(" or ")} (when it comes in: with his own post, or with the item)`); if (m.push !== undefined && m.kind !== "image") errors.push(`${where}.push: only an image is pushed in on`); if (m.crop !== undefined) { const c = m.crop; @@ -973,7 +1006,7 @@ export function nameHtml(who, { redact, cls = "" }) { * highlight?: { scope: string, from: number, to: number, color: string } | null, * redaction?: { terms: Array<{term: string, wholeWord?: boolean}>, markup?: Record<string, any> } | null, follow?: boolean, * thread?: { tiles?: Array<{ scope: string, mode: string }> } | null, - * join?: { A?: { x: number, y: number, width: number, height: number }, slotA?: Record<string, number> | null, fromUrl?: string | null, size?: number | null, same?: boolean } | null }} o + * join?: { A?: { x: number, y: number, width: number, height: number }, slotA?: Record<string, number> | null, fromUrl?: string | null, size?: number | null, same?: boolean, plain?: boolean, headSize?: number | null } | null }} o */ export function postCardHtml(entry, { width, height, palette = {}, fonts = {}, phase = "read", parentShotUrl = null, transparent = false, avatars = {}, highlight = null, redaction = null, follow = false, thread = null, join = null }) { const hlOf = (scope) => (highlight && highlight.scope === scope ? highlight : null); @@ -1075,10 +1108,12 @@ export function postCardHtml(entry, { width, height, palette = {}, fonts = {}, p // THE JOIN (post-join.mjs): the post the item before ended on -- carried in, or the scene's -- drawn as that item // drew its post (its head, its words at their size), so the item opens on it exactly as it ended. const asPost = (scope, p, r, attr, mode, slotAttr = "") => { + // A PLAIN card before (no thread): its head is the card's (not the words' size) and its words a card's gap below; + // a THREADED one: its head at ITS words' box size (`headSize`), not this card's. const sz = fin(join?.size) ? join.size : sizeFor(contextText(p) || " ", innerW, innerH - 170 * k); const own2 = { author: p.author, handle: p.handle }; const headP = `<div class="head"${r ? ' data-redacted=""' : ""}>${avatarHtml(own2, { redact: r, size: Math.round(64 * k), accent: r ? undefined : pal.accent, img: r ? null : pic(p) })}<div class="hwho">${nameHtml(own2, { redact: r, cls: "big" })}<div class="date">${esc(cardDate(p.date))}</div></div><div class="mark">${esc(PLATFORM_NAME[entry.platform] ?? "")}</div></div>`; - tileHtml.push(`<div class="tslot" data-thread-slot="${esc(scope)}"${slotAttr}><div class="tile tpost tcarry" data-thread-tile="${esc(scope)}" data-thread-mode="${mode}" ${attr} data-join-anchor="">${relationHtml(t0(scope))}${headP}<div class="twords" style="font-size:${sz}px">${wordsHtml(contextText(p), r && p.handle ? [...blurred, p.handle] : blurred)}</div></div></div>`); + tileHtml.push(`<div class="tslot" data-thread-slot="${esc(scope)}"${slotAttr}><div class="tile tpost tcarry${join?.plain ? " tplain" : ""}" data-thread-tile="${esc(scope)}" data-thread-mode="${mode}" ${attr} data-join-anchor="">${relationHtml(t0(scope))}${!join?.plain && fin(join?.headSize) ? headP.replace('<div class="head"', `<div class="head" style="font-size:${join.headSize}px"`) : headP}<div class="twords" style="font-size:${sz}px">${wordsHtml(contextText(p), r && p.handle ? [...blurred, p.handle] : blurred)}</div></div></div>`); }; const refTile = (scope, p, where, attr) => { const mode = tmode(scope); @@ -1210,6 +1245,8 @@ b, .name, .mark { font-family: 'PostSansBold', sans-serif; font-weight: 400; } .tparent { display: flex; gap: ${Math.round(16 * k)}px; position: relative; } .tparent::after { content: ""; position: absolute; left: ${Math.round(27 * k)}px; top: ${Math.round(64 * k)}px; bottom: -${Math.round(20 * k)}px; width: 2px; background: ${line}; } .tpost { display: flex; flex-direction: column; gap: ${Math.round(16 * k)}px; } +.tplain { gap: ${Math.round(18 * k)}px; } +.tplain > .head { font-size: 16px; line-height: normal; } ${tiles?.some((t) => t?.rel) ? `.rel { color: ${pal.muted}; font-size: ${Math.round(18 * k)}px; margin-bottom: ${Math.round(4 * k)}px; letter-spacing: 0.01em; } .rel::before { content: "\\21b3 "; } ` : ""}.tile .tt { display: block; -webkit-line-clamp: none; overflow: visible; line-height: ${LINE}; color: ${pal.fg}; margin-top: ${Math.round(6 * k)}px; } @@ -1266,6 +1303,23 @@ export function cardWordsSize(entry, { width, height }, { follow = false, thread } /** + * HOW AN ITEM DRAWS ITS POST, for the join (post-join.mjs) -- what the item after it carries in is drawn alike, pure: + * `{ size, plain, headSize }` -- its words' size (cardWordsSize; threaded when its plan is), whether its card is PLAIN + * (no thread: its head the card's), else the size its head is drawn at (its words box's, cardWordsSize unthreaded). + * `entry` as its segment draws it (its markup, its media scene, the panel rule laid on), `plan` its postItemPlan. + * The build draws the item before's page with its OWN join this way (as its segment drew it); Play's route the same. + * @param {Record<string, any>} entry + * @param {{ follow?: { thread?: any } | null }} plan + * @param {{ width: number, height: number }} box + * @param {Record<string, any>} [render] + */ +export function joinCarryOf(entry, plan, box, render = undefined) { + const follow = followKnobs(entry, render).on; + const threaded = follow && !!plan?.follow?.thread; + return { size: cardWordsSize(entry, box, { follow, threaded }), plain: !threaded, headSize: threaded ? cardWordsSize(entry, box, { follow }) : null }; +} + +/** * A MEDIA SCENE's earlier message as a tile of a later item's column * (post-media-scene.mjs; postCardHtml's threaded card): drawn as its own post * tile was while it was read -- the repost line, its author (under its own diff --git a/umtool/report-to-video/post-join-continuity.test.mjs b/umtool/report-to-video/post-join-continuity.test.mjs @@ -0,0 +1,110 @@ +// THE JOIN's continuity (operator, 4 Nov, on mid-7 at 2357 s: "the transition from some posts hard cutting into the +// same post with children should be addressed. If one post is visible in the next scene, there should be a +// transition"): the item opens EXACTLY as the item before ended -- its card, what only it drew (its counts, its quote, +// its clock) dissolving rather than gone at the second frame -- and the check that measures it (check-joins.mjs). +import assert from "node:assert/strict"; +import { test } from "node:test"; + +import { JOIN_CLOCK_NEAR, joinClockOf, joinFrameAt, joinOpacities } from "./post-join.mjs"; +import { clockJoinExpr, concatRate, postSegmentArgs, postSegmentKey, postSegmentKeyOf, POST_JOIN_DRAW_V } from "./post-render.mjs"; +import { joinCarryOf, postCardHtml, postItemPlan } from "./post-item.mjs"; +import { planContext } from "./post-conversation.mjs"; + +const at = (h) => `2026-11-04T${String(h).padStart(2, "0")}:00:00.000Z`; +const narrate = (e, parts) => ({ ...e, narration: { takes: [{ file: `narration/${e.id}.wav`, seconds: 6, parts: parts.map((p) => ({ text: p.join(" ") })) }], picked: 0 } }); +const post = (id, text, h, extra = {}) => ({ type: "post", id: `p-${id}`, post: `ObviousRises-x/${id}`, platform: "x", author: "MR. OBVIOUS", handle: "ObviousRises", date: at(h), text, url: `https://x.com/ObviousRises/status/${id}`, ...extra }); +const ref = (id, text, h) => ({ id, author: "MR. OBVIOUS", handle: "ObviousRises", date: at(h), text }); + +test("THE DISSOLVE: at the boundary the item before's card is whole and on top; this one is in under it before it starts to go; what both draw never dims", () => { + // The first frames (e ~ 0): the item before, exactly. + assert.deepEqual(joinOpacities(0, true), { own: 1, from: 1 }); + assert.deepEqual(joinOpacities(0, false), { own: 0, from: 1 }); + // Never a frame where the item before's card is gone at once (main's `same` dropped it after the first frame). + const g = { A: { x: 100, y: 100, width: 968, height: 554 }, B: { x: 100, y: 0, width: 968, height: 787 }, slotA: null, slotB: null, same: true }; + assert.equal(joinFrameAt(g, 1 / 18).from.op, 1, "the second frame still shows what the item before showed"); + // This card is whole before the item before's starts to fade: over it, the shared post is lit throughout. + for (let e = 0; e <= 1.0001; e += 0.05) { + const o = joinOpacities(e, false); + if (o.from < 1) assert.equal(o.own, 1, `at e ${e.toFixed(2)} this card is in before that one fades`); + } + assert.deepEqual(joinOpacities(1, false), { own: 1, from: 0 }); + assert.ok(joinFrameAt(g, 0.9).from.op === 0, "gone well before the join ends"); +}); + +test("THE CLOCK OVER A JOIN: near, it carries on (moved the little way); apart, the item before's is laid in its shot and dissolves, this one comes in -- never across the card's words", () => { + assert.deepEqual(joinClockOf({ from: { x: 100, y: 200 }, own: { x: 110, y: 190 }, k: 1 }), { bake: false, move: { dx: -10, dy: 10 }, fadeIn: false }); + // mid-7 at 2357 s: the card's foot (bottom-right) to above the card (top-right). + assert.deepEqual(joinClockOf({ from: { x: 1050, y: 620 }, own: { x: 1050, y: 20 }, k: 886 / 1080 }), { bake: true, move: null, fadeIn: true }); + assert.deepEqual(joinClockOf({ from: null, own: { x: 1, y: 1 } }), { bake: false, move: null, fadeIn: true }); + assert.deepEqual(joinClockOf({ from: { x: 1, y: 1 }, own: null }), { bake: true, move: null, fadeIn: false }); + assert.deepEqual(joinClockOf({ from: null, own: null }), { bake: false, move: null, fadeIn: false }); + assert.ok(JOIN_CLOCK_NEAR > 0); + // The move's expression: base + d at the start, base from the join's end. + const ex = clockJoinExpr(900, -12, 0.6); + // ffmpeg's expression, evaluated as ffmpeg would (if, lt, min, pow). + const ev = (t) => Function("t", "min", "pow", "lt", "iff", `return ${ex.replace(/\bif\(/g, "iff(")};`)(t, Math.min, Math.pow, (a, b) => a < b, (c, a, b) => (c ? a : b)); + assert.equal(ev(0), 888); + assert.equal(ev(0.6), 900); + assert.equal(ev(2), 900); +}); + +test("THE SEGMENT's CLOCK over a join: moved from the item before's place (an expression on t), or faded in -- a clock with no join drawn as before", () => { + const plan = { total: 10, steps: [], reading: 10 }; + const base = { entry: { id: "p-1", media: [] }, box: { width: 1574, height: 886 }, plan, layout: { mode: "text", slot: null }, cards: { read: "read.png" }, files: [], render: { fps: 30 }, outPath: "out.mp4" }; + const graph = (clock) => postSegmentArgs({ ...base, clock }).find((a) => String(a).includes("[clk]overlay")); + const plain = graph({ list: "c.ffconcat", x: 900, y: 600, until: 10 }); + assert.match(plain, /\[clk\]overlay=x=900:y=600:eof_action=repeat/); + assert.doesNotMatch(plain, /fade=t=in/); + const moved = graph({ list: "c.ffconcat", x: 900, y: 600, until: 10, join: { seconds: 0.6, from: { dx: 0, dy: 14 }, fadeIn: false } }); + assert.match(moved, /overlay=x=900:y='600\+14\*\(1-if\(lt\(min\(1,t\/0\.6\),0\.5\)/); + const faded = graph({ list: "c.ffconcat", x: 900, y: 20, until: 10, join: { seconds: 0.6, from: null, fadeIn: true } }); + assert.match(faded, /fade=t=in:st=0:d=0\.6:alpha=1\[clk\]/); + assert.match(faded, /overlay=x=900:y=20:/); +}); + +test("THE CARRIED POST drawn as a PLAIN card drew it: its head at the card's size (not the words'), its words a card's gap below; after a threaded card, its head at that card's words box size", () => { + const before = post("10", "I'm only giving mercy because I'm concerned for my moms.", 7); + const reply = narrate(post("11", "notice how thats the exact character limit", 8, { parents: [ref("10", before.text, 7)], thread: { group: "limit" } }), [["notice how thats the exact character limit"]]); + const tl = [narrate(before, [[before.text]]), reply]; + const ctx = planContext(tl, 1); + const plan = postItemPlan(reply, undefined, ctx); + const html = (plain, headSize = null) => postCardHtml(reply, { width: 1574, height: 886, follow: true, thread: plan.follow.thread, join: { A: { x: 10, y: 10, width: 800, height: 500 }, size: 38, plain, headSize } }); + assert.match(html(true), /class="tile tpost tcarry tplain"/); + assert.match(html(true), /\.tplain > \.head \{ font-size: 16px; line-height: normal; \}/); + assert.match(html(false), /class="tile tpost tcarry" /); + // A threaded card before: its head at its own words box's size, not this card's. + assert.match(html(false, 41), /data-join-anchor=""><div class="head" style="font-size:41px">/); + assert.doesNotMatch(html(true, 41), /font-size:41px/); +}); + +test("THE KEY: a joined item's key carries the join's drawing and the clock the item before ran -- its key changes; an item with no join keeps the key it had", () => { + const entry = post("11", "notice how", 8); + const plan = { narration: null, follow: null, total: 5, steps: [] }; + const common = { entry, box: { width: 1574, height: 886 }, render: { fps: 30, palette: {} }, plan }; + const none = postSegmentKeyOf(common); + assert.equal(none.joinFrom, undefined); + const from = { entry: post("10", "mercy", 7), plan: { follow: null, total: 15.9 }, media: [], fadeIn: false, clock: { to: 1, from: null, mode: "none", zone: "America/New_York", gap: 0, forced: false } }; + const joined = postSegmentKeyOf({ ...common, from }); + assert.equal(joined.joinFrom.jv, POST_JOIN_DRAW_V); + assert.deepEqual(joined.joinFrom.clock, from.clock); + const other = postSegmentKeyOf({ ...common, from: { ...from, clock: { ...from.clock, to: 2 } } }); + assert.notEqual(postSegmentKey(joined), postSegmentKey(other), "the item before's clock is in the key"); + assert.notEqual(postSegmentKey(joined), postSegmentKey(none)); +}); + +test("A FRAMES LIST reads each shot at the item's rate (ffconcat `option framerate`): no shot in six dropped and its neighbour held", () => { + assert.deepEqual(concatRate(30), ["option framerate 30"]); +}); + +test("HOW AN ITEM DRAWS ITS POST (joinCarryOf): a plain card's words and head; a threaded card's post tile size and its words box's head -- the build draws the item before's page with its own join this way, as its segment drew it", () => { + const box = { width: 1574, height: 886 }; + const before = narrate(post("10", "I'm only giving mercy because I'm concerned for my moms.", 7), [["I'm only giving mercy because I'm concerned for my moms."]]); + const reply = narrate(post("11", "notice how thats the exact character limit", 8, { parents: [ref("10", before.text, 7)], thread: { group: "limit" } }), [["notice how thats the exact character limit"]]); + const plain = joinCarryOf(before, postItemPlan(before), box); + assert.equal(plain.plain, true); + assert.equal(plain.headSize, null); + const tl = [before, reply]; + const threaded = joinCarryOf(reply, postItemPlan(reply, undefined, planContext(tl, 1)), box); + assert.equal(threaded.plain, false); + assert.ok(threaded.size > 0 && threaded.headSize > 0); +}); diff --git a/umtool/report-to-video/post-join.mjs b/umtool/report-to-video/post-join.mjs @@ -6,8 +6,11 @@ // // the CARD its container morphs from the item before's box (as it ended) to its own -- position, // width and height eased; the words inside scaled with its width, never re-flowed -// what it SHOWED the item before's card as it ended (the build: a shot of its page at its last frame; -// Play: its page in a second frame) rides the container and fades out as this one's fades in +// what it SHOWED the item before's card as it ended (the build: a shot of its page at its last frame -- its +// clock, its parent's shot, a visit's pointer on it; Play: its page in a second frame) rides +// the container on top and dissolves into this one's, whole under it first (joinOpacities) +// the CLOCK carried on from the item before's when near, else that one dissolves and this comes in +// (joinClockOf) -- never moved across the card's words // the COLUMN the post the item before ended on (carried, or the scene's) is drawn as that item drew it // -- its head, its words at their size -- and the column opens framed where it was // the SLOT a slot that appears fades in, one that goes fades out; another attachment cross-fades @@ -60,6 +63,17 @@ const lerpRect = (a, b, f) => ({ x: lerp(a.x, b.x, f), y: lerp(a.y, b.y, f), wid const sameRect = (a, b) => !!a && !!b && ["x", "y", "width", "height"].every((k) => Math.abs(a[k] - b[k]) < 1.5); /** + * THE DISSOLVE's strengths at eased progress `e`, pure: `{ own, from }` -- this card's (under) in by e 0.3 (from the + * first frame when the content is the same), the item before's (over it) out from e 0.25 to 0.75. Both are whole + * across the boundary (e 0: the item before as it ended) and the item before's is gone well before the join ends. + */ +export function joinOpacities(e, same = false) { + const own = same ? 1 : Math.min(1, Math.max(0, e / 0.3)); + const from = 1 - Math.min(1, Math.max(0, (e - 0.25) / 0.5)); + return { own, from }; +} + +/** * THE JOIN's FRAME at progress `p` (0: the item before as it ended, 1: this item's own), pure: `{ e, R, own, from, * slotFrom, slotTo }` -- `R` the container's box; `own` this card's transform (`tx`, `ty`, `s`: its top-left moved to * R's, scaled by R's width over its own; `clipH` the height of it that shows; `op`); `from` the item before's card @@ -73,22 +87,44 @@ export function joinFrameAt(g, p) { const B = g.B; const R = lerpRect(A, B, e); const s = R.width / Math.max(1, B.width); - // The content cross-fades over the middle half of the join; the same content (sameRect, a carry alike) shows - // this card's from the first frame -- the item before's drawn under it only as long as the box moves. - const x = Math.min(1, Math.max(0, (e - 0.4) / 0.4)); - const y = Math.min(1, Math.max(0, (e - 0.1) / 0.4)); - const opOwn = g.same ? 1 : x; + // The item before's card (on top) dissolves into this one's, which is in UNDER it before it starts to go -- so + // what both draw (the post carried in) never dims, and what only the item before drew (its counts, its quote, its + // clock) fades out; never a frame where it is all gone at once (operator, 4 Nov, mid-7: "if one post is visible + // in the next scene, there should be a transition"). The same content (a carry alike) is this card's from the + // first frame, under the item before's. + const { own: opOwn, from: opFrom } = joinOpacities(e, !!g.same); const sameSlot = sameRect(g.slotA, g.slotB); return { e: r2(e), R: { x: r2(R.x), y: r2(R.y), width: r2(R.width), height: r2(R.height) }, own: { tx: r2(R.x - B.x), ty: r2(R.y - B.y), s: Math.round(s * 10000) / 10000, clipH: r2(R.height / Math.max(1e-6, s)), op: r2(opOwn) }, - from: { x: r2(R.x), y: r2(R.y), s: Math.round((R.width / Math.max(1, A.width)) * 10000) / 10000, op: r2(g.same ? (p <= 0 ? 1 : 0) : 1 - y) }, + from: { x: r2(R.x), y: r2(R.y), s: Math.round((R.width / Math.max(1, A.width)) * 10000) / 10000, op: r2(opFrom) }, slotFrom: g.slotA && !sameSlot ? r2(1 - e) : g.slotA ? 1 : 0, slotTo: g.slotB && !sameSlot ? r2(e) : g.slotB ? 1 : 0, }; } +/** How far (px at 1080) the clock may carry on from the item before's place by moving: never across the card's words. */ +export const JOIN_CLOCK_NEAR = 24; + +/** + * THE CLOCK OVER A JOIN, pure (post-clock.mjs): `{ bake, move, fadeIn }` -- `from` where the item before's clock sat + * as it ended (or null: it showed none), `own` where this item's sits (or null), `k` the box's height over 1080. + * Near (within JOIN_CLOCK_NEAR): this one opens on that one's place and moves the little way (`move` its offset + * there), nothing faded. Apart: a move would cross the card's words -- that one is laid in the item before's shot + * (`bake`) and dissolves with it, this one comes in over the join (`fadeIn`). None before: this one comes in; none + * now: that one is laid in the shot. + * @param {{ from: { x: number, y: number } | null, own: { x: number, y: number } | null, k?: number }} o + */ +export function joinClockOf({ from, own, k = 1 }) { + if (!own) return { bake: !!from, move: null, fadeIn: false }; + if (!from) return { bake: false, move: null, fadeIn: true }; + const dx = from.x - own.x; + const dy = from.y - own.y; + if (Math.hypot(dx, dy) <= JOIN_CLOCK_NEAR * k) return { bake: false, move: { dx: r2(dx), dy: r2(dy) }, fadeIn: false }; + return { bake: true, move: null, fadeIn: true }; +} + /** The join's progress at item second `s` (null: over, or none). */ export const joinProgressAt = (join, s) => (join && fin(join.seconds) && s < join.seconds - 1e-6 ? Math.max(0, s / join.seconds) : null); @@ -171,8 +207,9 @@ export function applyJoinState(p, doc = document) { const L = (a, b2) => a + (b2 - a) * e; const R = { x: L(A.x, B.x), y: L(A.y, B.y), width: L(A.width, B.width), height: L(A.height, B.height) }; const s = R.width / Math.max(1, B.width); - const x = Math.min(1, Math.max(0, (e - 0.4) / 0.4)); - const y = Math.min(1, Math.max(0, (e - 0.1) / 0.4)); + // joinOpacities, inlined. + const x = g.same ? 1 : Math.min(1, Math.max(0, e / 0.3)); + const y = 1 - Math.min(1, Math.max(0, (e - 0.25) / 0.5)); const same = (a, b2) => !!a && !!b2 && ["x", "y", "width", "height"].every((k) => Math.abs(a[k] - b2[k]) < 1.5); const sameSlot = same(g.slotA, g.slotB); card.style.transformOrigin = "0 0"; @@ -180,7 +217,7 @@ export function applyJoinState(p, doc = document) { card.style.clipPath = `inset(0 0 ${Math.max(0, B.height - R.height / s)}px 0)`; card.style.background = "transparent"; card.style.borderColor = "transparent"; - card.style.opacity = String(g.same ? 1 : x); + card.style.opacity = String(x); if (bg) { bg.style.display = "block"; bg.style.left = `${R.x}px`; @@ -195,8 +232,8 @@ export function applyJoinState(p, doc = document) { from.style.width = `${A.width}px`; from.style.transform = `scale(${R.width / Math.max(1, A.width)})`; from.style.clipPath = `inset(0 0 ${Math.max(0, A.height - R.height / (R.width / Math.max(1, A.width)))}px 0)`; - // The same content drawn alike: the item before's card is the first frame only (never a double image). - from.style.opacity = String(g.same ? (v <= 0 ? 1 : 0) : 1 - y); + // Over this card, dissolving into it (the same content drawn alike: identical where they overlap). + from.style.opacity = String(y); } if (slotFrom) { slotFrom.style.display = g.slotA && !sameSlot ? "block" : "none"; diff --git a/umtool/report-to-video/post-media-enter.test.mjs b/umtool/report-to-video/post-media-enter.test.mjs @@ -0,0 +1,81 @@ +// ITS OWN ATTACHMENTS COME IN WITH ITS OWN POST (post-item.mjs ownMediaEnterAt; operator, 4 Nov, mid-11 at ~15:58: +// "the mr. obvious gif should come in when his post does rather than during the strawb megathread reading"). +import assert from "node:assert/strict"; +import { test } from "node:test"; + +import { ownMediaEnterAt, postItemPlan, stepAt, validatePostItem } from "./post-item.mjs"; +import { postSegmentArgs, postSegmentKey, postSegmentKeyOf } from "./post-render.mjs"; + +const at = (h) => `2026-11-04T${String(h).padStart(2, "0")}:00:00.000Z`; +/** A take of [text, role] pieces, each one part with its role set (as `umtool posts roles` sets them). */ +const narrate = (e, pieces) => { + let t = 0; + const parts = pieces.map(([text, role], n) => { + const seconds = Math.round((text.split(/\s+/).length / 3) * 100) / 100; + t += n ? 0.8 : 0; + const p = { n: n + 1, para: n * 100, text, start: Math.round(t * 100) / 100, seconds, ...(role ? { role } : {}) }; + t += seconds; + return p; + }); + return { ...e, narration: { script: e.text, takes: [{ file: `narration/posts/${e.id}/take-1.wav`, engine: "orpheus", voice: "leo+zac", seconds: Math.round(t * 100) / 100, script: pieces.map((p) => p[0]).join("\n\n"), parts }], pick: 0 } }; +}; +const gif = { src: "posts-media/ObviousRises-x/11/11_1.mp4", kind: "gif", width: 480, height: 270, seconds: 3 }; +const video = { src: "posts-media/ObviousRises-x/11/11_2.mp4", kind: "video", width: 1280, height: 720, seconds: 30, audio: true }; +const mega = "STRAWB MEGATHREAD: everything she said, in order, with the receipts for each part of it."; +const his = "this is what happens when you push people, they push back."; +const base = (extra = {}) => ({ type: "post", id: "p-11", post: "ObviousRises-x/11", platform: "x", author: "MR. OBVIOUS", handle: "ObviousRises", date: at(9), text: his, url: "https://x.com/ObviousRises/status/11", ...extra }); +const quoting = (media) => narrate(base({ media, quoted: { id: "5", author: "Strawb", handle: "strawb", date: at(7), text: mega } }), [[mega, "quoted"], [his, "post"]]); + +test("the item's own GIF comes in when his post's read begins -- the megathread read first shows none of it; crossfaded in from there", () => { + const e = quoting([gif]); + const plan = postItemPlan(e); + assert.ok(plan.follow?.thread, "a threaded read"); + const postStart = Math.min(...plan.follow.blocks.filter((b) => b.scope === "post" && b.start !== null).map((b) => b.start)); + const quoteStart = Math.min(...plan.follow.blocks.filter((b) => b.scope === "quoted" && b.start !== null).map((b) => b.start)); + assert.ok(quoteStart < postStart, "the quote is read first"); + assert.equal(plan.enter, postStart); + assert.equal(plan.steps[0].at, postStart, "its first step starts with his words"); + assert.equal(stepAt(plan, quoteStart + 0.5), null, "nothing of his while the megathread is read"); + assert.equal(stepAt(plan, postStart + 0.1)?.items[0].src, gif.src); + // The build: the GIF's layer is laid from that moment and faded in there, never from the first frame. + const args = postSegmentArgs({ entry: e, box: { width: 1574, height: 886 }, plan, layout: { mode: "side", slot: { x: 900, y: 0, width: 674, height: 886 }, card: { x: 0, y: 0, width: 880, height: 886 } }, cards: { read: "read.png" }, files: ["gif.mp4"], render: { fps: 30 }, outPath: "o.mp4" }); + const graph = args[args.indexOf("-filter_complex") + 1]; + assert.match(graph, new RegExp(`fade=t=in:st=${postStart}:d=0\\.3:alpha=1\\[m0_0\\]`)); + assert.match(graph, new RegExp(`\\[m0_0\\]overlay=x=900:y=\\d+:enable='between\\(t,${postStart},`)); +}); + +test("a video entering with his post starts there -- its offset counted from that moment, its sound too, its trim fitted to what is left", () => { + const e = quoting([video]); + const plan = postItemPlan(e); + const st = plan.steps[0]; + assert.equal(st.at, plan.enter); + assert.equal(st.srcFrom, 0, "from its own start at that moment"); + assert.ok(st.at + st.seconds <= plan.total + 1e-6); + const args = postSegmentArgs({ entry: e, box: { width: 1574, height: 886 }, plan, layout: { mode: "side", slot: { x: 900, y: 0, width: 674, height: 886 }, card: { x: 0, y: 0, width: 880, height: 886 } }, cards: { read: "read.png" }, files: ["v.mp4"], render: { fps: 30 }, outPath: "o.mp4" }); + const graph = args[args.indexOf("-filter_complex") + 1]; + const ms = Math.round(plan.enter * 1000); + assert.match(graph, new RegExp(`adelay=${ms}\\|${ms}`), "its sound delayed to his words"); +}); + +test("nothing changes for an item that reads only its post, one with enter: item, or one past the first of a media scene; the key changes only where it enters later", () => { + const only = narrate(base({ media: [gif] }), [[his, "post"]]); + const p0 = postItemPlan(only); + assert.equal(ownMediaEnterAt(only, p0.follow), 0); + assert.equal(p0.enter, undefined); + assert.equal(p0.steps[0].at, 0); + const item = quoting([{ ...gif, enter: "item" }]); + assert.equal(postItemPlan(item).enter, undefined); + assert.equal(postItemPlan(item).steps[0].at, 0); + const e = quoting([gif]); + const plan = postItemPlan(e); + assert.equal(ownMediaEnterAt(e, plan.follow, { mediaScene: { n: 1 } }), 0, "held through from the item before"); + assert.ok(ownMediaEnterAt(e, plan.follow, { mediaScene: { n: 0 } }) > 0, "the first of a media scene still waits"); + // The key: `enter` only on the item that enters later. + const box = { width: 1574, height: 886 }; + const render = { fps: 30, palette: {} }; + assert.equal(postSegmentKeyOf({ entry: only, box, render, plan: p0 }).enter, undefined); + assert.deepEqual(postSegmentKeyOf({ entry: e, box, render, plan }).enter, { at: plan.enter, fade: 0.3 }); + assert.notEqual(postSegmentKey(postSegmentKeyOf({ entry: e, box, render, plan })), postSegmentKey(postSegmentKeyOf({ entry: e, box, render, plan: { ...plan, enter: undefined } }))); + // The knob is checked. + assert.deepEqual(validatePostItem(quoting([{ ...gif, enter: "later" }])).filter((x) => x.includes("enter")).length, 1); +}); diff --git a/umtool/report-to-video/post-narration.mjs b/umtool/report-to-video/post-narration.mjs @@ -33,6 +33,7 @@ import { followKnobErrors } from "./read-follow.mjs"; import { threadKnobErrors } from "./post-thread.mjs"; +import { takeLexiconErrors } from "./post-say.mjs"; /** The engines a post's narration may name (the editor's tts op). */ export const POST_NARRATION_ENGINES = Object.freeze(["orpheus", "kokoro", "espeak-ng"]); @@ -186,7 +187,7 @@ const MIX_KEYS = ["lead", "tail", "ramp", "linger", "clip", "wet", "lowpassHz", // `thread`: the cut's thread reads (post-thread.mjs) -- what each context post is on screen, the shrink and dim. 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"]); +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"]); // `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). @@ -635,6 +636,9 @@ export function validatePostNarration(e) { } // What its audio does with the slurs its script holds (post-slurs.mjs): said (a beep or a mute covers them), left out, or a stand-in said. if (t.slurs !== undefined && !["said", "skip", "placeholder"].includes(t.slurs)) errors.push(`${tw}.slurs must be said, skip or placeholder`); + // The pronunciation entries its read applied (post-say.mjs), and how a thread read was asked for (postThreadRead.mjs). + errors.push(...takeLexiconErrors(t.lexicon, `${tw}.lexicon`)); + if (t.read !== undefined && !(isObj(t.read) && t.read.kind === "thread" && JSON.stringify(t.read).length <= 4000)) errors.push(`${tw}.read must be {kind: "thread", …} (how the thread read was asked for)`); if (t.words !== undefined) { // Its script's words, timed in take seconds (the editor's transcription, aligned: word-zoom.mjs scriptWordTimes). const ws = t.words; @@ -719,8 +723,8 @@ export function postNarrationDisclosure(entry) { /** 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 }); +/** The pause the parts are joined with: between paragraphs, inside one, and between the pieces of a thread read (lib/report/postThreadRead.mjs). */ +export const POST_PART_GAP = Object.freeze({ para: 0.6, inside: 0.25, piece: 0.8 }); const wordsOf = (t) => (String(t).trim() ? String(t).trim().split(/\s+/).length : 0); diff --git a/umtool/report-to-video/post-redact.mjs b/umtool/report-to-video/post-redact.mjs @@ -31,6 +31,7 @@ import { censorMarkupErrors } from "./post-censor.mjs"; import { BLACKOUT_MARK, SLUR_CSS, decodePlaceholder, hasSlurMarks, maskSlurs, placeholdersHtml, sayFor, slurMatches, slursOn, validateSlursRender } from "./post-slurs.mjs"; import { validateClockRender } from "./post-clock.mjs"; +import { applyLexicon } from "./post-say.mjs"; import { validateProgressRender } from "./post-progress.mjs"; /** The mark a redacted code unit becomes (a private-use character: never typed, never drawn as a letter). */ @@ -230,7 +231,10 @@ export function validatePostsMarkup(doc, where = "posts-markup.json") { * * and `slurs`, the cut's SLUR FILTER (post-slurs.mjs resolveSlurs: its list, on or off). * - * @typedef {{ terms: Array<{term: string, wholeWord?: boolean}>, markup?: Record<string, {redact: any[]}>, slurs?: ReturnType<typeof import("./post-slurs.mjs").resolveSlurs> | null }} Redaction + * and `say`, the project's PRONUNCIATION LEXICON (post-say.mjs: `narration/lexicon.json`, read by the umtool + * side's projectRedaction) -- applied by spokenRead only, never to anything drawn. + * + * @typedef {{ terms: Array<{term: string, wholeWord?: boolean}>, markup?: Record<string, {redact: any[]}>, slurs?: ReturnType<typeof import("./post-slurs.mjs").resolveSlurs> | null, say?: Array<Record<string, any>> | null }} Redaction */ /** Is there anything to blank? */ @@ -343,34 +347,45 @@ export function slurEntry(entry, slurs) { * redacted term left out, and each slur as the filter's voice has it -- skip, * left out as a redacted term is; placeholder, its stand-in said ("f-slur"); * beep, said (the render lays the beep over it by the take's word timings, - * post-render.mjs). Returns `{ text, slurs }`: `slurs` is what the take's + * post-render.mjs). Returns `{ text, slurs, lexicon? }`: `slurs` is what the take's * audio will do with them (take.slurs: "said" | "skip" | "placeholder"), null - * when the text holds none. + * when the text holds none; `lexicon` the pronunciation entries applied + * (post-say.mjs, `red.say`), present only when one was -- what the take records. + * + * The LEXICON is applied first, but never inside a slur (whatever the filter's + * voice) or a redacted term: those spans keep their words for the filter and + * the redaction, which then run over the result -- so a spoken form that says a + * slur or a blanked name is masked or dropped too. * * @param {string} text * @param {Record<string, any>} entry * @param {Redaction|null|undefined} red * @param {{ voice?: "skip"|"beep"|"placeholder" }} [o] the voice to use (default the filter's) + * @returns {{ text: string, slurs: "said" | "skip" | "placeholder" | null, lexicon?: Array<{ word: string, say: string, item?: string }> }} */ export function spokenRead(text, entry, red, { voice = undefined } = {}) { const s = red?.slurs; const terms = termsFor(entry, red); - const t = str(text); + const lex = Array.isArray(red?.say) && red.say.length && str(text) + ? applyLexicon(str(text), red.say, { item: str(entry?.id) || null, protect: [...(s ? slurMatches(str(text), s) : []), ...redactText(str(text), terms).spans] }) + : { text: str(text), applied: [] }; + const said = (r) => (lex.applied.length ? { ...r, lexicon: lex.applied } : r); + const t = lex.text; const hits = s ? slurMatches(t, s) : []; - if (!hits.length) return { text: spokenWithout(t, terms), slurs: null }; + if (!hits.length) return said({ text: spokenWithout(t, terms), slurs: null }); const v = voice ?? s.voice; - if (!slursOn(s) || v === "beep") return { text: spokenWithout(t, terms), slurs: "said" }; + if (!slursOn(s) || v === "beep") return said({ text: spokenWithout(t, terms), slurs: "said" }); if (v === "placeholder") { - let said = ""; + let out = ""; let at = 0; for (const h of hits) { - said += t.slice(at, h.start) + sayFor(s, h); + out += t.slice(at, h.start) + sayFor(s, h); at = h.end; } - return { text: spokenWithout(said + t.slice(at), terms), slurs: "placeholder" }; + return said({ text: spokenWithout(out + t.slice(at), terms), slurs: "placeholder" }); } const marked = redactText(t, terms, { spans: hits }); - return { text: marked.spans.length ? dropMarks(marked.text) : t, slurs: "skip" }; + return said({ text: marked.spans.length ? dropMarks(marked.text) : t, slurs: "skip" }); } /** diff --git a/umtool/report-to-video/post-render.mjs b/umtool/report-to-video/post-render.mjs @@ -18,7 +18,7 @@ import { createHash } from "node:crypto"; import { mkdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises"; import path from "node:path"; import { pathToFileURL } from "node:url"; -import { POST_PICTURE_XFADE, POST_PUSH, cardAuthors, fxRedactionErrors, mediaTimeAt, panelEntry, postCardHtml, postItemPlan, postLayout, stepAt, stepBoxes } from "./post-item.mjs"; +import { POST_ENTER_FADE, POST_PICTURE_XFADE, POST_PUSH, cardAuthors, fxRedactionErrors, joinCarryOf, mediaTimeAt, panelEntry, postCardHtml, postItemPlan, postLayout, stepAt, stepBoxes } from "./post-item.mjs"; import { isNarrated, narrationLevelDb, pickedTake, postNarrationFilters, postNarrationKnobs, rootTakeOf } from "./post-narration.mjs"; import { applyFollowState, followPath, followRuns, followStateAt, isDrawnState, measureFollow, readInViewErrors, shotStateAt } from "./read-follow.mjs"; import { redactEntry, redactionOn, shownLine, termsFor } from "./post-redact.mjs"; @@ -31,7 +31,7 @@ import { POST_PROGRESS_DRAW_V, measureProgressPlace, mountProgress, progressCss, import { SLAM_BAR, SLAM_DUST, SLAM_FACE_STACK, SLAM_MOTION, mountSlams, slamBarOf, setSlamState, slamCss, slamCoverErrors, slamHits, slamLayout, slamListAt, slamPlan, slamShakeExpr, slamSize, slamVars } from "./post-slam.mjs"; import { TRAILER_AUDIO, TRAILER_HIT_TIERS, trailerHitsGraph } from "./trailer-hits.mjs"; import { panelReadErrors } from "./post-thread.mjs"; -import { applyJoinState, endMediaOf } from "./post-join.mjs"; +import { applyJoinState, endMediaOf, joinClockOf } from "./post-join.mjs"; import { applyVisitState } from "./post-link-visit.mjs"; import { applyMapState, mapPageHtml, mapPlace, mapSize, mapStateAt } from "./post-branch-map.mjs"; import { WORD_ZOOM_DEFAULTS, findMatch, overlappingZooms, resolveWordZoom, targetScope, targetTextOf, wordZoomTimes, zoomSpan, zoomTarget, zoompanExprs } from "./word-zoom.mjs"; @@ -91,6 +91,16 @@ export function scrollExpr(keys) { * * @returns {string[]} */ +/** + * The clock's place over a join, an ffmpeg expression on `t`: `base + d` at the join's start, `base` from its end, + * eased between as the card is (post-join.mjs joinEase, in-out cubic). + */ +export function clockJoinExpr(base, d, seconds) { + const p = `min(1,t/${num(seconds)})`; + const e = `if(lt(${p},0.5),4*pow(${p},3),1-pow(2-2*${p},3)/2)`; + return `${num(base)}+${num(d)}*(1-${e})`; +} + export function postSegmentArgs({ entry, box, plan, layout, cards, files, render, place = [], encode = [], captions = [], fontfile = null, outPath, narration = null, zooms = [], follow = null, panelFiles = [], join = null, map = null, captionFx = [], clock = null, slams = [], slamHitList = [], progress = null }) { const fps = render.fps ?? 30; const T = plan.total; @@ -184,9 +194,14 @@ export function postSegmentArgs({ entry, box, plan, layout, cards, files, render // over the card's corner from the first frame (a stack card's: until its media phase). if (clock) { const ci = add(["-f", "concat", "-safe", "0", "-i", clock.list]); - parts.push(`[${ci}:v]fps=${fps},format=rgba,setsar=1,setpts=PTS-STARTPTS[clk]`); + // THE JOIN (post-join.mjs): it opens where the item before's clock sat and moves with the card (its ease), or, + // the item before showing none, comes in over the join. + const cj = clock.join && clock.join.seconds > 0 ? clock.join : null; + const fadeIn = cj?.fadeIn ? `,fade=t=in:st=0:d=${num(cj.seconds)}:alpha=1` : ""; + parts.push(`[${ci}:v]fps=${fps},format=rgba,setsar=1,setpts=PTS-STARTPTS${fadeIn}[clk]`); + const pos = (base, d) => (cj?.from && Math.abs(d) >= 0.5 ? `'${clockJoinExpr(base, d, cj.seconds)}'` : String(base)); const next = `b${++n}`; - parts.push(`[${cur}][clk]overlay=x=${clock.x}:y=${clock.y}:eof_action=repeat${clock.until < T ? `:enable='lt(t,${num(clock.until)})'` : ""}[${next}]`); + parts.push(`[${cur}][clk]overlay=x=${pos(clock.x, cj?.from?.dx ?? 0)}:y=${pos(clock.y, cj?.from?.dy ?? 0)}:eof_action=repeat${clock.until < T ? `:enable='lt(t,${num(clock.until)})'` : ""}[${next}]`); cur = next; } const audio = []; @@ -197,9 +212,12 @@ export function postSegmentArgs({ entry, box, plan, layout, cards, files, render const xfIn = si > 0 && picture(step) && picture(plan.steps[si - 1]) ? POST_PICTURE_XFADE : 0; const xfOut = !last && picture(step) && picture(plan.steps[si + 1]) ? POST_PICTURE_XFADE : 0; const until = last ? T : Math.min(T, step.at + step.seconds + xfOut); - const fadeIn = (from) => (xfIn ? `,format=rgba,fade=t=in:st=${num(from)}:d=${num(xfIn)}:alpha=1` : ""); - // Beside the card, the first attachment is up from the first frame (its first frame while the words are read). - const shownFrom = si === 0 && layout.mode === "side" ? 0 : step.at; + // ITS OWN ATTACHMENT entering with his own post (post-item.mjs ownMediaEnterAt): crossfaded in from that moment. + const enterIn = si === 0 && plan.enter > 0 ? POST_ENTER_FADE : 0; + const fadeIn = (from) => (xfIn ? `,format=rgba,fade=t=in:st=${num(from)}:d=${num(xfIn)}:alpha=1` : enterIn ? `,format=rgba,fade=t=in:st=${num(from)}:d=${num(enterIn)}:alpha=1` : ""); + // Beside the card, the first attachment is up from the first frame (its first frame while the words are read) -- + // unless it enters with his own post. + const shownFrom = si === 0 && layout.mode === "side" && !(plan.enter > 0) ? 0 : step.at; const boxes = stepBoxes(step, layout.slot); step.items.forEach((m, j) => { const b = boxes[j]; @@ -227,7 +245,7 @@ export function postSegmentArgs({ entry, box, plan, layout, cards, files, render const k = add([...(step.loop ? ["-stream_loop", "-1"] : []), "-ss", num(step.srcFrom), "-t", num(len), "-i", file]); parts.push( `[${k}:v]${crop}scale=${b.width}:${b.height},setsar=1,fps=${fps},setpts=PTS-STARTPTS,` + - `tpad=start_duration=${num(step.at)}:start_mode=clone:stop_mode=clone:stop_duration=${num(T)}[${raw}]`, + `tpad=start_duration=${num(step.at)}:start_mode=clone:stop_mode=clone:stop_duration=${num(T)}${fadeIn(shownFrom)}[${raw}]`, ); if (step.sound) { const ms = Math.round(step.at * 1000); @@ -422,19 +440,41 @@ export async function renderPostCards(entry, { box, render, dir, manifestDir, la const av = Object.fromEntries(Object.entries(avatars).map(([h, f]) => [h, pathToFileURL(f).href])); // THE JOIN (post-join.mjs): the item before's card as it ENDED -- its page drawn, its last frame's state set, its // card shot -- and where its post's words sat; this card opens on it and morphs into its own. + // The shot is the item before's LAST FRAME as its segment draws it (check-joins.mjs measures it): its page (its + // parent's shot too), its read-follow's last state, a link visit's pointer, and its clock -- in the shot when + // this item has none (it fades with the card), else this item's clock starts where that one sat and moves. let join = null; if (follow?.join && joinFrom?.entry) { const fps = render.fps ?? 30; const pe = joinFrom.entry; const pf = joinFrom.plan?.follow ?? null; - const ph = postCardHtml(pe, { width: box.width, height: box.height, palette: render.palette, fonts, phase: "read", avatars: av, follow: !!pf, thread: pf?.thread ?? null, redaction }); + const pShot = typeof pe.parentShot === "string" ? pathToFileURL(path.resolve(manifestDir, pe.parentShot)).href : null; + const ph = postCardHtml(pe, { width: box.width, height: box.height, palette: render.palette, fonts, phase: "read", parentShotUrl: pShot, avatars: av, follow: !!pf, thread: pf?.thread ?? null, redaction, join: joinFrom.carry ?? null }); const pfile = path.join(dir, "join-from.html"); await writeFile(pfile, ph, "utf8"); await page.goto(pathToFileURL(pfile).href, { waitUntil: "load" }); await page.waitForSelector("body[data-post-ready='1']", { timeout: 15000 }); + const endS = Math.max(0, joinFrom.plan.total - 1 / fps); + const pl0 = postLayout(pe, box); + // Its clock, placed as its own segment placed it (clockPlaceOn), shown at its end unless a stack card's media + // phase hid it. + const pClock = joinFrom.clock && !(pl0.mode === "stack" && joinFrom.plan.steps?.length) ? joinFrom.clock : null; + let clockFrom = null; + if (pClock) { + const k = box.height / 1080; + const face = clockFace(pClock.to, pClock.zone); + const size = await page.evaluate(mountClock, { css: clockCss({ height: box.height, palette: render.palette }), html: clockHtml(), widest: { time: "12:58 PM", zone: face.zone, date: "Wed 30 Sep" } }); + await page.evaluate(() => document.fonts.ready.then(() => true)); + const at = size ? await clockPlaceOn(page, { follow: pf, total: joinFrom.plan.total, size, k }) : null; + if (at) clockFrom = { x: at.x, y: at.y, st: clockStateAt(pClock, endS) }; + } if (pf) { const pgeo = await page.evaluate(measureFollow); - await page.evaluate(applyFollowState, followStateAt(pf, followPath(pf, pgeo), Math.max(0, joinFrom.plan.total - 1 / fps))); + // Its own join's opening frame (its record's `joinAnchor`): a read that never pans again ends where it opened. + if (pgeo && Number.isFinite(joinFrom.anchorY)) pgeo.joinAnchor = { y: joinFrom.anchorY }; + const st = followStateAt(pf, followPath(pf, pgeo), endS); + await page.evaluate(applyFollowState, st); + if (pf.visits?.length) await page.evaluate(applyVisitState, { visits: pf.visits, st: st.visit ?? null }); } const m = await page.evaluate(() => { const card = document.querySelector("[data-post-card]"); @@ -445,19 +485,36 @@ export async function renderPostCards(entry, { box, render, dir, manifestDir, la const post = document.querySelector('[data-thread-slot="post"] .head') ?? card.querySelector(".head"); const words = document.querySelector('[data-thread-slot="post"] .twords') ?? document.querySelector("[data-post-words]"); const pr = post ? post.getBoundingClientRect() : null; - return { A: { x: c.left, y: c.top, width: c.width, height: c.height }, anchor: pr ? pr.top - c.top : null, size: words ? parseFloat(getComputedStyle(words).fontSize) : null }; + return { A: { x: c.left, y: c.top, width: c.width, height: c.height }, anchor: pr ? pr.top - c.top : null, size: words ? parseFloat(getComputedStyle(words).fontSize) : null, plain: !document.querySelector('[data-thread-slot="post"]'), headSize: post ? parseFloat(getComputedStyle(post).fontSize) : null }; }); if (m) { const png = path.join(dir, "join-from.png"); const x = Math.max(0, Math.floor(m.A.x)); const y = Math.max(0, Math.floor(m.A.y)); - await page.screenshot({ path: png, clip: { x, y, width: Math.min(box.width - x, Math.ceil(m.A.width)), height: Math.min(box.height - y, Math.ceil(m.A.height)) } }); + const clip = { x, y, width: Math.min(box.width - x, Math.ceil(m.A.width)), height: Math.min(box.height - y, Math.ceil(m.A.height)) }; + await page.screenshot({ path: png, clip }); + // And with its clock on it, as it ended (laid in the shot when this item's clock does not carry on from it). + let pngClock = null; + if (clockFrom) { + pngClock = path.join(dir, "join-from-clock.png"); + await page.evaluate(setClockState, clockFrom); + await page.screenshot({ path: pngClock, clip }); + await page.evaluate(setClockState, null); + } const pl = postLayout(pe, box); const same = Math.abs(m.A.width - layout.card.width) < 2 && !!(follow.thread?.tiles ?? []).some((t) => t.mode === "carry" || (t.mode === "scene" && t.wasPost)); - join = { A: { x, y, width: Math.ceil(m.A.width), height: Math.ceil(m.A.height) }, slotA: pl.slot && pl.mode === "side" ? pl.slot : null, fromUrl: pathToFileURL(png).href, size: m.size, same, anchor: m.anchor }; - out.joinFrom = { A: join.A, layout: pl }; + join = { A: { x, y, width: Math.ceil(m.A.width), height: Math.ceil(m.A.height) }, slotA: pl.slot && pl.mode === "side" ? pl.slot : null, fromUrl: pathToFileURL(png).href, size: m.size, same, anchor: m.anchor, plain: m.plain, headSize: m.headSize }; + out.joinFrom = { A: join.A, layout: pl, clock: clockFrom ? { x: clockFrom.x, y: clockFrom.y } : null, pngClock }; } } + // THE CLOCK (post-clock.mjs), shot before the read's frames: over a join, where it opens decides the shot the + // card opens on (joinClockOf: carried on from the item before's clock, or that one laid in the shot, fading). + if (clock) out.clock = await shootClock(browser, entry, { box, render, dir, fonts, parentShotUrl, avatars, clock, redaction, follow, total }); + if (join) { + const jc = joinClockOf({ from: out.joinFrom?.clock ?? null, own: out.clock?.at ?? null, k: box.height / 1080 }); + if (jc.bake && out.joinFrom?.pngClock) join.fromUrl = pathToFileURL(out.joinFrom.pngClock).href; + if (out.clock) out.clock.join = { seconds: follow.join.seconds, from: jc.move, fadeIn: jc.fadeIn }; + } for (const phase of phases) { const html = postCardHtml(entry, { width: box.width, height: box.height, palette: render.palette, fonts, phase, parentShotUrl, @@ -489,6 +546,7 @@ export async function renderPostCards(entry, { box, render, dir, manifestDir, la return c && w ? { win: w.top - c.top, width: c.width, head: head && slot ? head.top - slot.top : 0 } : null; }); if (own) geo.joinAnchor = { y: Math.round((join.anchor / (join.A.width / own.width) - own.win - own.head) * 100) / 100 }; + if (geo.joinAnchor) out.joinAnchor = geo.joinAnchor.y; } out.follow = await shootFollow(page, { follow, total, fps, box, dir, geo }); // THE BRANCH MAP (post-branch-map.mjs): its own layer, shot on a transparent page, laid over the attachments. @@ -501,7 +559,6 @@ export async function renderPostCards(entry, { box, render, dir, manifestDir, la } await ctx.close(); if (zooms.length) out.zooms = await shootZooms(browser, entry, { box, render, dir, fonts, parentShotUrl, avatars, zooms, redaction, follow }); - if (clock) out.clock = await shootClock(browser, entry, { box, render, dir, fonts, parentShotUrl, avatars, clock, redaction, follow, total }); // The progress bar (post-progress.mjs): along the card's foot, short of the clock on its line. if (progress) { const k = box.height / 1080; @@ -518,6 +575,13 @@ export async function renderPostCards(entry, { box, render, dir, manifestDir, la } /** + * A shot's line in a frames list (ffconcat): its image read at the item's rate. Without it each PNG is read on the + * image demuxer's 1/25 s clock, its start rounded to a 40 ms step, and the 30 fps output drops one shot in six and + * holds its neighbour -- every pan, join and clock run juddered (measured: a held frame every 0.2 s in mid-7's joins). + */ +export const concatRate = (fps) => [`option framerate ${fps}`]; + +/** * READ-FOLLOW's FRAMES (read-follow.mjs): on the drawn card page, the pan's * path from its geometry (`geo`, measureFollow's: measured here when not * given), then every frame's state (followStateAt at frame i / fps); each @@ -563,8 +627,8 @@ export async function shootFollow(page, { follow, total, fps, box, dir, geo = nu if (follow.visits?.length) await page.evaluate(applyVisitState, { visits: follow.visits, st: null }); const q = (f) => `'${f.replace(/'/g, "'\\''")}'`; const lines = ["ffconcat version 1.0"]; - for (const run of runs) lines.push(`file ${q(shots.get(run.key))}`, `duration ${(run.n / fps).toFixed(6)}`); - lines.push(`file ${q(shots.get(runs[runs.length - 1].key))}`); + for (const run of runs) lines.push(`file ${q(shots.get(run.key))}`, ...concatRate(fps), `duration ${(run.n / fps).toFixed(6)}`); + lines.push(`file ${q(shots.get(runs[runs.length - 1].key))}`, ...concatRate(fps)); const list = path.join(fdir, "frames.ffconcat"); await writeFile(list, lines.join("\n") + "\n", "utf8"); return { list, clip, shots: shots.size, frames, geo, path: path0 }; @@ -618,8 +682,8 @@ async function shootMap(ctx, { map, layout, box, fps, dir, render, fonts, entry } const q = (f) => `'${f.replace(/'/g, "'\\''")}'`; const lines = ["ffconcat version 1.0"]; - for (const run of runs) lines.push(`file ${q(shots.get(run.key))}`, `duration ${(run.n / fps).toFixed(6)}`); - lines.push(`file ${q(shots.get(runs[runs.length - 1].key))}`); + for (const run of runs) lines.push(`file ${q(shots.get(run.key))}`, ...concatRate(fps), `duration ${(run.n / fps).toFixed(6)}`); + lines.push(`file ${q(shots.get(runs[runs.length - 1].key))}`, ...concatRate(fps)); const list = path.join(mdir, "frames.ffconcat"); await writeFile(list, lines.join("\n") + "\n", "utf8"); return { list, x: Math.round(at.x), y: Math.round(at.y), t0, t3 }; @@ -813,6 +877,26 @@ export async function shootCaptions(browser, entry, { box, render, dir, fonts, p } /** + * WHERE THE CLOCK SITS on a card page with the clock mounted (`size` its box): placed as the card is when its own + * post is in (the read's end: a threaded card's counts row is there), and judged over the read (its start, middle + * and end) -- the place covering fewest words over all three wins; the follow put back at its start. Null: no card. + * The item's own shot (shootClock) and the join's (the item before's clock, where it sat) place it alike. + */ +async function clockPlaceOn(page, { follow, total, size, k }) { + const fpath = follow ? followPath(follow, await page.evaluate(measureFollow)) : null; + const states = follow ? [total, 0, total / 2] : [0]; + const looks = []; + for (const s of states) { + if (follow) await page.evaluate(applyFollowState, followStateAt(follow, fpath, s)); + looks.push(await page.evaluate(measureClockPlace, { size, inset: Math.round(22 * k), fixed: looks[0]?.tries ?? null })); + } + const at0 = looks[0]; + const at = at0 ? at0.tries.map((t, i) => ({ ...t, covers: looks.reduce((a, l) => a + (l?.tries?.[i]?.covers ?? 0), 0) })).sort((a, b) => a.covers - b.covers)[0] : null; + if (follow) await page.evaluate(applyFollowState, followStateAt(follow, fpath, 0)); + return at; +} + +/** * Each SLAM's FRAMES (post-slam.mjs): on the card page as it is drawn at its * first hit (read-follow's state then), its words measured -- the matched * words' lines and the words read at a hit, which it may not cover, and the @@ -924,8 +1008,8 @@ export async function shootSlams(browser, entry, { box, render, dir, fonts, pare await stateAt(0); const qq = (f) => `'${f.replace(/'/g, "'\\''")}'`; const lines = ["ffconcat version 1.0"]; - for (const r of runs) lines.push(`file ${qq(shots.get(r.key))}`, `duration ${(r.n / fps).toFixed(6)}`); - lines.push(`file ${qq(shots.get(runs[runs.length - 1].key))}`); + for (const r of runs) lines.push(`file ${qq(shots.get(r.key))}`, ...concatRate(fps), `duration ${(r.n / fps).toFixed(6)}`); + lines.push(`file ${qq(shots.get(runs[runs.length - 1].key))}`, ...concatRate(fps)); const list = path.join(sdir, "frames.ffconcat"); await writeFile(list, lines.join("\n") + "\n", "utf8"); out.push({ ...q, list, t0: f0 / fps, t3: f1 / fps, landings: p.span.landings, layout, size, shots: shots.size }); @@ -1007,18 +1091,7 @@ export async function shootClock(browser, entry, { box, render, dir, fonts, pare const face = clockFace(clock.to, clock.zone); const size = await page.evaluate(mountClock, { css: clockCss({ height: box.height, palette: render.palette }), html: clockHtml(), widest: { time: "12:58 PM", zone: face.zone, date: "Wed 30 Sep" } }); await page.evaluate(() => document.fonts.ready.then(() => true)); - // Placed as the card is when its own post is in (the read's end: a threaded card's counts row is there), and - // judged over the read (its start, middle and end): the place covering fewest words over all three wins. - const fpath = follow ? followPath(follow, await page.evaluate(measureFollow)) : null; - const states = follow ? [total, 0, total / 2] : [0]; - const looks = []; - for (const s of states) { - if (follow) await page.evaluate(applyFollowState, followStateAt(follow, fpath, s)); - looks.push(await page.evaluate(measureClockPlace, { size, inset: Math.round(22 * k), fixed: looks[0]?.tries ?? null })); - } - const at0 = looks[0]; - const at = at0 ? at0.tries.map((t, i) => ({ ...t, covers: looks.reduce((a, l) => a + (l?.tries?.[i]?.covers ?? 0), 0) })).sort((a, b) => a.covers - b.covers)[0] : null; - if (follow) await page.evaluate(applyFollowState, followStateAt(follow, fpath, 0)); + const at = await clockPlaceOn(page, { follow, total, size, k }); if (!at) throw new Error(`${entry.id}: the clock has no card to sit on`); await page.evaluate(() => { const st = document.createElement("style"); @@ -1049,11 +1122,11 @@ export async function shootClock(browser, entry, { box, render, dir, fonts, pare } const q = (f) => `'${f.replace(/'/g, "'\\''")}'`; const lines = ["ffconcat version 1.0"]; - runs.forEach((r, i) => lines.push(`file ${q(shots.get(r.key))}`, `duration ${(r.n / fps).toFixed(6)}`)); - lines.push(`file ${q(shots.get(runs[runs.length - 1].key))}`); + runs.forEach((r, i) => lines.push(`file ${q(shots.get(r.key))}`, ...concatRate(fps), `duration ${(r.n / fps).toFixed(6)}`)); + lines.push(`file ${q(shots.get(runs[runs.length - 1].key))}`, ...concatRate(fps)); const list = path.join(fdir, "frames.ffconcat"); await writeFile(list, lines.join("\n") + "\n", "utf8"); - return { list, x: clip.x, y: clip.y, place: at.place, covers: at.covers, shots: shots.size, box: { x: at.x - Math.round(240 * k), y: at.y, width: size.width + Math.round(240 * k), height: size.height } }; + return { list, x: clip.x, y: clip.y, at: { x: at.x, y: at.y }, place: at.place, covers: at.covers, shots: shots.size, box: { x: at.x - Math.round(240 * k), y: at.y, width: size.width + Math.round(240 * k), height: size.height } }; } finally { await ctx.close(); } @@ -1099,6 +1172,12 @@ export function postZoomPlan(entry, render, total = Infinity, schedule = undefin * a cut-level pace changes them without touching the entry) */ export const POST_CAPTION_DRAW_V = 2; +/** + * The join's drawing (in a joined item's key only: an item with no join keeps its key). 2: the item before's card + * dissolves into this one's (never gone at the first frame), its last frame shot whole (its clock, its parent's shot, + * a visit's pointer), the carried post's head drawn as a plain card drew it, this item's clock moving from that one's. + */ +export const POST_JOIN_DRAW_V = 2; export const POST_CLOCK_DRAW_V = 1; /** * A SLAM's drawing and sound (post-slam.mjs): bumped when its look changes. Its @@ -1155,8 +1234,13 @@ export function postSegmentKeyOf({ entry, redaction = null, box, place = [], ren ...(plan.follow ? { follow: plan.follow } : {}), ...(bleeps ? { bleeps } : {}), ...(slursOn(redaction?.slurs) ? { slurs: redaction.slurs } : {}), - ...(from ? { joinFrom: { entry: from.entry, follow: from.plan.follow ?? null, total: from.plan.total, media: from.media.map((x) => [x.m.src, x.t, x.box]), fadeIn: from.fadeIn } } : {}), + // `jv`: the join's drawing (POST_JOIN_DRAW_V) and what the item before showed as it ended beyond its card -- its + // clock (where this one's starts) and its parent's shot. + ...(from ? { joinFrom: { entry: from.entry, follow: from.plan.follow ?? null, total: from.plan.total, media: from.media.map((x) => [x.m.src, x.t, x.box]), fadeIn: from.fadeIn, jv: POST_JOIN_DRAW_V, clock: from.clock ?? null, ...(from.carry ? { carry: from.carry } : {}), ...(Number.isFinite(from.anchorY) ? { anchorY: from.anchorY } : {}) } } : {}), ...(plan.panel ? { panel: plan.panel } : {}), + // Its own attachment entering with his own post (post-item.mjs ownMediaEnterAt): only an item that reads + // something before its post carries it -- every other keeps its key. + ...(plan.enter > 0 ? { enter: { at: plan.enter, fade: POST_ENTER_FADE } } : {}), ...(layout?.panel === "top" || layout?.panel === "bottom" ? { layout: { panel: layout.panel, card: layout.card, slot: layout.slot } } : {}), // A caption, the clock, the pace (post-caption.mjs, post-clock.mjs): nothing for an item with none of them. ...postFxKeyFields(entry, render, prev, { plan, layout }), @@ -1214,10 +1298,24 @@ export async function buildPostSegment(entry, { render, outDir, manifestDir, box const ownBox = firstOwn && layout.slot && layout.mode === "side" ? stepBoxes(plan.steps[0], layout.slot)[0] : null; // The same attachment in the same box (a media scene): held, neither faded. const held = !!firstOwn && ends.length === 1 && ends[0].m.src === firstOwn.src && !!ownBox && Math.abs(ownBox.x - eb[0].x) < 2 && Math.abs(ownBox.y - eb[0].y) < 2 && Math.abs(ownBox.width - eb[0].width) < 2; + // How ITS segment drew the post it carried in (its own join: post-item.mjs joinCarryOf of the item before it) -- + // its page here drawn as it was, never with a carried post of another size (a re-wrapped tile at the first frame). + let carry = null; + const bf = joinFrom.join ? joinFrom.before : null; + if (bf?.entry?.type === "post") { + const be = panelEntry(sceneEntry(censorEntry(bf.entry, redaction), bf.mediaScene ?? null, { censor: (e) => censorEntry(e, redaction) }), render); + carry = joinCarryOf(be, postItemPlan(be, render, { prev: bf.prev ?? null, scene: bf.scene ?? null, mediaScene: bf.scene ? null : bf.mediaScene ?? null, join: bf.join ?? null }), box, render); + } + // Where ITS read opened (its own join's anchor, in its record): its last frame is drawn from the same path. + const prevRec = joinFrom.join ? await readFile(postRecordPath(path.join(outDir, "segments", `${joinFrom.entry.id}.mp4`)), "utf8").then((t) => JSON.parse(t), () => null) : null; from = { - entry: pe, plan: pp, + entry: pe, plan: pp, carry, + anchorY: Number.isFinite(prevRec?.joinAnchor) ? prevRec.joinAnchor : null, + // Its clock (post-clock.mjs) as its own segment runs it: from the clock item before IT. + clock: clockPlan(pe, render, joinFrom.prev ?? null), media: held ? [] : ends.map((x, j) => ({ file: path.resolve(manifestDir, x.m.src), m: x.m, t: x.t, box: eb[j] })), - fadeIn: !held && !!firstOwn, + // Entering with his own post (plan.enter): not faded in over the join -- the item before's goes, the slot waits. + fadeIn: !held && !!firstOwn && !(plan.enter > 0), }; } const files = (entry.media ?? []).map((m) => path.resolve(manifestDir, m.src)); @@ -1236,7 +1334,7 @@ export async function buildPostSegment(entry, { render, outDir, manifestDir, box if (takeFile && !(await stat(takeFile).catch(() => null))) throw new Error(`${entry.id}: its narration take is not on disk: ${takeFile} (${take.file})`); // The slurs its take SAYS, covered (post-slurs.mjs): a public render never plays one -- without word timings it is refused. const bleeps = take ? takeSlurBleeps(entry, take, redaction) : null; - const stamps = await Promise.all([...files, ...panelFiles.flat(), ...(from?.media ?? []).map((x) => x.file), ...wordFiles.filter(Boolean), ...Object.values(avatars), ...(takeFile ? [takeFile] : []), ...(entry.parentShot ? [path.resolve(manifestDir, entry.parentShot)] : [])].map(async (f) => { + const stamps = await Promise.all([...files, ...panelFiles.flat(), ...(from?.media ?? []).map((x) => x.file), ...wordFiles.filter(Boolean), ...Object.values(avatars), ...(takeFile ? [takeFile] : []), ...(entry.parentShot ? [path.resolve(manifestDir, entry.parentShot)] : []), ...(typeof from?.entry?.parentShot === "string" ? [path.resolve(manifestDir, from.entry.parentShot)] : [])].map(async (f) => { const st = await stat(f).catch(() => null); return st ? `${f}:${st.size}:${Math.round(st.mtimeMs)}` : `${f}:-`; })); @@ -1318,7 +1416,7 @@ export async function buildPostSegment(entry, { render, outDir, manifestDir, box // The follow frames are in the segment now: a rebuild shoots them again (they are many, and the key decides). if (cards.follow) await rm(path.dirname(cards.follow.list), { recursive: true, force: true }); // Through a rename: a record `--from` linked in (another take's) is replaced, never written through. - await writeFile(`${record}.tmp`, JSON.stringify({ version: 1, id: entry.id, key, layout: layout.mode, total: plan.total, steps: plan.steps.length, ...(zooms.length ? { zooms: zooms.map((z) => ({ i: z.i, at: z.t, source: z.source, span: z.span, region: z.region, word: z.word })) } : {}), ...(cards.captions?.length ? { captions: cards.captions.map((c) => ({ i: c.i, at: c.t, source: c.source, span: c.span, place: c.placed.place, rel: c.placed.rel, box: { x: c.placed.x, y: c.placed.y, width: c.placed.width, height: c.placed.height }, word: c.placed.word, covers: c.placed.covers, leader: c.placed.leader, ...(c.cutByPan ? { cutByPan: c.cutByPan } : {}) })) } : {}), ...(cards.slams?.length ? { slams: cards.slams.map((sl) => ({ i: sl.i, text: sl.fx.text, at: sl.t, end: sl.end, source: sl.source, landings: sl.landings, span: { t0: sl.span.t0, t2: sl.span.t2, t3: sl.span.t3 }, where: sl.layout.where, box: { x: sl.layout.x, y: sl.layout.y, width: sl.layout.width, height: sl.layout.height }, ...(sl.layout.bar ? { bar: { text: sl.fx.bar, style: sl.fx.barStyle, x: sl.layout.bar.x, y: sl.layout.bar.y, width: sl.layout.bar.width, height: sl.layout.bar.height } } : {}), size: sl.size, covers: sl.layout.covers, sfx: sl.fx.sfx, shots: sl.shots })) } : {}), ...(narration ? { narration: { take: take.file, ...plan.narration, gainDb: narration.gainDb, measured: narration.lufs, ...(bleeps ? { slurs: { mode: bleeps.mode, spans: bleeps.spans } } : {}) } } : {}), ...(cards.follow ? { follow: { blocks: plan.follow.blocks.length, shots: cards.follow.shots, frames: cards.follow.frames, pan: cards.follow.path.segments.length, max: cards.follow.path.max } } : {}) }, null, 2) + "\n", "utf8"); + await writeFile(`${record}.tmp`, JSON.stringify({ version: 1, id: entry.id, key, layout: layout.mode, total: plan.total, steps: plan.steps.length, ...(zooms.length ? { zooms: zooms.map((z) => ({ i: z.i, at: z.t, source: z.source, span: z.span, region: z.region, word: z.word })) } : {}), ...(cards.captions?.length ? { captions: cards.captions.map((c) => ({ i: c.i, at: c.t, source: c.source, span: c.span, place: c.placed.place, rel: c.placed.rel, box: { x: c.placed.x, y: c.placed.y, width: c.placed.width, height: c.placed.height }, word: c.placed.word, covers: c.placed.covers, leader: c.placed.leader, ...(c.cutByPan ? { cutByPan: c.cutByPan } : {}) })) } : {}), ...(cards.slams?.length ? { slams: cards.slams.map((sl) => ({ i: sl.i, text: sl.fx.text, at: sl.t, end: sl.end, source: sl.source, landings: sl.landings, span: { t0: sl.span.t0, t2: sl.span.t2, t3: sl.span.t3 }, where: sl.layout.where, box: { x: sl.layout.x, y: sl.layout.y, width: sl.layout.width, height: sl.layout.height }, ...(sl.layout.bar ? { bar: { text: sl.fx.bar, style: sl.fx.barStyle, x: sl.layout.bar.x, y: sl.layout.bar.y, width: sl.layout.bar.width, height: sl.layout.bar.height } } : {}), size: sl.size, covers: sl.layout.covers, sfx: sl.fx.sfx, shots: sl.shots })) } : {}), ...(narration ? { narration: { take: take.file, ...plan.narration, gainDb: narration.gainDb, measured: narration.lufs, ...(bleeps ? { slurs: { mode: bleeps.mode, spans: bleeps.spans } } : {}) } } : {}), ...(cards.follow ? { follow: { blocks: plan.follow.blocks.length, shots: cards.follow.shots, frames: cards.follow.frames, pan: cards.follow.path.segments.length, max: cards.follow.path.max } } : {}), ...(Number.isFinite(cards.joinAnchor) ? { joinAnchor: cards.joinAnchor } : {}) }, null, 2) + "\n", "utf8"); await rename(`${record}.tmp`, record); if (pool) await poolPut(pool, "post", key, { "seg.mp4": seg, "post.json": record }); emit("note", { diff --git a/umtool/report-to-video/post-say.mjs b/umtool/report-to-video/post-say.mjs @@ -0,0 +1,266 @@ +// WHAT A SYNTHESIZED READ SAYS, AND IN WHOSE VOICE (operator, 4 Nov 2026: "we +// want the plain apps to do as much heavy lifting as possible so cheaper +// models can more easily do these tasks without having to improvise shell +// scripts"). umtool/docs/knobs.md, "Pronunciation and voices". +// +// THE LEXICON -- a project's pronunciation list, `narration/lexicon.json` in +// the project (never the manifest: the narrated segments' cache keys carry +// render.postNarration, and a word said differently is a new TAKE, not a new +// card) -- `[{ word, say, case?, item?, note? }]`: +// +// word a word or a phrase as the posts write it ("tbh", "@grok", "at the moment") +// say what the voice is asked to say for it ("T-B-H", "At grok") +// case true: matched with its case (default: without) +// item a post item's id: only that item's read (default: every read) +// +// A match is a WHOLE word: no letter, digit or underscore either side, and no +// apostrophe-and-letter after it ("can" is not the "can" of "can't"); the +// words of a phrase across any run of spaces. Regex characters in a word are +// literal ("C++", "(sic)"). An item's own entry wins over the project's for +// the same text; a longer match wins over a shorter one inside it; a +// replacement is never matched again. +// +// It is applied where the words are turned into the text a voice SAYS +// (post-redact.mjs spokenRead): every synthesized read -- a script's take, +// each piece of a thread read, the bench's re-take. The slur filter and the +// redaction WIN: a span the filter masks or the redaction blanks is never +// replaced (the slur is left out, beeped or its stand-in said; a blanked name +// is dropped, even when an entry's spoken form would say it). +// +// A take records what it applied (`takes[i].lexicon`: `[{ word, say, item? }]`), +// so a read SAID THE OLD WAY is known (staleLexicon): an entry that matches +// the words the take read and that the take did not apply with the same +// spoken form. +// +// THE VOICE MAP -- `narration/voices.json` in the project, `{ "<handle>": +// "<voice>", "*": "<voice>" }`: the stock voice each author's words are read +// in by a thread read (lib/report/postThreadRead.mjs). Handles without "@", +// any case. "*" is everyone the map does not name (default: CONTEXT_VOICE_DEFAULTS +// for the engine). The item's own author reads in the item's narrator voice +// unless the map names them. +// +// PURE and dependency-free. + +/** At most this many entries; a word, a spoken form at most this long. */ +export const LEXICON_MAX = 500; +export const LEXICON_WORD_MAX = 120; +export const LEXICON_SAY_MAX = 300; +export const LEXICON_KEYS = Object.freeze(["word", "say", "case", "item", "note"]); +/** The project files (relative to the project's folder). */ +export const LEXICON_FILE = "narration/lexicon.json"; +export const VOICES_FILE = "narration/voices.json"; +/** The voice map's key for everyone it does not name. */ +export const VOICE_MAP_OTHER = "*"; +export const VOICE_MAP_MAX = 200; +/** The voice a context post's author reads in when the map names neither them nor "*", by engine. */ +export const CONTEXT_VOICE_DEFAULTS = Object.freeze({ orpheus: "leo" }); + +const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); +const str = (v) => (typeof v === "string" ? v : ""); +const VOICE_RE = /^[A-Za-z0-9][A-Za-z0-9_.+-]{0,63}$/; +const ITEM_RE = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/; +const HANDLE_RE = /^[A-Za-z0-9_.-]{1,64}$/; +// (No `-` or `/` escaped: under the `u` flag an escape outside a class must be a syntax character.) +const escRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); +const W = "[\\p{L}\\p{N}_]"; + +/** A word as written, its spaces collapsed. */ +const tidy = (w) => str(w).replace(/\s+/g, " ").trim(); + +/** Every reason a lexicon is refused (empty: it is fine). */ +export function validateLexicon(list, where = LEXICON_FILE) { + if (list === undefined || list === null) return []; + if (!Array.isArray(list)) return [`${where} must be a list of {word, say, case?, item?, note?}`]; + if (list.length > LEXICON_MAX) return [`${where}: at most ${LEXICON_MAX} entries`]; + const errors = []; + const seen = new Set(); + list.forEach((x, i) => { + const w = `${where}[${i}]`; + if (!isObj(x)) return errors.push(`${w} must be {word, say}`); + for (const k of Object.keys(x)) if (!LEXICON_KEYS.includes(k)) errors.push(`${w}.${k} is not a lexicon key (${LEXICON_KEYS.join(", ")})`); + const word = tidy(x.word); + if (!word || !/[\p{L}\p{N}]/u.test(word)) errors.push(`${w}.word must hold a letter or a digit`); + else if (word.length > LEXICON_WORD_MAX) errors.push(`${w}.word: at most ${LEXICON_WORD_MAX} characters`); + if (typeof x.say !== "string" || !x.say.trim()) errors.push(`${w}.say must be what the voice says for it (a redaction leaves a word out: umtool posts redact)`); + else if (x.say.length > LEXICON_SAY_MAX) errors.push(`${w}.say: at most ${LEXICON_SAY_MAX} characters`); + else if (/<(?!\/?(?:laugh|chuckle|sigh|cough|sniffle|groan|yawn|gasp)>)[^>]*>/i.test(x.say)) errors.push(`${w}.say: only Orpheus's tags may be in angle brackets`); + if (x.case !== undefined && typeof x.case !== "boolean") errors.push(`${w}.case must be true or false`); + if (x.item !== undefined && !(typeof x.item === "string" && ITEM_RE.test(x.item))) errors.push(`${w}.item must be a post item's id`); + if (x.note !== undefined && typeof x.note !== "string") errors.push(`${w}.note must be a string`); + const key = lexiconKey(x); + if (word && seen.has(key)) errors.push(`${w}: "${word}" is on the list twice${x.item ? ` for ${x.item}` : ""}`); + seen.add(key); + }); + return errors; +} + +/** The identity of an entry: its words (in its case when `case`), and its item. */ +export function lexiconKey(x) { + const w = tidy(x?.word); + return `${x?.case === true ? w : w.toLowerCase()}|${x?.case === true ? "c" : "i"}|${str(x?.item)}`; +} + +/** A list as `{ word, say, case, item }` -- the invalid ones dropped. */ +export function normalizeLexicon(list) { + return (Array.isArray(list) ? list : []) + .filter((x) => isObj(x) && tidy(x.word) && /[\p{L}\p{N}]/u.test(x.word) && typeof x.say === "string" && x.say.trim()) + .map((x) => ({ word: tidy(x.word), say: x.say.trim(), case: x.case === true, item: typeof x.item === "string" && x.item ? x.item : null })); +} + +/** One entry's pattern source: the word's characters literal, its spaces any run of spaces, whole-word edges. */ +export function lexiconPattern(x) { + const w = tidy(x?.word); + if (!w) return null; + const body = w.split(" ").map(escRe).join("\\s+"); + return `(?<!${W})(?<![\\p{L}\\p{N}]['’])${body}(?!${W})(?!['’][\\p{L}\\p{N}])`; +} + +/** The entries that apply to post item `item` (its own first, then the project's), longest first in each. */ +export function lexiconFor(lexicon, item = null) { + const list = normalizeLexicon(lexicon); + const own = list.filter((x) => x.item && x.item === item); + const all = list.filter((x) => !x.item); + const byLen = (a, b) => b.word.length - a.word.length; + return [...own.sort(byLen), ...all.sort(byLen)]; +} + +const overlaps = (a, b) => a.start < b.end && b.start < a.end; + +/** + * Every place `lexicon` replaces in `text` for item `item`: `[{ start, end, entry }]`, in order, none + * overlapping another or a `protect` span (`{start, end}` code units: a slur, a redacted term). + */ +export function lexiconHits(text, lexicon, { item = null, protect = [] } = {}) { + const t = str(text); + const entries = lexiconFor(lexicon, item); + if (!t || !entries.length) return []; + const taken = (Array.isArray(protect) ? protect : []).filter((s) => Number.isFinite(s?.start) && Number.isFinite(s?.end) && s.end > s.start).map((s) => ({ start: s.start, end: s.end })); + const hits = []; + for (const x of entries) { + const re = new RegExp(lexiconPattern(x), x.case ? "gu" : "giu"); + for (const m of t.matchAll(re)) { + if (!m[0]) continue; + const h = { start: m.index, end: m.index + m[0].length, entry: x }; + if (taken.some((s) => overlaps(s, h))) continue; + taken.push(h); + hits.push(h); + } + } + return hits.sort((a, b) => a.start - b.start); +} + +/** An entry as a take records it. */ +export const appliedOf = (x) => ({ word: x.word, say: x.say, ...(x.item ? { item: x.item } : {}) }); + +/** + * `text` with the lexicon applied for item `item`, never inside a `protect` span. Returns `{ text, applied }`: + * `applied` the entries it replaced, once each, as a take records them. + */ +export function applyLexicon(text, lexicon, { item = null, protect = [] } = {}) { + const t = str(text); + const hits = lexiconHits(t, lexicon, { item, protect }); + if (!hits.length) return { text: t, applied: [] }; + let out = ""; + let at = 0; + const applied = new Map(); + for (const h of hits) { + out += t.slice(at, h.start) + h.entry.say; + at = h.end; + applied.set(lexiconKey(h.entry), appliedOf(h.entry)); + } + return { text: out + t.slice(at), applied: [...applied.values()] }; +} + +/** The words a take read, as its record has them: its script, else its parts' words, else the item's script. */ +export function takeReadText(take, entry = null) { + if (typeof take?.script === "string" && take.script.trim()) return take.script; + const parts = Array.isArray(take?.parts) ? take.parts : []; + if (parts.some((p) => typeof p?.text === "string")) return parts.map((p) => str(p.text)).join("\n\n"); + return str(entry?.narration?.script); +} + +/** + * THE ENTRIES A TAKE STILL SAYS THE OLD WAY, pure: each entry of the lexicon that applies to the item and matches + * the words the take read (takeReadText), unless the take applied it with the same spoken form -- + * `[{ word, say, item?, was? }]` (`was`: the spoken form the take used, when it used another). A recorded take is + * a person's own read: never stale. + */ +export function staleLexicon(entry, take, lexicon) { + if (!take || take.engine === "recorded" || take?.source?.kind === "recorded") return []; + const text = takeReadText(take, entry); + const done = new Map((Array.isArray(take.lexicon) ? take.lexicon : []).filter(isObj).map((x) => [lexiconKey({ word: x.word, item: x.item, case: false }), str(x.say)])); + const out = []; + const seen = new Set(); + for (const h of lexiconHits(text, lexicon, { item: entry?.id ?? null })) { + const x = h.entry; + const k = lexiconKey(x); + if (seen.has(k)) continue; + seen.add(k); + const was = done.get(lexiconKey({ word: x.word, item: x.item, case: false })); + if (was === x.say) continue; + out.push({ ...appliedOf(x), ...(was !== undefined ? { was } : {}) }); + } + return out; +} + +/** A take's lexicon record is fine (empty: it is). */ +export function takeLexiconErrors(v, where) { + if (v === undefined) return []; + if (!Array.isArray(v) || v.length > LEXICON_MAX || !v.every((x) => isObj(x) && typeof x.word === "string" && typeof x.say === "string" && (x.item === undefined || typeof x.item === "string") && Object.keys(x).every((k) => ["word", "say", "item"].includes(k)))) { + return [`${where} must be the lexicon entries it applied, [{word, say, item?}]`]; + } + return []; +} + +// --------------------------------------------------------------------------- +// The voice map. +// --------------------------------------------------------------------------- + +/** A handle as the map keys it: no "@", lower case ("*" stays). */ +export const handleKey = (h) => (str(h).trim() === VOICE_MAP_OTHER ? VOICE_MAP_OTHER : str(h).trim().replace(/^@+/, "").toLowerCase()); + +/** Every reason a voice map is refused. */ +export function validateVoiceMap(map, where = VOICES_FILE) { + if (map === undefined || map === null) return []; + if (!isObj(map)) return [`${where} must be {"<handle>": "<voice>", "*": "<voice>"}`]; + const keys = Object.keys(map); + if (keys.length > VOICE_MAP_MAX) return [`${where}: at most ${VOICE_MAP_MAX} handles`]; + const errors = []; + for (const k of keys) { + if (k !== VOICE_MAP_OTHER && (!HANDLE_RE.test(k) || k !== handleKey(k))) errors.push(`${where}: "${k}" is not a handle as the map keys it (lower case, no @), or "*"`); + if (typeof map[k] !== "string" || !VOICE_RE.test(map[k])) errors.push(`${where}.${k} must be a stock voice's id`); + } + return errors; +} + +/** + * The voice one piece of a read is said in, pure. In order: the run's own `overrides` (`--voice-for`), the + * item's `voice` for its own post (`--voice`), the map's for the author, the narrator's for the item's own author, + * the map's "*", the engine's context default, the narrator's. + * + * @param {{ handle?: string | null, role: string }} piece + * @param {{ map?: Record<string, string>, overrides?: Record<string, string>, self?: string | null, voice?: string | null, + * narrator: string, engine?: string }} o + */ +export function voiceForPiece(piece, { map = {}, overrides = {}, self = null, voice = null, narrator, engine = "orpheus" }) { + const h = handleKey(piece?.handle); + const mine = piece?.role === "post" || (!!h && h === handleKey(self)); + if (h && overrides[h]) return overrides[h]; + if (piece?.role === "post" && voice) return voice; + if (h && map[h]) return map[h]; + if (mine) return narrator; + return map[VOICE_MAP_OTHER] ?? CONTEXT_VOICE_DEFAULTS[engine] ?? narrator; +} + +/** `--voice-for h=v` words as `{ handle: voice }` (handles keyed as the map keys them); throws naming a bad one. */ +export function voiceOverridesOf(list) { + const out = {}; + for (const raw of (Array.isArray(list) ? list : []).flatMap((x) => String(x).split(",")).map((x) => x.trim()).filter(Boolean)) { + const eq = raw.lastIndexOf("="); + const h = eq > 0 ? handleKey(raw.slice(0, eq)) : ""; + const v = eq > 0 ? raw.slice(eq + 1).trim() : ""; + if (!h || (h !== VOICE_MAP_OTHER && !HANDLE_RE.test(h)) || !VOICE_RE.test(v)) throw new Error(`--voice-for takes <handle>=<voice> (got ${raw})`); + out[h] = v; + } + return out; +} diff --git a/umtool/report-to-video/post-say.test.mjs b/umtool/report-to-video/post-say.test.mjs @@ -0,0 +1,136 @@ +// post-say.mjs: the pronunciation lexicon (whole words, case, phrases, regex +// characters, an item's own entries, what wins) and its place in what a voice +// SAYS (post-redact.mjs spokenRead: the slur filter and the redaction win over +// it); a read said the old way (staleLexicon); the voice map. The slurs come +// from slurs.json: no test spells one out. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; + +import { + applyLexicon, handleKey, lexiconFor, lexiconHits, staleLexicon, takeLexiconErrors, validateLexicon, validateVoiceMap, voiceForPiece, voiceOverridesOf, +} from "./post-say.mjs"; +import { spokenRead } from "./post-redact.mjs"; +import { resolveSlurs } from "./post-slurs.mjs"; +import { validatePostNarration } from "./post-narration.mjs"; + +const LIST = JSON.parse(readFileSync(new URL("./slurs.json", import.meta.url), "utf8")); +const F = LIST.entries.find((e) => e.id === "f-slur").word; +const say = (text, lex, o) => applyLexicon(text, lex, o).text; + +test("a whole word, without case by default: tbh, TBH and Tbh all said T-B-H; never inside a word", () => { + const lex = [{ word: "tbh", say: "T-B-H" }]; + assert.equal(say("tbh it's fine. TBH! (Tbh)", lex), "T-B-H it's fine. T-B-H! (T-B-H)"); + assert.equal(say("tbhx xtbh tbh_ _tbh tbh2", lex), "tbhx xtbh tbh_ _tbh tbh2"); + // An apostrophe and a letter after it are the word going on ("can" is not the "can" of "can't"). + assert.equal(say("I can't, I can.", [{ word: "can", say: "tin can" }]), "I can't, I tin can."); + // With case: only as written. + assert.equal(say("US us Us", [{ word: "US", say: "U.S.", case: true }]), "U.S. us Us"); +}); + +test("a phrase across any spaces; regex characters are literal; @handles and C++", () => { + assert.equal(say("at the\nmoment, at the moments", [{ word: "at the moment", say: "right now" }]), "right now, at the moments"); + assert.equal(say("@grok is this true? grok", [{ word: "@grok", say: "At grok" }]), "At grok is this true? grok"); + assert.equal(say("me@grok", [{ word: "@grok", say: "At grok" }]), "me@grok"); + assert.equal(say("C++ and C+", [{ word: "C++", say: "C plus plus" }]), "C plus plus and C+"); + assert.equal(say("a (sic) b sic", [{ word: "(sic)", say: "sick" }]), "a sick b sic"); + assert.equal(say("1.5x a 1x5x", [{ word: "1.5x", say: "one and a half times" }]), "one and a half times a 1x5x"); + assert.equal(say("$5 or 5", [{ word: "$5", say: "five dollars" }]), "five dollars or 5"); +}); + +test("what wins: an item's own entry over the project's, a longer match over one inside it; a replacement is never matched again", () => { + const lex = [ + { word: "atm", say: "A-T-M" }, + { word: "atm", say: "at the moment", item: "p-2" }, + { word: "not atm", say: "not right now" }, + { word: "A-T-M", say: "loop" }, + ]; + assert.equal(say("atm, not atm", lex, { item: "p-1" }), "A-T-M, not right now"); + assert.equal(say("atm", lex, { item: "p-2" }), "at the moment"); + assert.equal(say("atm", lex), "A-T-M", "no item: the project's only"); + assert.deepEqual(lexiconFor(lex, "p-2").map((x) => x.say), ["at the moment", "not right now", "loop", "A-T-M"]); + assert.deepEqual(applyLexicon("atm atm", lex).applied, [{ word: "atm", say: "A-T-M" }], "applied once each"); + assert.deepEqual(applyLexicon("atm", lex, { item: "p-2" }).applied, [{ word: "atm", say: "at the moment", item: "p-2" }]); +}); + +test("a protected span is never replaced", () => { + const text = "tbh tbh"; + assert.equal(say(text, [{ word: "tbh", say: "T-B-H" }], { protect: [{ start: 0, end: 3 }] }), "tbh T-B-H"); + assert.equal(lexiconHits(text, [{ word: "tbh", say: "x" }], { protect: [{ start: 2, end: 5 }] }).length, 0); +}); + +test("spokenRead: the lexicon applied, recorded -- and the slur filter and the redaction WIN over it", () => { + const e = { id: "p-1", post: "c/1" }; + const slurs = (cfg) => resolveSlurs(cfg, LIST); + // A lexicon entry for a slur's own word never fires: the filter's voice has it. + const lex = [{ word: F, say: "friend" }, { word: "tbh", say: "T-B-H" }]; + const text = `tbh a ${F}`; + assert.deepEqual(spokenRead(text, e, { terms: [], slurs: slurs({ voice: "skip" }), say: lex }), { text: "T-B-H a", slurs: "skip", lexicon: [{ word: "tbh", say: "T-B-H" }] }); + assert.deepEqual(spokenRead(text, e, { terms: [], slurs: slurs({ voice: "placeholder" }), say: lex }), { text: "T-B-H a f-slur", slurs: "placeholder", lexicon: [{ word: "tbh", say: "T-B-H" }] }); + assert.deepEqual(spokenRead(text, e, { terms: [], slurs: slurs({}), say: lex }), { text: `T-B-H a ${F}`, slurs: "said", lexicon: [{ word: "tbh", say: "T-B-H" }] }); + // Even with the filter off: a slur's word is the filter's, never the lexicon's. + assert.equal(spokenRead(text, e, { terms: [], slurs: slurs({ on: false }), say: lex }).text, `T-B-H a ${F}`); + // A spoken form that says a slur: the filter masks it too. + assert.equal(spokenRead("lol", e, { terms: [], slurs: slurs({ voice: "skip" }), say: [{ word: "lol", say: `ha ${F}` }] }).text, "ha"); + // A redacted word is dropped, never replaced -- and a spoken form that says a blanked name is dropped too. + const red = { terms: [{ term: "Quentin" }], slurs: null, say: [{ word: "Quentin", say: "Q" }, { word: "QE", say: "Quentin Example" }] }; + assert.equal(spokenRead("Quentin, hi", e, red).text, "hi"); + assert.equal(spokenRead("QE said", e, red).text, "Example said"); + // No lexicon: no record (the shape the takes had before it). + assert.deepEqual(spokenRead("tbh", e, { terms: [], slurs: null }), { text: "tbh", slurs: null }); + // An item's entry, by the entry's id. + assert.equal(spokenRead("atm", { id: "p-2" }, { terms: [], say: [{ word: "atm", say: "A-T-M", item: "p-2" }] }).text, "A-T-M"); + assert.equal(spokenRead("atm", { id: "p-3" }, { terms: [], say: [{ word: "atm", say: "A-T-M", item: "p-2" }] }).text, "atm"); +}); + +test("staleLexicon: a take that says an entry the old way -- unless it applied it with the same spoken form", () => { + const lex = [{ word: "tbh", say: "T-B-H" }, { word: "Pepe", say: "Pepe the frog" }]; + const e = { id: "p-1" }; + // A take from before the lexicon: its script says tbh. + assert.deepEqual(staleLexicon(e, { file: "a.wav", script: "tbh it is" }, lex), [{ word: "tbh", say: "T-B-H" }]); + // A take that applied it: not stale -- even when the spoken form holds the word. + assert.deepEqual(staleLexicon(e, { file: "a.wav", script: "tbh it is Pepe", lexicon: [{ word: "tbh", say: "T-B-H" }, { word: "Pepe", say: "Pepe the frog" }] }, lex), []); + // A thread read's script is what it said: "T-B-H" is not "tbh". + assert.deepEqual(staleLexicon(e, { file: "a.wav", script: "T-B-H it is" }, lex), []); + // Applied with another spoken form since changed: stale, with what it said. + assert.deepEqual(staleLexicon(e, { file: "a.wav", script: "tbh", lexicon: [{ word: "tbh", say: "tee bee aitch" }] }, lex), [{ word: "tbh", say: "T-B-H", was: "tee bee aitch" }]); + // A recording is a person's read: never stale. A take with no script reads its parts' words. + assert.deepEqual(staleLexicon(e, { file: "a.wav", engine: "recorded", script: "tbh" }, lex), []); + assert.deepEqual(staleLexicon(e, { file: "a.wav", parts: [{ text: "hi" }, { text: "tbh" }] }, lex).map((x) => x.word), ["tbh"]); +}); + +test("validateLexicon: the shape, the limits, a duplicate; a take's record is checked by the build", () => { + assert.deepEqual(validateLexicon([{ word: "tbh", say: "T-B-H" }, { word: "tbh", say: "x", item: "p-1" }, { word: "TBH", say: "y", case: true }]), []); + assert.match(validateLexicon([{ word: "tbh", say: "a" }, { word: "TBH", say: "b" }]).join(), /twice/); + assert.match(validateLexicon([{ word: "!!", say: "a" }]).join(), /letter or a digit/); + assert.match(validateLexicon([{ word: "a", say: "" }]).join(), /what the voice says/); + assert.match(validateLexicon([{ word: "a", say: "<b>x</b>" }]).join(), /Orpheus's tags/); + assert.deepEqual(validateLexicon([{ word: "a", say: "<laugh> a" }]), []); + assert.match(validateLexicon([{ word: "a", say: "b", how: 1 }]).join(), /not a lexicon key/); + assert.match(validateLexicon({}).join(), /must be a list/); + assert.deepEqual(takeLexiconErrors([{ word: "tbh", say: "T-B-H" }], "t"), []); + assert.match(takeLexiconErrors([{ word: "tbh" }], "t").join(), /entries it applied/); + const e = { id: "p-1", type: "post", narration: { takes: [{ file: "narration/posts/1/take-1.orpheus-zac.wav", seconds: 1, lexicon: [{ word: "tbh", say: "T-B-H" }], read: { kind: "thread", parents: "0" } }] } }; + assert.deepEqual(validatePostNarration(e), []); + e.narration.takes[0].read = { kind: "other" }; + assert.match(validatePostNarration(e).join(), /read must be/); +}); + +test("the voice map: a handle keyed without @ and case; who reads in what", () => { + assert.equal(handleKey("@KirscheVerstahl"), "kirscheverstahl"); + assert.deepEqual(validateVoiceMap({ kirscheverstahl: "tara", "*": "leo" }), []); + assert.match(validateVoiceMap({ "@Kirsche": "tara" }).join(), /not a handle/); + assert.match(validateVoiceMap({ a: "no voice!" }).join(), /stock voice/); + const o = { map: { kirscheverstahl: "tara", movail2: "leah" }, self: "ObviousRises", narrator: "zac", engine: "orpheus" }; + assert.equal(voiceForPiece({ handle: "KirscheVerstahl", role: "parent:0" }, o), "tara"); + assert.equal(voiceForPiece({ handle: "someone", role: "parent:0" }, o), "leo", "everyone else: leo on Orpheus"); + assert.equal(voiceForPiece({ handle: "someone", role: "quoted" }, { ...o, map: { ...o.map, "*": "dan" } }), "dan"); + assert.equal(voiceForPiece({ handle: "obviousrises", role: "parent:1" }, o), "zac", "his own words up the thread: the narrator"); + assert.equal(voiceForPiece({ handle: "ObviousRises", role: "post" }, o), "zac"); + assert.equal(voiceForPiece({ handle: "ObviousRises", role: "post" }, { ...o, voice: "leo" }), "leo", "--voice: his post"); + assert.equal(voiceForPiece({ handle: "KirscheVerstahl", role: "post" }, { ...o, self: "KirscheVerstahl" }), "tara", "her own item: the map names her"); + assert.equal(voiceForPiece({ handle: "KirscheVerstahl", role: "parent:0" }, { ...o, overrides: { kirscheverstahl: "mia" } }), "mia", "--voice-for wins"); + assert.equal(voiceForPiece({ handle: "x", role: "parent:0" }, { ...o, engine: "kokoro", narrator: "af_heart" }), "af_heart", "no context default for the engine: the narrator"); + assert.deepEqual(voiceOverridesOf(["@KirscheVerstahl=tara", "a=leo,b=dan"]), { kirscheverstahl: "tara", a: "leo", b: "dan" }); + assert.throws(() => voiceOverridesOf(["tara"]), /<handle>=<voice>/); +});