Archilyzer · Source

archilyzer

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

commit 4c5f8ad81146943c325e28bb01a2ee7fe892701e
parent b951527c4625df41183a2f61743834bd6454c02c
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Thu, 12 Nov 2026 18:41:13 -0500

Merge lane/screen-reads: a text screenshot is read as part of its post -- a post item carries screens (DMs, an email, another post, text; inside its video or an image attachment), transcribed once, drawn typeset in the card under "transcribed" and read line by line, whole or in excerpts, in the speakers' voices by the thread read; e-mails, phone, card, order and id numbers are masked on the card and never said; a line changed since the read, a broken excerpt or a recorded line that says other words is refused by the build; umtool posts screen and the post bench's Screens section set it; an item without screens draws and reads as before

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

Diffstat:
Mumtool/bin/umtool.mjs | 1+
Mumtool/components/projects/PostBench.tsx | 6++++++
Mumtool/components/projects/PostFollowPanel.tsx | 5++++-
Aumtool/components/projects/PostScreensPanel.tsx | 314+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/docs/cli.md | 4+++-
Mumtool/docs/knobs.md | 27+++++++++++++++++++++++++++
Mumtool/docs/report-video.md | 89+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/e2e/post-screens.spec.ts | 121+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/cli/groups.mjs | 9+++++++--
Mumtool/lib/cli/verbs.mjs | 8++++++++
Mumtool/lib/report/castProject.mjs | 7+++++++
Mumtool/lib/report/manifest.mjs | 25++++++++++++++++++++++---
Mumtool/lib/report/postNarrationCli.mjs | 22++++++++++++++++++++--
Mumtool/lib/report/postPause.mjs | 2+-
Mumtool/lib/report/postSay.mjs | 3+++
Aumtool/lib/report/postScreens.test.mjs | 308+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/postScreensCli.mjs | 389+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/postThreadCli.mjs | 5+++--
Mumtool/lib/report/postThreadRead.mjs | 154+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------
Mumtool/lib/report/postsCli.mjs | 20+++++++++++++++-----
Mumtool/report-to-video/build-video.mjs | 10+++++++++-
Mumtool/report-to-video/package.json | 1+
Mumtool/report-to-video/post-anon.mjs | 63++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mumtool/report-to-video/post-item.mjs | 79++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----
Mumtool/report-to-video/post-narration.mjs | 6++++--
Mumtool/report-to-video/post-redact.mjs | 19+++++++++++++++++++
Mumtool/report-to-video/post-render.mjs | 15++++++++++++---
Aumtool/report-to-video/post-screens-pin.test.mjs | 129+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/post-screens-review.test.mjs | 233+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/post-screens-review2.test.mjs | 155+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/post-screens.mjs | 747+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/post-screens.test.mjs | 268+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/post-thread.mjs | 145+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------
Mumtool/report-to-video/read-follow.mjs | 41++++++++++++++++++++++++++++++++++++-----
34 files changed, 3375 insertions(+), 55 deletions(-)

diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs @@ -135,6 +135,7 @@ // 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) +// screen <project> <item> list | add | set | rm | check | read … its text screenshots (postScreensCli.mjs) // set-item | roles | narrate | reread | fx … --in-take <take> the edit on a take's patch (takeScope.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 diff --git a/umtool/components/projects/PostBench.tsx b/umtool/components/projects/PostBench.tsx @@ -11,6 +11,7 @@ import { POST_HOLD, POST_MEDIA_MIN_SPAN, POST_PARAPHRASE_MAX, contextReadSeconds import PostItemPlayer, { type PostPlan } from "./review/PostItemPlayer"; import PostFollowPanel from "./PostFollowPanel"; import PostThreadPanel from "./PostThreadPanel"; +import PostScreensPanel from "./PostScreensPanel"; import BlurBoxPad, { type Band } from "./BlurBoxPad"; import PostNarrationPanel from "./PostNarrationPanel"; import PostComboPanel from "./PostComboPanel"; @@ -39,6 +40,8 @@ import { sceneEntry } from "umtool-report-to-video/post-media-scene"; // transcription (a job on a local worker), never ASR here // thread a read of the post it answers or quotes: what each is on // screen while it is read and after (PostThreadPanel) +// screens the text screenshots in its attachments, transcribed, drawn and +// read after its words (PostScreensPanel) // context the post it quotes, the posts it answers: a paraphrase of // a long one, drawn in place of its words with a // "paraphrased" label (its own text kept, shown beside) @@ -227,6 +230,8 @@ export default function PostBench({ ), // Picture-only (post-picture.mjs): true, false, or null (the rule). pictureOnly: typeof e.pictureOnly === "boolean" ? e.pictureOnly : null, + // Its screens (post-screens.mjs): the whole list as it stands (null: none). + screens: Array.isArray(e.screens) && e.screens.length ? e.screens : null, ...(e.quoted && typeof e.quoted === "object" ? { quoted: { paraphrase: e.quoted.paraphrase?.trim() ? e.quoted.paraphrase : null, pictureOnly: typeof e.quoted.pictureOnly === "boolean" ? e.quoted.pictureOnly : null } } : {}), ...(Array.isArray(e.parents) && e.parents.length ? { parents: Object.fromEntries(e.parents.map((p, i) => [i, { paraphrase: p?.paraphrase?.trim() ? p.paraphrase : null, pictureOnly: typeof p?.pictureOnly === "boolean" ? p.pictureOnly : null }])) } @@ -426,6 +431,7 @@ export default function PostBench({ /> <PostFollowPanel entry={entry} plan={plan} render={render} s={s} setS={setS} setEntry={(f) => setEntry((e) => f(e) as Entry)} /> <PostThreadPanel project={project} entry={entry} plan={plan} render={render} before={before} scene={conversation} setS={setS} setEntry={(f) => setEntry((e) => f(e) as Entry)} /> + <PostScreensPanel project={project} entry={entry} setEntry={(f) => setEntry((e) => f(e) as Entry)} /> <PostNarrationPanel project={project} entry={entry} diff --git a/umtool/components/projects/PostFollowPanel.tsx b/umtool/components/projects/PostFollowPanel.tsx @@ -4,6 +4,7 @@ import { useMemo } from "react"; import { FOLLOW_DEFAULTS, FOLLOW_LIMITS, cardScopes, followBlockAt, followKnobs } from "umtool-report-to-video/read-follow"; import { cardWordsOf } from "umtool-report-to-video/word-zoom"; import type { PostPlan } from "./review/PostItemPlayer"; +import { screenLineSaid, screenOf } from "umtool-report-to-video/post-screens"; // --------------------------------------------------------------------------- // A POST's READ-FOLLOW ON THE BENCH (report-to-video/read-follow.mjs; knobs.md, @@ -106,7 +107,9 @@ export default function PostFollowPanel({ {follow.blocks.map((b) => { const words = texts.get(b.scope) ?? []; // A part read off an attachment (post-thread.mjs: a screenshot's words) has no words on the card. - const head = b.from === null || b.to === null ? "(read off the attachment)" : words.slice(b.from, Math.min(b.to + 1, b.from + 8)).join(" "); + // A SCREEN's line (post-screens.mjs): its words, as the screen reads them. + const line = typeof (b as { line?: unknown }).line === "number" && String(b.scope).startsWith("screen:") ? screenLineSaid(screenOf(entry, String(b.scope).slice(7)), (b as { line?: number }).line) : null; + const head = line !== null ? `line ${(b as { line?: number }).line}: ${line.split(/\s+/).slice(0, 8).join(" ")}` : b.from === null || b.to === null ? "(read off the attachment)" : words.slice(b.from, Math.min(b.to + 1, b.from + 8)).join(" "); return ( <li key={b.k} data-post-follow-row={b.k} data-current={cur === b.k ? "1" : undefined} className={cur === b.k ? "rounded bg-white/10" : ""}> <button diff --git a/umtool/components/projects/PostScreensPanel.tsx b/umtool/components/projects/PostScreensPanel.tsx @@ -0,0 +1,314 @@ +"use client"; + +import { useMemo, useRef, useState } from "react"; +import { SCREEN_KINDS, lineOfText, screenReadLines, screenWarnings, shapeSpans, validateScreens, withoutLines } from "umtool-report-to-video/post-screens"; +import { isNarrated, pickedTake } from "umtool-report-to-video/post-narration"; +import { partRoles, threadReadErrors } from "umtool-report-to-video/post-thread"; +import { postFileUrl } from "./review/PostItemPlayer"; + +// --------------------------------------------------------------------------- +// A POST's SCREENS ON THE BENCH (report-to-video/post-screens.mjs; docs/report-video.md, "Screens"; operator, 12 Nov: +// "The 'read text screenshots as posts' ability in different variations should be first class"): the text screenshots +// the post carries -- each the attachment it is in (and, in a video, the seconds it is visible), what it is (DMs, an +// email, a post, text), its lines transcribed by hand (pasted as `who: words | time`), who says each and on which side, +// which lines are read (a line's excerpt trimmed to the words read), and whether a person checked the transcription. +// No model: everything here is typed. The bench's Save writes it (updatePostItem's `screens`); the read is made with +// `umtool posts screen <p> <item> read` (the line shown here). +// --------------------------------------------------------------------------- + +type Line = { who?: string; side?: "left" | "right"; text: string; time?: string; redact?: true }; +type Read = "all" | "none" | Array<{ line: number; text?: string }>; +type Screen = { id: string; media: number; at?: [number, number]; kind: string; title?: string; source?: string; checked?: { by: string; at: string }; ref?: string; unread?: "omit" | "dim"; lines: Line[]; read: Read }; +type Media = { src: string; kind: string; seconds?: number }; +type Entry = Record<string, unknown> & { id: string; media?: Media[]; screens?: Screen[] }; + +const r2 = (v: number) => Math.round(v * 100) / 100; + +/** The read as a list of `{ line, text? }` (all: every line not redacted; none: none). */ +const readList = (sc: Screen): Array<{ line: number; text?: string }> => (sc.read === "all" ? sc.lines.map((l, i) => (l.redact ? null : { line: i })).filter((x): x is { line: number } => !!x) : sc.read === "none" ? [] : sc.read); + +export default function PostScreensPanel({ project, entry, setEntry }: { project: string; entry: Entry; setEntry: (f: (e: Entry) => Entry) => void }) { + const screens = useMemo(() => (Array.isArray(entry.screens) ? entry.screens : []), [entry.screens]); + const media = Array.isArray(entry.media) ? entry.media : []; + const errors = useMemo(() => validateScreens(entry) as string[], [entry]); + // The build's guard on the read as it is (post-thread.mjs): a line edited, removed or moved under a read is refused + // until the read is made again -- Save keeps the screens; the build will not play the old read. + const refused = useMemo(() => (isNarrated(entry) ? (threadReadErrors(entry, {}) as string[]).filter((x) => /screen [a-z0-9-]+/.test(x)) : []), [entry]); + const warnings = useMemo(() => screenWarnings(entry, { narrated: isNarrated(entry), takeRoles: pickedTake(entry) ? (partRoles(entry) as Array<{ role: string | null }>).map((r) => r.role) : [] }) as string[], [entry]); + const [paste, setPaste] = useState<Record<string, string>>({}); + const setScreens = (f: (list: Screen[]) => Screen[]) => + setEntry((e) => { + const next = f(Array.isArray(e.screens) ? (e.screens as Screen[]) : []); + const out = { ...e }; + if (next.length) out.screens = next; + else delete out.screens; + return out; + }); + const setScreen = (id: string, f: (s: Screen) => Screen) => setScreens((list) => list.map((s) => (s.id === id ? f(s) : s))); + // Lines or words changed: the check was for the words before. + const setLines = (id: string, f: (lines: Line[]) => Line[]) => setScreen(id, (s) => { + const { checked: _c, ...rest } = s; + void _c; + return { ...rest, lines: f(s.lines) }; + }); + const add = () => { + const have = new Set(screens.map((s) => s.id)); + let n = 1; + while (have.has(`s${n}`)) n += 1; + const m = media[0]; + const sc: Screen = { id: `s${n}`, media: 0, kind: "dm", source: "transcribed", lines: [], read: "all", ...(m && (m.kind === "video" || m.kind === "gif") ? { at: [0, r2(Math.min(5, m.seconds ?? 5))] as [number, number] } : {}) }; + setScreens((list) => [...list, sc]); + }; + if (!media.length) return null; + return ( + <section className="rounded border border-[var(--color-line)] bg-[var(--color-panel)] p-3 text-[12px]" data-post-screens-panel="" data-screens={screens.length}> + <div className="mb-2 flex flex-wrap items-center gap-2"> + <h2 className="micro m-0">screens</h2> + <span className="text-text-2">text screenshots in its attachments, transcribed, drawn on the card and read after its words</span> + <button type="button" className="ink-link ml-auto" onClick={add} data-post-screens-add=""> + Add a screen + </button> + </div> + {screens.map((sc) => ( + <ScreenEditor + key={sc.id} + project={project} + entry={entry} + sc={sc} + media={media} + paste={paste[sc.id] ?? ""} + setPaste={(v) => setPaste((p) => ({ ...p, [sc.id]: v }))} + setScreen={(f) => setScreen(sc.id, f)} + setLines={(f) => setLines(sc.id, f)} + remove={() => setScreens((list) => list.filter((s) => s.id !== sc.id))} + /> + ))} + {screens.length > 0 && ( + <p className="m-0 mt-2 font-mono text-text-2" data-post-screens-read-cmd=""> + umtool posts screen {project} {entry.id} read + </p> + )} + {errors.length > 0 && ( + <ul className="m-0 mt-1 list-disc pl-4 text-[var(--color-bad,#e5484d)]" data-post-screens-errors=""> + {errors.map((er, i) => ( + <li key={i}>{er}</li> + ))} + </ul> + )} + {refused.length > 0 && ( + <ul className="m-0 mt-1 list-disc pl-4 text-[var(--color-bad,#e5484d)]" data-post-screens-refused=""> + {refused.map((er, i) => ( + <li key={i}>{er}</li> + ))} + </ul> + )} + {warnings.length > 0 && ( + <ul className="m-0 mt-1 list-disc pl-4 text-text-2" data-post-screens-warnings=""> + {warnings.map((w, i) => ( + <li key={i}>{w}</li> + ))} + </ul> + )} + </section> + ); +} + +function ScreenEditor({ + project, entry, sc, media, paste, setPaste, setScreen, setLines, remove, +}: { + project: string; + entry: Entry; + sc: Screen; + media: Media[]; + paste: string; + setPaste: (v: string) => void; + setScreen: (f: (s: Screen) => Screen) => void; + setLines: (f: (lines: Line[]) => Line[]) => void; + remove: () => void; +}) { + const m = media[sc.media]; + const timed = m?.kind === "video" || m?.kind === "gif"; + const video = useRef<HTMLVideoElement | null>(null); + const reads = new Map(readList(sc).map((r) => [r.line, r])); + const drawnReads = new Map((screenReadLines(sc) as Array<{ n: number; cutBefore: boolean; cutAfter: boolean }>).map((r) => [r.n, r])); + const setRead = (list: Array<{ line: number; text?: string }>) => setScreen((s) => ({ ...s, read: list.length === s.lines.filter((l) => !l.redact).length && list.every((x) => !x.text) ? "all" : list.length ? [...list].sort((a, b) => a.line - b.line) : "none" })); + const toggleRead = (n: number, on: boolean) => { + const list = readList(sc).filter((x) => x.line !== n); + setRead(on ? [...list, { line: n }] : list); + }; + const setExcerpt = (n: number, text: string) => setRead([...readList(sc).filter((x) => x.line !== n), text.trim() ? { line: n, text } : { line: n }]); + const setLine = (n: number, patch: Partial<Line>) => + setLines((lines) => + lines.map((l, i) => { + if (i !== n) return l; + const out: Record<string, unknown> = { ...l, ...patch }; + for (const [k, v] of Object.entries(out)) if (v === undefined || v === "" || v === false) if (k !== "text") delete out[k]; + return out as Line; + }), + ); + const at = sc.at ?? [0, 0]; + return ( + <div className="mb-3 rounded border border-[var(--color-line)] p-2" data-post-screen={sc.id}> + <div className="mb-1 flex flex-wrap items-center gap-2"> + <span className="font-mono">{sc.id}</span> + <label className="flex items-center gap-1"> + what + <select value={sc.kind} onChange={(e) => setScreen((s) => ({ ...s, kind: e.target.value }))} data-post-screen-kind=""> + {SCREEN_KINDS.map((k: string) => ( + <option key={k} value={k}> + {k === "dm" ? "DMs" : k} + </option> + ))} + </select> + </label> + <label className="flex items-center gap-1"> + title + <input className="w-36" value={sc.title ?? ""} placeholder="(from what it is)" onChange={(e) => setScreen((s) => { const { title: _t, ...rest } = s; void _t; return e.target.value ? { ...rest, title: e.target.value } : rest; })} data-post-screen-title="" /> + </label> + <label className="flex items-center gap-1"> + in + <select + value={sc.media} + onChange={(e) => + setScreen((s) => { + const i = Number(e.target.value); + const mm = media[i]; + const { at: _a, ...rest } = s; + void _a; + return mm && (mm.kind === "video" || mm.kind === "gif") ? { ...rest, media: i, at: s.at ?? [0, r2(Math.min(5, mm.seconds ?? 5))] } : { ...rest, media: i }; + }) + } + data-post-screen-media="" + > + {media.map((mm, i) => ( + <option key={i} value={i}> + attachment {i + 1} ({mm.kind}) + </option> + ))} + </select> + </label> + {timed && ( + <span className="flex items-center gap-1" data-post-screen-at=""> + visible + <input type="number" step={0.1} min={0} className="w-16" value={at[0]} onChange={(e) => setScreen((s) => ({ ...s, at: [r2(Number(e.target.value)), at[1]] }))} data-post-screen-at-from="" aria-label="from (s)" /> + – + <input type="number" step={0.1} min={0} className="w-16" value={at[1]} onChange={(e) => setScreen((s) => ({ ...s, at: [at[0], r2(Number(e.target.value))] }))} data-post-screen-at-to="" aria-label="to (s)" /> + s + </span> + )} + <label className="flex items-center gap-1"> + lines not read + <select value={sc.unread ?? "omit"} onChange={(e) => setScreen((s) => { const { unread: _u, ...rest } = s; void _u; return e.target.value === "dim" ? { ...rest, unread: "dim" } : rest; })} data-post-screen-unread=""> + <option value="omit">left out</option> + <option value="dim">drawn dim</option> + </select> + </label> + <label className="flex items-center gap-1" title="the transcription read against the screenshot"> + <input + type="checkbox" + checked={!!sc.checked} + onChange={(e) => setScreen((s) => { const { checked: _c, ...rest } = s; void _c; return e.target.checked ? { ...rest, checked: { by: "operator", at: new Date().toISOString() } } : rest; })} + data-post-screen-checked="" + /> + checked + </label> + <button type="button" className="ink-link ml-auto" onClick={remove} data-post-screen-remove=""> + Remove + </button> + </div> + {timed && m && ( + <div className="mb-1 flex items-center gap-2" data-post-screen-scrub=""> + <video ref={video} src={postFileUrl(project, m.src)} className="h-28 rounded bg-black" controls muted preload="metadata" onLoadedMetadata={(e) => (e.currentTarget.currentTime = at[0])} /> + <div className="flex flex-col gap-1"> + <button type="button" className="ink-link text-left" onClick={() => video.current && setScreen((s) => ({ ...s, at: [r2(video.current!.currentTime), Math.max(r2(video.current!.currentTime) + 0.5, (s.at ?? at)[1])] }))} data-post-screen-from-here=""> + visible from here + </button> + <button type="button" className="ink-link text-left" onClick={() => video.current && setScreen((s) => ({ ...s, at: [(s.at ?? at)[0], r2(video.current!.currentTime)] }))} data-post-screen-to-here=""> + to here + </button> + </div> + </div> + )} + {sc.lines.length > 0 && ( + <table className="w-full border-collapse" data-post-screen-lines=""> + <thead> + <tr className="text-left text-text-2"> + <th className="w-6">#</th> + <th className="w-10">read</th> + <th className="w-28">who</th> + <th className="w-16">side</th> + <th>words (the excerpt read below, when trimmed)</th> + <th className="w-20">time</th> + <th className="w-14">redact</th> + </tr> + </thead> + <tbody> + {sc.lines.map((l, n) => { + const r = reads.get(n); + const d = drawnReads.get(n); + const shapes = (shapeSpans(l.text) as Array<{ kind: string }>).map((x) => x.kind); + return ( + <tr key={n} className="align-top" data-post-screen-line={n}> + <td className="font-mono">{n}</td> + <td> + <input type="checkbox" disabled={!!l.redact} checked={!!r && !l.redact} onChange={(e) => toggleRead(n, e.target.checked)} data-post-screen-read={n} aria-label={`read line ${n}`} /> + </td> + <td> + <input className="w-full" value={l.who ?? ""} placeholder="—" onChange={(e) => setLine(n, { who: e.target.value || undefined })} data-post-screen-who={n} /> + </td> + <td> + <select value={l.side ?? ""} onChange={(e) => setLine(n, { side: (e.target.value || undefined) as Line["side"] })} data-post-screen-side={n}> + <option value="">auto</option> + <option value="left">left</option> + <option value="right">right</option> + </select> + </td> + <td> + <input className="w-full" value={l.text} onChange={(e) => setLine(n, { text: e.target.value })} data-post-screen-text={n} /> + {r && !l.redact && ( + <input className="mt-0.5 w-full text-text-2" value={r.text ?? ""} placeholder="excerpt: the words read (all of them when empty)" onChange={(e) => setExcerpt(n, e.target.value)} data-post-screen-excerpt={n} /> + )} + {d && (d.cutBefore || d.cutAfter) && <span className="text-text-2">reads an excerpt</span>} + {shapes.length > 0 && !l.redact && <span className="text-text-2" data-post-screen-masked={n}> · masked: {shapes.join(", ")}</span>} + </td> + <td> + <input className="w-full" value={l.time ?? ""} onChange={(e) => setLine(n, { time: e.target.value || undefined })} data-post-screen-time={n} /> + </td> + <td> + <input type="checkbox" checked={!!l.redact} onChange={(e) => setLine(n, { redact: e.target.checked ? true : undefined })} data-post-screen-redact={n} aria-label={`redact line ${n}`} /> + <button type="button" className="ink-link ml-1" onClick={() => setScreen((s) => { const { checked: _c, ...rest } = withoutLines(s, [n]) as Screen; void _c; return rest; })} title="remove the line (the read follows it)" data-post-screen-line-remove={n}> + × + </button> + </td> + </tr> + ); + })} + </tbody> + </table> + )} + <div className="mt-1 flex items-start gap-2"> + <textarea + className="min-h-12 flex-1 font-mono" + value={paste} + placeholder={"paste the lines: who: words | time ([right] for her side, - words for none, [redact] never shown)"} + onChange={(e) => setPaste(e.target.value)} + data-post-screen-paste="" + /> + <button + type="button" + className="ink-link" + disabled={!paste.trim()} + onClick={() => { + const lines = paste.split(/\r?\n/).map((x) => lineOfText(x) as Line | null).filter((x): x is Line => !!x); + setLines((old) => [...old, ...lines]); + setPaste(""); + }} + data-post-screen-paste-add="" + > + Add the lines + </button> + </div> + {entry.narration === undefined && <p className="m-0 mt-1 text-text-2">not narrated: a screen is drawn and read with the item&apos;s read</p>} + </div> + ); +} diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md @@ -131,9 +131,10 @@ Inbox cannot disagree about what is wrong with one. | `posts reread <project> <item> --pause "<word>[#<n>]=<seconds>\|@<take s>=<seconds>[,…]" [--target post\|parent:0\|quoted\|linked:0] [--dry-run] [--json]` | **pauses put in after words** of a narrated read, no TTS (`lib/report/postPause.mjs`; operator, 5 Nov: a countdown "20 10 4 0" read without a breath): the picked take cut just after each word named (half way into the quiet before the next word, at most 0.1 s past its end) and that much silence (0.05–3 s) put in -- each cut moved to the quietest 10 ms its word allows (40 ms before its timed end up to the next word, ±40 ms when they run together) when that is clearly quieter (~3 dB) than the timing's own, and each side of the silence faded over 10 ms, so a pause in normally paced speech does not click -- everything after moved on -- its words (by index), its parts (one a pause falls in grows), its length -- so word zooms, captions, slams, beeps and the read-follow stay on their words; an effect with a set `at` does not move (the plan counts them). A word is matched as a word zoom's is (case and edge punctuation aside; a phrase pauses after its last word; `#n` its n-th time in the read; `--target` counts only the words of the parts reading that piece). A derived take (`steps: [{op: "pause", pauses: [{word, w, at, seconds}]}]`) picked in ONE write. **Absolute**, like a tempo: on a take whose last step is a pause it re-cuts from the take before (the pauses it had kept, a word named again takes the new seconds, `=0` takes one away). `--in-take <t>` puts it in a take's read. No word timings (**exit 1**, naming `posts narrate <p> <item> --words`), a word not read, an occurrence not there, nothing to change: **exit 1**; a malformed spec, seconds outside 0.05–3, `--pause` with another reread form: **exit 2** | | `posts reread <project> <item> --revoice "<phrase>[#<n>]" --say "<what to say instead>" [--target <piece>] [--voice <v>\|auto] [--xfade 0.03] [--splice <from>-<to>] [--dry-run] [--json]` | **one phrase of an approved read re-voiced**, the rest untouched (`lib/report/postRevoice.mjs`; operator, 5 Nov: the countdown gabbled, and pauses cut into it "choppy"): the phrase found in the picked take's word timings as `--pause` finds a word (`#n`, `--target`; inside one part), the original cut from just before its first word to just after its last -- each cut at the quietest 10 ms within ±40 ms of the boundary, and when that is still speech within ±0.15 s (never inside the phrase as timed; a nearer quiet preferred) -- **`--say` alone synthesized by the editor's TTS** (narrate-via-editor; the engine of the root take, the voice of the part the phrase is in, `--voice` overrides; the project's lexicon, redaction and slur filter applied; kept in `narration/parts-cache/` like a thread read's parts, so asking again is free), its lead and tail of silence trimmed, loudness-matched to the speech in the 2 s either side (±6 dB) and spliced in with equal-power crossfades (`--xfade`, 0–0.2 s) at both joins, at the take's rate and layout. The length is exact: the take − the span cut + the piece. Everything after moves by the difference (its words, the part holding the span, the later parts) so zooms, captions, slams, beeps and the read-follow stay on their words; the new words are timed from the piece's speech and marked `estimated` (a later `posts narrate … --words` refines them); the part's text and the script say `--say`. A derived take (`steps: [{op: "revoice", revoice: {word, count, words, phrase, say, said, voice, engine, from, to, seconds, gain, xfade, key}}]`) picked in ONE write; re-voicing exactly the words a re-voice put in re-cuts from the take before. `--dry-run`: the span (words, seconds), each cut and its level, what is said and in which voice, the length change when the piece is cached -- no TTS. A cut still in speech is warned of (the word timings off there): `--splice 65.03-66.00` sets the cuts (either side may be left out). `--in-take <t>` puts it in a take's read. No word timings (naming `posts narrate <p> <item> --words`), the phrase not read or across two parts, a recorded read, the TTS failing: **exit 1**; no `--say`, a bad voice, crossfade or splice, `--revoice` with another reread form: **exit 2** | | `posts progress <project> [auto\|on\|off\|default] [--json]` | the cut's **progress bar** default (`render.posts.progress`, `updatePostProgressRender`; [report-video.md](report-video.md#the-progress-bar)); bare, which items draw it | +| `posts screen <project> <item> list\|add\|set\|rm\|check\|read …` (add: `--media <i> [--at <from>,<to>] --kind dm\|email\|post\|text [--id <id>] [--title "…"] [--from <file>] [--line "who: words"]… [--read all\|none\|<n>,…] [--unread omit\|dim] [--ref <channel>/<postId>]`; set: `<id> kind= title= media= at=<a>,<b>\|off unread= ref= read=all\|none\|<n>,… read.<n>="excerpt"\|on\|off line.add="who: words" line.<n>=off line.<n>.who= line.<n>.side=left\|right\|auto line.<n>.text= line.<n>.time= line.<n>.redact=on\|off [--from <file>]`; check: `<id> [--by <name>] [--undo]`; read: `[--post-take <n>] [--line-take screen:<id>:<line>=<n>]… [--voice-for h=v]… [--force] [--dry-run]`; `--json`, `--dry-run`, `--take <take>`) | a post's **SCREENS** ([report-video.md](report-video.md#screens-text-screenshots-read-as-part-of-the-post), [knobs.md](knobs.md#screens-a-posts-text-screenshots), `post-screens.mjs`): the text screenshots its attachments carry -- a DM exchange or an email shown in its video (`--at`: the seconds it is visible), an image that is a screenshot -- transcribed once (`--from`: a JSON screen, or text lines `[right] who: words \| time`, `- words`, `[redact] …`), checked by a person (`check`; a screen not checked is a lint WARNING; new words take the check away), and read whole or in excerpts. Each write is the post item's one writer (`updatePostItem`'s `screens`, one undo point), refused in the build's words (**exit 1**); an attachment a screen is in cannot be removed. An e-mail address, a phone number, an order or long number in a line is masked on the card and never said. `read` makes the THREAD READ with the screens (as `posts narrate <p> <item> --take --thread`): her own line from the take that plays (or the one the thread read used; `--post-take n` another), never made again; each read line in its speaker's voice (`who`: the post's author in hers, a handle or a character's name in theirs); `--line-take` takes a line from the item's take n (a recording of it). Usage errors: **exit 2** | | `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: a reply's leading @handles, links, emoji dropped -- a handle typed inside the message is kept and said "at <handle>", the lexicon first; `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**) A `--take` whose read says a slur the cut BEEPS is word-timed by the editor's transcription before it is kept -- never waited on: with the transcription lane held (as while Orpheus runs) the take is kept as read and the timing deferred (it says so, naming `posts narrate <p> <item> --words` to run after the release; the build refuses the take until then), and a timing still queued after 5 min is deferred the same way. An excerpted item (`posts set-item … excerpt=`) reads its spans. | -| `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] [--speed s] [--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 item's own character, this video's characters and voice map, the cast: `cast project`; his own: the narrator's) and at its character's speed (its synthetic preset's; `--speed`: every part at that one; Orpheus has none; a part at another speed is another cached part), 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). **`--post-take <n>`**: his OWN line is the item's take n (as `--list` numbers them) -- a recording, or one converted to his character's voice -- not synthesized; the context pieces are, in their authors' voices, and each part of the new take records where it came from (a synthesized part its parts-cache file and voice; the take's part its file and `take`: that take's id; the read's `postTake`). A thread take, or one whose file is gone: **exit 1**. 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 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] [--speed s] [--no-screens] [--line-take screen:<id>:<line>=<n>]… [--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 item's own character, this video's characters and voice map, the cast: `cast project`; his own: the narrator's) and at its character's speed (its synthetic preset's; `--speed`: every part at that one; Orpheus has none; a part at another speed is another cached part), 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). **`--post-take <n>`**: his OWN line is the item's take n (as `--list` numbers them) -- a recording, or one converted to his character's voice -- not synthesized; the context pieces are, in their authors' voices, and each part of the new take records where it came from (a synthesized part its parts-cache file and voice; the take's part its file and `take`: that take's id; the read's `postTake`). A thread take, or one whose file is gone: **exit 1**. 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** Its SCREENS (`posts screen`) are read after his words, each line in its speaker's voice (`--no-screens`: left out); `--line-take screen:<id>:<line>=<n>` takes a line from the item's take n as `--post-take` does his own | | `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 character <project> <item> [<character> \| --clear] [--json]` | **THE CHARACTER ONE ITEM's OWN READ IS MADE WITH** (`narration.character`, [knobs.md](knobs.md#this-videos-own-characters-and-an-items-own)): the id of one of this video's own characters, else of the cast's -- its presets answer for that item before its author's handle does (the synthetic one for `--take` and a thread read, the recorded one for `--recording`). No character: the one it names and what its read resolves to now; `--clear`: by its handle again. One undoable write; no take is made. An id nobody has: **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** | @@ -362,6 +363,7 @@ draft (the project's manifest); *project*: a project's other files, or reads; *c | `posts reel <project> --channel CHANNEL… [--since SINCE] [--until UNTIL] [--own] [--with-media] [--replies include\|only\|exclude] [--order chrono\|reverse] [--limit N] [--after AFTER] [--dry-run]` | post items from posts channels, in one write | form · *draft* | | `posts set-item <project> <item> key=value… [--in-take IN-TAKE]` | a post item's knobs | form · *draft* | | `posts narrate <project> [<item>] [key=value…] [--script SCRIPT] [--take] [--note NOTE] [--voice VOICE] [--engine ENGINE] [--speed N] [--pick N] [--approve] [--unapprove] [--off] [--on] [--thread] [--parents PARENTS] [--post-take N] [--words] [--import] [--list] [--all] [--draft-scripts] [--limit N] [--force] [--recording RECORDING] [--as AS] [--pitch target\|source\|contour] [--semitones N] [--dry-run] [--in-take IN-TAKE]` | a post item's narration: script, takes, pick, approve, mix | form · queued · *draft* | +| `posts screen <project> <item> list\|add\|set\|rm\|check\|read [<screen>] [key=value…] [--media N] [--at AT] [--kind dm\|email\|post\|text] [--title TITLE] [--line LINE…] [--read READ] [--unread omit\|dim] [--by BY] [--undo] [--post-take N] [--line-take LINE-TAKE…] [--dry-run] [--in-take IN-TAKE]` | a post item's text screenshots: transcribed, drawn, read | form · *draft* | | `posts say <project> ls\|add\|remove\|try\|stale [<word>] [<spoken>] [--case] [--item ITEM] [--note NOTE]` | the pronunciation lexicon | form · *draft* | | `posts character <project> <item> [<character>] [--clear]` | the character one post item's own read is made with | form · *draft* | | `posts voices <project> ls\|set\|remove [<handle>] [<voice>]` | the voice map a thread read uses | form · *draft* | diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md @@ -1820,6 +1820,33 @@ the card's video unmuted on its clock through the beat. A GIF stays silent; carr | `parents[i].pictureOnly`, `quoted.pictureOnly` -- the same for a context post | post bench, **picture-only**: its row | `umtool posts set-item <p> <item> parent.0.pictureOnly=on` · `quoted.pictureOnly=off` (`auto`) | same, `patch: {parents: {"0": {pictureOnly}}, quoted: {pictureOnly}}` | | `render.posts.pictureReply` -- the cut's rule: `{on, image, min, max, maxSound}` (default `on: true`; a beat is a GIF's or a silent video's own length, an image `image` = 2 s, clamped to `min`–`max` = 1.5–4 s; a VIDEO WITH ITS SOUND its whole length up to `maxSound` = 8 s); `on: false` turns the rule off (a post's own `pictureOnly: true` still wins) | — | `umtool posts picture-reply <p> on=off` · `maxSound=10 max=5` (`k=` the default) · `--in-take <take>` | — | +## Screens: a post's text screenshots + +A post's text SCREENSHOTS -- a DM exchange or an email shown in its video, an image that is a screenshot of a chat, a +letter, another post -- are first-class parts of the post ([report-video.md](report-video.md#screens-text-screenshots-read-as-part-of-the-post); +`report-to-video/post-screens.mjs`): transcribed once, checked by a person, drawn legibly on the card after its words +and read -- whole or in excerpts -- in the voices of the people in them, each line lit while it is said. No model: every +line is typed or pasted. A screen is drawn only once the item's read reads it (`posts screen … read`); until then the +lint says so. Nothing in a screen is drawn that is not read, unless `unread: "dim"`. + +| Knob | In umtool | From a terminal | Route | +|---|---|---|---| +| `screens[]` -- add one: `{ id, media, at?, kind, title?, lines, read }` (`media` the attachment it is in; `at` the seconds of a video or GIF it is visible in; `kind` dm \| email \| post \| text) | post bench, **screens**: **Add a screen**, pick the attachment, scrub the video (**visible from here** / **to here**), paste the lines | `umtool posts screen <p> <item> add --media 0 --at 3.5,8 --kind dm --from lines.txt` (or `--line "who: words"`…) | `POST /api/report/post-item {project, op: "set", id, patch: {screens: [...]}, token}` | +| a line: `who` (a handle or a name: the post's author, else another speaker), `side` (left \| right; absent: hers right, others left), `text`, `time`, `redact: true` (never drawn nor read) | the lines table: who, side, words, time, redact | `… set s1 line.2.who=TheQuartering line.2.side=left line.4.redact=on line.add="who: words" line.3=off` | same | +| `read` -- `"all"`, `"none"` (transcribed only: not drawn, not read), or `[{ line, text? }]` (`text` an EXCERPT: a run of that line's own words, drawn "…excerpt…") | the **read** ticks, the excerpt box under a ticked line | `… set s1 read=0,2,5 read.5="I think you're 400 pounds"` (`read.<n>=on\|off`) | same | +| `unread` -- the lines not read: `"omit"` (default: left out, a "⋯" row where they were) or `"dim"` (drawn dim, never lit) | **lines not read** | `… set s1 unread=dim` | same | +| `title` (the header's word in place of the kind's), `ref` (a screenshot of a post: the archived post it pictures) | **title** | `… set s1 title="Refund email"` · `ref=<channel>/<postId>` | same | +| `checked: { by, at }` -- the transcription read against the screenshot (a screen not checked is a lint WARNING; new words take it away) | **checked** | `… check s1 [--by <name>]` · `--undo` | same | +| THE READ -- her words, then each read line in its speaker's voice; her own line from the take that plays (never made again); a line from an existing take | the command shown under the screens | `umtool posts screen <p> <item> read [--post-take n] [--line-take screen:s1:3=4]… [--dry-run]` (= `posts narrate <p> <item> --take --thread`, `--no-screens` leaves them out) | — | + +What is never drawn nor said, marked or not -- in a line, a speaker, a time or a title: an e-mail address, a phone-style +run of nine digits or more or a local number, an order / confirmation / tracking / account / card / code value, a +"#1234", a token of six digits or more -- never an amount, a decimal, a date or a time -- a bar on the card; the lint +names the line (`line.<n>.redact=on` takes the whole line out). A line edited, removed or moved under a read refuses the +read until it is made again (`posts screen … read`, which keeps the playing read's options). A speaker who is not the post's author is drawn under the item's +privacy rule (named when a subject, or with the item's `redact: false`; else blurred -- the lint says so); an anonymous +character under its shown name (a `who` written as an anonymous author's display name is refused: write the handle). + A LONG READ on a card alone (no attachment, or a picture-only one in the card): words that do not fit the card at any size are drawn at a reading size (`POST_LONG_READ_SIZE`, 36 px of a 1080 frame) and panned by read-follow -- never shrunk to fit; beside an attachment they keep read-follow's minimum (28 px). diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md @@ -1387,6 +1387,95 @@ One standing between two read pieces has no beat (drawn in its card, it gives wa carried in from the item before is that item's (no beat). `render.posts.pictureReply.on: false` restores the old drawing (a chip, the picture in the slot) for every post that does not say `pictureOnly: true`. +### Screens: text screenshots read as part of the post + +A post's text screenshots are part of the post, not transparent decoration (operator, 12 Nov, on quartering-diet +rev9-a9, Savvy's scale video carrying four X DM exchanges and a refund email as semi-transparent overlays that "flash by +unreadable": "the screenshots should be treated as extensions of the post rather than transparent, probably read and +probably with excerpts because it's long text. You can show it alongside the video in the tweet slot as you read" -- +"The 'read text screenshots as posts' ability in different variations should be first class, it's a very common +pattern"). `report-to-video/post-screens.mjs` is the model (pure); the thread read, read-follow, the plan and the card +carry it. + +```jsonc +"screens": [{ + "id": "s1", "media": 0, "at": [3.5, 8], // the attachment it is in; a video's seconds it is visible in + "kind": "dm", // dm | email | post | text + "title": "Refund email", // optional: the header's word in place of the kind's + "source": "transcribed", "checked": { "by": "operator", "at": "2026-11-12T10:00:00Z" }, + "unread": "omit", // the lines not read: left out (a "⋯" row) | "dim" + "lines": [{ "who": "TheQuartering", "side": "left", "text": "what's your email so I can refund your order", "time": "11:32 AM" }, + { "who": "MadamSavvy", "text": "where is my scale video" }, + { "text": "Order #4419283", "redact": true }], + "read": [{ "line": 0 }, { "line": 1, "text": "my scale video" }] // or "all" | "none" (transcribed only) +}] +``` + +**The variations.** (1) INSIDE THE POST's VIDEO: `at` names the span the screen is visible; while its lines are read +the card shows it typeset and the slot plays that span -- its LAST FRAME HELD when the read outlasts it (a looped span +would replay the overlay fading in and out). (2) AN IMAGE THAT IS A SCREENSHOT: the image stays in the slot while the card +shows its transcript. (3) A SCREENSHOT OF ANOTHER POST (`kind: "post"`): drawn as a post tile from its own lines, +labelled "screenshot"; `ref` names the archived post it pictures (the lint points at `posts set-item … link.add=`, which +draws the real one -- not drawn from the archive here). (4) A PICTURE-ONLY POST whose picture is text may carry a screen +on its own picture: its read's parts then light the typeset lines under the picture in its card (no slot: the picture +stays in the card) instead of reading `media:0`, all dim. + +**The read** (`lib/report/postThreadRead.mjs`). Each read line is a piece of the THREAD READ after his words, in the +screens' order and their lines', its role `screen:<id>:<n>` (n the line's index; stored on the take's parts -- a short +DM line is never matched by its words); `who` resolves as a thread read's pieces do (post-say.mjs): the post's author +(by handle or name) in her own voice, a handle or a character's NAME (the project's characters, then the cast) in +theirs, anyone else in the context default. Two lines of one screen are joined 0.35 s apart (`SCREEN_LINE_GAP`), a new +screen 0.8 s. `umtool posts screen <p> <item> read` makes it with her own line from the take that plays when that is not +a thread read (or the take the thread read used): a recorded or picked read of her words is never made again; each +synthesized line is cached by its words and voice (an edited line re-synthesizes that line alone). `--line-take +screen:<id>:<n>=<take n>` takes a LINE from an existing take of the item (a recording of that line, or one converted +to its speaker's character), as `--post-take` does her words. The item is as long as its read. + +**The card.** A screen the take reads is a TILE of the threaded card after his post: as its first line comes his post +shrinks and dims to a strip (`thread.shrink`, `.dim`), the screen is revealed under it; each read line is a +read-follow block -- lit while it is said, dimmed back after -- and a long screen pans line by line, never shrinks; +when the next screen comes the one read COLLAPSES away (stacked, they would bury the one being read). A header says what +it is and that it is transcribed, with the author's SHOWN name ("DMs shown in Savvy's video · transcribed"; an anonymous +author's shown name, "the post's" for a blurred one; "excerpt" when lines or words are left out), and a BADGE ("DMs · +transcribed") is pinned to the card's top-right while a screen is up (`followStateAt`'s `screen`) -- so it never reads +as a real capture, even panned. A DM is bubbles (hers right in the accent, the others left, the speaker's name on first +use, the time small); an email or text a quiet letter block (a From line when the speaker changes); a post a post tile. +The page's own fonts and palette; lines at 30 px of a 1080 frame. + +**What is never drawn or said.** A line marked `redact: true`; and, marked or not, in a line's words, its speaker, its +time and the screen's title: an e-mail address (any script, or spelt out "x at y dot com"), a phone-style run of nine +digits or more (a card, a phone, a spaced SSN; dashes, dots, middle dots, slashes, fullwidth digits) or a local number +(555 1234), the value after order / confirmation / tracking / reference / account / card / code / cvv / exp / date of +birth ("is", ":", "#", "ending in" between) or a "#1234", a token of six digits or more -- never an amount ($104.90, +1,000,000), a free-standing decimal, a PLAUSIBLE date (a 19xx/20xx year with a month and a day, or a month and a day +then a year: 11/02/2026, 2026-11-02; a 3-2-4 group is never one) or a time (`shapeSpans`) -- masked with the redaction's bar, dropped from the read; the +lint names the line (never the value). A pasted `who: words` never splits a shape into a speaker ("Order number: 4419" +stays one line); two adjacent lines whose digits together make a shape ("4111 1111" / "1111 1111") are a lint +WARNING naming the lines. The project's redaction terms and slur filter mark a screen's words and speakers as a post's. +A speaker who is not the post's author is named when the item names them a subject or says `redact: false`, else +blurred (the lint says so); an anonymous one is drawn under the shown name and the words' @handles anonymised +(post-anon.mjs); a `who` written as an anonymous author's display name is an ERROR. + +**The guard and the lint.** A part that reads a line the screen does not read (left out, redacted, `read: "none"`) or a +screen the item does not carry is REFUSED by the build (`threadReadErrors`), with the fix -- the writer lets the screen +change first (the read is re-made from it). So is a part whose line CHANGED since the read (`screenLineChanged`: each +part stores the line and the speaker it was made from, `parts[k].line` / `.speaker`; edited, removed, moved or given to +another speaker, the old audio never plays under new lit text), and a part that SAYS a shape. The BUILD's enforced lint +(build-video.mjs enforcedLint: every build and every take's render) refuses them (`validateScreenReads`), judged on the +cut AS WRITTEN -- never the anonymised copy it draws. A read whose screens changed while it was being made is not kept; a +`--line-take` is refused unless its take says its line word for word (one short plain word more and one fewer of slack), +holding no shape, no @handle, no anonymous handle and no redacted term (its part's words are the take's own, so every +check reads what the audio says); it is re-attached on the next read only while its line says the same. An excerpt no longer in its line as drawn (after the redaction and +anonymity passes, which rewrite excerpts as they rewrite lines) is never drawn whole: the line is left out and the +build refused up front (`screenDrawErrors`, in the enforced lint; again in the segment for the redaction's). WARNINGS: a transcription not checked; a masked shape; read lines the picked +take does not read ("make the read"); screens on an item not narrated (not drawn: a screen is drawn and read with the +item's read); a speaker blurred by the privacy rule; a screenshot of a post naming an archived one. + +**Byte-identical without.** An item with no `screens` draws, plans and keys exactly as before +(`post-screens-pin.test.mjs`); a segment with screens carries `screens: POST_SCREEN_DRAW_V` in its key. + +The knobs: [knobs.md](knobs.md#screens-a-posts-text-screenshots); the CLI: `umtool posts screen <p> <item> +list|add|set|rm|check|read` ([cli.md](cli.md)); the post bench's **screens** section. ### The combo counter diff --git a/umtool/e2e/post-screens.spec.ts b/umtool/e2e/post-screens.spec.ts @@ -0,0 +1,121 @@ +import { test, expect, type Page } from "@playwright/test"; +import { copyFileSync, existsSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import * as urls from "./urls"; + +// --------------------------------------------------------------------------- +// A POST's SCREENS ON THE POST BENCH (report-to-video/post-screens.mjs; knobs.md, "Screens: a post's text screenshots"; +// operator, 12 Nov: "The 'read text screenshots as posts' ability in different variations should be first class"): +// - the bench's screens section adds a screen in the post's video, takes pasted lines, a line not read, an excerpt, +// the transcription checked -- saved by the bench's Save through the item's one writer, no model anywhere; +// - a narrated item whose read reads the screen draws it on the card after its words: typeset, its line being read +// lit, "· transcribed" in its header and on the card's badge while it is up. +// Fixture: e2e/fixtures/post-narration-fixture.mjs's p-11 (a 4 s video, a 2 s take), rewritten here. +// +// POST_SCREENS_SHOTS=<dir> screenshots there +// --------------------------------------------------------------------------- + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const REPORTS = path.join(HERE, "..", ".e2e-song", "reports"); +const DIR = path.join(REPORTS, "post-narration-fixture"); +const MANIFEST = path.join(DIR, "video.manifest.json"); +const PROJECT = "reports/post-narration-fixture"; +const SHOTS = process.env.POST_SCREENS_SHOTS ?? null; + +type Line = { who?: string; side?: string; text: string; time?: string; redact?: boolean }; +type Screen = { id: string; media: number; at?: number[]; kind: string; lines: Line[]; read: unknown; checked?: { by: string } }; +const item = (id: string) => (JSON.parse(readFileSync(MANIFEST, "utf8")) as { timeline: Array<{ id: string; screens?: Screen[] }> }).timeline.find((e) => e.id === id); + +test.beforeAll(() => { + if (!existsSync(`${MANIFEST}.pristine`)) copyFileSync(MANIFEST, `${MANIFEST}.pristine`); +}); +test.beforeEach(() => { + test.setTimeout(120_000); + copyFileSync(`${MANIFEST}.pristine`, MANIFEST); + rmSync(path.join(DIR, "revisions"), { recursive: true, force: true }); + rmSync(path.join(DIR, "notes.json"), { force: true }); +}); +test.afterAll(() => { + if (existsSync(`${MANIFEST}.pristine`)) copyFileSync(`${MANIFEST}.pristine`, MANIFEST); +}); + +const panel = (page: Page) => page.locator("[data-post-screens-panel]"); + +test("the bench's screens: add one in the video, paste its lines, leave one unread, trim an excerpt, mark it checked -- Save writes it", async ({ page }) => { + await page.setViewportSize({ width: 1366, height: 1100 }); + await page.goto(urls.postBenchHref(PROJECT, "p-11")); + await expect(panel(page)).toBeVisible({ timeout: 15_000 }); + await expect(panel(page)).toHaveAttribute("data-screens", "0"); + await panel(page).locator("[data-post-screens-add]").click(); + const sc = page.locator('[data-post-screen="s1"]'); + await expect(sc).toBeVisible(); + await expect(sc.locator("[data-post-screen-kind]")).toHaveValue("dm"); + // In the video: the seconds it is visible. + await sc.locator("[data-post-screen-at-from]").fill("0.5"); + await sc.locator("[data-post-screen-at-to]").fill("3.5"); + await expect(sc.locator("[data-post-screen-scrub] video")).toHaveCount(1); + // Pasted lines: who: words | time, her side by hand, a line with a shape the card masks. + await sc.locator("[data-post-screen-paste]").fill( + ["TheQuartering: what's your email so I can refund your order | 11:32 AM", "[right] narrsubject: where is my scale video | 11:53 AM", "TheQuartering: you HONESTLY believe that I have lied about weight loss?", "- reply to support@coffee.example"].join("\n"), + ); + await sc.locator("[data-post-screen-paste-add]").click(); + await expect(sc.locator("[data-post-screen-line]")).toHaveCount(4); + await expect(sc.locator('[data-post-screen-masked="3"]')).toContainText("email"); + // Line 3 not read; line 2 read as an excerpt. + await sc.locator('[data-post-screen-read="3"]').uncheck(); + await sc.locator('[data-post-screen-excerpt="2"]').fill("I have lied about weight loss"); + await sc.locator("[data-post-screen-checked]").check(); + await expect(panel(page).locator("[data-post-screens-errors]")).toHaveCount(0); + await expect(panel(page).locator("[data-post-screens-read-cmd]")).toContainText("umtool posts screen reports/post-narration-fixture p-11 read"); + if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "post-screens-bench.png"), fullPage: true }); + await page.locator("[data-post-bench-save]").click(); + await expect.poll(() => item("p-11")?.screens?.length ?? 0).toBe(1); + const saved = item("p-11")!.screens![0]; + expect(saved.at).toEqual([0.5, 3.5]); + expect(saved.lines.map((l) => `${l.who ?? "-"}|${l.side ?? "auto"}|${l.time ?? ""}`)).toEqual(["TheQuartering|auto|11:32 AM", "narrsubject|right|11:53 AM", "TheQuartering|auto|", "-|auto|"]); + expect(saved.read).toEqual([{ line: 0 }, { line: 1 }, { line: 2, text: "I have lied about weight loss" }]); + expect(saved.checked?.by).toBe("operator"); + // The lint's word: its read does not read it yet. + await expect(panel(page).locator("[data-post-screens-warnings]")).toContainText("does not read screen s1"); + // An excerpt that is not the line's own words is refused on the page before Save. + await page.locator('[data-post-screen="s1"] [data-post-screen-excerpt="2"]').fill("I lied about weight"); + await expect(panel(page).locator("[data-post-screens-errors]")).toContainText("is not a run of line 2's words"); +}); + +test("a read that reads the screen draws it on the card after its words: typeset, the line read lit, transcribed in its header and on the badge", async ({ page }) => { + // Its 2 s take, its parts' roles stored: his words, then the screen's two lines. + const m = JSON.parse(readFileSync(MANIFEST, "utf8")); + const e = m.timeline.find((x: { id: string }) => x.id === "p-11"); + e.screens = [{ id: "s1", media: 0, at: [0.5, 3.5], kind: "dm", read: "all", lines: [{ who: "TheQuartering", text: "hop on the scale fatso", time: "12:18 PM" }, { who: "narrsubject", text: "you first" }] }]; + e.narration.script = "The video speaks for itself."; + e.narration.takes[0].parts = [ + { n: 1, para: 0, text: "The video speaks for itself.", start: 0, seconds: 0.6, role: "post" }, + { n: 2, para: 100, text: "hop on the scale fatso", start: 0.8, seconds: 0.5, role: "screen:s1:0" }, + { n: 3, para: 200, text: "you first", start: 1.5, seconds: 0.5, role: "screen:s1:1" }, + ]; + e.redact = false; + writeFileSync(MANIFEST, JSON.stringify(m, null, 2) + "\n"); + await page.setViewportSize({ width: 1366, height: 1100 }); + await page.goto(urls.postBenchHref(PROJECT, "p-11")); + const frame = page.frameLocator('[data-post-card-frame="read"]'); + await expect(frame.locator("body")).toHaveAttribute("data-post-ready", "1", { timeout: 15_000 }); + await expect(frame.locator('[data-post-screen="s1"]')).toHaveCount(1); + await expect(frame.locator('[data-post-screen="s1"] [data-screen-transcribed]')).toContainText("transcribed"); + await expect(frame.locator('[data-post-screen="s1"] .stitle')).toContainText("DMs shown in Narr Subject's video"); + // Its second line being read (the item's 0.4 s lead + 1.5 s): lit, the badge up. + await page.locator("[data-post-bench-scrub]").fill("2.1"); + await expect(async () => { + const op = await frame.locator('[data-screen-badge="s1"]').evaluate((el) => Number(getComputedStyle(el).opacity)); + expect(op).toBeGreaterThan(0.9); + }).toPass({ timeout: 10_000 }); + await expect(frame.locator('[data-screen-badge="s1"]')).toContainText("DMs · transcribed"); + const opOf = (n: number) => frame.locator(`[data-screen-line="${n}"] .sbub`).evaluate((el) => Number(getComputedStyle(el).opacity || "1")); + await expect(async () => { + expect(await opOf(1)).toBeGreaterThan(0.95); + expect(await opOf(0)).toBeLessThan(0.9); + }).toPass({ timeout: 10_000 }); + // Shown by name: the item says redact: false. + await expect(frame.locator('[data-screen-line="0"] .sname')).toHaveText("TheQuartering"); + if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "post-screens-card.png") }); +}); diff --git a/umtool/lib/cli/groups.mjs b/umtool/lib/cli/groups.mjs @@ -1005,6 +1005,9 @@ export const GROUPS = [ " its manifest read as the take's, the write in takes/<take>/take.json's patch (an undo point of the take's,", " `umtool timeline <p> --take <take> undo`), the project's manifest untouched; set-item/roles/reread/fx", " take --take <take> for it too (narrate's --take is a new read)", + " umtool posts screen <project> <item> list | add --media <i> [--at a,b] --kind dm|email|post|text [--from <file>] [--line …]…", + " | set <id> <key>=<value>… | rm <id> | check <id> [--by n] [--undo] | read [--post-take n] [--line-take r=n]…", + " a post's SCREENS: its text screenshots transcribed, drawn on its card and read after its words", " 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", @@ -1039,12 +1042,14 @@ export const GROUPS = [ "**one phrase of an approved read re-voiced**, the rest untouched (`lib/report/postRevoice.mjs`; operator, 5 Nov: the countdown gabbled, and pauses cut into it \"choppy\"): the phrase found in the picked take's word timings as `--pause` finds a word (`#n`, `--target`; inside one part), the original cut from just before its first word to just after its last -- each cut at the quietest 10 ms within ±40 ms of the boundary, and when that is still speech within ±0.15 s (never inside the phrase as timed; a nearer quiet preferred) -- **`--say` alone synthesized by the editor's TTS** (narrate-via-editor; the engine of the root take, the voice of the part the phrase is in, `--voice` overrides; the project's lexicon, redaction and slur filter applied; kept in `narration/parts-cache/` like a thread read's parts, so asking again is free), its lead and tail of silence trimmed, loudness-matched to the speech in the 2 s either side (±6 dB) and spliced in with equal-power crossfades (`--xfade`, 0–0.2 s) at both joins, at the take's rate and layout. The length is exact: the take − the span cut + the piece. Everything after moves by the difference (its words, the part holding the span, the later parts) so zooms, captions, slams, beeps and the read-follow stay on their words; the new words are timed from the piece's speech and marked `estimated` (a later `posts narrate … --words` refines them); the part's text and the script say `--say`. A derived take (`steps: [{op: \"revoice\", revoice: {word, count, words, phrase, say, said, voice, engine, from, to, seconds, gain, xfade, key}}]`) picked in ONE write; re-voicing exactly the words a re-voice put in re-cuts from the take before. `--dry-run`: the span (words, seconds), each cut and its level, what is said and in which voice, the length change when the piece is cached -- no TTS. A cut still in speech is warned of (the word timings off there): `--splice 65.03-66.00` sets the cuts (either side may be left out). `--in-take <t>` puts it in a take's read. No word timings (naming `posts narrate <p> <item> --words`), the phrase not read or across two parts, a recorded read, the TTS failing: **exit 1**; no `--say`, a bad voice, crossfade or splice, `--revoice` with another reread form: **exit 2**"], ["`posts progress <project> [auto\\|on\\|off\\|default] [--json]`", "the cut's **progress bar** default (`render.posts.progress`, `updatePostProgressRender`; [report-video.md](report-video.md#the-progress-bar)); bare, which items draw it"], + ["`posts screen <project> <item> list\\|add\\|set\\|rm\\|check\\|read …` (add: `--media <i> [--at <from>,<to>] --kind dm\\|email\\|post\\|text [--id <id>] [--title \"…\"] [--from <file>] [--line \"who: words\"]… [--read all\\|none\\|<n>,…] [--unread omit\\|dim] [--ref <channel>/<postId>]`; set: `<id> kind= title= media= at=<a>,<b>\\|off unread= ref= read=all\\|none\\|<n>,… read.<n>=\"excerpt\"\\|on\\|off line.add=\"who: words\" line.<n>=off line.<n>.who= line.<n>.side=left\\|right\\|auto line.<n>.text= line.<n>.time= line.<n>.redact=on\\|off [--from <file>]`; check: `<id> [--by <name>] [--undo]`; read: `[--post-take <n>] [--line-take screen:<id>:<line>=<n>]… [--voice-for h=v]… [--force] [--dry-run]`; `--json`, `--dry-run`, `--take <take>`)", + "a post's **SCREENS** ([report-video.md](report-video.md#screens-text-screenshots-read-as-part-of-the-post), [knobs.md](knobs.md#screens-a-posts-text-screenshots), `post-screens.mjs`): the text screenshots its attachments carry -- a DM exchange or an email shown in its video (`--at`: the seconds it is visible), an image that is a screenshot -- transcribed once (`--from`: a JSON screen, or text lines `[right] who: words \\| time`, `- words`, `[redact] …`), checked by a person (`check`; a screen not checked is a lint WARNING; new words take the check away), and read whole or in excerpts. Each write is the post item's one writer (`updatePostItem`'s `screens`, one undo point), refused in the build's words (**exit 1**); an attachment a screen is in cannot be removed. An e-mail address, a phone number, an order or long number in a line is masked on the card and never said. `read` makes the THREAD READ with the screens (as `posts narrate <p> <item> --take --thread`): her own line from the take that plays (or the one the thread read used; `--post-take n` another), never made again; each read line in its speaker's voice (`who`: the post's author in hers, a handle or a character's name in theirs); `--line-take` takes a line from the item's take n (a recording of it). Usage errors: **exit 2**"], ["`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: a reply's leading @handles, links, emoji dropped -- a handle typed inside the message is kept and said \"at <handle>\", the lexicon first; `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**) A `--take` whose read says a slur the cut BEEPS is word-timed by the editor's transcription before it is kept -- never waited on: with the transcription lane held (as while Orpheus runs) the take is kept as read and the timing deferred (it says so, naming `posts narrate <p> <item> --words` to run after the release; the build refuses the take until then), and a timing still queued after 5 min is deferred the same way. An excerpted item (`posts set-item … excerpt=`) reads its spans."], - ["`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] [--speed s] [--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 item's own character, this video's characters and voice map, the cast: `cast project`; his own: the narrator's) and at its character's speed (its synthetic preset's; `--speed`: every part at that one; Orpheus has none; a part at another speed is another cached part), 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). **`--post-take <n>`**: his OWN line is the item's take n (as `--list` numbers them) -- a recording, or one converted to his character's voice -- not synthesized; the context pieces are, in their authors' voices, and each part of the new take records where it came from (a synthesized part its parts-cache file and voice; the take's part its file and `take`: that take's id; the read's `postTake`). A thread take, or one whose file is gone: **exit 1**. 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 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] [--speed s] [--no-screens] [--line-take screen:<id>:<line>=<n>]… [--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 item's own character, this video's characters and voice map, the cast: `cast project`; his own: the narrator's) and at its character's speed (its synthetic preset's; `--speed`: every part at that one; Orpheus has none; a part at another speed is another cached part), 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). **`--post-take <n>`**: his OWN line is the item's take n (as `--list` numbers them) -- a recording, or one converted to his character's voice -- not synthesized; the context pieces are, in their authors' voices, and each part of the new take records where it came from (a synthesized part its parts-cache file and voice; the take's part its file and `take`: that take's id; the read's `postTake`). A thread take, or one whose file is gone: **exit 1**. 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** Its SCREENS (`posts screen`) are read after his words, each line in its speaker's voice (`--no-screens`: left out); `--line-take screen:<id>:<line>=<n>` takes a line from the item's take n as `--post-take` does his own"], ["`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 character <project> <item> [<character> \\| --clear] [--json]`", diff --git a/umtool/lib/cli/verbs.mjs b/umtool/lib/cli/verbs.mjs @@ -502,6 +502,14 @@ function posts() { pick("--pitch", ["target", "source", "contour"], { help: "a convert's pitch (--recording, --derive)" }), num("--semitones", { help: "-12…12, moves a followed pitch" }), dry(), pairs({ required: false, help: "the mix: lead= tail= linger= rate= …, one per line" }), inTake(), ], { ...Q, ...POST_ITEM }), + p("screen", "draft", "a post item's text screenshots: transcribed, drawn, read", [ + item(), pick("op", ["list", "add", "set", "rm", "check", "read"], { required: true }), arg("screen", { required: false, help: "the screen's id (set, rm, check)" }), + num("--media", { help: "add: the attachment it is in" }), opt("--at", { help: "add: <from>,<to> seconds of a video" }), pick("--kind", ["dm", "email", "post", "text"]), opt("--title"), + many("--line", { repeat: true, item: "line", help: "add: a line `who: words`, one per line" }), + opt("--read", { help: "add: all, none or line numbers" }), pick("--unread", ["omit", "dim"]), opt("--by", { help: "check: who checked it" }), bool("--undo", "check: not checked"), + num("--post-take", { help: "read: her own line is this take of the item" }), many("--line-take", { repeat: true, item: "role=n", help: "read: screen:<id>:<line>=<take n>, one per line" }), + pairs({ required: false, help: "set: kind= title= at= read= read.<n>=\"excerpt\" line.<n>.who= …, one per line" }), dry(), inTake(), + ], { shape: "posts screen <project> <item> <op>", ...POST_ITEM }), p("say", "draft", "the pronunciation lexicon", [pick("op", ["ls", "add", "remove", "try", "stale"], { required: true }), arg("word", { required: false, allowAt: true, help: "the word or phrase (try: the text)" }), arg("spoken", { required: false }), bool("--case"), opt("--item"), opt("--note")], { shape: "posts say <project> <op>" }), p("character", "draft", "the character one post item's own read is made with", [item(), arg("character", { required: false, help: "a character's id (this video's own, else the cast's); none: print it" }), bool("--clear", "by its author's handle again")], POST_ITEM), p("voices", "draft", "the voice map a thread read uses", [pick("op", ["ls", "set", "remove"], { required: true }), arg("handle", { required: false, help: "a handle, or *" }), arg("voice", { required: false })], { shape: "posts voices <project> <op>" }), diff --git a/umtool/lib/report/castProject.mjs b/umtool/lib/report/castProject.mjs @@ -184,6 +184,13 @@ export function threadArgvOf(read, { handles = [], author = null, takes = null } const at = Array.isArray(takes) ? takes.findIndex((t) => t?.file === read.postTake.file) : -1; a.push("--post-take", String(at >= 0 ? at + 1 : read.postTake.n)); } + // Its screens (post-screens.mjs): left out, or lines from takes (found again by their files). + if (read.screens === false) a.push("--no-screens"); + for (const [r, x] of Object.entries(read.lineTakes ?? {})) { + if (typeof x?.file !== "string") continue; + const at = Array.isArray(takes) ? takes.findIndex((t) => t?.file === x.file) : -1; + a.push("--line-take", `${r}=${at >= 0 ? at + 1 : x.n}`); + } return a; } diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs @@ -2898,7 +2898,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", "pictureOnly", "excerpt"]); +export const POST_ITEM_KNOBS = Object.freeze(["hold", "mediaLayout", "panel", "redact", "follow", "thread", "scene", "progress", "pictureOnly", "excerpt", "screens"]); /** 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", "enter"]); /** A context post's knobs (`quoted`, `parents[i]`): the operator's paraphrase of its words. */ @@ -2993,6 +2993,7 @@ export async function updatePostItem(dir, id, patch, { token = null } = {}) { if (isObj(patch.media)) { const drop = new Set(Object.entries(patch.media).filter(([, v]) => v === null).map(([k2]) => Number(k2))); if (drop.size) { + remapScreens(e, drop, id); e.media = (e.media ?? []).filter((_, n) => !drop.has(n)); if (!e.media.length) delete e.media; } @@ -3012,6 +3013,7 @@ export async function updatePostItem(dir, id, patch, { token = null } = {}) { const show = patch.mediaShow !== undefined ? idx(patch.mediaShow, "mediaShow") : new Set(); for (const n of hide) if (!isObj(on[n])) throw new Error(`${id} shows no attachment ${n}${on.length ? ` (0–${on.length - 1})` : ""}`); for (const n of show) if (!isObj(off[n])) throw new Error(`${id} has no attachment switched off at ${n}${off.length ? ` (0–${off.length - 1})` : ""}`); + remapScreens(e, hide, id); const media = [...on.filter((_, n) => !hide.has(n)), ...off.filter((_, n) => show.has(n))]; const mediaOff = [...off.filter((_, n) => !show.has(n)), ...on.filter((_, n) => hide.has(n))]; if (media.length) e.media = media; @@ -3099,19 +3101,36 @@ export async function updatePostItem(dir, id, patch, { token = null } = {}) { } // NEVER NARRATE HIDDEN TEXT (post-thread.mjs): a change to what the card shows that leaves a part of its read // off the screen is refused, with the fix (one it had before is the guard's, not this write's). - if ("thread" in patch || "follow" in patch || "parents" in patch || "links" in patch || "linksAdd" in patch) { + // An attachment removed or hidden matters to the guard only for an item with SCREENS (it moves their indices). + const screensMoved = (Array.isArray(was.screens) && was.screens.length > 0) && ((isObj(patch.media) && Object.values(patch.media).includes(null)) || "mediaHide" in patch); + if ("thread" in patch || "follow" in patch || "parents" in patch || "links" in patch || "linksAdd" in patch || "screens" in patch || screensMoved) { // With the item before it and the scene its run leaves on screen (post-conversation.mjs; a fresh list, so never // a context worked out before this write). const ctx = planContext(m.timeline.slice(), i, m.render); const guard = (x) => threadReadErrors(x, m.render, { ...ctx, followOn: followKnobs(x, m.render).on }); const had = new Set(guard(was)); - const now = guard(e).filter((x) => !had.has(x)); + // A SCREEN's line the picked take reads that the screen no longer reads (post-screens.mjs) is the build's to refuse, + // not this write's: the read is re-made FROM the screens (umtool posts screen <p> <item> read), so they change first. + const now = guard(e).filter((x) => !had.has(x) && !/ reads (?:line \d+ of )?screen [a-z0-9-]+,/.test(x)); if (now.length) throw new StructureRefused(now); } return { id, at: i, entry: e }; }); } +/** + * ITS SCREENS (post-screens.mjs) as attachments `drop` leave the item: a screen in one of them REFUSES the write (remove + * the screen first); the others' indices move down past the ones that go. In place. + */ +function remapScreens(e, drop, id) { + if (!Array.isArray(e.screens) || !drop.size) return; + for (const sc of e.screens) { + if (!isObj(sc) || !Number.isInteger(sc.media)) continue; + if (drop.has(sc.media)) throw new StructureRefused([`${id}: attachment ${sc.media} carries screen ${sc.id} -- remove the screen first (umtool posts screen <p> ${id} rm ${sc.id})`]); + } + for (const sc of e.screens) if (isObj(sc) && Number.isInteger(sc.media)) sc.media -= [...drop].filter((n) => n < sc.media).length; +} + // ---- the combo counter (report-to-video/post-combo.mjs) -------------------- /** diff --git a/umtool/lib/report/postNarrationCli.mjs b/umtool/lib/report/postNarrationCli.mjs @@ -54,7 +54,8 @@ export const NARRATE_USAGE = [ " umtool posts narrate <project> <item> --derive <n> --op enhance|convert [--engine e] [--voice v] [--as <character>]", " [--pitch target|source|contour] [--semitones <n>]", " 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] [--speed s] [--post-take <n>] [--force] [--dry-run]", + " [--no-linked] [--read-seen] [--voice-for <handle>=<voice>]… [--voice v] [--speed s] [--post-take <n>]", + " [--no-screens] [--line-take screen:<id>:<line>=<n>]… [--force] [--dry-run]", " umtool posts narrate <project> <item> … --in-take <take> any of these on a TAKE of the project: the pick, a new", " read (--take, --thread), the script, the mix -- written into the take's patch (umtool posts --help)", " umtool posts narrate <project> --all --draft-scripts [--force] | --all --take [--limit N]", @@ -230,10 +231,13 @@ export function normalizeParts(raw) { seconds: r3(p.seconds), ...(Number.isFinite(Number(p.gapBefore)) ? { gapBefore: r3(p.gapBefore) } : {}), // The text it reads (post-thread.mjs), the voice and the piece the batch read it in. - ...(typeof p.role === "string" && /^(post|quoted|parent:\d|media:\d|linked:\d)$/.test(p.role) ? { role: p.role } : {}), + ...(typeof p.role === "string" && /^(post|quoted|parent:\d|media:\d|linked:\d|screen:[a-z0-9][a-z0-9-]{0,23}:\d{1,2})$/.test(p.role) ? { role: p.role } : {}), ...(typeof p.voice === "string" && /^[A-Za-z0-9][A-Za-z0-9_.+-]{0,63}$/.test(p.voice) ? { voice: p.voice } : {}), ...(typeof p.engine === "string" && /^(orpheus|kokoro|espeak-ng)$/.test(p.engine) ? { engine: p.engine } : {}), ...(Number.isInteger(p.piece) && p.piece >= 0 ? { piece: p.piece } : {}), + // A screen line's part (post-screens.mjs): the line and the speaker it was made from (the stale-read guard's). + ...(typeof p.line === "string" ? { line: p.line } : {}), + ...(typeof p.speaker === "string" ? { speaker: p.speaker } : {}), })); } @@ -695,9 +699,12 @@ export async function narrateCommand(project, words, flags, { json = false, dryR voice: str("--voice"), engine: str("--engine"), speed: speedFlag(str), note: str("--note"), force: flags.has("--force"), hold: !flags.has("--no-hold"), dryRun, // His own line from an existing take (its number as --list shows it), the context synthesized around it. postTake: str("--post-take"), + // ITS SCREENS (post-screens.mjs): read after his words unless --no-screens; a line from a take (--line-take). + screens: !flags.has("--no-screens"), lineTakes: lineTakesOf(multi("--line-take")), }); } if (str("--post-take") !== null) throw new NarrateError("--post-take is a thread read's (umtool posts narrate <p> <item> --take --thread --post-take <n>)"); + if (multi("--line-take").length) throw new NarrateError("--line-take is a thread read's (umtool posts narrate <p> <item> --take --thread --line-take screen:<id>:<line>=<n>)"); if (flags.has("--thread")) throw new NarrateError("--thread goes with --take (umtool posts narrate <p> <item> --take --thread)"); if (flags.has("--take")) { const r = await makeTake(project, e, { @@ -731,6 +738,17 @@ export async function narrateCommand(project, words, flags, { json = false, dryR return 0; } +/** `--line-take screen:<id>:<n>=<take n>` words as `{ <role>: <take n> }`; throws naming a bad one. */ +export function lineTakesOf(list) { + const out = {}; + for (const raw of (Array.isArray(list) ? list : []).flatMap((x) => String(x).split(",")).map((x) => x.trim()).filter(Boolean)) { + const m = /^(screen:[a-z0-9][a-z0-9-]{0,23}:\d{1,2})=(\d{1,3})$/.exec(raw); + if (!m) throw new NarrateError(`--line-take takes screen:<id>:<line>=<take n> (got ${raw})`); + out[m[1]] = Number(m[2]); + } + return out; +} + export const CHARACTER_USAGE = [ "usage: umtool posts character <project> <item> [<character> | --clear] [--json]", " THE CHARACTER ONE POST ITEM's OWN READ IS MADE WITH (its `narration.character`): the id of one of this video's", diff --git a/umtool/lib/report/postPause.mjs b/umtool/lib/report/postPause.mjs @@ -62,7 +62,7 @@ export const PAUSE_CUT_BACK = 0.04; export const PAUSE_FADE = 0.01; /** How far either side of an @time pause the quietest cut is looked for, seconds. */ export const PAUSE_PIN_WINDOW = 0.15; -const ROLE_RE = /^(post|quoted|parent:\d|media:\d|linked:\d)$/; +const ROLE_RE = /^(post|quoted|parent:\d|media:\d|linked:\d|screen:[a-z0-9][a-z0-9-]{0,23}:\d{1,2})$/; /** A pause the plan cannot make (no word timings, the word not read, nothing to change): exit 1, not a usage error. */ export class PauseError extends Error { diff --git a/umtool/lib/report/postSay.mjs b/umtool/lib/report/postSay.mjs @@ -198,6 +198,9 @@ export function threadArgsOf(read) { 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)}`); + // Its screens (post-screens.mjs): left out, or lines from takes -- by their numbers then (the files are in the record). + if (read.screens === false) a.push("--no-screens"); + for (const [r, x] of Object.entries(read.lineTakes ?? {})) if (Number.isInteger(x?.n)) a.push(`--line-take ${q(`${r}=${x.n}`)}`); return a.length ? ` ${a.join(" ")}` : ""; } diff --git a/umtool/lib/report/postScreens.test.mjs b/umtool/lib/report/postScreens.test.mjs @@ -0,0 +1,308 @@ +// A post's SCREENS from the CLI and in the read (postScreensCli.mjs, postThreadRead.mjs; post-screens.mjs): the text +// lines a person pastes, the `set` keys, the writer (one write, refused in the build's words; an attachment a screen +// is in cannot go, the others' indices follow), check / rm / list, and the THREAD READ with screens -- each line in +// its speaker's voice, her own lines in hers, a line from an existing take (--line-take), her own line from the take +// that plays (never made again), the short pause between lines, --no-screens. No editor (a stub tts); temp dirs. +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { after, test } from "node:test"; +import { encodeWav16 } from "yt-dlp-transcript-common/lib/montage/voiceMatch.mjs"; +import { VOICE_A, VOICE_B, syntheticVoice, withSilence } from "yt-dlp-transcript-common/testing/audio/syntheticVoice.mjs"; +import { postsCommand } from "./postsCli.mjs"; +import { applyPairs, defaultLineTakes, defaultPostTake, lineOfText, linesOfText, screenReadOptions } from "./postScreensCli.mjs"; +import { withoutLines } from "umtool-report-to-video/post-screens"; +import { characterNames, joinTimes, readParts, saysLine, threadReadPlan, threadTake } from "./postThreadRead.mjs"; +import { normalizeParts } from "./postNarrationCli.mjs"; +import { threadArgsOf } from "./postSay.mjs"; +import { threadArgvOf } from "./castProject.mjs"; +import { updatePostItem } from "./manifest.mjs"; +import { threadReadErrors } from "umtool-report-to-video/post-thread"; + +const ROOT = await mkdtemp(path.join(tmpdir(), "umtool-screens-")); +after(() => rm(ROOT, { recursive: true, force: true })); +const wavOf = async (file, voice, seconds = 1.2) => { + await mkdir(path.dirname(file), { recursive: true }); + await writeFile(file, encodeWav16(withSilence(syntheticVoice({ ...voice, seconds }), { before: 0.1, after: 0.1 }))); +}; +const stubAsk = (asked) => async (body) => { + asked.push(body); + await wavOf(body.out, VOICE_B, 0.6); + return { jobId: `job-${asked.length}`, result: { wav: body.out } }; +}; +const NO_RED = { terms: [], markup: {}, slurs: null }; +const VID = { src: "posts-media/savvy-x/2117/2117_1.mp4", kind: "video", width: 1920, height: 1080, seconds: 61.742, audio: true }; +const IMG = { src: "posts-media/savvy-x/2117/2117_2.jpg", kind: "image", width: 900, height: 1400 }; +const T1 = { file: "narration/posts/2117/take-1.recorded.wav", engine: "recorded", voice: "operator", seconds: 1.4, script: "Hey, you told me. Your turn.", source: { kind: "recorded", voice: "operator" } }; +const T2 = { file: "narration/posts/2117/take-2.recorded-tq.wav", engine: "recorded", voice: "tq", seconds: 1.0, script: "You can't be this dumb", source: { kind: "recorded", voice: "tq" } }; +const ITEM = { + type: "post", id: "p-2117", post: "savvy-x/2117", platform: "x", author: "Savvy", handle: "MadamSavvy", date: "2026-11-02T01:40:36.000Z", + text: "Hey, you told me. Your turn.", subjects: ["MadamSavvy"], media: [VID, IMG], + narration: { script: "Hey, you told me. Your turn.", takes: [T1, T2], pick: 0 }, +}; + +async function project(name, item = ITEM) { + const dir = path.join(ROOT, name); + await mkdir(dir, { recursive: true }); + for (const t of item.narration?.takes ?? []) await wavOf(path.join(dir, t.file), VOICE_A, 1); + await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify({ + schemaVersion: 1, slug: name, title: name, provenance: { channelsDir: "../channels", channelSlug: "chan" }, + render: { width: 1920, height: 1080, fps: 30, postNarration: { engine: "kokoro", voice: "af_heart" } }, + timeline: [item], + }, null, 2)); + await mkdir(path.join(dir, "narration"), { recursive: true }); + await writeFile(path.join(dir, "narration", "voices.json"), JSON.stringify({ thequartering: "kokoro:am_michael" })); + return { id: name, dir }; +} +const read = async (p) => JSON.parse(await readFile(path.join(p.dir, "video.manifest.json"), "utf8")); +const posts = async (args) => { + const lines = []; + const code = await postsCommand(args, { root: ROOT, out: (s) => lines.push(s), err: (s) => lines.push(s) }); + return { code, text: lines.join("\n"), json: () => JSON.parse(lines.join("\n")) }; +}; + +test("text lines as a person pastes them: `[right] who: words | time`, `- words`, `[redact] …`", () => { + assert.deepEqual(lineOfText("TheQuartering: what's your email | 11:32 AM"), { who: "TheQuartering", text: "what's your email", time: "11:32 AM" }); + assert.deepEqual(lineOfText("[right] MadamSavvy: where is my scale video"), { who: "MadamSavvy", side: "right", text: "where is my scale video" }); + assert.deepEqual(lineOfText("- Total amount refunded: $99.95"), { text: "Total amount refunded: $99.95" }); + assert.deepEqual(lineOfText("[redact] Order #4419283"), { text: "Order #4419283", redact: true }); + assert.deepEqual(lineOfText("see https://x.com/a"), { text: "see https://x.com/a" }); + assert.equal(linesOfText("a: b\n\n \nc: d\n").length, 2); +}); + +test("set keys: kind, title, at, read, an excerpt, a line's who / side / redact, a line added and one removed (the read follows)", () => { + const sc = { id: "s1", media: 0, at: [1, 2], kind: "dm", read: "all", lines: [{ who: "a", text: "one two three" }, { who: "b", text: "four" }, { who: "a", text: "five six" }] }; + const x = applyPairs(sc, ["kind=text", "title=\"A note\"", "at=3.5,8", "read=0,2", "read.0=\"two three\"", "line.1.side=right", "line.1.redact=on", "line.add=\"c: seven\""]); + assert.deepEqual([x.kind, x.title, x.at], ["text", "A note", [3.5, 8]]); + assert.deepEqual(x.read, [{ line: 0, text: "two three" }, { line: 2 }]); + assert.deepEqual(x.lines[1], { who: "b", text: "four", side: "right", redact: true }); + assert.deepEqual(x.lines[3], { who: "c", text: "seven" }); + const y = applyPairs(x, ["line.0=off"]); + assert.deepEqual(y.read, [{ line: 1 }]); + assert.equal(y.lines[0].who, "b"); + assert.throws(() => applyPairs(sc, ["colour=red"]), /not a screen's knob/); + assert.throws(() => applyPairs(sc, ["line.9.who=x"]), /the screen has lines 0–2/); + assert.equal(sc.kind, "dm", "a copy"); +}); + +test("the CLI: add from a pasted file, list, set, check, rm -- one write each, refused in the build's words; the item's attachments guarded", async () => { + const p = await project("cli"); + const file = path.join(ROOT, "s1.txt"); + await writeFile(file, "TheQuartering: what's your email so I can refund your order | 11:32 AM\nMadamSavvy: where is my scale video | 11:53 AM\nTheQuartering: You can't be this dumb\n"); + let r = await posts(["screen", "cli", "p-2117", "add", "--media", "0", "--at", "3.5,8", "--kind", "dm", "--from", file, "--json"]); + assert.equal(r.code, 0, r.text); + const j = r.json(); + assert.equal(j.screens[0].id, "s1"); + assert.equal(j.screens[0].lines.length, 3); + assert.ok(j.warnings.some((w) => /transcription not checked/.test(w))); + assert.ok(j.warnings.some((w) => /does not read screen s1/.test(w))); + r = await posts(["screen", "cli", "p-2117", "add", "--media", "1", "--kind", "email", "--line", "coffee: Some items in your order have been refunded", "--line", "- Order number 4419283", "--read", "0"]); + assert.equal(r.code, 0, r.text); + assert.match(r.text, /added screen s2/); + assert.match(r.text, /NOT CHECKED/); + // Refused in the build's words: an excerpt not in the line. + r = await posts(["screen", "cli", "p-2117", "set", "s1", "read.0=\"refund my email\""]); + assert.equal(r.code, 1); + assert.match(r.text, /is not a run of line 0's words/); + r = await posts(["screen", "cli", "p-2117", "check", "s1", "--by", "op"]); + assert.equal(r.code, 0, r.text); + assert.equal((await read(p)).timeline[0].screens[0].checked.by, "op"); + // A word changed: the check goes. + r = await posts(["screen", "cli", "p-2117", "set", "s1", "line.2.text=You cant be this dumb"]); + assert.equal(r.code, 0, r.text); + assert.equal((await read(p)).timeline[0].screens[0].checked, undefined); + r = await posts(["screen", "cli", "p-2117", "list"]); + assert.match(r.text, /s1 {2}dm {2}attachment 0 \(video\) at 3\.5–8 s/); + assert.match(r.text, /\* {2}0 TheQuartering: what's your email/); + // The attachment a screen is in cannot go; one before it moves its index. + await assert.rejects(() => updatePostItem(p.dir, "p-2117", { media: { 1: null } }), /attachment 1 carries screen s2/); + r = await posts(["screen", "cli", "p-2117", "rm", "s2"]); + assert.equal(r.code, 0, r.text); + await updatePostItem(p.dir, "p-2117", { mediaAdd: [IMG] }); + await updatePostItem(p.dir, "p-2117", { media: { 0: null } }).catch((e) => assert.match(String(e.errors ?? e.message), /attachment 0 carries screen s1/)); + // --dry-run checks and writes nothing. + r = await posts(["screen", "cli", "p-2117", "add", "--media", "1", "--kind", "dm", "--line", "a: b", "--dry-run"]); + assert.equal(r.code, 0, r.text); + assert.equal((await read(p)).timeline[0].screens.length, 1); + r = await posts(["screen", "cli", "p-2117", "frob"]); + assert.equal(r.code, 2); +}); + +test("the read: after her words, each line in its speaker's voice (hers in hers), a character's name resolved, --no-screens, the pauses", async () => { + const e = { ...ITEM, screens: [{ id: "s1", media: 0, at: [3.5, 8], kind: "dm", read: "all", lines: [ + { who: "TheQuartering", text: "what's your email so I can refund your order" }, + { who: "MadamSavvy", text: "where is my scale video" }, + { who: "Jeremy", text: "You can't be this dumb" }, + ] }] }; + const m = { render: { postNarration: { engine: "kokoro", voice: "af_heart" } }, timeline: [e] }; + const plan = threadReadPlan(m, e, { red: NO_RED, map: { thequartering: "kokoro:am_michael" }, names: characterNames({ cast: { characters: [{ id: "tq", name: "Jeremy", handles: ["TheQuartering"] }] } }) }); + assert.deepEqual(plan.pieces.map((p) => [p.role, p.voice]), [["post", "af_heart"], ["screen:s1:0", "am_michael"], ["screen:s1:1", "af_heart"], ["screen:s1:2", "am_michael"]]); + assert.equal(threadReadPlan(m, e, { red: NO_RED, screens: false }).pieces.length, 1); + const parts = readParts(plan); + const { meta } = joinTimes(parts, parts.map(() => 1)); + assert.deepEqual(meta.map((x) => x.gapBefore), [0, 0.8, 0.35, 0.35]); + assert.deepEqual(meta.map((x) => x.role), ["post", "screen:s1:0", "screen:s1:1", "screen:s1:2"]); +}); + +test("the read made: her line from the take that plays (not made again), a line from a recorded take (--line-take), each part's role stored; the guard is quiet", async () => { + const item = { ...ITEM, screens: [{ id: "s1", media: 0, at: [3.5, 8], kind: "dm", read: "all", lines: [ + { who: "TheQuartering", text: "what's your email so I can refund your order" }, + { who: "MadamSavvy", text: "where is my scale video" }, + { who: "TheQuartering", text: "You can't be this dumb" }, + ] }] }; + const p = await project("made", item); + assert.equal(defaultPostTake(item), 1); + const asked = []; + const r = await threadTake(p, (await read(p)).timeline[0], { red: NO_RED, ask: stubAsk(asked), lanes: null, postTake: defaultPostTake(item), lineTakes: { "screen:s1:2": 2 } }); + assert.equal(asked.length, 2, "only the two lines no take reads are synthesized"); + const take = r.take; + assert.deepEqual(take.parts.map((x) => [x.role, x.take ?? null]), [["post", "take-1.recorded"], ["screen:s1:0", null], ["screen:s1:1", null], ["screen:s1:2", "take-2.recorded-tq"]]); + assert.equal(take.parts[3].text, "You can't be this dumb"); + assert.deepEqual(take.read.lineTakes, { "screen:s1:2": { n: 2, file: T2.file, line: "You can't be this dumb" } }); + assert.equal(take.read.postTake.file, T1.file); + const after1 = (await read(p)).timeline[0]; + assert.deepEqual(threadReadErrors(after1, {}), []); + // Asked again: up to date (the same takes, the same words). + const again = await threadTake(p, after1, { red: NO_RED, ask: stubAsk(asked), lanes: null, postTake: defaultPostTake(after1), lineTakes: { "screen:s1:2": 2 } }); + assert.equal(again.upToDate, true); + // The flags that ask for it again carry the line take; the default for her own line is the take the thread read used. + assert.match(threadArgsOf(take.read), /--line-take screen:s1:2=2/); + assert.deepEqual(threadArgvOf(take.read, { takes: after1.narration.takes }).slice(-4), ["--post-take", "1", "--line-take", "screen:s1:2=2"]); + assert.equal(defaultPostTake(after1), 1); + // A line take that is a thread read, or out of range, is refused. + await assert.rejects(() => threadTake(p, after1, { red: NO_RED, ask: stubAsk(asked), lanes: null, lineTakes: { "screen:s1:2": 9 } }), /--line-take screen:s1:2=/); +}); + +test("the CLI's read: `posts screen <p> <item> read --dry-run` lists the pieces, her line from the take that plays", async () => { + const item = { ...ITEM, screens: [{ id: "s1", media: 0, at: [3.5, 8], kind: "dm", read: [{ line: 0 }], lines: [{ who: "TheQuartering", text: "what's your email" }] }] }; + await project("dry", item); + const r = await posts(["screen", "dry", "p-2117", "read", "--dry-run", "--json"]); + assert.equal(r.code, 0, r.text); + const j = r.json(); + assert.deepEqual(j.pieces.map((x) => [x.role, x.take?.n ?? null]), [["post", 1], ["screen:s1:0", null]]); + assert.equal(j.pieces[1].voice, "am_michael"); +}); + +// --------------------------------------------------------------------------- +// REVIEW 1 (12 Nov): the read's side of the must-fixes. +// --------------------------------------------------------------------------- + +const DM = (lines, read = "all") => ({ id: "s1", media: 0, at: [3.5, 8], kind: "dm", read, lines }); + +test("MUST 6: a --line-take whose take says something else than the line is REFUSED; one that says it records what the TAKE says", async () => { + const item = { ...ITEM, screens: [DM([{ who: "TheQuartering", text: "You can't be this dumb" }, { who: "TheQuartering", text: "something else said here" }])] }; + const p = await project("m6", item); + const e = (await read(p)).timeline[0]; + // Take 1 is the post's own read: not this line's words. + await assert.rejects(() => threadTake(p, e, { red: NO_RED, ask: stubAsk([]), lanes: null, lineTakes: { "screen:s1:0": 1 } }), /--line-take screen:s1:0=1: its take does not say line 0 of screen s1/); + // Take 2 says it (its script): the part's text is the TAKE's words, the line it stands for stored beside them. + const r = await threadTake(p, e, { red: NO_RED, ask: stubAsk([]), lanes: null, postTake: 1, lineTakes: { "screen:s1:0": 2 } }); + const part = r.take.parts.find((x) => x.role === "screen:s1:0"); + assert.equal(part.text, T2.script); + assert.equal(part.line, "You can't be this dumb"); + assert.equal(r.take.read.lineTakes["screen:s1:0"].line, "You can't be this dumb"); +}); + +test("MUST 1: each part of a screens read stores the line it was made from; the guard holds it to the line as it is now", async () => { + const item = { ...ITEM, screens: [DM([{ who: "TheQuartering", text: "hop on the scale fatso" }, { who: "MadamSavvy", text: "you first" }])] }; + const p = await project("m1", item); + const r = await threadTake(p, (await read(p)).timeline[0], { red: NO_RED, ask: stubAsk([]), lanes: null, postTake: 1 }); + assert.deepEqual(r.take.parts.filter((x) => x.role.startsWith("screen:")).map((x) => x.line), ["hop on the scale fatso", "you first"]); + const now = (await read(p)).timeline[0]; + assert.deepEqual(threadReadErrors(now, {}), []); + const edited = structuredClone(now); + edited.screens[0].lines[1].text = "you first, big boy"; + assert.ok(threadReadErrors(edited, {}).some((x) => /line 1 of screen s1 changed since the read/.test(x))); + // The line takes the read used are re-attached only while their line is the same. + const withLt = structuredClone(now); + withLt.narration.takes[withLt.narration.pick].read.lineTakes = { "screen:s1:1": { n: 2, file: T2.file, line: "you first" } }; + assert.deepEqual(defaultLineTakes(withLt), { "screen:s1:1": 2 }); + withLt.screens[0].lines[1].text = "you first, big boy"; + assert.deepEqual(defaultLineTakes(withLt), {}); +}); + +test("MUST 1 (race): the screens changed while the read was being made: it is not kept (run it again; its parts are cached)", async () => { + const item = { ...ITEM, screens: [DM([{ who: "TheQuartering", text: "hop on the scale fatso" }])] }; + const p = await project("race", item); + const e = (await read(p)).timeline[0]; + const ask = async (body) => { + // A bench edit lands while the tts is busy. + const m = await read(p); + m.timeline[0].screens[0].lines[0].text = "hop on the scale, fatso, now"; + await writeFile(path.join(p.dir, "video.manifest.json"), JSON.stringify(m, null, 2)); + return stubAsk([])(body); + }; + await assert.rejects(() => threadTake(p, e, { red: NO_RED, ask, lanes: null, postTake: 1 }), /changed while its read was made/); + assert.equal((await read(p)).timeline[0].narration.takes.length, 2, "nothing kept"); +}); + +test("SHOULD a: `posts screen … read` keeps the playing thread read's options (parents, skips, voices, quoted)", async () => { + const t = { ...T1, file: "narration/posts/2117/take-3.kokoro-thread.wav", read: { kind: "thread", parents: "all", skip: ["9"], quoted: false, linked: false, seen: true, voiceFor: { someone: "kokoro:bf_emma" }, voice: "af_bella", speed: 1.1 } }; + const e = { ...ITEM, narration: { ...ITEM.narration, takes: [T1, T2, t], pick: 2 } }; + assert.deepEqual(screenReadOptions(e, { flags: new Map(), flag: () => null, multi: () => [] }), { parents: "all", skip: ["9"], quoted: false, linked: false, readSeen: true, overrides: { someone: "kokoro:bf_emma" }, voice: "af_bella", speed: 1.1 }); + // A flag given wins. + const o = screenReadOptions(e, { flags: new Map([["--no-quoted", true]]), flag: (n) => (n === "--parents" ? "0" : null), multi: (n) => (n === "--voice-for" ? ["someone=kokoro:am_adam"] : []) }); + assert.equal(o.parents, "0"); + assert.deepEqual(o.overrides, { someone: "kokoro:am_adam" }); +}); + +test("bench and CLI: removing a line remaps the read (one rule: withoutLines)", () => { + const sc = DM([{ text: "a" }, { text: "b" }, { text: "c" }, { text: "d" }], [{ line: 0 }, { line: 2 }, { line: 3, text: "d" }]); + assert.deepEqual(withoutLines(sc, [0]).read, [{ line: 1 }, { line: 2, text: "d" }]); + assert.deepEqual(withoutLines(sc, [0]).lines.map((l) => l.text), ["b", "c", "d"]); + assert.deepEqual(withoutLines({ ...sc, read: "all" }, [1]).read, "all"); +}); + +test("SHOULD g: an item WITHOUT screens: removing or hiding an attachment is not held to the thread-read guard (as before)", async () => { + const p = await project("g", { ...ITEM, narration: { ...ITEM.narration, takes: [{ ...T1, parts: [{ n: 1, para: 0, text: "words no card holds at all", start: 0, seconds: 1, role: "quoted" }] }], pick: 0 } }); + await updatePostItem(p.dir, "p-2117", { media: { 1: null } }); + assert.equal((await read(p)).timeline[0].media.length, 1); +}); + +// --------------------------------------------------------------------------- +// REVIEW 2 (12 Nov). +// --------------------------------------------------------------------------- + +test("MUST 2 (q1): a line take must say the line -- at most one word more or less, never a shape, a handle or a redacted term", () => { + const line = "please call me at tonight after work ok"; + assert.equal(saysLine("please call me at 555 201 4477 tonight after work ok", line), false, "the masked number said"); + assert.equal(saysLine("a b c d e f my ssn is 123456789", "a b c d e f"), false, "extra words"); + assert.equal(saysLine("please call me at @secretkid tonight after work ok", line), false, "a handle"); + assert.equal(saysLine("please call me at secretkid tonight after work ok", line), false, "a name-like extra word, with no set given (q1)"); + assert.equal(saysLine("please call me at secretkid tonight after work ok", line, { handles: ["secretkid"] }), false, "an anonymous handle, bare"); + assert.equal(saysLine("please call me at Jenny tonight after work ok", line, { terms: ["Jenny"] }), false, "a redaction term"); + assert.equal(saysLine("please call me at tonight after work, okay", line), false, "a word swapped is an extra word (round 3: none allowed)"); + assert.equal(saysLine("please call me tonight after work ok", line), true, "one word fewer"); + assert.equal(saysLine("please call me tonight after ok", line), false, "two fewer"); +}); + +test("SHOULD (re-import): the batch import keeps a part's line and speaker", () => { + const [p] = normalizeParts([{ n: 1, para: 100, text: "x", start: 0, seconds: 1, role: "screen:s1:0", line: "hop on it", speaker: "TheQuartering" }]); + assert.equal(p.line, "hop on it"); + assert.equal(p.speaker, "TheQuartering"); +}); + +test("ROUND 3 (q3): a line take says the line's words IN ORDER -- no extra word, at most one missing, never a negation missing", () => { + assert.equal(saysLine("my pin is nine thanks", "my pin is thanks"), false, "a spelt digit as the extra word"); + assert.equal(saysLine("I did not take it", "I did take it"), false, "meaning flipped by one short word"); + assert.equal(saysLine("I never said no", "I never said yes"), false, "a substitution"); + assert.equal(saysLine("ask jenny about it", "ask about it"), false, "a redacted short name, with no term given"); + assert.equal(saysLine("ask savvy about it", "ask about it", { handles: ["madamsavvy"] }), false, "an anonymous author's short display name"); + assert.equal(saysLine("ask JENNY about it", "ask about it", { terms: ["jenny"] }), false); + assert.equal(saysLine("take it about ask", "ask about take it"), false, "out of order"); + assert.equal(saysLine("I did take it", "I did not take it"), false, "a negation left out"); + assert.equal(saysLine("I didn't take it", "I didn't take it"), true); + assert.equal(saysLine("I take it", "I didn't take it"), false, "an n't word left out"); + assert.equal(saysLine("I did take it", "I did take it now"), true, "one word fewer (not a negation)"); + assert.equal(saysLine("Ask about it.", "ask about it"), true, "case and punctuation"); +}); + +test("ROUND 3: the thread read refuses a line take that says a per-post redaction term (termsFor, not only the project's)", async () => { + const item = { ...ITEM, screens: [DM([{ who: "TheQuartering", text: "You can't be this dumb" }])] }; + const p = await project("r3", item); + const e = (await read(p)).timeline[0]; + // The post's own markup term (the item's, not the project's list) -- the take says it, the line as said leaves it out. + const red = { ...NO_RED, markup: { [e.post]: { redact: [{ term: "dumb" }] } } }; + await assert.rejects(() => threadTake(p, e, { red, ask: stubAsk([]), lanes: null, postTake: 1, lineTakes: { "screen:s1:0": 2 } }), /--line-take screen:s1:0=2: its take does not say line 0 of screen s1 \(it says a redacted term\)/); +}); diff --git a/umtool/lib/report/postScreensCli.mjs b/umtool/lib/report/postScreensCli.mjs @@ -0,0 +1,389 @@ +// `umtool posts screen` -- A POST's SCREENS from the CLI (report-to-video/post-screens.mjs; docs/report-video.md, +// "Screens: text screenshots read as part of the post"): the text screenshots a post carries, transcribed once, drawn +// on its card and read -- whole or in excerpts -- in the voices of the people in them. +// +// umtool posts screen <p> <item> list [--json] +// umtool posts screen <p> <item> add --media <i> [--at <from>,<to>] --kind dm|email|post|text [--id <id>] [--title "…"] +// [--from <file>] [--line "who: words"]… [--read all|none|<n>,<n>…] [--unread omit|dim] +// [--ref <channel>/<postId>] [--json] +// umtool posts screen <p> <item> set <id> <key>=<value>… [--from <file>] [--json] +// umtool posts screen <p> <item> rm <id> [--json] +// umtool posts screen <p> <item> check <id> [--by <name>] [--undo] [--json] +// umtool posts screen <p> <item> read [--post-take <n>] [--line-take screen:<id>:<n>=<take n>]… [--force] [--dry-run] [--json] … +// +// Every write goes through the post item's one writer (manifest.mjs updatePostItem, `screens`: the whole list, under +// the manifest's token), refused in the build's words. `read` is the thread read (postThreadRead.mjs) with the screens: +// his own line from the take that plays when it is not a thread read (or the one the thread read used), so a recorded +// or picked read of his words is never made again. +// +// --from <file>: a JSON screen (or { lines: […] }, or a list of lines), or TEXT, one line per line: +// [right] who: words | time `[right]`/`[left]` the side; `who:` the speaker; `| time` the time shown +// - words a line with no speaker; [redact] … a line never drawn nor read +// Plain ESM: the CLI runs it under bare node. +import { readFile } from "node:fs/promises"; +import path from "node:path"; +import { draftScript } from "umtool-report-to-video/post-narration"; +import { voiceOverridesOf } from "umtool-report-to-video/post-say"; +import { readManifest } from "../projects/report.mjs"; +import { withEditNotes } from "./edit-guard.mjs"; +import { manifestToken, updatePostItem } from "./manifest.mjs"; +import { SCREEN_KINDS, SCREEN_SIDES, SCREEN_UNREAD, lineOfText, screenLineSaid, screenReadLines, withoutLines, screenRows, screenWarnings, screensOf, validateScreens } from "umtool-report-to-video/post-screens"; + +export const SCREEN_USAGE = [ + "usage: umtool posts screen <project> <item> list [--json]", + " umtool posts screen <project> <item> add --media <i> [--at <from>,<to>] --kind dm|email|post|text [--id <id>] [--title \"…\"]", + " [--from <file>] [--line \"who: words\"]… [--read all|none|<n>,<n>…] [--unread omit|dim] [--ref <channel>/<postId>] [--json]", + " umtool posts screen <project> <item> set <id> <key>=<value>… [--from <file>] [--json]", + " umtool posts screen <project> <item> rm <id> [--json]", + " umtool posts screen <project> <item> check <id> [--by <name>] [--undo] [--json]", + " umtool posts screen <project> <item> read [--post-take <n>] [--line-take screen:<id>:<line>=<n>]… [--voice-for h=v]… [--force] [--dry-run] [--json]", + " A post's SCREENS: the text screenshots it carries (a DM exchange or an email in its video, a screenshot attached),", + " transcribed once, drawn on its card and read in the voices of the people in them, each line lit while it is said.", + " --media: the attachment it is in (its index); --at: the seconds of a video it is visible in. --read: the lines read", + " (all; none: transcribed only, not drawn); --unread: the lines not read left out (omit) or drawn dim. --from: a JSON", + " screen, or text lines `[right] who: words | time` (`- words`: no speaker; `[redact] …`: never drawn nor read).", + " set keys: kind= title=|off media= at=<a>,<b>|off unread= ref=|off read=all|none|<n>,… read.<n>=\"excerpt\"|on|off", + " line.add=\"who: words\" line.<n>=off line.<n>.who=|off line.<n>.side=left|right|auto line.<n>.text=", + " line.<n>.time=|off line.<n>.redact=on|off", + " check: the transcription read against the screenshot (by you, now); --undo takes it back. A screen not checked is a", + " lint WARNING. An e-mail address, a phone number, an order or reference number in a line is masked whatever you do.", + " read: the thread read with the screens (posts narrate <p> <item> --take --thread): his words from the take that plays", + " (--post-take n: another), each read line in its speaker's voice; --line-take: that line from the item's take n.", +].join("\n"); + +export class ScreenUsageError extends Error { + constructor(message) { + super(message); + this.name = "ScreenUsageError"; + } +} + +const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); +const str = (v) => (typeof v === "string" ? v : ""); +const unq = (v) => String(v).replace(/^"(.*)"$/s, "$1"); +const fail = (m) => { + throw new ScreenUsageError(m); +}; + +/** Lines of TEXT as screen lines. */ +export { lineOfText }; +export const linesOfText = (text) => String(text).split(/\r?\n/).map(lineOfText).filter(Boolean); + +/** What `--from <file>` holds: `{ screen?: {…}, lines?: […] }` (JSON: a screen, { lines }, or a list of lines; else text lines). */ +export async function readFrom(file) { + const raw = await readFile(file, "utf8").catch(() => fail(`--from ${file}: not there`)); + const t = raw.trim(); + if (t.startsWith("{") || t.startsWith("[")) { + let v; + try { + v = JSON.parse(t); + } catch (e) { + fail(`--from ${file}: not JSON (${e instanceof Error ? e.message : e})`); + } + if (Array.isArray(v)) return { lines: v.map((l) => (typeof l === "string" ? lineOfText(l) : l)).filter(Boolean) }; + if (isObj(v) && Array.isArray(v.lines) && Object.keys(v).length === 1) return { lines: v.lines }; + if (isObj(v)) return { screen: v }; + fail(`--from ${file}: a screen, { lines }, or a list of lines`); + } + return { lines: linesOfText(raw) }; +} + +const numList = (v, what) => { + const parts = String(v).split(",").map((x) => x.trim()).filter(Boolean); + if (!parts.length || !parts.every((x) => /^\d{1,2}$/.test(x))) fail(`${what} takes line numbers (0, 1, …) separated by commas`); + return parts.map(Number); +}; +const span = (v) => { + const m = /^\s*(\d+(?:\.\d+)?)\s*[,-]\s*(\d+(?:\.\d+)?)\s*$/.exec(String(v)); + if (!m) fail(`at takes <from>,<to> (seconds of the video: 3.5,8)`); + return [Math.round(Number(m[1]) * 100) / 100, Math.round(Number(m[2]) * 100) / 100]; +}; +const readOf = (v) => (v === "all" || v === "none" ? v : numList(v, "read").map((line) => ({ line }))); + +/** + * A screen with `key=value` pairs laid on (the `set` keys, SCREEN_USAGE), pure; a copy. Throws ScreenUsageError for a + * key it does not know or a value it cannot read; what the build refuses is the writer's to say. + */ +export function applyPairs(screen, pairs) { + const sc = JSON.parse(JSON.stringify(screen)); + sc.lines = Array.isArray(sc.lines) ? sc.lines : []; + const lineAt = (n) => { + if (!isObj(sc.lines[n])) fail(`line ${n}: the screen has lines 0–${sc.lines.length - 1}`); + return sc.lines[n]; + }; + const drops = []; + for (const pair of pairs) { + const eq = pair.indexOf("="); + if (eq < 1) fail(`${pair}: <key>=<value> (posts screen --help)`); + const key = pair.slice(0, eq); + const v = unq(pair.slice(eq + 1)); + const off = v === "off" || v === ""; + let m; + if (key === "kind") { + if (!SCREEN_KINDS.includes(v)) fail(`kind= takes ${SCREEN_KINDS.join(", ")}`); + sc.kind = v; + } else if (key === "title") { + if (off) delete sc.title; + else sc.title = v; + } else if (key === "media") { + if (!/^\d$/.test(v)) fail("media= takes the attachment's index (0, 1, …)"); + sc.media = Number(v); + } else if (key === "at") { + if (off) delete sc.at; + else sc.at = span(v); + } else if (key === "unread") { + if (!SCREEN_UNREAD.includes(v)) fail(`unread= takes ${SCREEN_UNREAD.join(" or ")}`); + sc.unread = v; + } else if (key === "ref") { + if (off) delete sc.ref; + else sc.ref = v; + } else if (key === "read") { + sc.read = readOf(v); + } else if ((m = /^read\.(\d{1,2})$/.exec(key))) { + const n = Number(m[1]); + lineAt(n); + const list = sc.read === "all" ? sc.lines.map((l, i) => (isObj(l) && l.redact !== true ? { line: i } : null)).filter(Boolean) : Array.isArray(sc.read) ? sc.read : []; + const rest = list.filter((x) => x?.line !== n); + if (v === "off") sc.read = rest; + else sc.read = [...rest, v === "on" ? { line: n } : { line: n, text: v }].sort((a, b) => a.line - b.line); + } else if (key === "line.add") { + const l = lineOfText(v); + if (!l) fail("line.add= takes a line (who: words)"); + sc.lines.push(l); + } else if ((m = /^line\.(\d{1,2})$/.exec(key))) { + if (v !== "off") fail(`${key}= takes off (the line removed; line.${m[1]}.text= to change its words)`); + lineAt(Number(m[1])); + drops.push(Number(m[1])); + } else if ((m = /^line\.(\d{1,2})\.(who|side|text|time|redact)$/.exec(key))) { + const l = lineAt(Number(m[1])); + const f = m[2]; + if (f === "side") { + if (v === "auto") delete l.side; + else if (!SCREEN_SIDES.includes(v)) fail(`${key}= takes left, right or auto`); + else l.side = v; + } else if (f === "redact") { + if (v === "on") l.redact = true; + else if (v === "off") delete l.redact; + else fail(`${key}= takes on or off`); + } else if (f === "text") l.text = v; + else if (off) delete l[f]; + else l[f] = v; + } else fail(`${key} is not a screen's knob (posts screen --help)`); + } + // Lines removed: the read's line numbers follow them (a dropped line's read goes too) -- the bench's rule too. + return drops.length ? withoutLines(sc, drops) : sc; +} + +/** The next free screen id of an item: s1, s2, … */ +export function nextScreenId(e) { + const have = new Set(screensOf(e).map((s) => s.id)); + for (let n = 1; ; n += 1) if (!have.has(`s${n}`)) return `s${n}`; +} + +/** One screen as listing lines (text). */ +export function screenListing(e, sc) { + const reads = new Map(screenReadLines(sc).map((r) => [r.n, r])); + const m = (Array.isArray(e.media) ? e.media : [])[sc.media]; + const head = `${sc.id} ${sc.kind}${sc.title ? ` "${sc.title}"` : ""} attachment ${sc.media}${m ? ` (${m.kind})` : ""}${Array.isArray(sc.at) ? ` at ${sc.at[0]}–${sc.at[1]} s` : ""} read ${sc.read === "all" ? "all" : sc.read === "none" ? "none (transcribed only)" : `${reads.size} line(s)`}${sc.unread === "dim" ? ", the rest dim" : ""} ${sc.checked ? `checked by ${sc.checked.by} ${String(sc.checked.at).slice(0, 10)}` : "NOT CHECKED"}`; + const rows = sc.lines.map((l, n) => { + const r = reads.get(n); + const mark = l?.redact ? "x" : r ? (r.cutBefore || r.cutAfter ? "~" : "*") : " "; + const ex = r && (r.cutBefore || r.cutAfter) ? ` [reads: "${str(l.text).slice(r.start, r.end)}"]` : ""; + return ` ${mark} ${String(n).padStart(2)} ${(l?.side ? `[${l.side}] ` : "") + (l?.who ? `${l.who}: ` : "- ")}${l?.redact ? "(redacted)" : str(l?.text)}${l?.time ? ` | ${l.time}` : ""}${ex}`; + }); + return [head, ...rows]; +} + +/** + * `umtool posts screen <p> <item> <verb> …`. `project` is resolved; `rest` the words after the project + * (`<item> <verb> [<id>] [pairs…]`); `opt` the posts command's flags and helpers. + */ +export async function screenCommand(project, rest, { flags, str: flag, multi, json = false, out = (s) => console.log(s), dryRun = false }) { + const [ref, verb, ...words] = rest; + if (!ref || !verb || flags.has("--help")) { + out(SCREEN_USAGE); + return 2; + } + // The token of the manifest as READ here: a write after someone else's is refused (StaleToken), never laid over it. + const token0 = await manifestToken(project.dir); + const manifest = await readManifest(project.dir); + if (!manifest) throw new ScreenUsageError(`${project.id} has no manifest`); + const tl = Array.isArray(manifest.timeline) ? manifest.timeline : []; + const e = tl.find((x) => x?.type === "post" && (x.id === ref || String(x.post ?? "").split("/")[1] === ref)); + if (!e) throw new ScreenUsageError(`no post item ${ref} in ${project.id} (its id, or the post's id)`); + const screens = screensOf(e); + const write = async (next, what) => { + const { result, editNotes } = await withEditNotes(project, async () => updatePostItem(project.dir, e.id, { screens: next.length ? next : null }, { token: token0 })); + const entry = result.entry; + const { pickedTake, isNarrated } = await import("umtool-report-to-video/post-narration"); + const { partRoles } = await import("umtool-report-to-video/post-thread"); + const warnings = screenWarnings(entry, { narrated: isNarrated(entry), takeRoles: pickedTake(entry) ? partRoles(entry).map((r) => r.role) : [] }); + const { threadReadErrors } = await import("umtool-report-to-video/post-thread"); + const { followKnobs } = await import("umtool-report-to-video/read-follow"); + const { planContext } = await import("umtool-report-to-video/post-conversation"); + const m2 = await readManifest(project.dir); + const i = (m2?.timeline ?? []).findIndex((x) => x?.id === e.id); + const at = i >= 0 ? m2.timeline[i] : null; + const refused = at && isNarrated(at) ? threadReadErrors(at, m2.render ?? {}, { ...planContext(m2.timeline, i, m2.render ?? {}), followOn: followKnobs(at, m2.render ?? {}).on }) : []; + if (json) { + out(JSON.stringify({ ok: true, id: e.id, what, screens: entry.screens ?? [], warnings, refusedUntilRead: refused, token: result.token, editNotes }, null, 2)); + return 0; + } + out(`${e.id}: ${what}`); + for (const sc of screensOf(entry)) for (const l of screenListing(entry, sc)) out(` ${l}`); + for (const x of refused) out(` the build REFUSES the read as it is until it is re-made (umtool posts screen ${project.id} ${e.id} read): ${x}`); + for (const w of warnings) out(` warning: ${w}`); + if (result.snapshot?.rel && !result.snapshot.skipped) out(` undo point: ${result.snapshot.rel} (umtool timeline ${project.id} undo)`); + if (editNotes) out(` edit noted for ${editNotes.generatedBy}`); + return 0; + }; + const byId = (id) => { + if (!id) fail(`which screen? (${screens.map((s) => s.id).join(", ") || "it has none"})`); + const sc = screens.find((s) => s.id === id); + if (!sc) fail(`${e.id} has no screen ${id} (${screens.map((s) => s.id).join(", ") || "none"})`); + return sc; + }; + if (verb === "list") { + if (json) { + out(JSON.stringify({ ok: true, id: e.id, screens, rows: Object.fromEntries(screens.map((s) => [s.id, screenRows(s)])), errors: validateScreens(e), warnings: screenWarnings(e, { narrated: (await import("umtool-report-to-video/post-narration")).isNarrated(e), takeRoles: (await import("umtool-report-to-video/post-thread")).partRoles(e).map((r) => r.role) }) }, null, 2)); + return 0; + } + if (!screens.length) out(`${e.id}: no screens (umtool posts screen ${project.id} ${e.id} add --media <i> --kind dm --from <file>)`); + for (const sc of screens) for (const l of screenListing(e, sc)) out(l); + return 0; + } + if (verb === "add") { + const from = flag("--from") ? await readFrom(path.resolve(String(flag("--from")))) : {}; + const base = from.screen ?? {}; + const id = flag("--id") ?? base.id ?? nextScreenId(e); + if (screens.some((s) => s.id === id)) fail(`${e.id} has a screen ${id} already (set changes it)`); + const lines = [...(from.lines ?? base.lines ?? []), ...multi("--line").map(lineOfText).filter(Boolean)]; + const sc = { + ...base, + id, + ...(flag("--media") !== null ? { media: /^\d$/.test(String(flag("--media"))) ? Number(flag("--media")) : fail("--media takes the attachment's index") } : base.media === undefined ? { media: 0 } : {}), + ...(flag("--at") !== null ? { at: span(flag("--at")) } : {}), + ...(flag("--kind") !== null ? { kind: flag("--kind") } : {}), + ...(flag("--title") !== null ? { title: flag("--title") } : {}), + ...(flag("--ref") !== null ? { ref: flag("--ref") } : {}), + ...(flag("--unread") !== null ? { unread: flag("--unread") } : {}), + source: "transcribed", + lines, + read: flag("--read") !== null ? readOf(flag("--read")) : base.read ?? "all", + }; + if (!sc.kind) fail("--kind dm|email|post|text: what the screenshot is"); + if (dryRun) { + const errs = validateScreens({ ...e, screens: [...screens, sc] }); + out(json ? JSON.stringify({ ok: !errs.length, dryRun: true, screen: sc, errors: errs }, null, 2) : [`would add ${sc.id}:`, ...screenListing(e, sc).map((l) => ` ${l}`), ...errs.map((x) => ` refused: ${x}`)].join("\n")); + return errs.length ? 1 : 0; + } + return write([...screens, sc], `added screen ${sc.id}`); + } + if (verb === "set") { + const sc = byId(words[0]); + let next = sc; + if (flag("--from")) { + const from = await readFrom(path.resolve(String(flag("--from")))); + next = from.screen ? { ...from.screen, id: sc.id } : { ...sc, lines: from.lines ?? sc.lines }; + // New lines: the checked mark goes (it was for the words before). + delete next.checked; + } + const pairs = words.slice(1); + if (!pairs.length && !flag("--from")) fail("set <id> <key>=<value>… (posts screen --help)"); + next = applyPairs(next, pairs); + // Words changed: what was checked is not what is there now. + if (JSON.stringify(next.lines) !== JSON.stringify(sc.lines)) delete next.checked; + return write(screens.map((s) => (s.id === sc.id ? next : s)), `set screen ${sc.id}`); + } + if (verb === "rm") { + const sc = byId(words[0]); + return write(screens.filter((s) => s.id !== sc.id), `removed screen ${sc.id}`); + } + if (verb === "check") { + const sc = byId(words[0]); + const next = { ...sc }; + if (flags.has("--undo")) delete next.checked; + else next.checked = { by: flag("--by") ?? process.env.USER ?? "operator", at: new Date().toISOString() }; + return write(screens.map((s) => (s.id === sc.id ? next : s)), flags.has("--undo") ? `screen ${sc.id}: not checked` : `screen ${sc.id}: checked`); + } + if (verb === "read") { + if (!screens.length) fail(`${e.id} has no screens to read (add one first)`); + const { threadCommand, parentsSelector } = await import("./postThreadRead.mjs"); + const { lineTakesOf } = await import("./postNarrationCli.mjs"); + const postTake = flag("--post-take") ?? defaultPostTake(e); + const o = screenReadOptions(e, { flags, flag, multi }); + return threadCommand(project, e, { + manifest, json, out, ...o, parents: parentsSelector(o.parents), engine: flag("--engine"), note: flag("--note"), force: flags.has("--force"), hold: !flags.has("--no-hold"), dryRun, + postTake, lineTakes: { ...defaultLineTakes(e), ...lineTakesOf(multi("--line-take")) }, + }); + } + fail(`posts screen ${verb}: list, add, set, rm, check or read`); + return 2; +} + +/** + * HIS OWN LINE for a screens read (`read` with no --post-take): the take that plays when it is not a thread read (its + * number, from 1), else the take the thread read that plays used for it (`read.postTake.n`), else none (synthesized; + * from the parts cache when it was before). + */ +export function defaultPostTake(e) { + const takes = Array.isArray(e?.narration?.takes) ? e.narration.takes : []; + const k = Number.isInteger(e?.narration?.pick) && e.narration.pick >= 0 && e.narration.pick < takes.length ? e.narration.pick : 0; + const t = takes[k]; + if (!t || e?.narration?.off === true) return null; + const thread = /-thread\.wav$/.test(str(t.file)) || t.read?.kind === "thread"; + if (!thread) return k + 1; + const f = str(t.read?.postTake?.file); + // Its number then may have moved: found again by its file. + const at = takes.findIndex((x) => str(x?.file) === f); + return at >= 0 ? at + 1 : null; +} + +/** + * The lines the playing thread read took from takes (`read.lineTakes`), found again by their files -- each ONLY while + * its line still says what it said then (`line`, stored with it): a line edited, removed or moved is read afresh, never + * with the old recording. `{ <role>: n }`. + */ +export function defaultLineTakes(e) { + const takes = Array.isArray(e?.narration?.takes) ? e.narration.takes : []; + const k = Number.isInteger(e?.narration?.pick) ? e.narration.pick : 0; + const lt = takes[k]?.read?.lineTakes; + if (!isObj(lt)) return {}; + const out = {}; + for (const [role, x] of Object.entries(lt)) { + const at = takes.findIndex((t) => str(t?.file) === str(x?.file)); + const m = /^screen:([a-z0-9][a-z0-9-]{0,23}):(\d{1,2})$/.exec(role); + const sc = m ? screensOf(e).find((s) => s.id === m[1]) : null; + const now = sc ? lineWritten(screenLineSaid(sc, Number(m[2]))) : ""; + if (at >= 0 && typeof x?.line === "string" && now && norm(x.line) === norm(now)) out[role] = at + 1; + } + return out; +} + +const norm = (t) => String(t ?? "").replace(/\s+/g, " ").trim(); +/** A line's words as a read writes them (post-narration.mjs draftScript). */ +const lineWritten = (t) => draftScript(String(t ?? "")).script; + +/** + * THE READ's OPTIONS for `posts screen … read`, pure: the playing thread read's own (`read`: its parents, skips, + * quoted / linked, seen, voices, voice, speed) -- so making the screens' read never quietly resets the read it + * replaces -- each flag given winning. `{ parents, skip, quoted, linked, readSeen, overrides, voice, speed }`. + */ +export function screenReadOptions(e, { flags, flag, multi }) { + const takes = Array.isArray(e?.narration?.takes) ? e.narration.takes : []; + const k = Number.isInteger(e?.narration?.pick) && e.narration.pick >= 0 && e.narration.pick < takes.length ? e.narration.pick : 0; + const r = takes[k]?.read?.kind === "thread" ? takes[k].read : {}; + const vf = multi("--voice-for"); + const overrides = vf.length ? voiceOverridesOf(vf) : {}; + const skip = multi("--skip-parent"); + return { + parents: flag("--parents") ?? (r.parents !== undefined ? String(r.parents) : "0"), + skip: skip.length ? skip : Array.isArray(r.skip) ? [...r.skip] : [], + quoted: flags.has("--no-quoted") ? false : r.quoted !== false, + linked: flags.has("--no-linked") ? false : r.linked !== false, + readSeen: flags.has("--read-seen") || r.seen === true, + overrides: vf.length ? overrides : isObj(r.voiceFor) ? { ...r.voiceFor } : {}, + voice: flag("--voice") ?? (typeof r.voice === "string" ? r.voice : null), + speed: flag("--speed") !== null ? Number(flag("--speed")) : typeof r.speed === "number" ? r.speed : null, + }; +} diff --git a/umtool/lib/report/postThreadCli.mjs b/umtool/lib/report/postThreadCli.mjs @@ -15,6 +15,7 @@ import { isNarrated, pickedTake } from "umtool-report-to-video/post-narration"; import { partRoles, readPieces, threadLayout, threadReadErrors, threadReadWarnings } from "umtool-report-to-video/post-thread"; import { followKnobs } from "umtool-report-to-video/read-follow"; +import { tileOfRole } from "umtool-report-to-video/post-screens"; import { planContext } from "umtool-report-to-video/post-conversation"; import { readManifest } from "../projects/report.mjs"; import { withEditNotes } from "./edit-guard.mjs"; @@ -37,7 +38,7 @@ export class RolesError extends Error { } } -const ROLE_RE = /^(post|quoted|parent:\d|media:\d|linked:\d)$/; +const ROLE_RE = /^(post|quoted|parent:\d|media:\d|linked:\d|screen:[a-z0-9][a-z0-9-]{0,23}:\d{1,2})$/; /** * A narrated item's read, piece by piece: `{ id, take, pieces: [{ role, parts, source, mode }], errors, threaded }`. @@ -47,7 +48,7 @@ export function readListing(e, render, ctx) { const t = pickedTake(e); const roles = partRoles(e); const L = threadLayout(e, render, ctx ?? {}); - const mode = (role) => (!role ? null : role.startsWith("media:") ? "attachment" : L.tiles.find((x) => x.scope === role)?.mode ?? "absent"); + const mode = (role) => (!role ? null : role.startsWith("media:") ? "attachment" : L.tiles.find((x) => x.scope === tileOfRole(role))?.mode ?? "absent"); const pieces = readPieces(e, roles).map((p) => ({ role: p.role, parts: p.parts.map((k) => k + 1), diff --git a/umtool/lib/report/postThreadRead.mjs b/umtool/lib/report/postThreadRead.mjs @@ -61,8 +61,9 @@ import { POST_PART_GAP, draftScript, nextTakeNumber, pickedTake, postIdOf, postN 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 { spokenRead, termsFor } from "umtool-report-to-video/post-redact"; import { readSpeedOf, resolvePieceVoice } from "umtool-report-to-video/post-say"; +import { SCREEN_LINE_GAP, parseScreenRole, screenWho, shapeSpans } from "umtool-report-to-video/post-screens"; import { readManifest } from "../projects/report.mjs"; import { withEditNotes } from "./edit-guard.mjs"; import { manifestToken, updatePostNarration } from "./manifest.mjs"; @@ -102,6 +103,10 @@ export const THREAD_READ_USAGE = [ " --post-take <n>: his own line is the item's take n (as --list numbers them; a recording, or one converted to his", " character's voice), not synthesized -- the context pieces are, in their authors' voices; each part of the new take", " says where it came from. A thread take, or a take whose file is gone, is refused.", + " ITS SCREENS (umtool posts screen): each line a screen reads is read after his words, in the screens' order, in its", + " speaker's voice (`who`: the post's author in hers; a handle or a character's name in theirs) -- --no-screens leaves", + " them out. --line-take screen:<id>:<n>=<take n>: that LINE is the item's take n (a recording of that line, or one", + " converted to its speaker's character), not synthesized; repeatable.", ].join("\n"); /** @@ -161,7 +166,7 @@ export function seenIds(manifest, e) { * @param {{ red?: any, map?: Record<string, any>, cast?: Record<string, any>, item?: any, overrides?: Record<string, string>, parents?: string, * skip?: string[], quoted?: boolean, linked?: boolean, readSeen?: boolean, voice?: string | null, engine?: string | null, speed?: number | null }} [o] */ -export function threadReadPlan(manifest, e, { red = null, map = {}, cast = {}, item = null, overrides = {}, parents = "0", skip = [], quoted = true, linked = true, readSeen = false, voice = null, engine = null, speed = null, postTake = null } = {}) { +export function threadReadPlan(manifest, e, { red = null, map = {}, cast = {}, item = null, overrides = {}, parents = "0", skip = [], quoted = true, linked = true, readSeen = false, voice = null, engine = null, speed = null, postTake = null, screens = true, names = {}, lineTakes = {} } = {}) { const render = manifest?.render ?? {}; const k = postNarrationKnobs(e, render); const eng = engine ?? e.narration?.engine ?? k.engine; @@ -209,6 +214,41 @@ export function threadReadPlan(manifest, e, { red = null, map = {}, cast = {}, i skipped.push({ role: p.role, why: "--no-linked" }); continue; } + // A SCREEN's line (post-screens.mjs): its speaker's voice -- the post's author's own lines in hers. + if (parseScreenRole(p.role)) { + if (!screens) { + skipped.push({ role: p.role, why: "--no-screens" }); + continue; + } + const sw = screenWho(p.who, e, names); + const handle = sw.self ? str(e.handle) : sw.handle; + const written = draftScript(p.text).script; + 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 lt = lineTakes?.[p.role] ?? null; + if (lt) { + // THE LINE FROM A TAKE (--line-take): that take's file is the line's piece, and its words are what the TAKE says + // (`said`, else its script -- as --post-take's are), so every check that reads a read's words reads the audio's. + // A take that does not say the line is REFUSED, never played as it. + const words = norm(lt.take.said) || norm(lt.take.script); + const anonHandles = red?.anon instanceof Map ? [...red.anon.keys()] : Object.keys(red?.anon ?? {}).filter((x) => x !== "postIds"); + // The project's terms AND the post's own (its markup): what the card blanks, a take never says. + const why = lineTakeProblem(words, said.text, { handles: anonHandles, terms: termsFor(e, red).map((x) => x.term) }); + if (why) { + const sp = /^screen:([a-z0-9-]+):(\d+)$/.exec(p.role); + throw new ThreadReadError(`--line-take ${p.role}=${lt.n}: its take does not say line ${sp[2]} of screen ${sp[1]} (it says ${why === "other words" ? "other words than the line: another line's, more words, or the line changed" : why}) -- record that line, or name the take that reads it`); + } + pieces.push({ role: p.role, handle, who: p.who, speaker: str(p.who), date: null, voice: takeVoiceOf(lt.take), from: "take", written, line: written, text: words, lexicon: [], slurs: lt.take.slurs ?? null, take: { n: lt.n, id: takeIdOf(lt.take), file: lt.take.file, ...(lt.take.engine ? { engine: lt.take.engine } : {}) } }); + continue; + } + const v = resolvePieceVoice({ handle, role: sw.self ? "post" : p.role }, { map, cast, item, overrides, self: str(e.handle), voice: null, narrator, engine: eng }); + const spd = readSpeedOf({ flag: speed, preset: v.speed ?? null, own: sw.self ? e.narration?.speed ?? null : null, engine: v.engine }); + pieces.push({ role: p.role, handle, who: p.who, speaker: str(p.who), date: null, line: written, voice: v.voice, engine: v.engine, from: v.from, ...(spd !== null ? { speed: spd } : {}), ...(v.character ? { character: v.character } : {}), written, text: said.text.trim(), lexicon: said.lexicon ?? [], slurs: said.slurs, ...(said.anonymised ? { anonymised: said.anonymised } : {}) }); + 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" }); @@ -248,6 +288,68 @@ export function threadReadPlan(manifest, e, { red = null, map = {}, cast = {}, i }; } +/** + * The characters' NAMES -> their first handle (the project's own over the cast's), lower case: a screen line's `who` + * may be a name (post-screens.mjs screenWho). `{}` with no layers. + */ +export function characterNames(L) { + const out = {}; + const add = (c) => { + const n = str(c?.name).trim().toLowerCase(); + const h = Array.isArray(c?.handles) ? str(c.handles[0]) : ""; + if (n && h && !out[n] && c?.anonymous !== true) out[n] = h; + }; + for (const c of Array.isArray(L?.cast?.characters) ? L.cast.characters : []) add(c); + const own = Array.isArray(L?.project?.characters) ? L.project.characters : []; + for (const c of own) { + const n = str(c?.name).trim().toLowerCase(); + if (n) delete out[n]; + } + for (const c of own) add(c); + return out; +} + +/** A NEGATION: a line that has one, a take must say it (it is never the word left out). */ +const NEGATION_RE = /^(?:not|no|nope|never|nor|none|nothing|nobody|nowhere|neither|cannot|.+n't|(?:do|does|did|ca|wo|is|are|was|were|could|should|would|have|has|had|ai|must|need|might)nt)$/u; + +/** + * WHAT A LINE TAKE SAYS AMISS, pure: null when its words SAY the line -- the line's said words IN ORDER, normalized + * (case, edge punctuation), NO word more, at most one word fewer and never a negation (not, no, never, -n't…) -- else + * why not: "a shape" (an e-mail, a number: shapeSpans), "a handle" (an @handle, an anonymous author's `handles`), "a + * redacted term" (`terms`: the project's and the post's own, post-redact.mjs termsFor), "other words". + */ +export function lineTakeProblem(takeWords, lineWords, { handles = [], terms = [] } = {}) { + if (shapeSpans(str(takeWords)).length) return "a shape"; + const keys = (t) => str(t).toLowerCase().replace(/[’‘]/g, "'").split(/\s+/).map((w) => w.replace(/^[^\p{L}\p{N}@]+|[^\p{L}\p{N}]+$/gu, "")).filter(Boolean); + const a = keys(takeWords); + const b = keys(lineWords); + const banned = new Set(handles.map((h) => String(h).replace(/^@+/, "").toLowerCase())); + if (a.some((w) => w.startsWith("@") || banned.has(w))) return "a handle"; + const termRes = terms.map((t) => new RegExp(`(?<![\\p{L}\\p{N}])${String(t).replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?![\\p{L}\\p{N}])`, "iu")); + if (termRes.some((re) => re.test(str(takeWords)))) return "a redacted term"; + if (!a.length || !b.length || a.length > b.length || b.length - a.length > 1) return "other words"; + // In order, every word the line's; one word of the line may be left out -- never a negation. + let i = 0; + let skipped = null; + for (const w of a) { + while (i < b.length && b[i] !== w) { + if (skipped !== null) return "other words"; + skipped = b[i]; + i += 1; + } + if (i >= b.length) return "other words"; + i += 1; + } + if (i < b.length) { + if (skipped !== null || i + 1 < b.length) return "other words"; + skipped = b[i]; + } + return skipped !== null && NEGATION_RE.test(skipped) ? "other words" : null; +} + +/** Whether a take's words SAY a line (lineTakeProblem's null). */ +export const saysLine = (takeWords, lineWords, o = {}) => lineTakeProblem(takeWords, lineWords, o) === null; + /** A take's voice as a thread read's label says it: its voice (or recorded label) without an engine ("am_michael", "operator"). */ export function takeVoiceOf(t) { const v = str(t?.voice) || str(t?.label) || (t?.engine === "recorded" ? "recorded" : "take"); @@ -272,9 +374,11 @@ export function postTakeOf(e, n) { /** The read's PARTS, pure: each piece's parts (scriptParts) with its voice, engine, role and cache key, in order -- a take's line one part, its file. */ export function readParts(plan) { return plan.pieces.flatMap((pc, piece) => { - if (pc.take) return [{ piece, para: 0, role: pc.role, voice: pc.voice, text: pc.text, file: pc.take.file, take: pc.take.id, key: null }]; + // A screen line's parts carry the line they were made from (`line`): the guard holds the read to the line as it is. + const line = typeof pc.line === "string" ? { line: pc.line, speaker: str(pc.speaker) } : {}; + if (pc.take) return [{ piece, para: 0, role: pc.role, voice: pc.voice, text: pc.text, file: pc.take.file, take: pc.take.id, key: null, ...line }]; const eng = pc.engine ?? plan.engine; - return scriptParts(pc.text).map((q) => ({ piece, para: q.para, role: pc.role, voice: pc.voice, engine: eng, ...(pc.speed !== undefined ? { speed: pc.speed } : {}), text: q.text, key: partKey(eng, pc.voice, q.text, pc.speed ?? null) })); + return scriptParts(pc.text).map((q) => ({ piece, para: q.para, role: pc.role, voice: pc.voice, engine: eng, ...(pc.speed !== undefined ? { speed: pc.speed } : {}), text: q.text, key: partKey(eng, pc.voice, q.text, pc.speed ?? null), ...line })); }); } @@ -290,11 +394,13 @@ export function joinTimes(parts, seconds, { fileOf = (p) => (p.take ? p.file : ` 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; + // Two lines of one SCREEN (post-screens.mjs): a short pause, an exchange's. + const sameScreen = !!prev && p.piece !== prev.piece && parseScreenRole(p.role) !== null && parseScreenRole(p.role)?.id === parseScreenRole(prev.role)?.id; + const gap = !prev ? 0 : sameScreen ? SCREEN_LINE_GAP : 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]); // A part from a take (--post-take) says which (`take`: its id); a synthesized one its parts-cache file and voice. - const row = { n: i + 1, para: p.piece * 100 + p.para, text: p.text, voice: p.voice, ...(p.engine ? { engine: p.engine } : {}), ...(typeof p.speed === "number" ? { speed: p.speed } : {}), role: p.role, piece: p.piece, file: fileOf(p), ...(p.take ? { take: p.take } : {}), start: r3(t), seconds: r3(s), gapBefore: gap }; + const row = { n: i + 1, para: p.piece * 100 + p.para, text: p.text, ...(typeof p.line === "string" ? { line: p.line, speaker: str(p.speaker) } : {}), voice: p.voice, ...(p.engine ? { engine: p.engine } : {}), ...(typeof p.speed === "number" ? { speed: p.speed } : {}), role: p.role, piece: p.piece, file: fileOf(p), ...(p.take ? { take: p.take } : {}), start: r3(t), seconds: r3(s), gapBefore: gap }; t += s; return row; }); @@ -302,7 +408,7 @@ export function joinTimes(parts, seconds, { fileOf = (p) => (p.take ? p.file : ` } /** 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, speed = null, postTake = null }) { +export function readRecordOf({ parents = "0", skip = [], quoted = true, linked = true, readSeen = false, overrides = {}, voice = null, speed = null, postTake = null, screens = true, lineTakes = {} }) { return { kind: "thread", parents: parentsSelector(parents), ...(skip?.length ? { skip: [...skip] } : {}), ...(quoted ? {} : { quoted: false }), ...(linked ? {} : { linked: false }), @@ -311,6 +417,10 @@ export function readRecordOf({ parents = "0", skip = [], quoted = true, linked = ...(typeof speed === "number" && Number.isFinite(speed) ? { speed } : {}), // His line from a take (--post-take): its number then, and its file. ...(postTake ? { postTake: { n: postTake.n, file: postTake.take.file } } : {}), + // Its screens (post-screens.mjs): left out; lines from takes (--line-take). + ...(screens ? {} : { screens: false }), + // Each with the line it said then (`line`): it is re-attached only while the line says the same (defaultLineTakes). + ...(Object.keys(lineTakes ?? {}).length ? { lineTakes: Object.fromEntries(Object.entries(lineTakes).map(([r, lt]) => [r, { n: lt.n, file: lt.take.file, ...(typeof lt.line === "string" ? { line: lt.line } : {}) }])) } : {}), }; } @@ -319,7 +429,11 @@ export function upToDate(e, plan) { const t = pickedTake(e); if (!t || norm(t.script) !== norm(plan.want) || str(t.voice) !== plan.voice || (t.engine ?? "orpheus") !== plan.engine) return false; // His line from a take: the same take's file, or not up to date. - if (str(t.read?.postTake?.file) !== str(plan.pieces.find((p) => p.take)?.take?.file)) return false; + if (str(t.read?.postTake?.file) !== str(plan.pieces.find((p) => p.take && p.role === "post")?.take?.file)) return false; + // A screen line from a take: the same takes' files, or not up to date. + const lines = Object.fromEntries(plan.pieces.filter((p) => p.take && p.role !== "post").map((p) => [p.role, p.take.file])); + const had = Object.fromEntries(Object.entries(t.read?.lineTakes ?? {}).map(([r, x]) => [r, str(x?.file)])); + if (JSON.stringify(Object.entries(lines).sort()) !== JSON.stringify(Object.entries(had).sort())) return false; // A take whose parts say their voices: each piece in the same engine and voice, at the same speed. const parts = Array.isArray(t.parts) ? t.parts.filter((p) => typeof p?.voice === "string") : []; if (!parts.length) return !plan.pieces.some((p) => typeof p.speed === "number"); @@ -347,6 +461,7 @@ export async function threadTake(project, e, opts = {}) { manifest: m0 = null, red: red0 = undefined, map: map0 = undefined, cast: cast0 = undefined, item: item0 = undefined, overrides = {}, parents = "0", skip = [], quoted = true, linked = true, readSeen = false, voice = null, engine = null, speed = null, note = null, force = false, hold = true, dryRun = false, ask = null, lanes: lanes0 = undefined, emit = () => {}, editor = null, signals = false, postTake: postTakeN = null, + screens = true, lineTakes: lineTakesN = {}, names: names0 = undefined, } = opts; const manifest = m0 ?? (await readManifest(project.dir)); if (!manifest) throw new ThreadReadError(`${project.id} has no manifest`); @@ -358,13 +473,25 @@ export async function threadTake(project, e, opts = {}) { const cast = cast0 !== undefined ? cast0 : L.castMap; const item = item0 !== undefined ? item0 : L?.itemOf(e) ?? null; const postTake = postTakeN === null || postTakeN === undefined ? null : postTakeOf(e, postTakeN); - const plan = threadReadPlan(manifest, e, { red, map, cast, item, overrides, parents, skip, quoted, linked, readSeen, voice, engine, speed, postTake }); + // A screen line from a take (--line-take): checked as --post-take's is. + const lineTakes = Object.fromEntries(Object.entries(lineTakesN ?? {}).map(([role, n]) => { + if (!parseScreenRole(role)) throw new ThreadReadError(`--line-take names a screen's line as screen:<id>:<n> (got ${role})`); + try { + return [role, postTakeOf(e, n)]; + } catch (err) { + throw new ThreadReadError(String(err instanceof Error ? err.message : err).replace(/--post-take/g, `--line-take ${role}=`)); + } + })); + // The characters' names (a screen's `who` may be one), to their handles. + const names = names0 !== undefined ? names0 : characterNames(L); + const plan = threadReadPlan(manifest, e, { red, map, cast, item, overrides, parents, skip, quoted, linked, readSeen, voice, engine, speed, postTake, screens, names, lineTakes }); + for (const [r, lt] of Object.entries(lineTakes)) lt.line = plan.pieces.find((pc) => pc.role === r)?.line; const parts = readParts(plan); const cacheDir = path.join(project.dir, ...PARTS_CACHE.split("/")); const wavOf = (p) => (p.take ? path.join(project.dir, ...p.file.split("/")) : path.join(cacheDir, `${p.key}.wav`)); const have = await Promise.all(parts.map((p) => fileThere(wavOf(p)))); const lost = parts.find((p, i) => p.take && !have[i]); - if (lost) throw new ThreadReadError(`--post-take ${postTake.n}: its file ${lost.file} is not there`); + if (lost) throw new ThreadReadError(`${lost.role === "post" ? `--post-take ${postTake?.n}` : `--line-take ${lost.role}`}: its file ${lost.file} is not there`); 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 }; @@ -469,9 +596,14 @@ export async function threadTake(project, e, opts = {}) { ...(plan.lexicon.length ? { lexicon: plan.lexicon } : {}), // Where its parts' speeds came from: --speed (kept as asked), else their characters' presets / the item's own. ...(plan.pieces.some((p) => typeof p.speed === "number") ? { speedAsked: typeof speed === "number" ? true : "preset" } : {}), - read: readRecordOf({ parents, skip, quoted, linked, readSeen, overrides, voice, speed, postTake }), + read: readRecordOf({ parents, skip, quoted, linked, readSeen, overrides, voice, speed, postTake, screens, lineTakes }), }; const patch = { addTake: take, ...(plan.script ? { script: plan.script } : {}) }; + // THE ITEM CHANGED WHILE ITS READ WAS MADE (a bench edit during minutes of synthesis): what was read is not what it + // holds now -- refused, never kept as a stale read (the parts made are cached: running it again is quick). + const nowE = ((await readManifest(project.dir))?.timeline ?? []).find((x) => x?.id === e.id); + const sig = (x) => JSON.stringify([x?.screens ?? null, x?.text ?? null, x?.narration?.script ?? null]); + if ((Array.isArray(e.screens) || Array.isArray(nowE?.screens)) && (!nowE || sig(nowE) !== sig(e))) throw new ThreadReadError(`${e.id} changed while its read was made (its screens or its words): run it again -- the parts made are cached`); 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 }; } diff --git a/umtool/lib/report/postsCli.mjs b/umtool/lib/report/postsCli.mjs @@ -105,6 +105,7 @@ export const POSTS_USAGE = [ " POST ITEMS: each archived post as an entry of the cut, its card and its attachments (report-video.md, \"Post items\"):", " the channels merged in time order, de-duplicated by post id; a post already in the cut is skipped, so a re-run", " adds only what is new -- in ONE write (one undo point), at the end unless --after.", + " umtool posts screen <project> <item> list | add | set | rm | check | read … its text screenshots (posts screen --help)", " umtool posts set-item <project> <item> [hold=<s>|off] [layout=sequence|grid] [redact=on|off|auto] [scene=off|join|auto] [follow=on|off|auto] [follow.dim=<0.2-1>] [follow.ease=<s>]", " [excerpt='[\"<span>\", …]'|off] read only these verbatim spans (in the post's order, joined \" … \"); the card shows the whole post, the rest dimmed", " [thread.parent[.<i>]=auto|full|excerpt|context|carry|hidden] [thread.quoted=auto|full|excerpt|context|hidden]", @@ -198,9 +199,9 @@ export const POSTS_USAGE = [ " none: the rule as it stands", ].join("\n"); -const VALUED = new Set(["--in-take", "--set", "--attach", "--flag", "--author", "--id", "--crop", "--since", "--until", "--replies", "--order", "--limit", "--after", "--script", "--note", "--voice", "--engine", "--speed", "--pick", "--linger", "--derive", "--op", "--pitch", "--semitones", "--delete", "--match", "--target", "--occurrence", "--at", "--scale", "--hold", "--lead", "--ease", "--highlight", "--worker", "--without", "--drop-parts", "--text", "--place", "--rewind", "--zone", "--gap", "--from-scale", "--color", "--outline", "--outline-width", "--size", "--face", "--sfx", "--volume", "--bar", "--bar-style", "--tempo-for", "--tempo", "--parts", "--stretch", "--yell-gain", "--yell-style", "--pause", "--revoice", "--say", "--xfade", "--splice", "--parents", "--skip-parent", "--voice-for", "--item", "--recording", "--as", "--label", "--out", "--trim-span", "--post-take"]); +const VALUED = new Set(["--in-take", "--set", "--attach", "--flag", "--author", "--id", "--crop", "--since", "--until", "--replies", "--order", "--limit", "--after", "--script", "--note", "--voice", "--engine", "--speed", "--pick", "--linger", "--derive", "--op", "--pitch", "--semitones", "--delete", "--match", "--target", "--occurrence", "--at", "--scale", "--hold", "--lead", "--ease", "--highlight", "--worker", "--without", "--drop-parts", "--text", "--place", "--rewind", "--zone", "--gap", "--from-scale", "--color", "--outline", "--outline-width", "--size", "--face", "--sfx", "--volume", "--bar", "--bar-style", "--tempo-for", "--tempo", "--parts", "--stretch", "--yell-gain", "--yell-style", "--pause", "--revoice", "--say", "--xfade", "--splice", "--parents", "--skip-parent", "--voice-for", "--item", "--recording", "--as", "--label", "--out", "--trim-span", "--post-take", "--line-take", "--from", "--media", "--kind", "--title", "--line", "--read", "--unread", "--by", "--ref"]); /** The valued flags that may be given more than once (each value kept, in order). */ -const MULTI = new Set(["--skip-parent", "--voice-for", "--trim-span"]); +const MULTI = new Set(["--skip-parent", "--voice-for", "--trim-span", "--line-take", "--line"]); const SLUG_RE = /^[A-Za-z0-9._-]+$/; const POST_ID_RE = /^[A-Za-z0-9_-]{1,64}$/; @@ -492,6 +493,15 @@ export async function postsCommand(args, { root = REPORTS_ROOT, out = (s) => con try { const [verb, projectArg, ref] = words; if (verb === "reel" && projectArg && !flags.has("--help")) return await reelCommand(projectArg, { channels, flags, str, root, json, dryRun, out }); + if (verb === "screen") { + // A POST's SCREENS (postScreensCli.mjs, post-screens.mjs): its text screenshots, transcribed, drawn and read. + const { SCREEN_USAGE, screenCommand } = await import("./postScreensCli.mjs"); + if (!projectArg || !ref || flags.has("--help")) { + err(SCREEN_USAGE); + return 2; + } + return await screenCommand(await projectOf(projectArg, root), words.slice(2), { flags, str, multi, json, out, dryRun }); + } if (verb === "set-item" && projectArg && ref && !flags.has("--help")) return await setItemCommand(projectArg, ref, words.slice(3), { root, json, out, reread: !flags.has("--no-reread") }); if (verb === "reread") { // A read re-joined without a piece (postReread.mjs): no TTS, a new take picked in one write. @@ -700,7 +710,7 @@ export async function postsCommand(args, { root = REPORTS_ROOT, out = (s) => con return 1; } err(`umtool posts: ${e instanceof Error ? e.message : String(e)}`); - return e instanceof CliError || e?.constructor?.name === "NarrateError" || e?.constructor?.name === "FxError" ? 2 : 1; + return e instanceof CliError || e?.constructor?.name === "NarrateError" || e?.constructor?.name === "FxError" || e?.constructor?.name === "ScreenUsageError" ? 2 : 1; } } @@ -735,9 +745,9 @@ async function setCommand(projectArg, ref, pairs, { root, json, out }) { } /** The verbs `--in-take <take>` scopes (each writes a post item through manifest.mjs's structural writers). */ -export const IN_TAKE_VERBS = ["set-item", "roles", "narrate", "reread", "fx", "picture-reply"]; +export const IN_TAKE_VERBS = ["set-item", "roles", "narrate", "reread", "fx", "picture-reply", "screen"]; /** The verbs whose `--take <take>` is `--in-take <take>` (narrate's `--take` is its own: a new read). */ -const TAKE_ALIAS_VERBS = new Set(["set-item", "roles", "reread", "fx"]); +const TAKE_ALIAS_VERBS = new Set(["set-item", "roles", "reread", "fx", "screen"]); /** * `--in-take <take>` (or, on set-item/roles/reread/fx, `--take <take>`) taken out of a posts command line: diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs @@ -869,6 +869,8 @@ export { tightestContaining, windowContains, windowsFromNames, } from "./sources.mjs"; import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; +import { validateScreenReads } from "./post-thread.mjs"; +import { screenDrawErrors } from "./post-screens.mjs"; // The yt-dlp argv for one clip window. The platform's fixed args come from // common's table (`platformArgsForUrl`) -- the same copy every editor spawn @@ -6599,7 +6601,13 @@ export async function prepareLocalMedia(timeline, manifestDir, render = {}) { * With no anonymous handle, lintManifest's result as it was. `--no-lint` is the only override. */ export function enforcedLint(manifest, lintOpts, { cut, anonymity }) { - const base = lintManifest(manifest, lintOpts); + const base0 = lintManifest(manifest, lintOpts); + // ITS SCREENS (post-screens.mjs, post-thread.mjs): a screen part whose line changed since the read, that the screen does + // not read, or that SAYS a shape -- judged on the cut AS WRITTEN (the anonymised copy rewrites the lines it draws) -- + // and an excerpt that is not in its line as drawn. A cut with no screens: lintManifest's as it was. + const mine = (m) => (lintOpts?.only ? { ...m, timeline: (m?.timeline ?? []).filter((e) => e?.id === lintOpts.only) } : m); + const screenErr = [...validateScreenReads(mine(cut ?? manifest)), ...(mine(manifest)?.timeline ?? []).flatMap((e) => (e?.type === "post" && Array.isArray(e.screens) ? screenDrawErrors(e) : []))]; + const base = screenErr.length ? { ...base0, errors: [...base0.errors, ...screenErr] } : base0; if (!anonymity?.set?.size) return base; const anon = anonymityProblems(cut, anonymity.doc, { set: anonymity.set }); return anon.errors.length ? { ...base, errors: [...base.errors, ...anon.errors] } : base; diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json @@ -84,6 +84,7 @@ "./post-censor": "./post-censor.mjs", "./post-media-scene": "./post-media-scene.mjs", "./post-picture": "./post-picture.mjs", + "./post-screens": "./post-screens.mjs", "./post-redact": "./post-redact.mjs", "./post-say": "./post-say.mjs", "./cast": "./cast.mjs", diff --git a/umtool/report-to-video/post-anon.mjs b/umtool/report-to-video/post-anon.mjs @@ -254,6 +254,10 @@ function stripped(e) { out = { ...(out === e ? e : out), [k]: list.map(unflag) }; } for (const k of ["quoted", "repostedBy"]) if (isObj(out[k]) && "anonymous" in out[k]) out = { ...(out === e ? e : out), [k]: unflag(out[k]) }; + // A screen's lines (post-screens.mjs): the flag is this pass's alone there too. + if (Array.isArray(out.screens) && out.screens.some((sc) => isObj(sc) && Array.isArray(sc.lines) && sc.lines.some((l) => isObj(l) && "anonymous" in l))) { + out = { ...(out === e ? e : out), screens: out.screens.map((sc) => (isObj(sc) && Array.isArray(sc.lines) ? { ...sc, lines: sc.lines.map(unflag) } : sc)) }; + } return out; } @@ -310,6 +314,46 @@ export function anonymiseEntry(e0, set) { if (replyShown) edit().replyingTo = pseudonymOf(replyShown); // The subjects name handles: an anonymous one is its pseudonym there too (the card's subject accent still finds it). if (Array.isArray(e.subjects) && e.subjects.some((h) => of(h))) edit().subjects = e.subjects.map((h) => (of(h) ? pseudonymOf(of(h)) : h)); + // ITS SCREENS (post-screens.mjs): a speaker who is an anonymous handle under the shown name (flagged, drawn as it), every + // line's words and a title anonymised as the card's words are. + if (Array.isArray(e.screens)) { + let changed = false; + const screens = e.screens.map((sc) => { + if (!isObj(sc) || !Array.isArray(sc.lines)) return sc; + let mine = false; + const lines = sc.lines.map((l) => { + if (!isObj(l)) return l; + const s = typeof l.who === "string" ? of(l.who) : null; + // A speaker that is not the handle itself ("x.com/<handle>", "@<handle>") has its words anonymised as a post's are. + const who = s ?? anonymiseWords(l.who, set); + const text = anonymiseWords(l.text, set); + const time = anonymiseWords(l.time, set); + if (!s && text === l.text && who === l.who && time === l.time) return l; + mine = true; + return { ...l, ...(s ? { who: s, anonymous: true } : who !== undefined ? { who } : {}), text, ...(time !== undefined ? { time } : {}) }; + }); + const title = anonymiseWords(sc.title, set); + // Each EXCERPT rewritten as its line is: still a run of the line's words as drawn. + const read = Array.isArray(sc.read) ? sc.read.map((x) => (isObj(x) && typeof x.text === "string" ? { ...x, text: anonymiseWords(x.text, set) } : x)) : sc.read; + const readChanged = Array.isArray(sc.read) && read.some((x, i) => x !== sc.read[i] && x.text !== sc.read[i].text); + if (!mine && title === sc.title && !readChanged) return sc; + changed = true; + return { ...sc, lines, ...(title !== undefined ? { title } : {}), ...(readChanged ? { read } : {}) }; + }); + if (changed) edit().screens = screens; + // Its takes' screen parts record the line and the speaker they were made from: rewritten as the lines are, so the + // drawn copy is judged against itself (the build judges staleness on the cut as written: post-thread.mjs). + const takes = Array.isArray(e.narration?.takes) ? e.narration.takes : null; + if (takes?.some((t) => Array.isArray(t?.parts) && t.parts.some((pt) => isObj(pt) && (typeof pt.line === "string" || typeof pt.speaker === "string")))) { + const next = takes.map((t) => (Array.isArray(t?.parts) ? { ...t, parts: t.parts.map((pt) => { + if (!isObj(pt) || (typeof pt.line !== "string" && typeof pt.speaker !== "string")) return pt; + const sp = typeof pt.speaker === "string" ? of(pt.speaker) ?? anonymiseWords(pt.speaker, set) : undefined; + return { ...pt, ...(typeof pt.line === "string" ? { line: anonymiseWords(pt.line, set) } : {}), ...(sp !== undefined ? { speaker: sp } : {}) }; + }) } : t)); + const o = edit(); + o.narration = { ...e.narration, takes: next }; + } + } // The words the card draws. const w = withWords(out ?? e, set); if (w !== (out ?? e)) out = w; @@ -489,7 +533,24 @@ export function anonymityProblems(manifest, doc, { set: given = null } = {}) { if (!anonymousUrl(g.host, g.path.replace(/[.,;:!?)\]]+$/, ""), set)) warnings.push(`timeline ${e.id}: ${set.get(handleKey(e.handle))}'s words carry a link the pass cannot classify (${g.host}/…) -- drawn as written: check it does not lead to them`); } } - const drawn = whoOf(e).flatMap((w) => [str(w.text), str(w.paraphrase)]).join("\n"); + // ITS SCREENS (post-screens.mjs): a speaker written as an anonymous author's display name is drawn as written -- + // refused (write the handle: it is drawn under the shown name); their words are drawn as written, as a post's are. + const screens = (Array.isArray(e.screens) ? e.screens : []).filter((sc) => isObj(sc) && Array.isArray(sc.lines)); + for (const sc of screens) { + // A SPEAKER, A TIME, THE TITLE: short fields drawn as written but for an exact handle -- any other form of an + // anonymous handle ("SecretKid (alt)", "x.com/secretkid", "@secretkid") or display name in one is an ERROR. + // A speaker that IS the handle (any case, an "@" before it) is the pass's: drawn under the shown name -- not an error. + const fields = [["its title", sc.title], ...sc.lines.flatMap((l, i) => (isObj(l) ? [[`line ${i}'s speaker`, l.who, l.anonymous === true || (typeof l.who === "string" && set.has(handleKey(l.who)))], [`line ${i}'s time`, l.time]] : []))]; + for (const [where, v, flagged] of fields) { + if (typeof v !== "string" || !v.trim() || flagged) continue; + for (const [n, shown] of names) if (phraseRe(n).test(v)) errors.push(`timeline ${e.id}: screen ${str(sc.id)} ${where} writes ${shown}'s display name -- an anonymous author's: write their handle (a speaker is drawn as "${shown}") or leave it out`); + for (const [h, shown] of set) { + if (h === "postIds") continue; + if (phraseRe(h).test(v)) errors.push(`timeline ${e.id}: screen ${str(sc.id)} ${where} writes ${shown}'s handle -- an anonymous author's: write the handle alone as the speaker (drawn as "${shown}") or leave it out`); + } + } + } + const drawn = [...whoOf(e).flatMap((w) => [str(w.text), str(w.paraphrase)]), ...screens.flatMap((sc) => [str(sc.title), ...sc.lines.map((l) => str(l?.text))])].join("\n"); for (const [n, shown] of names) if (phraseRe(n).test(drawn)) warnings.push(`timeline ${e.id}: its words write out ${shown}'s display name -- the card draws words as written: edit them, or redact the name (umtool posts redact)`); if (typeof e.parentShot === "string") warnings.push(`timeline ${e.id}: its captured thread shot is not drawn -- this video has anonymous authors, and a shot may picture them (the card's "Replying to" line stands in)`); } diff --git a/umtool/report-to-video/post-item.mjs b/umtool/report-to-video/post-item.mjs @@ -43,6 +43,7 @@ import { validatePostLinkVisit, validatePostLinkVisitRender, visitsEnd } from ". import { progressErrors } from "./post-progress.mjs"; import { validatePostMapRender } from "./post-branch-map.mjs"; import { validatePostScene, validatePostSceneRender } from "./post-media-scene.mjs"; +import { hasScreens, isScreenScope, screenBadgeHtml, screenCss, screenOf, screenShows, screenTileHtml, screenWho, validateScreens } from "./post-screens.mjs"; /** The platforms a post item may come from (deck.mjs POST_PLATFORMS). */ export const POST_ITEM_PLATFORMS = Object.freeze(["x", "bluesky", "web"]); @@ -401,14 +402,18 @@ function planOf(entry, render, hold, prev = null, scene = null, mediaScene = nul 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, avail)) }; }); + // ITS SCREENS (post-screens.mjs) read: its own attachments until the first is up, then each screen's span. + const shows = !hasScreens(entry) || ownPictureOnly(entry) ? [] : screenShows(entry, follow, { lead: 0.4 }); + const ownUntil = shows.length ? Math.max(enter, shows[0].t0) : null; + const avail1 = ownUntil === null ? avail : round3(Math.max(0, ownUntil - enter)); 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, (avail - videos) / pics.length) : 0; + const share = pics.length ? Math.max(POST_PICTURE_MIN, (avail1 - 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, enter + media, follow?.visits ? visitsEnd(follow.visits) : 0)); - const plan = planSteps(steps, enter, total); + const total = hold ?? round3(Math.max(span, ownUntil === null ? enter + media : 0, follow?.visits ? visitsEnd(follow.visits) : 0)); + const plan = ownUntil === null ? planSteps(steps, enter, total) : screenPlan(entry, steps, enter, ownUntil, shows, 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) { @@ -423,6 +428,46 @@ function planOf(entry, render, hold, prev = null, scene = null, mediaScene = nul return { ...plan, reading: 0, total, ...extra, ...(panel ? { panel } : {}), ...(enter > 0 && plan.steps.length ? { enter } : {}), ...(inCard.length ? { pics: inCard } : {}) }; } +/** + * THE PLAN's STEPS with ITS SCREENS (post-screens.mjs): its own attachments from `enter`, cut at the first screen's + * show; then, for each screen, its attachment from its show to the next one's (the last to the item's end) -- a video + * or a GIF from its span's start (`at`), its last frame HELD when the read outlasts the span (a looped span would + * replay the overlay fading in and out); an image held. Each such step says `screen: <id>`. + */ +function screenPlan(entry, steps, enter, ownUntil, shows, total) { + const own = ownUntil > enter + 0.05 ? planSteps(steps, enter, ownUntil).steps : []; + // Its last own step runs on to the first screen, its last frame held (`hold`: the build plays no further than its span). + const lastOwn = own[own.length - 1]; + if (lastOwn && lastOwn.at + lastOwn.seconds < ownUntil - 0.01) { + lastOwn.seconds = round3(ownUntil - lastOwn.at); + if (lastOwn.kind === "video") lastOwn.hold = true; + } + const media = Array.isArray(entry?.media) ? entry.media : []; + const out = [...own]; + shows.forEach((sh, i) => { + const m = media[sh.media]; + const until = i + 1 < shows.length ? shows[i + 1].t0 : total; + if (!isObj(m) || until <= sh.t0 + 0.05) return; + const seconds = round3(until - sh.t0); + const timed = m.kind === "video" || m.kind === "gif"; + const from = timed && Array.isArray(sh.at) ? round3(sh.at[0]) : 0; + const to = timed && Array.isArray(sh.at) ? round3(sh.at[1]) : null; + out.push({ + kind: m.kind, + items: [{ ...m, i: sh.media, ...(timed ? { start: from, end: to } : {}) }], + at: round3(sh.t0), + seconds, + ...(timed ? { srcFrom: from, srcTo: to } : {}), + loop: m.kind === "gif", + sound: m.kind === "video" && m.mute !== true && m.audio !== false, + ...(m.kind === "video" ? { hold: true } : {}), + screen: sh.id, + }); + }); + const end = out.length ? out[out.length - 1].at + out[out.length - 1].seconds : enter; + return { steps: out, held: out.length ? round3(Math.max(0, total - end)) : 0 }; +} + /** Whether any context post of the item (a parent, the quoted post) is picture-only. */ const hasPictureContext = (entry) => parentsOf(entry).some(refPictureOnly) || (isObj(entry?.quoted) && refPictureOnly(entry.quoted)); @@ -737,6 +782,8 @@ export function validatePostItem(e) { errors.push(...progressErrors(e.progress, `timeline ${e?.id ?? "?"}.progress`)); // Picture-only (post-picture.mjs): its own, a parent's, the quoted post's -- true or false. errors.push(...validatePictureOnly(e)); + // Its screens (post-screens.mjs): the text screenshots it carries, transcribed, and what of them is read. + errors.push(...validateScreens(e)); return errors; } @@ -1267,6 +1314,16 @@ export function postCardHtml(entry, { width, height, palette = {}, fonts = {}, p return { media: post ? censorEntry({ post, media }, redaction).media : media }; }; const menSize = Math.round(22 * k); + // A SCREEN's speaker (post-screens.mjs): the post's author under the card's rule for her; an anonymous one (the pass + // flagged it) under the shown name; anyone else under the privacy rule -- a subject, or the item's redact: false. + const screenShown = (l) => { + const s = screenWho(l?.who, entry); + if (s.self) return !red("author"); + if (l?.anonymous === true) return true; + if (entry.redact === true) return false; + if (entry.redact === false) return true; + return !!s.handle && subjectsOf(entry).some((h) => String(h).replace(/^@/, "").toLowerCase() === String(s.handle).toLowerCase()); + }; const ownPicMax = Math.max(Math.round(140 * k), L.card.height - 2 * L.pad - Math.round(250 * k) - Math.min(2, parentsOf(entry).length) * Math.round(130 * k) - (isObj(entry.quoted) ? Math.round(170 * k) : 0)); const own = { author: entry.author, handle: entry.handle, ...(entry.anonymous === true ? { anonymous: true } : {}) }; const ownRed = red("author"); @@ -1414,9 +1471,21 @@ export function postCardHtml(entry, { width, height, palette = {}, fonts = {}, p `<div class="tslot" data-thread-slot="${esc(t.scope)}" data-thread-scene="${t.action === "keep" ? "keep" : "collapse"}"><div class="tile tparent tscene" data-thread-tile="${esc(t.scope)}" data-thread-mode="scene" data-post-scene="${esc(t.scope.slice(5))}"${r ? ' data-redacted=""' : ""}>${avatarHtml(ref, { redact: r, size: av, img: pic(ref) })}<div class="pbody">${relationHtml(t)}<div class="phead">${nameHtml(ref, { redact: r, cls: "big" })}<span class="pdate">${esc(cardDate(ref.date).split(" · ")[0])}</span>${ref.paraphrased ? '<span class="plabel" data-post-paraphrased="">paraphrased</span>' : ""}</div><div class="ptext tt${spic ? " pmen" : ""}" style="font-size:${tsize}px">${wordsHtml(text, r && ref.handle ? [...blurred, ref.handle] : blurred)}</div>${spic ? picIn(t.scope, spic, innerW - av - Math.round(16 * k), Math.round(innerH * 0.6)) : ""}</div></div></div>`, ); } + // ITS SCREENS (post-screens.mjs): each screen the take reads, typeset -- a tile after his post, its lines the + // read-follow's blocks (by role, never by words), with its badge pinned to the card's top while it is up. + const badges = []; + for (const t of tiles) { + if (!isScreenScope(t.scope)) continue; + const sc = screenOf(entry, t.scope.slice(7)); + if (!sc) continue; + const lines = new Map((fmap?.blocks ?? []).filter((b) => b.scope === t.scope && Number.isInteger(b.line)).map((b) => [b.line, b.k])); + tileHtml.push(screenTileHtml(entry, sc, { k, size: Math.max(followMin, Math.round(30 * k)), blocks: lines, shown: screenShown, authorHidden: ownRed, h: { esc } })); + badges.push(screenBadgeHtml(entry, sc, { esc, authorHidden: ownRed })); + } const order = [...tiles.map((t) => t.scope).filter((sc) => byScope.has(sc)), ...[...byScope.keys()].filter((sc) => !tiles.some((t) => t.scope === sc))]; return { - html: `<div class="card thread" data-post-card="${esc(entry.id)}" data-post-thread="${tiles.length}"${L.mode === "text" ? ' data-thread-fit=""' : ""} style="left:${box.x}px;top:${box.y}px;height:${box.height}px;width:${box.width}px"><div class="words" data-post-words="" style="font-size:${size}px"><div class="wflow" data-post-flow="">${order.map((sc) => byScope.get(sc)).join("")}</div><div class="wfade" data-post-fade="top"></div><div class="wfade" data-post-fade="bottom"></div></div></div>`, + html: `<div class="card thread" data-post-card="${esc(entry.id)}" data-post-thread="${tiles.length}"${L.mode === "text" ? ' data-thread-fit=""' : ""} style="left:${box.x}px;top:${box.y}px;height:${box.height}px;width:${box.width}px"><div class="words" data-post-words="" style="font-size:${size}px"><div class="wflow" data-post-flow="">${order.map((sc) => byScope.get(sc)).join("")}</div><div class="wfade" data-post-fade="top"></div><div class="wfade" data-post-fade="bottom"></div></div>${badges.join("")}</div>`, + screens: badges.length > 0, css: cutCss.length ? `\n${cutCss.join(", ")} { display: none; }` : "", }; }; @@ -1503,7 +1572,7 @@ ${tiles?.some((t) => t?.rel) ? `.rel { color: ${pal.muted}; font-size: ${Math.ro ` : ""}.tile .tt { display: block; -webkit-line-clamp: none; overflow: visible; line-height: ${LINE}; color: ${pal.fg}; margin-top: ${Math.round(6 * k)}px; } .twords { line-height: ${LINE}; overflow-wrap: anywhere; } .tile.quoted .tt { color: ${mixHex(pal.fg, pal.bg, 0.08)}; } -.tile.quoted.tabove .tt { color: ${pal.fg}; }${tc.css}` : ""}${highlight ? ` +.tile.quoted.tabove .tt { color: ${pal.fg}; }${tc.css}${tc.screens ? screenCss({ k, pal, mixHex, rgbaOf, pad: L.pad }) : ""}` : ""}${highlight ? ` [data-w-hl] { background: ${rgbaOf(highlight.color, WORD_ZOOM_HIGHLIGHT_ALPHA)}; box-shadow: inset 0 -0.12em 0 ${highlight.color}; border-radius: 0.16em; padding: 0 0.08em; margin: 0 -0.08em; -webkit-box-decoration-break: clone; box-decoration-break: clone; }` : ""} ${BAR_CSS(pal.fg)} </style></head> diff --git a/umtool/report-to-video/post-narration.mjs b/umtool/report-to-video/post-narration.mjs @@ -202,7 +202,7 @@ const STEP_KEYS = new Set(["op", "engine", "voice", "pitch", "semitones", "param // `tempo`: the part's reading speed in the take's file against its first read (a `tempo` step's; absent: 1). // `speed`: the speed the part was synthesized at (its character's preset's, or the read's --speed; absent: 1). // `take`: a thread read's part that IS one of the item's takes (postThreadRead.mjs --post-take): that take's id. -const PART_KEYS = new Set(["n", "para", "text", "file", "start", "seconds", "gapBefore", "note", "at", "jobId", "role", "voice", "engine", "piece", "tempo", "speed", "take"]); +const PART_KEYS = new Set(["n", "para", "text", "file", "start", "seconds", "gapBefore", "note", "at", "jobId", "role", "voice", "engine", "piece", "tempo", "speed", "take", "line", "speaker"]); const VOICE_RE = /^[A-Za-z0-9][A-Za-z0-9_.+-]{0,63}$/; /** Orpheus's expressive tags (narration.mjs NARRATION_TAGS, the editor's list). */ const TAGS = ["laugh", "chuckle", "sigh", "cough", "sniffle", "groan", "yawn", "gasp"]; @@ -711,9 +711,11 @@ export function validatePostNarration(e) { if (!(fin(p.start) && p.start >= 0)) errors.push(`${pw}.start must be where it starts in the take, seconds`); if (!(fin(p.seconds) && p.seconds > 0)) errors.push(`${pw}.seconds must be its length`); if (p.text !== undefined && typeof p.text !== "string") errors.push(`${pw}.text must be the words it reads`); + if (p.line !== undefined && typeof p.line !== "string") errors.push(`${pw}.line must be the screen line it was made from (its words)`); + if (p.speaker !== undefined && typeof p.speaker !== "string") errors.push(`${pw}.speaker must be the screen line's speaker it was made for`); if (p.speed !== undefined && !numIn(p.speed, POST_NARRATION_LIMITS.speed)) errors.push(`${pw}.speed must be ${POST_NARRATION_LIMITS.speed.join("–")} (the speed it was synthesized at)`); if (p.tempo !== undefined && !numIn(p.tempo, POST_NARRATION_LIMITS.tempo)) errors.push(`${pw}.tempo must be ${POST_NARRATION_LIMITS.tempo.join("–")} (its reading speed in the take)`); - if (p.role !== undefined && !(typeof p.role === "string" && /^(post|quoted|parent:\d|media:\d|linked:\d)$/.test(p.role))) errors.push(`${pw}.role must be post, quoted, parent:<i>, linked:<i> or media:<i> (the text it reads)`); + if (p.role !== undefined && !(typeof p.role === "string" && /^(post|quoted|parent:\d|media:\d|linked:\d|screen:[a-z0-9][a-z0-9-]{0,23}:\d{1,2})$/.test(p.role))) errors.push(`${pw}.role must be post, quoted, parent:<i>, linked:<i>, media:<i> or screen:<id>:<line> (the text it reads)`); if (p.engine !== undefined && !POST_NARRATION_ENGINES.includes(p.engine)) errors.push(`${pw}.engine must be one of ${POST_NARRATION_ENGINES.join(", ")}`); if (p.take !== undefined && !(typeof p.take === "string" && n.takes.some((x) => x !== t && takeIdOf(x) === p.take))) errors.push(`${pw}.take must be the id of another of its takes (the take this part is)`); }); diff --git a/umtool/report-to-video/post-redact.mjs b/umtool/report-to-video/post-redact.mjs @@ -288,6 +288,8 @@ export function redactEntry(entry, red) { if (isObj(entry.quoted)) out.quoted = ref(entry.quoted, "quoted"); // A post its words link to (post-thread.mjs): marked by the project's terms, as a quoted post is. if (Array.isArray(entry.links)) out.links = entry.links.map((p) => ref(p, "quoted")); + // ITS SCREENS (post-screens.mjs): every line's words and its speaker marked by the project's terms. + if (Array.isArray(entry.screens)) out.screens = screensMarked(entry.screens, (v) => mark(v, all)); return slurEntry(out, red?.slurs); } @@ -336,9 +338,26 @@ export function slurEntry(entry, slurs) { if (Array.isArray(entry.parents)) out.parents = entry.parents.map(ref); if (isObj(entry.quoted)) out.quoted = ref(entry.quoted); if (Array.isArray(entry.links)) out.links = entry.links.map((r) => (isObj(r) && "transcript" in r ? { ...ref(r), transcript: m(r.transcript) } : ref(r))); + if (Array.isArray(entry.screens)) out.screens = screensMarked(entry.screens, m); return out; } +/** + * A screens list (post-screens.mjs) with each line's words, its speaker, its time and the title passed through `m` (a + * copy) -- and each EXCERPT the same way, so it is still a run of its line's words as drawn (else the card would have + * to draw the whole line: it draws none, and the build refuses -- screenDrawErrors). + */ +function screensMarked(screens, m) { + return screens.map((sc) => (isObj(sc) && Array.isArray(sc.lines) + ? { + ...sc, + ...("title" in sc ? { title: m(sc.title) } : {}), + lines: sc.lines.map((l) => (isObj(l) ? { ...l, ...("text" in l ? { text: m(l.text) } : {}), ...("who" in l ? { who: m(l.who) } : {}), ...("time" in l ? { time: m(l.time) } : {}) } : l)), + ...(Array.isArray(sc.read) ? { read: sc.read.map((x) => (isObj(x) && typeof x.text === "string" ? { ...x, text: m(x.text) } : x)) } : {}), + } + : sc)); +} + // --------------------------------------------------------------------------- // What is SAID and what a line of text SHOWS, the redaction and the slur filter together. // --------------------------------------------------------------------------- diff --git a/umtool/report-to-video/post-render.mjs b/umtool/report-to-video/post-render.mjs @@ -32,6 +32,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 { POST_SCREEN_DRAW_V, hasScreens, screenDrawErrors } from "./post-screens.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"; @@ -261,16 +262,18 @@ export function postSegmentArgs({ entry, box, plan, layout, cards, files, render parts.push(`[${k}:v]${crop}scale=${b.width}:${b.height},setsar=1,fps=${fps}${fadeIn(shownFrom)}[${raw}]`); } } else { - // A video or a GIF: its span from srcFrom, its first frame held from the item's start until it plays. + // A video or a GIF: its span from srcFrom, its first frame held from the item's start until it plays. A step + // that HOLDS (post-item.mjs: a screen's span, post-screens.mjs) plays no further than its span: its last frame held. const len = until - step.at; - const k = add([...(step.loop ? ["-stream_loop", "-1"] : []), "-ss", num(step.srcFrom), "-t", num(len), "-i", file]); + const play = step.hold === true && Number.isFinite(step.srcTo) ? Math.min(len, Math.max(0.05, step.srcTo - step.srcFrom)) : len; + const k = add([...(step.loop ? ["-stream_loop", "-1"] : []), "-ss", num(step.srcFrom), "-t", num(play), "-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)}${fadeIn(shownFrom)}[${raw}]`, ); if (step.sound) { const ms = Math.round(step.at * 1000); - const dur = Math.min(step.seconds, len); + const dur = Math.min(step.seconds, play); audio.push({ label: `a${si}`, chain: `[${k}:a]aresample=${render.audioRate ?? 48000},aformat=channel_layouts=stereo,asetpts=PTS-STARTPTS,atrim=0:${num(dur)},afade=t=in:d=0.04,afade=t=out:st=${num(Math.max(0, dur - 0.06))}:d=0.06,adelay=${ms}|${ms}[a${si}]` }); } } @@ -1362,6 +1365,8 @@ export function postSegmentKeyOf({ entry, redaction = null, box, place = [], ren ...(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 }), + // ITS SCREENS (post-screens.mjs): their drawing's version -- only an item that carries screens. + ...(hasScreens(entry) ? { screens: POST_SCREEN_DRAW_V } : {}), ...(POST_SEGMENT_RV ? { rv: POST_SEGMENT_RV } : {}), }; } @@ -1530,6 +1535,10 @@ export async function buildPostSegment(entry, { render, outDir, manifestDir, box } cardPics = { mediaUrl: (src) => pathToFileURL(path.resolve(manifestDir, src)).href, posters }; } + // ITS SCREENS AS DRAWN (post-screens.mjs, after the redaction and anonymity passes): an excerpt no longer in its line + // is never drawn whole -- the segment is refused, naming the line. + const screenErr = hasScreens(entry) ? screenDrawErrors(redactEntry(entry, redaction)) : []; + if (screenErr.length) throw new Error(`${entry.id}: a screen cannot be drawn as chosen:\n ${screenErr.join("\n ")}`); const cards = await renderPostCards(entry, { box, render, dir: cardDir, manifestDir, layout, avatars, zooms: zoomPlan, pics: plan.pics ?? [], cardPics, redaction, follow: plan.follow ?? null, total: plan.total, joinFrom: from, captions: capPlan, clock: clk, obstacles: layout.slot ? plan.steps.flatMap((st) => stepBoxes(st, layout.slot)) : [], slams: slPlan, progress: prog }); // NO HIDDEN TEXT IS EVER NARRATED (operator, 4 Nov): a part whose words are not in view, whole and lit, while it // is said -- or a context post drawn over its context size -- refuses the build (READ_IN_VIEW=warn: a note). diff --git a/umtool/report-to-video/post-screens-pin.test.mjs b/umtool/report-to-video/post-screens-pin.test.mjs @@ -0,0 +1,129 @@ +// THE PIN (lane/screen-reads, 12 Nov 2026): with no `screens` on an item, every page and every plan is BYTE-IDENTICAL +// to what main drew before screens existed. The hashes below were recorded on main (9277318c) before a line of the +// screens code was written; a change that moves any of them changes what an item without screens draws or plays. +// +// Covered: the card page (plain, following, threaded), the plan (its steps, its follow schedule, its thread rows, +// its panel and its pictures), and the segment key, over a spread of items -- text only, a video, images in a grid, +// a narrated reply that reads its parent, a quoted post read first, a picture-only parent, an excerpt, a linked post. +import assert from "node:assert/strict"; +import { createHash } from "node:crypto"; +import { test } from "node:test"; +import { postCardHtml, postItemPlan } from "./post-item.mjs"; +import { postSegmentKeyOf } from "./post-render.mjs"; + +const sha = (v) => createHash("sha1").update(typeof v === "string" ? v : JSON.stringify(v)).digest("hex"); +const at = (h, m = 0) => `2026-11-02T${String(h).padStart(2, "0")}:${String(m).padStart(2, "0")}:00.000Z`; +const VID = { src: "posts-media/subj-x/1/1_1.mp4", kind: "video", width: 1080, height: 1200, seconds: 46.3, audio: true, start: 2, end: 9 }; +const IMG = { src: "posts-media/kir-x/7/7_1.jpg", kind: "image", width: 1127, height: 500 }; +const IMG2 = { src: "posts-media/kir-x/7/7_2.jpg", kind: "image", width: 800, height: 800 }; +const GIF = { src: "posts-media/furri-x/9/9_1.mp4", kind: "gif", width: 480, height: 270, seconds: 2.53 }; +const WORDS = "That is exactly what I was saying yesterday morning.\n\nWe should have bought the generator in the spring."; +const PARENT = "The first thing anyone notices is the noise from the street.\n\nThen the lights in the hall go out without warning."; +const QUOTED = "Here is the plan for the weekend repairs on the roof."; +const base = (o = {}) => ({ type: "post", id: "p-1", post: "subj-x/1001", platform: "x", author: "Subject", handle: "subject", date: at(21, 5), text: WORDS, engagement: { likes: 12, replies: 3 }, ...o }); +function take(pieces) { + const parts = []; + let t = 0; + pieces.forEach(([text, role], pi) => { + text.split(/\n\n/).forEach((para, k) => { + const seconds = Math.round((para.split(/\s+/).length / 3) * 100) / 100; + t += parts.length ? (k === 0 ? 0.8 : 0.6) : 0; + parts.push({ n: parts.length + 1, para: pi * 100 + k, text: para, start: Math.round(t * 100) / 100, seconds, role }); + t += seconds; + }); + }); + return { file: "narration/posts/1001/take-1.orpheus-thread.wav", engine: "orpheus", voice: "leo+zac", seconds: Math.round(t * 100) / 100, script: pieces.map((p) => p[0]).join("\n\n"), parts }; +} +const narrate = (e, pieces) => ({ ...e, narration: { script: e.text, takes: [take(pieces)], pick: 0 } }); + +const FIXTURES = { + text: base(), + video: base({ media: [VID] }), + grid: base({ media: [IMG, IMG2], mediaLayout: "grid" }), + narratedVideo: narrate(base({ media: [VID] }), [[WORDS, "post"]]), + threadParent: narrate(base({ parents: [{ id: "900", author: "Neighbour", handle: "neighbour_one", date: at(19, 9), text: PARENT }] }), [[PARENT, "parent:0"], [WORDS, "post"]]), + quotedFirst: narrate(base({ quoted: { id: "901", author: "Other", handle: "other", date: at(20, 1), text: QUOTED }, media: [IMG] }), [[QUOTED, "quoted"], [WORDS, "post"]]), + picParent: narrate(base({ parents: [{ id: "9", author: "Furri", handle: "furri", date: at(20, 58), text: "@subject", media: [GIF] }] }), [[WORDS, "post"]]), + excerpt: base({ excerpt: ["We should have bought the generator"] }), + linked: narrate(base({ text: `${WORDS} https://x.com/other/status/902`, links: [{ id: "902", author: "Other", handle: "other", date: at(20, 30), text: QUOTED }] }), [[WORDS, "post"], [QUOTED, "linked:0"]]), +}; + +/** Every output an item without screens has: its plan, its card pages, its segment key. */ +function outputs(e) { + const render = { postNarration: { lead: 0.4 } }; + const plan = postItemPlan(e, render); + const box = { width: 1600, height: 900 }; + return { + plan: sha(plan), + plain: sha(postCardHtml(e, { ...box })), + follow: sha(postCardHtml(e, { ...box, follow: true, thread: plan.follow?.thread ?? null })), + key: sha(postSegmentKeyOf({ entry: e, box, render: { fps: 30, palette: null }, plan, take: plan.narration ? {} : null })), + }; +} + +// Recorded on main (9277318c), before the screens code: `node -e` over this file's FIXTURES (see PIN_RECORD below). +const PINNED = { + text: { + plan: "163438f691c524bb395e1c39fd09dcc2e72f795e", + plain: "e7f0130b9fbe6dc32cc5657fa0bb00c57ffe54b4", + follow: "d9bbbb211005c4b9fd9bad0351a11ae50a15e46e", + key: "FAKE-TEST-VALUE" + }, + video: { + plan: "1d721cc3154e0a4f10e6711e9f8f265ed53180d7", + plain: "000f4bcbfea50af05acc3dc1c15cac97663ef6c7", + follow: "31c6fc090691da173a7fc4ac32894d285127a032", + key: "FAKE-TEST-VALUE" + }, + grid: { + plan: "c5353695c813395f12cd5d761a6019cbb2f536e2", + plain: "2afaf9cdce76fd8233b031b0e84802b5bfcc3e7c", + follow: "63689e568b23744aa90ed725c28dd034d842ecea", + key: "0deaf8e92086f7f7fde3efbd7707064092e60389" + }, + narratedVideo: { + plan: "030e22c63f5c262f5c8afe725e9c40a5f6470bc4", + plain: "000f4bcbfea50af05acc3dc1c15cac97663ef6c7", + follow: "31c6fc090691da173a7fc4ac32894d285127a032", + key: "FAKE-TEST-VALUE" + }, + threadParent: { + plan: "b01efeba3f9bf621538de9eefa25cd806fb963ca", + plain: "6bcbf761983dbf527e2138f1f2d7c584e9cceba6", + follow: "a1f25c09c2b7a7186b05552eeb6d2611bcbf73a0", + key: "FAKE-TEST-VALUE" + }, + quotedFirst: { + plan: "754b4d53adf5f47924d56a3c31a5cb44f323fb98", + plain: "4c1fbde072185ee99e8480611fe5a0c21d03ef8f", + follow: "c0392234597dda7834f42241072a18956e75677b", + key: "FAKE-TEST-VALUE" + }, + picParent: { + plan: "4ed61fa9691664d7fae9b1890ca7799effdf145e", + plain: "98b193ab29ae5fc7276934e513b06e73fc994e91", + follow: "6e68386aa3c41648d30eb928b7d989f266b4cf98", + key: "FAKE-TEST-VALUE" + }, + excerpt: { + plan: "fa0050d888b4dbd703945ac3b43a21ad8776f8ec", + plain: "697905a289f7106d9bff49d023f7086980d9a7b2", + follow: "79380dda1310b2c2fc23af21deacf229b1bbcd25", + key: "FAKE-TEST-VALUE" + }, + linked: { + plan: "3bc1b5e16edf0157c8c74bb3422bfa422f1f4468", + plain: "becaf617d978eb6bf9444ddb5d00e977f647de17", + follow: "13d8f6ab3af100545b6d50a231f5e9bb8ca1a07c", + key: "FAKE-TEST-VALUE" + } +}; + +test("an item without screens draws, plans and keys BYTE-IDENTICALLY to main before screens", () => { + const now = Object.fromEntries(Object.entries(FIXTURES).map(([k, e]) => [k, outputs(e)])); + if (process.env.PIN_RECORD === "1") { + console.log(JSON.stringify(now, null, 1)); + return; + } + assert.deepEqual(now, PINNED); +}); diff --git a/umtool/report-to-video/post-screens-review.test.mjs b/umtool/report-to-video/post-screens-review.test.mjs @@ -0,0 +1,233 @@ +// lane/screen-reads REVIEW 1 (12 Nov): the reviewer's probes ($J/screen-reads/review/p1-p9) as tests, one a finding. Each +// must-fix is a privacy leak or a wrong word in a read; the rule throughout: nothing is drawn or said that the operator +// did not choose -- when an excerpt, a take or a line no longer matches, the build REFUSES, never falls back to more. +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { postCardHtml, postItemPlan, validatePostItem } from "./post-item.mjs"; +import { threadReadErrors, validateThreadReadWarnings } from "./post-thread.mjs"; +import { redactEntry } from "./post-redact.mjs"; +import { anonymiseEntry, anonymityProblems } from "./post-anon.mjs"; +import { REDACT_MARK } from "./post-redact.mjs"; +import { + lineOfText, maskShapes, screenDrawErrors, screenLineSaid, screenPieces, screenRows, screenTileHtml, screenWarnings, validateScreens, +} from "./post-screens.mjs"; + +const IMG = { src: "posts-media/savvy-x/2117/2117_2.jpg", kind: "image", width: 900, height: 1400 }; +const base = (screens, o = {}) => ({ type: "post", id: "p-1", post: "savvy-x/2117", platform: "x", author: "Savvy", handle: "MadamSavvy", date: "2026-11-02T01:40:36.000Z", text: "Your turn.", media: [IMG], screens, ...o }); +/** A thread read of `roles` ([id, n]…), each part saying the line as it is now (as the read would have said it). */ +function narr(e, roles) { + const parts = [{ n: 1, para: 0, text: "Your turn.", role: "post", start: 0, seconds: 1 }]; + let t = 1.8; + roles.forEach(([id, n], i) => { + const sc = e.screens.find((s) => s.id === id); + const text = screenLineSaid(sc, n); + parts.push({ n: parts.length + 1, para: (i + 1) * 100, text, role: `screen:${id}:${n}`, start: t, seconds: 2 }); + t += 2.8; + }); + return { ...e, narration: { script: "Your turn.", pick: 0, takes: [{ file: "narration/posts/1/take-1.orpheus-thread.wav", engine: "orpheus", voice: "x", seconds: t, script: "x", parts }] } }; +} +const shown = (t) => maskShapes(t).text.replace(new RegExp(REDACT_MARK, "g"), "█"); +const card = (e, o = {}) => { + const plan = postItemPlan(e, { postNarration: { lead: 0.4 } }); + return postCardHtml(e, { width: 1600, height: 900, follow: true, thread: plan.follow?.thread ?? null, ...o }); +}; + +// --------------------------------------------------------------------------- +// MUST 1: a stale take -- the line changed, removed or moved after the read -- is refused. +// --------------------------------------------------------------------------- + +test("MUST 1 (p4): a line's words changed after the read: the guard refuses (old audio under new lit text)", () => { + const S = { id: "s1", media: 0, kind: "text", read: [{ line: 0, text: "Jenny said it was fine" }], lines: [{ text: "Long preamble nobody needs. Jenny said it was fine. And then a private aside about her family." }] }; + const e = narr(base([S]), [["s1", 0]]); + assert.deepEqual(threadReadErrors(e, {}), []); + const e2 = structuredClone(e); + e2.screens[0].lines[0].text = "Long preamble. Jenny said it was NOT fine at all. aside"; + e2.screens[0].read = [{ line: 0, text: "Jenny said it was NOT fine" }]; + assert.deepEqual(validatePostItem(e2), []); + assert.ok(threadReadErrors(e2, {}).some((x) => /line 0 of screen s1 changed since the read/.test(x)), threadReadErrors(e2, {}).join("\n")); +}); + +test("MUST 1 (p6): a line removed (the bench's ×, or line.<n>=off) under a read: refused -- the take would SAY the removed line", () => { + const S = { id: "s1", media: 0, kind: "dm", read: [{ line: 0 }, { line: 2 }], lines: [{ who: "a", text: "my home address is 12 Elm Street Springfield" }, { who: "b", text: "ok" }, { who: "a", text: "see you there" }, { who: "b", text: "bye now" }] }; + const e = narr(base([S]), [["s1", 0], ["s1", 2]]); + assert.deepEqual(threadReadErrors(e, {}), []); + // The probe's own case: the line filtered out, `read` left as it was -- each role now names another line. + const e1 = structuredClone(e); + e1.screens[0].lines = e1.screens[0].lines.slice(1); + const errs1 = threadReadErrors(e1, {}); + assert.ok(errs1.some((x) => /line 0 of screen s1 changed since the read/.test(x)), errs1.join("\n")); + assert.ok(errs1.some((x) => /line 2 of screen s1 changed since the read/.test(x)), errs1.join("\n")); + // The read remapped as the bench's × and `line.<n>=off` now do: the roles name lines the screen no longer reads. + const e2 = structuredClone(e); + e2.screens[0].lines = e2.screens[0].lines.slice(1); + e2.screens[0].read = [{ line: 1 }]; + const errs = threadReadErrors(e2, {}); + assert.ok(errs.some((x) => /reads line 0 of screen s1, which the screen does not read/.test(x)), errs.join("\n")); + assert.ok(errs.some((x) => /reads line 2 of screen s1, which the screen does not read/.test(x)), errs.join("\n")); + // A part that stored the line it was made from is judged by it, exactly. + const e3 = structuredClone(e); + e3.narration.takes[0].parts[1].line = "my home address is 12 Elm Street"; + assert.ok(threadReadErrors(e3, {}).some((x) => /line 0 of screen s1 changed since the read/.test(x))); +}); + +// --------------------------------------------------------------------------- +// MUST 2: title, time and who are masked on the card. +// --------------------------------------------------------------------------- + +test("MUST 2 (p3): an e-mail or phone number in a title, a time or a speaker never reaches the card; the lint names them", () => { + const S = { id: "s1", media: 0, kind: "email", title: "Email from savvy.r@gmail.com", read: "all", lines: [{ who: "savvy.r@gmail.com", text: "Hello there friend", time: "555-201-4477" }, { who: "+1 555 201 4477", text: "Card 4111 1111 1111 1111 please" }] }; + for (const red of [undefined, false]) { + const e = narr(base([S], red === undefined ? {} : { redact: red }), [["s1", 0], ["s1", 1]]); + assert.deepEqual(validatePostItem(e), []); + const html = card(e); + for (const needle of ["savvy.r@gmail.com", "555-201-4477", "555 201 4477", "4111"]) assert.ok(!html.includes(needle), `${needle} (redact ${red})`); + assert.ok(!screenLineSaid(S, 1).includes("4111")); + } + const w = screenWarnings(base([S]), { narrated: false }); + assert.ok(w.some((x) => /screen s1's title holds/.test(x))); + assert.ok(w.some((x) => /screen s1 line 0's time holds/.test(x))); + assert.ok(w.some((x) => /screen s1 line 1's speaker holds/.test(x))); + assert.ok(!w.some((x) => /savvy\.r|555|4111/.test(x)), "no value quoted"); +}); + +// --------------------------------------------------------------------------- +// MUST 3: a pasted line never splits a shape into a speaker. +// --------------------------------------------------------------------------- + +test("MUST 3 (p7): `Order number: 4419`, `Ref: AB-1234`, `Tracking: 1Z999AA1`, `Order #: 48213` stay one line, masked", () => { + for (const raw of ["Confirmation code: 552-118", "Order #: 48213", "Order number: 4419", "Tracking: 1Z999AA1", "savvy@gmail.com: hi there", "Phone: 555 201 4477", "Ref: AB-1234"]) { + const l = lineOfText(raw); + assert.equal(l.who, undefined, `${raw}: no speaker split off`); + assert.equal(shown(l.text), shown(raw), `${raw}: masked as the whole line is`); + assert.ok(/█/.test(shown(l.text)), `${raw}: something masked`); + } + assert.deepEqual(lineOfText("TheQuartering: what's your email | 11:32 AM"), { who: "TheQuartering", text: "what's your email", time: "11:32 AM" }); +}); + +// --------------------------------------------------------------------------- +// MUST 4 + SHOULD e: the shapes. +// --------------------------------------------------------------------------- + +test("MUST 4 (p1, p2): cards, spaced SSNs and local numbers, dash/dot separators, fullwidth digits, `is` after the keyword, non-ASCII e-mail -- all masked", () => { + const masked = [ + ["card 4111 1111 1111 1111 exp 12/27", "card ████ ████ ████ ████ exp █████"] /* exp MM/YY masked since review 2 */, + ["Order: 1234 5678 9012 3456 7890", "Order: ████ ████ ████ ████ ████"], + ["call 555 – 123 – 4567", "call ███ █ ███ █ ████"], + ["call 555 · 123 · 4567", "call ███ █ ███ █ ████"], + ["call 555-123-4567", "call ████████████"], + ["Your order number is 48213", "Your order number is █████"], + ["confirmation code is 5521", "confirmation code is ████"], + ["ssn 123 45 6789", "ssn ███ ██ ████"], + ["call 555 1234", "call ███ ████"], + ["jöhn.doe@exämple.com", "████████████████████"], + ["tracking 1Z 999 AA1 01 2345 6784", "tracking ██ ███ ███ ██ ████ ████"], + ["Your order is 48213", "Your order is █████"], + ["code 12345", "code █████"], + ["account ending 4821", "account ending ████"], + ]; + for (const [t, want] of masked) assert.equal(shown(t), want, t); + // Still shown: amounts, weights, years, times, DATES (should-fix e). + for (const t of ["Total $104.90 USD", "1,000,000 views", "$1,250.00 refund", "lost 12.5 lbs since 2024", "400 pounds", "290", "at 12:18 PM", "on 11/02/2026 at 10:42", "weighed 312.4 on 2026-11-02", "zip 90210"]) assert.equal(shown(t), t, t); +}); + +// --------------------------------------------------------------------------- +// MUST 5: the redaction and anonymity passes keep excerpts -- and a broken excerpt is refused, never drawn whole. +// --------------------------------------------------------------------------- + +test("MUST 5 (p4): a redaction term inside an excerpt: the card draws the excerpt (labelled), never the whole line", () => { + const S = { id: "s1", media: 0, kind: "text", read: [{ line: 0, text: "Jenny said it was fine" }], lines: [{ text: "Long preamble nobody needs. Jenny said it was fine. And then a private aside about her family." }] }; + const e = narr(base([S]), [["s1", 0]]); + const red = { terms: ["Jenny"] }; + const r = redactEntry(e, red); + const rows = screenRows(r.screens[0]); + assert.equal(rows.filter((x) => !x.gap).length, 1); + assert.ok(!rows[0].text.includes("private aside") && !rows[0].text.includes("preamble"), rows[0].text); + const html = card(e, { redaction: red }); + assert.ok(!html.includes("private aside")); + assert.ok(html.includes("data-screen-excerpt")); + assert.ok(!html.includes("Jenny")); + assert.deepEqual(screenDrawErrors(r), []); +}); + +test("MUST 5 (p5): after the anonymity pass the excerpt is the excerpt (its @handle rewritten), never the whole line", () => { + const set = new Map([["secretkid", "Kid A"]]); + const S = { id: "s1", media: 0, kind: "dm", read: [{ line: 0, text: "ask @secretkid about it" }], lines: [{ who: "secretkid", text: "private stuff first. ask @secretkid about it. more private stuff" }] }; + const a = anonymiseEntry(base([S]), set); + const rows = screenRows(a.screens[0]).filter((x) => !x.gap); + assert.equal(rows.length, 1); + assert.equal(rows[0].text, "ask @Kid_A about it."); + assert.deepEqual(screenDrawErrors(a), []); +}); + +test("MUST 5: an excerpt that no longer matches the line as drawn is NOT drawn whole: the line is left out and the build is told", () => { + const S = { id: "s1", media: 0, kind: "text", read: [{ line: 0, text: "said it was fine" }], lines: [{ text: "Preamble. He said it was fine. Private aside." }] }; + const broken = structuredClone(S); + broken.lines[0].text = "Preamble. He said it was okay. Private aside."; + const rows = screenRows(broken); + assert.ok(!rows.some((r) => !r.gap && /Private aside/.test(r.text)), JSON.stringify(rows)); + assert.equal(screenLineSaid(broken, 0), ""); + assert.ok(screenDrawErrors(base([broken])).some((x) => /line 0 of screen s1: its excerpt is not in the line/.test(x))); + assert.ok(validateScreens(base([broken])).some((x) => /\.read\[0\]\.text is not a run of line 0's words/.test(x))); +}); + +// --------------------------------------------------------------------------- +// SHOULD b, c, d, f. +// --------------------------------------------------------------------------- + +test("SHOULD b (p9): a screenshot of a post names its author from a DRAWN line, never a redacted one", () => { + const esc = (s) => String(s).replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[c]); + const sc = { id: "s1", media: 0, kind: "post", read: [{ line: 1 }], lines: [{ who: "secret_person", text: "hidden words", redact: true }, { text: "visible words" }] }; + const html = screenTileHtml({ author: "A", handle: "aa", media: [{ kind: "image" }], redact: false }, sc, { k: 1, size: 30, blocks: new Map(), shown: () => true, h: { esc } }); + assert.ok(!html.includes("secret_person") && !html.includes("hidden words")); +}); + +test("SHOULD c (p5): the anonymity lint catches a speaker, title or time that writes an anonymous handle in any form", () => { + const S = { id: "s1", media: 0, kind: "dm", read: "all", title: "chat with secretkid", lines: [{ who: "SecretKid (alt)", text: "hi" }, { who: "x.com/secretkid", text: "yo", time: "@secretkid" }] }; + const m = { timeline: [base([S])] }; + const errs = anonymityProblems(m, {}, { set: new Map([["secretkid", "Kid A"]]) }).errors; + assert.ok(errs.filter((x) => /screen s1/.test(x)).length >= 3, errs.join("\n")); + assert.ok(!errs.some((x) => /secretkid/i.test(x)), "never the real handle"); +}); + +test("SHOULD d: lint and validation name a line, never quote its value", () => { + const S = { id: "s1", media: 0, kind: "dm", read: [{ line: 0, text: "my secret words here" }], lines: [{ who: "privateperson", text: "something else entirely" }] }; + const v = validateScreens(base([S])); + assert.ok(v.some((x) => /read\[0\]\.text is not a run of line 0's words/.test(x))); + assert.ok(!v.some((x) => /secret words/.test(x))); + const w = screenWarnings(base([{ ...S, read: "all" }]), { narrated: true, takeRoles: ["screen:s1:0"] }); + assert.ok(w.some((x) => /line 0's speaker is drawn blurred/.test(x)), w.join("\n")); + assert.ok(!w.some((x) => /privateperson/.test(x))); +}); + +test("SHOULD f (p8): at the limits (8 screens × 60 long lines, each an excerpt) the plan and the card stay quick", () => { + const W = "the of and to in is you that it he was for on are as with his they I at be this have from or one had by word but not what all were we when your can said there use an each which she do how their if will up".split(" "); + const line = Array.from({ length: 110 }, (_, i) => W[(i * 7) % W.length]).join(" ").slice(0, 598); + const ex = line.split(" ").slice(40, 80).join(" "); + const mk = (id) => ({ id, media: 0, kind: "dm", read: Array.from({ length: 60 }, (_, n) => ({ line: n, text: ex })), lines: Array.from({ length: 60 }, (_, n) => ({ who: n % 2 ? "x" : "y", text: line })) }); + const e0 = base(Array.from({ length: 8 }, (_, i) => mk(`s${i + 1}`))); + let t = performance.now(); + const pcs = screenPieces(e0); + assert.equal(pcs.length, 480); + const parts = [{ n: 1, para: 0, text: "Your turn.", role: "post", start: 0, seconds: 1 }]; + let s = 2; + pcs.forEach((p, i) => { + parts.push({ n: parts.length + 1, para: (i + 1) * 100, text: p.text, role: p.role, start: s, seconds: 1 }); + s += 1.5; + }); + const e = { ...e0, narration: { script: "Your turn.", pick: 0, takes: [{ file: "narration/posts/1/take-1.orpheus-thread.wav", engine: "orpheus", voice: "x", seconds: s, script: "x", parts }] } }; + t = performance.now(); + const plan = postItemPlan(e, { postNarration: { lead: 0.4 } }); + const planMs = performance.now() - t; + t = performance.now(); + postCardHtml(e, { width: 1600, height: 900, follow: true, thread: plan.follow?.thread ?? null }); + const cardMs = performance.now() - t; + assert.ok(planMs < 1500, `plan ${planMs.toFixed(0)} ms`); + assert.ok(cardMs < 1500, `card ${cardMs.toFixed(0)} ms`); +}); + +test("MINOR: a narration with attach: after does not play the screens' spans -- the lint says so", () => { + const S = { id: "s1", media: 0, kind: "dm", read: "all", lines: [{ who: "a", text: "hello" }] }; + const e = narr(base([S]), [["s1", 0]]); + e.narration.attach = "after"; + assert.ok(validateThreadReadWarnings({ timeline: [e], render: {} }).some((x) => /attach: after/.test(x))); +}); diff --git a/umtool/report-to-video/post-screens-review2.test.mjs b/umtool/report-to-video/post-screens-review2.test.mjs @@ -0,0 +1,155 @@ +// lane/screen-reads REVIEW 2 (12 Nov): the reviewer's probes q1/q2 as tests. Three blockers -- the staleness guard +// judged on the drawn (anonymised) copy; a line take that says a shape or extra words; dash-written SSNs and phone runs +// split by a decimal -- and five should-fixes. The build's ENFORCED lint (build-video.mjs enforcedLint, the seam the +// build and every take's render go through) is where a read of a screen is refused. Temp dirs only. +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { after, test } from "node:test"; +import { buildVideo, enforcedLint, selectVariant } from "./build-video.mjs"; +import { anonymiseEntry, anonymiseManifest } from "./post-anon.mjs"; +import { projectAnonymousSet } from "./project-characters-file.mjs"; +import { draftScript } from "./post-narration.mjs"; +import { threadReadErrors, validateScreenReads } from "./post-thread.mjs"; +import { REDACT_MARK } from "./post-redact.mjs"; +import { maskShapes, screenLineSaid, screenWarnings } from "./post-screens.mjs"; + +const TMP = await mkdtemp(path.join(tmpdir(), "umtool-screens-review2-")); +after(() => rm(TMP, { recursive: true, force: true })); +const shown = (t) => maskShapes(t).text.replace(new RegExp(REDACT_MARK, "g"), "█"); +const IMG = { src: "a.jpg", kind: "image", width: 10, height: 10 }; +const mk = (lines, read = "all") => ({ type: "post", id: "p-1", post: "x/1", platform: "x", author: "A", handle: "aa", date: "2026-11-02T01:40:36.000Z", text: "Your turn.", url: "https://x.com/aa/status/1", media: [IMG], screens: [{ id: "s1", media: 0, kind: "dm", read, lines }] }); +/** A thread read of every read line, each part storing the line and the speaker it was made from (as the read does). */ +function take(e) { + const sc = e.screens[0]; + const parts = [{ n: 1, para: 0, text: "Your turn.", role: "post", start: 0, seconds: 1 }]; + sc.lines.forEach((l, n) => { + const s = screenLineSaid(sc, n); + if (s) parts.push({ n: parts.length + 1, para: (n + 1) * 100, text: s, line: draftScript(s).script, speaker: l.who ?? "", role: `screen:s1:${n}`, start: 2 + n * 3, seconds: 2 }); + }); + return { ...e, narration: { script: "Your turn.", pick: 0, takes: [{ file: "narration/posts/1/take-1.orpheus-thread.wav", engine: "orpheus", voice: "x", seconds: 20, script: "x", parts }] } }; +} + +// --------------------------------------------------------------------------- +// MUST 1: staleness is judged on the cut AS WRITTEN; the build's enforced lint refuses a stale read, never a fresh one. +// --------------------------------------------------------------------------- + +const CHARS = { format: "umtool-project-characters", version: 1, characters: [{ id: "anon-1", name: "Real Guy", anonymous: true, shown: "Anon 1", handles: ["secretkid"] }] }; +const wholeOf = (e) => ({ schemaVersion: 1, title: "T", slug: "t", provenance: {}, render: { width: 1280, height: 720, fps: 30 }, timeline: [e] }); +async function project(name, whole) { + const dir = path.join(TMP, name); + await mkdir(path.join(dir, "narration/posts/1"), { recursive: true }); + await writeFile(path.join(dir, "narration/characters.json"), JSON.stringify(CHARS)); + await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify(whole)); + return dir; +} +const seam = async (dir, whole) => { + const anonymity = await projectAnonymousSet(dir, whole); + const cut = selectVariant(whole, "sourced"); + const drawn = anonymiseManifest(cut, anonymity.doc, { set: anonymity.set }); + return enforcedLint(drawn, { manifestDir: dir, whole, only: null, validators: false }, { cut, anonymity }); +}; + +test("MUST 1 (q1): a line mentioning an anonymous handle -- its fresh read is not refused (as drawn or at the build's seam)", async () => { + // As a synthesized read says it (the shown name), so the anonymity lint is quiet too. + const e = take(mk([{ who: "bob", text: "ask @secretkid about it" }])); + e.narration.takes[0].parts[1].text = "ask Anon 1 about it."; + assert.deepEqual(threadReadErrors(e, {}), []); + assert.deepEqual(threadReadErrors(anonymiseEntry(e, new Map([["secretkid", "Anon 1"]])), {}), [], "the drawn copy is self-consistent too"); + const whole = wholeOf(e); + const lint = await seam(await project("q1", whole), whole); + assert.ok(!lint.errors.some((x) => /screen s1|changed since the read/.test(x)), lint.errors.join("\n")); +}); + +test("MUST 1: the build's enforced lint REFUSES a stale screen read -- at the seam and through a take's render manifest", async () => { + const e = take(mk([{ who: "bob", text: "ask @secretkid about it" }, { who: "aa", text: "will do" }])); + e.narration.takes[0].parts[1].text = "ask Anon 1 about it."; + e.screens[0].lines[1].text = "will NOT do"; + const whole = wholeOf(e); + const dir = await project("stale", whole); + const lint = await seam(dir, whole); + assert.ok(lint.errors.some((x) => /line 1 of screen s1 changed since the read/.test(x)), lint.errors.join("\n")); + const renderManifest = path.join(dir, ".take-t1.render.json"); + await writeFile(renderManifest, JSON.stringify(whole)); + await assert.rejects(buildVideo({ manifestPath: renderManifest, opts: { noNetwork: true, skipFetch: true } }), /lint: .*line 1 of screen s1 changed since the read/); + // The fresh one's render stops on its missing files alone, never on its screen. + const fresh = wholeOf(take(mk([{ who: "bob", text: "ask @secretkid about it" }]))); + fresh.timeline[0].narration.takes[0].parts[1].text = "ask Anon 1 about it."; + const d2 = await project("fresh", fresh); + const rm2 = path.join(d2, ".take-t2.render.json"); + await writeFile(rm2, JSON.stringify(fresh)); + await assert.rejects(buildVideo({ manifestPath: rm2, opts: { noNetwork: true, skipFetch: true } }), (err) => /lint:/.test(err.message) && !/screen s1/.test(err.message)); +}); + +test("SHOULD (who): a speaker-only edit under a read is refused -- the old voice under a new name", () => { + const base = take(mk([{ who: "bob", text: "hello there" }, { who: "aa", text: "see you soon" }])); + assert.deepEqual(threadReadErrors(base, {}), []); + const x = structuredClone(base); + x.screens[0].lines[0].who = "SomeoneElse"; + assert.ok(threadReadErrors(x, {}).some((m) => /line 0 of screen s1 changed since the read/.test(m))); + const y = structuredClone(base); + y.screens[0].lines[1].side = "left"; + assert.deepEqual(threadReadErrors(y, {}), [], "a side is not a word"); + // A part that recorded no speaker (a take made before speakers were recorded, or by hand) is judged by its words + // alone: an unchanged line is not refused for it. + const z = structuredClone(base); + for (const pt of z.narration.takes[0].parts) delete pt.speaker; + assert.deepEqual(threadReadErrors(z, {}), []); +}); + +// --------------------------------------------------------------------------- +// MUST 2: what a screen piece SAYS holds no shape -- refused by the build's enforced lint. +// --------------------------------------------------------------------------- + +test("MUST 2: a screen part that says a shape (a recorded line take saying the number) is refused by validateScreenReads", () => { + const e = take(mk([{ who: "bob", text: "please call me at 555 201 4477 tonight after work ok" }])); + assert.deepEqual(validateScreenReads({ timeline: [e] }), []); + e.narration.takes[0].parts[1].text = "please call me at 555 201 4477 tonight after work ok"; + assert.ok(validateScreenReads({ timeline: [e] }).some((x) => /part 2 \(line 0 of screen s1\) says a long number or a phone number/.test(x))); + assert.ok(!validateScreenReads({ timeline: [e] }).some((x) => /555/.test(x)), "never the value"); +}); + +// --------------------------------------------------------------------------- +// MUST 3 + SHOULD keywords: the shapes. +// --------------------------------------------------------------------------- + +test("MUST 3 (q1): dash- and dot-written SSNs, 3-2-4 groups, a phone run around a decimal -- masked; plausible dates kept", () => { + for (const [t, want] of [ + ["my social is 123-45-6789", "my social is ███████████"], + ["call 555-12-3456", "call ███████████"], + ["1234-56-7890", "████████████"], + ["acct 12/34/5678", "acct ██████████"], + ["SSN: 078.05.1120", "SSN: ███████████"], + ["call 555 201-44.77 now", "call ███ █████████ now"], + ]) assert.equal(shown(t), want, t); + for (const t of ["on 11/02/2026 at 10:42", "weighed 312.4 on 2026-11-02", "lost 41.2 lbs, 312.4 to 271.2", "since 02.11.26", "weights 312.4 310.2 308.0 305.5", "paid $104.90 today"]) assert.equal(shown(t), t, t); +}); + +test("SHOULD (keywords): cvv, cvc, security code, exp MM/YY, a date of birth -- masked", () => { + for (const [t, want] of [ + ["exp 12/27 cvv 123", "exp █████ cvv ███"], + ["cvc 4821", "cvc ████"], + ["security code 991", "security code ███"], + ["DOB 1990-04-12", "DOB ██████████"], + ["my birthday is 4/12/1990", "my birthday is █████████"], + ["born 04/12/1990", "born ██████████"], + ]) assert.equal(shown(t), want, t); +}); + +test("SHOULD (split digits): two adjacent lines whose digits together make a shape -- the lint names the lines", () => { + const e = mk([{ who: "a", text: "my card is 4111 1111" }, { who: "a", text: "1111 1111" }, { who: "a", text: "call 555 201" }, { who: "a", text: "4477 thanks" }, { who: "a", text: "ok" }]); + const w = screenWarnings(e, { narrated: false }); + assert.ok(w.some((x) => /lines 0 and 1 of screen s1 together hold/.test(x)), w.join("\n")); + assert.ok(w.some((x) => /lines 2 and 3 of screen s1 together hold/.test(x)), w.join("\n")); + assert.ok(!w.some((x) => /lines 3 and 4/.test(x))); + assert.ok(!w.some((x) => /4111|555/.test(x))); +}); + +test("SHOULD (draw errors up front): an excerpt not in its line as drawn is refused by the build's enforced lint", async () => { + const e = take(mk([{ who: "bob", text: "Preamble. He said it was fine. Private aside." }], [{ line: 0, text: "said it was fine" }])); + const whole = wholeOf(e); + whole.timeline[0].screens[0].read = [{ line: 0, text: "said it was okay" }]; + const lint = await seam(await project("draw", whole), whole); + assert.ok(lint.errors.some((x) => /line 0 of screen s1: its excerpt is not in the line as drawn/.test(x)), lint.errors.join("\n")); +}); diff --git a/umtool/report-to-video/post-screens.mjs b/umtool/report-to-video/post-screens.mjs @@ -0,0 +1,747 @@ +// A POST's SCREENS: TEXT SCREENSHOTS READ AS PART OF THE POST (umtool/docs/report-video.md, "Screens"; operator, 12 Nov +// 2026, on quartering-diet rev9-a9: "the screenshots should be treated as extensions of the post rather than +// transparent, probably read and probably with excerpts because it's long text. You can show it alongside the video in +// the tweet slot as you read" -- "The 'read text screenshots as posts' ability in different variations should be first +// class, it's a very common pattern"). +// +// A post item may carry SCREENS: the text screenshots that belong to the post -- a DM exchange or an email shown in its +// video, an image attachment that is a screenshot of a chat, a letter, another post. Each is TRANSCRIBED once (data, a +// person checks it), DRAWN legibly on the card as part of the post, and READ -- whole or in excerpts -- in the voices of +// the people in it, each line lit while it is said. The standing rule holds: no hidden text is ever narrated, and every +// read piece is on screen in full and lit while it is read (post-thread.mjs). +// +// screens: [{ id: "s1", media: 0, at: [3.5, 8], kind: "dm", title?, source?: "transcribed", checked?: { by, at }, +// ref?: "<channel>/<postId>", unread?: "omit" | "dim", +// lines: [{ who?, side?: "left" | "right", text, time?, redact?: true }], +// read: "all" | "none" | [{ line, text? }] }] +// +// - `media` names the attachment (an index into the item's `media`); `at` the source span a video or GIF shows it. +// - `read`: every line ("all"), none ("none": transcribed only -- not drawn, not read), or the lines listed, each read +// whole or an EXCERPT (`text`: a contiguous run of that line's words; drawn "…excerpt…", the cut sides marked). +// - `unread`: the lines a read screen does not read are left out ("omit", the default: a "⋯" row where they were) or +// drawn dim ("dim"). A line marked `redact: true` is never drawn nor read. +// - THE SHAPES: an e-mail address, a phone number, a long run of digits, an order or confirmation number in a line are +// MASKED (a bar on the card, never said) whether or not anyone marked them -- the lint says which line held one. +// - `who`: a handle or a name; it is the post's author (her own lines, on the right), or another speaker, voiced through +// the project's characters and the cast as a thread read's pieces are (post-say.mjs) and drawn under the item's +// privacy rule (a subject, or `redact: false`, shown; else blurred), an anonymous one under its shown name. +// +// THE READ (lib/report/postThreadRead.mjs): each read line is a piece of the thread read, after the post's own words, in +// the screens' order, its ROLE `screen:<id>:<n>` (n the line's index). THE CARD (post-thread.mjs threadLayout): a screen +// the take reads is a tile `screen:<id>` after his post -- his post shrinks to a strip as it is revealed, it collapses as +// the next comes in. THE MEDIA (post-item.mjs planOf): while a screen is read the slot plays its span, its last frame held. +// +// PURE and dependency-free but for its siblings. +import { REDACT_MARK, dropMarks, redactText } from "./post-redact.mjs"; +import { handleKey } from "./post-say.mjs"; + +export const SCREEN_KINDS = Object.freeze(["dm", "email", "post", "text"]); +export const SCREEN_SIDES = Object.freeze(["left", "right"]); +export const SCREEN_UNREAD = Object.freeze(["omit", "dim"]); +export const SCREEN_ID_RE = /^[a-z0-9][a-z0-9-]{0,23}$/; +export const SCREENS_MAX = 8; +export const SCREEN_LINES_MAX = 60; +export const SCREEN_LINE_MAX = 600; +export const SCREEN_TITLE_MAX = 80; +export const SCREEN_WHO_MAX = 64; +export const SCREEN_TIME_MAX = 24; +/** The least span (s) a screen may name in a video. */ +export const SCREEN_MIN_SPAN = 0.5; +/** The pause between two lines of one screen in a joined read (a new piece is POST_PART_GAP.piece). */ +export const SCREEN_LINE_GAP = 0.35; +/** The drawing's version: a change to how a screen is drawn rebuilds the segments that draw one (post-render.mjs). */ +export const POST_SCREEN_DRAW_V = 1; +/** A screen line's role: `screen:<id>:<n>`. */ +export const SCREEN_ROLE_RE = /^screen:([a-z0-9][a-z0-9-]{0,23}):(\d{1,2})$/; + +const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); +const fin = (v) => typeof v === "number" && Number.isFinite(v); +const str = (v) => (typeof v === "string" ? v : ""); +const r3 = (v) => Math.round(v * 1000) / 1000; + +/** A line's role. */ +export const screenRole = (id, n) => `screen:${id}:${n}`; +/** A screen's tile scope on the card. */ +export const screenScope = (id) => `screen:${id}`; +/** A role's screen and line, or null when it is not a screen line's. */ +export function parseScreenRole(role) { + const m = SCREEN_ROLE_RE.exec(str(role)); + return m ? { id: m[1], n: Number(m[2]) } : null; +} +/** Whether a scope or role is a screen's. */ +export const isScreenScope = (s) => str(s).startsWith("screen:"); +/** The TILE a role is read on: a screen line's is its screen's; any other role is its own. */ +export const tileOfRole = (role) => { + const p = parseScreenRole(role); + return p ? screenScope(p.id) : role; +}; + +/** An item's screens as drawn and read (each an object with an id and lines); [] when it has none. */ +export const screensOf = (entry) => + Array.isArray(entry?.screens) ? entry.screens.filter((s) => isObj(s) && SCREEN_ID_RE.test(str(s.id)) && Array.isArray(s.lines)).slice(0, SCREENS_MAX) : []; +/** Whether an item carries screens. */ +export const hasScreens = (entry) => screensOf(entry).length > 0; +/** One screen by id. */ +export const screenOf = (entry, id) => screensOf(entry).find((s) => s.id === id) ?? null; + +// --------------------------------------------------------------------------- +// THE SHAPES: what is never typeset nor read, marked or not. +// --------------------------------------------------------------------------- + +// Letters and digits of any script (`u`): "jöhn.doe@exämple.com", fullwidth digits "555". +const EMAIL_RE = /[\p{L}\p{N}._%+-]+[@@](?:[\p{L}\p{N}-]+(?:\.[\p{L}\p{N}-]+)+|[\p{L}\p{N}-]{2,})/gu; +const SPOKEN_EMAIL_RE = /[\p{L}\p{N}._-]+ (?:at) [\p{L}\p{N}-]+ (?:dot) (?:com|net|org|co|uk|io|me|us|edu|gov|ca|de|fr|au)\b/giu; +/** A PHONE-STYLE RUN: digits joined by spaces, dashes, dots, middle dots, slashes or brackets (at most three between). */ +const RUN_RE = /[+(]?\p{Nd}(?:[ \t\-‐‑–—·./()]{0,3}\p{Nd})*/gu; +/** A decimal (an amount, a weight: "99.95", "312.4") -- never part of a run. */ +const DECIMAL_RE = /\p{Nd}+[.,]\p{Nd}{1,2}(?!\p{Nd})/gu; +/** + * A PLAUSIBLE date -- shown: a year of 19xx / 20xx first with a month and a day after it (2026-11-02), or a month and a + * day (either order) then a two-digit or a 19xx / 20xx year (11/02/2026, 02.11.26). A 3-2-4 group (an SSN) is never one. + */ +const DATE_SHAPE = /^(\p{Nd}{1,4})[/.\-‐‑–—](\p{Nd}{1,2})[/.\-‐‑–—](\p{Nd}{1,4})$/u; +const isDate = (v) => { + const m = DATE_SHAPE.exec(str(v).replace(/\p{Nd}/gu, (d) => String(Number.parseInt(d.normalize("NFKC"), 10)))); + if (!m) return false; + const [a, b, c] = [m[1], m[2], m[3]]; + const year4 = (y) => /^(19|20)\d\d$/.test(y); + const md = (x, y) => (Number(x) >= 1 && Number(x) <= 12 && Number(y) >= 1 && Number(y) <= 31) || (Number(y) >= 1 && Number(y) <= 12 && Number(x) >= 1 && Number(x) <= 31); + if (year4(a)) return Number(b) >= 1 && Number(b) <= 12 && Number(c) >= 1 && Number(c) <= 31 && c.length <= 2; + return a.length <= 2 && b.length <= 2 && (c.length === 2 || year4(c)) && md(a, b); +}; +/** Case-insensitive by letters (the `i` flag would make the IBAN's \p{Lu} match any letter). */ +const ci = (w) => w.replace(/[a-z]/g, (c) => `[${c}${c.toUpperCase()}]`); +const KEYWORDS = "order|confirmation|conf|invoice|tracking|reference|ref|account|acct|card|iban|ssn|social security|security code|code|pin|passcode|routing|member|customer|ticket|receipt|transaction|policy|booking|reservation|serial|cvv|cvc|exp|expiry|expires|dob|date of birth|born|birthday|id".split("|").map(ci).join("|"); +const GROUP = String.raw`[#]?[\p{L}\p{N}\-/.]*\p{Nd}[\p{L}\p{N}\-/.]*`; +/** A keyword, "number" / "no." / "#", "is" / ":" / "ending in", then its value: groups with digits (an IBAN's capitals between them). */ +const ORDER_RE = new RegExp(String.raw`(?<![\p{L}\p{N}])(?:${KEYWORDS})(?:\s+(?:${["number", "no", "no.", "num", "id", "code"].map(ci).join("|").replace(/\./g, "\\.")}|#))?(?:\s*(?:${["is", "was", "ending in", "ending"].map(ci).join("|")}|=|:|#))*\s*(${GROUP}(?:[ \t](?:${GROUP}|\p{Lu}{1,4}(?=[ \t]${GROUP})))*)`, "gu"); +const HASHNUM_RE = /#\s?[\p{L}\p{N}-]*\p{Nd}{4,}[\p{L}\p{N}-]*/gu; +const TOKEN_RE = /[^\s]+/g; +const AMOUNT_RE = /^[($]*\$?\p{Nd}{1,3}(?:,\p{Nd}{3})+(?:\.\p{Nd}+)?[).,;:!?]*$|^[($]*\$\p{Nd}{1,8}(?:\.\p{Nd}+)?[).,;:!?]*$|^\p{Nd}+\.\p{Nd}{1,2}[).,;:!?]*$/u; +const digitsIn = (t) => (str(t).match(/\p{Nd}/gu) ?? []).length; +const SHAPE_CACHE = new Map(); + +/** + * THE SHAPES in a line, pure: `[{ start, end, kind }]` -- what is never drawn nor said, marked or not: + * "email" an e-mail address (any script; with or without its domain's ending), or one spelt out ("x at y dot com") + * "number" a phone-style run of nine digits or more (a card, an IBAN's digits, a phone, a spaced SSN), a local number + * (555 1234), a token of six digits or more -- never an amount ($104.90, 1,000,000), a decimal, a DATE + * (11/02/2026, 2026-11-02) or a time + * "order" the value after order / confirmation / tracking / reference / account / card / code … ("is", ":", "#", + * "ending in" between), or a "#1234" + * Merged, in order. Linear in the line (one pass a pattern). + */ +export function shapeSpans(text) { + const t = str(text); + if (!t) return []; + const hit = SHAPE_CACHE.get(t); + if (hit) return hit.map((x) => ({ ...x })); + const out = []; + for (const m of t.matchAll(EMAIL_RE)) { + // "@handle" alone is a mention (a local part is needed); a trailing dot is the sentence's. + const v = m[0].replace(/[.\-]+$/, ""); + if (/^[@@]/.test(v)) continue; + out.push({ start: m.index, end: m.index + v.length, kind: "email" }); + } + for (const m of t.matchAll(SPOKEN_EMAIL_RE)) out.push({ start: m.index, end: m.index + m[0].length, kind: "email" }); + // Runs, a free-standing decimal blanked first (a list of weights is not a phone number) -- never one that touches a + // run's separator or another digit ("555 201-44.77", "078.05.1120": those are the run). + const blank = t.replace(DECIMAL_RE, (d, at) => (/[\-‐‑–—·./()\p{Nd}]/u.test(t[at - 1] ?? "") || /[\-‐‑–—·./()\p{Nd}]/u.test(t[at + d.length] ?? "") ? d : "x".repeat(d.length))); + for (const m of blank.matchAll(RUN_RE)) { + const v = m[0].replace(/[ \t\-‐‑–—·./(]+$/, ""); + const n = digitsIn(v); + if (n < 7 || isDate(v.replace(/^[+(]/, ""))) continue; + const local = n <= 8 && /^\p{Nd}{3}[ \t\-‐‑–—·.]{1,3}\p{Nd}{4}$/u.test(v); + if (n >= 9 || local) out.push({ start: m.index, end: m.index + v.length, kind: "number" }); + } + for (const m of t.matchAll(ORDER_RE)) { + const v = m[1].replace(/[.\-]+$/, ""); + if (digitsIn(v) < 3) continue; + const at = m.index + m[0].length - m[1].length; + out.push({ start: at, end: at + v.length, kind: "order" }); + } + for (const m of t.matchAll(HASHNUM_RE)) out.push({ start: m.index, end: m.index + m[0].length, kind: "order" }); + for (const m of t.matchAll(TOKEN_RE)) { + const tok = m[0]; + if (digitsIn(tok) < 6 || AMOUNT_RE.test(tok)) continue; + const lead = tok.match(/^[("'“[]*/)[0].length; + const trail = tok.match(/[)"'”\].,;:!?]*$/)[0].length; + const core = tok.slice(lead, tok.length - trail); + if (isDate(core) || /^\p{Nd}{1,2}:\p{Nd}{2}(?::\p{Nd}{2})?$/u.test(core)) continue; + out.push({ start: m.index + lead, end: m.index + tok.length - trail, kind: "number" }); + } + out.sort((a, b) => a.start - b.start || b.end - a.end); + const merged = []; + for (const sp of out) { + if (sp.end <= sp.start) continue; + const last = merged[merged.length - 1]; + if (last && sp.start <= last.end) last.end = Math.max(last.end, sp.end); + else merged.push({ ...sp }); + } + if (SHAPE_CACHE.size > 20000) SHAPE_CACHE.clear(); + SHAPE_CACHE.set(t, merged.map((x) => ({ ...x }))); + return merged; +} + +/** A line's words with its shapes MASKED (the redaction's marks: drawn as bars, dropped when said), and what was masked. */ +export function maskShapes(text) { + const spans = shapeSpans(text); + if (!spans.length) return { text: str(text), kinds: [] }; + return { text: redactText(str(text), [], { spans }).text, kinds: [...new Set(spans.map((s) => s.kind))] }; +} + +/** A short field (a title, a speaker, a time) as drawn: its shapes masked. */ +export const maskedField = (v) => maskShapes(str(v)).text; + +// --------------------------------------------------------------------------- +// WHAT IS READ AND WHAT IS DRAWN of a screen. +// --------------------------------------------------------------------------- + +const words = (t) => [...str(t).matchAll(/\S+/g)].map((m) => ({ w: m[0], start: m.index, end: m.index + m[0].length })); +const wkey = (w) => w.toLowerCase().replace(/^[^\p{L}\p{N}$#@]+|[^\p{L}\p{N}%]+$/gu, ""); + +/** + * Where an EXCERPT stands in its line, pure: `{ start, end }` (character offsets of the line's own words it names, a + * contiguous run; their edge punctuation need not match) -- or null when it is not a run of the line's words. + */ +export function excerptRun(line, excerpt) { + const L = words(line); + const E = words(excerpt).map((x) => wkey(x.w)); + if (!E.length || E.length > L.length) return null; + const keys = L.map((x) => wkey(x.w)); + for (let i = 0; i + E.length <= L.length; i += 1) { + let ok = true; + for (let j = 0; j < E.length; j += 1) { + if (keys[i + j] !== E[j]) { + ok = false; + break; + } + } + if (ok) return { start: L[i].start, end: L[i + E.length - 1].end }; + } + return null; +} + +/** Whether a line can be read or drawn at all: not marked redact, with words. */ +const lineOk = (l) => isObj(l) && l.redact !== true && !!str(l.text).trim(); + +/** One screen worked out once (memoized by the screen object and what it holds): its read lines, its broken excerpts. */ +const VIEWS = new WeakMap(); +function viewOf(screen) { + if (!isObj(screen)) return { reads: [], broken: [] }; + const lines = Array.isArray(screen.lines) ? screen.lines : []; + const key = JSON.stringify([screen.read, lines]); + const had = VIEWS.get(screen); + if (had && had.key === key) return had; + const r = screen.read; + const asked = r === "all" ? lines.map((_, n) => ({ line: n })) : Array.isArray(r) ? r.filter((x) => isObj(x) && Number.isInteger(x.line)) : []; + const seen = new Set(); + const reads = []; + const broken = []; + for (const x of asked) { + const l = lines[x.line]; + if (!lineOk(l) || seen.has(x.line)) continue; + seen.add(x.line); + const t = str(l.text); + const all = { start: t.search(/\S/), end: t.trimEnd().length }; + let span = all; + if (str(x.text).trim()) { + const run = excerptRun(t, x.text); + // An excerpt that is not in the line (as drawn: after the redaction or anonymity passes) is NEVER read or drawn + // whole: the line is left out, and the build is told (screenDrawErrors). + if (!run) { + broken.push(x.line); + continue; + } + span = run; + } + const masked = maskShapes(t).text; + const cut = masked.slice(span.start, span.end); + reads.push({ n: x.line, start: span.start, end: span.end, cutBefore: span.start > all.start, cutAfter: span.end < all.end, said: cut.includes(REDACT_MARK) ? dropMarks(cut) : cut.trim(), shown: cut }); + } + reads.sort((a, b) => a.n - b.n); + const v = { key, reads, broken }; + VIEWS.set(screen, v); + return v; +} + +/** + * A screen's READ LINES, pure, in the line order: `[{ n, start, end, cutBefore, cutAfter }]` -- each line read, the + * run of its words read (the whole line, or its excerpt), and whether words were cut before or after it. "none", a + * redacted line, a line with no words, or an EXCERPT NOT IN ITS LINE: none (never the whole line instead). + */ +export function screenReadLines(screen) { + return viewOf(screen).reads.map(({ said: _s, shown: _w, ...r }) => r); +} + +/** The screens the DATA says are read (a read line or more), in order. */ +export const readScreens = (entry) => screensOf(entry).filter((s) => viewOf(s).reads.length > 0); + +/** What a read line SAYS (before the thread read's spokenRead): its read run, its shapes left out ("" when not read). */ +export function screenLineSaid(screen, n) { + return viewOf(screen).reads.find((x) => x.n === n)?.said ?? ""; +} + +/** + * A screen with lines `drops` (their indices) REMOVED, pure (a copy): its read follows them -- a removed line's read + * goes, the later lines' numbers move down (the CLI's `line.<n>=off`, the post bench's ×: one rule). A read the take + * already made is then held to the lines as they are (post-thread.mjs screenLineChanged). + */ +export function withoutLines(screen, drops) { + const gone = new Set(drops); + const to = (n) => n - [...gone].filter((d) => d < n).length; + const out = { ...screen, lines: (Array.isArray(screen?.lines) ? screen.lines : []).filter((_, n) => !gone.has(n)) }; + if (Array.isArray(screen?.read)) out.read = screen.read.filter((x) => !gone.has(x?.line)).map((x) => ({ ...x, line: to(x.line) })); + return out; +} + +/** Every reason the screens AS DRAWN (after the redaction and anonymity passes) cannot be drawn as the operator chose. */ +export function screenDrawErrors(entry) { + const out = []; + for (const sc of screensOf(entry)) for (const n of viewOf(sc).broken) out.push(`timeline ${entry?.id ?? "?"}: line ${n} of screen ${sc.id}: its excerpt is not in the line as drawn -- the line is left out (fix the excerpt: umtool posts screen <p> ${entry?.id ?? "<item>"} set ${sc.id} read.${n}=…)`); + return out; +} + +/** + * A screen's DRAWN ROWS, pure: `[{ n, text, read, cutBefore, cutAfter } | { gap: true, lines }]` -- each line drawn + * (masked; a read excerpt alone, its cut sides marked "…"), whether it is read; the lines not read left out (a gap row + * where they were) under `unread: "omit"`, drawn dim under "dim". A redacted line is never drawn (a gap row under omit); + * nor is a line whose excerpt is broken (screenDrawErrors). + */ +export function screenRows(screen) { + const lines = Array.isArray(screen?.lines) ? screen.lines : []; + const v = viewOf(screen); + const reads = new Map(v.reads.map((r) => [r.n, r])); + const broken = new Set(v.broken); + const dim = screen?.unread === "dim"; + const out = []; + let gap = 0; + const flush = () => { + if (gap && out.length) out.push({ gap: true, lines: gap }); + gap = 0; + }; + lines.forEach((l, n) => { + const r = reads.get(n); + if (!r && !(dim && lineOk(l) && !broken.has(n))) { + gap += 1; + return; + } + flush(); + out.push({ n, text: r ? r.shown : maskShapes(str(l.text)).text.trim(), read: !!r, cutBefore: !!r?.cutBefore, cutAfter: !!r?.cutAfter }); + }); + // A gap after the last row drawn: the screen goes on past what is shown. + if (gap && out.length) out.push({ gap: true, lines: gap }); + return out; +} + +/** Whether a screen's drawing leaves anything of it out (a line, or words of one): its header says "excerpt". */ +export const screenIsExcerpt = (screen) => screenRows(screen).some((r) => r.gap || r.cutBefore || r.cutAfter); + +// --------------------------------------------------------------------------- +// WHO SAYS IT. +// --------------------------------------------------------------------------- + +/** + * WHO a line is, pure: `{ self, handle, name }` -- `self` when it is the post's author (by handle or by name), else the + * handle it resolves to: written as a handle, or a character's name (`names`: lower-case name -> handle, the project's + * characters and the cast's) resolved to its handle; `name` as written. An empty `who`: the author's when the screen's + * kind is a letter, none else. + * + * @param {string | undefined} who + * @param {{ handle?: string, author?: string }} entry + * @param {Record<string, string> | Map<string, string>} [names] + */ +export function screenWho(who, entry, names = {}) { + const w = str(who).trim(); + const key = handleKey(w); + const self = !!w && ((!!key && key === handleKey(entry?.handle)) || w.toLowerCase() === str(entry?.author).trim().toLowerCase()); + if (!w) return { self: false, handle: null, name: "" }; + if (self) return { self: true, handle: str(entry?.handle).replace(/^@/, "") || null, name: w }; + const byName = names instanceof Map ? names.get(w.toLowerCase()) : names?.[w.toLowerCase()]; + if (byName) return { self: false, handle: str(byName).replace(/^@/, ""), name: w }; + return { self: false, handle: /^@?[A-Za-z0-9_]{1,30}$/.test(w) ? w.replace(/^@/, "") : null, name: w }; +} + +/** The side a line is drawn on: its own `side`, else the author's lines on the right and the others on the left. */ +export const screenSide = (line, entry) => (SCREEN_SIDES.includes(line?.side) ? line.side : screenWho(line?.who, entry).self ? "right" : "left"); + +// --------------------------------------------------------------------------- +// A LINE TYPED OR PASTED (the CLI's --from text, the post bench's paste box: one rule). +// --------------------------------------------------------------------------- + +/** One line of TEXT as a screen line: `[right] who: words | time`, `- words`, `[redact] …`. Null: a blank line. */ +export function lineOfText(raw) { + let t = String(raw).trim(); + if (!t) return null; + const out = {}; + for (;;) { + const m = /^\[(left|right|redact)\]\s*/i.exec(t); + if (!m) break; + if (m[1].toLowerCase() === "redact") out.redact = true; + else out.side = m[1].toLowerCase(); + t = t.slice(m[0].length); + } + const bar = t.lastIndexOf(" | "); + if (bar > 0) { + out.time = t.slice(bar + 3).trim(); + t = t.slice(0, bar).trim(); + } + if (t.startsWith("- ")) t = t.slice(2); + else { + const c = /^([^:]{1,64}?):\s+(.*)$/s.exec(t); + // NEVER a shape split into a speaker ("Order number: 4419", "Ref: AB-1234", "savvy@x.com: hi"): a "speaker" with a + // digit, an @, a shape keyword, or a shape of the whole line that reaches into it stays part of the line's words. + const keyword = new RegExp(`^(?:${KEYWORDS}|${["phone", "tel", "mobile", "cell", "fax", "email", "e-mail", "address", "zip", "postcode", "number", "no"].map(ci).join("|")})(?![\\p{L}\\p{N}])`, "u"); + const splits = !!c && !/^https?$/i.test(c[1]) && !/[\p{Nd}@@#]/u.test(c[1]) && !keyword.test(c[1].trim()) && !shapeSpans(t).some((sp) => sp.start < c[1].length + 1); + if (c && splits) { + out.who = c[1].trim(); + t = c[2]; + } + } + return { ...(out.who ? { who: out.who } : {}), ...(out.side ? { side: out.side } : {}), text: t.trim(), ...(out.time ? { time: out.time } : {}), ...(out.redact ? { redact: true } : {}) }; +} + +// --------------------------------------------------------------------------- +// THE VALIDATION. +// --------------------------------------------------------------------------- + +/** Every reason an item's `screens` cannot be drawn or read (validatePostItem). */ +export function validateScreens(e) { + const s = e?.screens; + if (s === undefined) return []; + const w = `timeline ${e?.id ?? "?"}.screens`; + if (!Array.isArray(s)) return [`${w} must be a list of the text screenshots the post carries`]; + const errors = []; + if (s.length > SCREENS_MAX) errors.push(`${w}: at most ${SCREENS_MAX} screens`); + const media = Array.isArray(e?.media) ? e.media : []; + const ids = new Set(); + s.forEach((sc, i) => { + const at = `${w}[${i}]`; + if (!isObj(sc)) { + errors.push(`${at} must be an object`); + return; + } + const known = new Set(["id", "media", "at", "kind", "title", "source", "checked", "ref", "unread", "lines", "read"]); + for (const k of Object.keys(sc)) if (!known.has(k)) errors.push(`${at}.${k} is not a screen's field (${[...known].join(", ")})`); + if (!SCREEN_ID_RE.test(str(sc.id))) errors.push(`${at}.id must be a short name (lower-case letters, digits, -)`); + else if (ids.has(sc.id)) errors.push(`${at}.id "${sc.id}" is the id of another screen of the item`); + else ids.add(sc.id); + const m = Number.isInteger(sc.media) ? media[sc.media] : undefined; + if (!Number.isInteger(sc.media) || !isObj(m)) errors.push(`${at}.media must be the index of the attachment it is in (0–${Math.max(0, media.length - 1)}${media.length ? "" : ": the item has none"})`); + const timed = m?.kind === "video" || m?.kind === "gif"; + if (sc.at !== undefined) { + if (m && !timed) errors.push(`${at}.at: only a video or a GIF has a span (attachment ${sc.media} is ${m.kind === "image" ? "an image" : m.kind})`); + else if (!(Array.isArray(sc.at) && sc.at.length === 2 && sc.at.every((v) => fin(v) && v >= 0) && sc.at[1] - sc.at[0] >= SCREEN_MIN_SPAN - 1e-9 && (!fin(m?.seconds) || sc.at[1] <= m.seconds + 0.05))) { + errors.push(`${at}.at must be [from, to], the seconds of attachment ${sc.media} it is visible in (at least ${SCREEN_MIN_SPAN} s${fin(m?.seconds) ? `, inside 0–${m.seconds}` : ""})`); + } + } else if (timed) errors.push(`${at}.at must be [from, to]: the seconds of the ${m.kind} it is visible in`); + if (!SCREEN_KINDS.includes(sc.kind)) errors.push(`${at}.kind must be one of ${SCREEN_KINDS.join(", ")}`); + if (sc.title !== undefined && !(typeof sc.title === "string" && sc.title.trim() && sc.title.length <= SCREEN_TITLE_MAX)) errors.push(`${at}.title must be words (at most ${SCREEN_TITLE_MAX} characters)`); + if (sc.source !== undefined && sc.source !== "transcribed") errors.push(`${at}.source must be "transcribed"`); + if (sc.checked !== undefined && !(isObj(sc.checked) && typeof sc.checked.by === "string" && sc.checked.by.trim() && sc.checked.by.length <= 40 && typeof sc.checked.at === "string" && !Number.isNaN(Date.parse(sc.checked.at)))) { + errors.push(`${at}.checked must be { by, at }: who checked the transcription and when (ISO)`); + } + if (sc.ref !== undefined && !(sc.kind === "post" && typeof sc.ref === "string" && /^[A-Za-z0-9._-]+\/[A-Za-z0-9_-]+$/.test(sc.ref))) errors.push(`${at}.ref must be <channel>/<postId> (a screenshot of a post only)`); + if (sc.unread !== undefined && !SCREEN_UNREAD.includes(sc.unread)) errors.push(`${at}.unread must be ${SCREEN_UNREAD.join(" or ")}`); + const lines = Array.isArray(sc.lines) ? sc.lines : null; + if (!lines || !lines.length) errors.push(`${at}.lines must be the transcription: a list of { who?, side?, text, time?, redact? }`); + else { + if (lines.length > SCREEN_LINES_MAX) errors.push(`${at}.lines: at most ${SCREEN_LINES_MAX}`); + lines.forEach((l, n) => { + const lw = `${at}.lines[${n}]`; + if (!isObj(l)) { + errors.push(`${lw} must be { who?, side?, text, time?, redact? }`); + return; + } + for (const k of Object.keys(l)) if (!["who", "side", "text", "time", "redact", "anonymous"].includes(k)) errors.push(`${lw}.${k} is not a line's field (who, side, text, time, redact)`); + if (l.anonymous !== undefined && l.anonymous !== true) errors.push(`${lw}.anonymous is the anonymising pass's own flag (true, or absent)`); + if (typeof l.text !== "string" || l.text.length > SCREEN_LINE_MAX) errors.push(`${lw}.text must be the line's words (at most ${SCREEN_LINE_MAX} characters)`); + else if (!l.text.trim() && l.redact !== true) errors.push(`${lw}.text is empty (a line with no words: remove it, or mark it redact)`); + if (l.who !== undefined && !(typeof l.who === "string" && l.who.trim() && l.who.length <= SCREEN_WHO_MAX)) errors.push(`${lw}.who must be a handle or a name`); + if (l.side !== undefined && !SCREEN_SIDES.includes(l.side)) errors.push(`${lw}.side must be left or right`); + if (l.time !== undefined && !(typeof l.time === "string" && l.time.length <= SCREEN_TIME_MAX)) errors.push(`${lw}.time must be the time shown (at most ${SCREEN_TIME_MAX} characters)`); + if (l.redact !== undefined && l.redact !== true) errors.push(`${lw}.redact must be true (or absent)`); + }); + } + const r = sc.read; + if (r === "all" || r === "none") return; + if (!Array.isArray(r)) { + errors.push(`${at}.read must be "all", "none" or a list of { line, text? }`); + return; + } + const lines2 = lines ?? []; + const seen = new Set(); + r.forEach((x, j) => { + const rw = `${at}.read[${j}]`; + if (!isObj(x) || !Number.isInteger(x.line) || !isObj(lines2[x.line])) { + errors.push(`${rw} must be { line, text? } naming a line (0–${Math.max(0, lines2.length - 1)})`); + return; + } + if (seen.has(x.line)) errors.push(`${rw}: line ${x.line} is read twice`); + seen.add(x.line); + if (lines2[x.line].redact === true) errors.push(`${rw}: line ${x.line} is redacted -- it is never read`); + if (x.text !== undefined) { + if (typeof x.text !== "string" || !x.text.trim()) errors.push(`${rw}.text must be the words of the line to read (an excerpt)`); + else if (!excerptRun(str(lines2[x.line].text), x.text)) errors.push(`${rw}.text is not a run of line ${x.line}'s words (an excerpt is the line's own words, in a row)`); + } + for (const k of Object.keys(x)) if (!["line", "text"].includes(k)) errors.push(`${rw}.${k} is not a read's field (line, text)`); + }); + }); + return errors; +} + +/** + * A screen line the take reads, checked against the data: null when it is drawn and read, else why not (the guard, + * post-thread.mjs threadReadErrors). + */ +export function screenLineProblem(entry, role) { + const p = parseScreenRole(role); + if (!p) return "not a screen line"; + const sc = screenOf(entry, p.id); + if (!sc) return `screen ${p.id}, which the item does not carry`; + const l = sc.lines[p.n]; + if (!isObj(l)) return `line ${p.n} of screen ${p.id}, which it does not have`; + if (l.redact === true) return `line ${p.n} of screen ${p.id}, which is redacted (never drawn)`; + if (!screenReadLines(sc).some((r) => r.n === p.n)) return `line ${p.n} of screen ${p.id}, which the screen does not read (${sc.read === "none" ? 'read: "none" -- not drawn' : sc.unread === "dim" ? "drawn dim, never lit" : "left out of the card"})`; + return null; +} + +// --------------------------------------------------------------------------- +// THE PIECES a read reads (post-thread.mjs chronoPieces): after the post's own words. +// --------------------------------------------------------------------------- + +/** Each read line of the item's read screens, in order: `[{ role, who, text }]` (`text` what it says). */ +export function screenPieces(entry) { + const out = []; + for (const sc of readScreens(entry)) { + for (const r of screenReadLines(sc)) { + const text = screenLineSaid(sc, r.n); + if (text.trim()) out.push({ role: screenRole(sc.id, r.n), who: str(sc.lines[r.n].who) || null, text, screen: sc.id }); + } + } + return out; +} + +/** The read's order of a screen role: after every other text, by its screen's place and its line (null: not one). */ +export function screenOrder(entry, role) { + const p = parseScreenRole(role); + if (!p) return null; + const at = screensOf(entry).findIndex((s) => s.id === p.id); + return 100 + Math.max(0, at) + p.n / 1000; +} + +// --------------------------------------------------------------------------- +// THE MEDIA: what the slot plays while a screen is read (post-item.mjs planOf). +// --------------------------------------------------------------------------- + +/** + * WHEN EACH SCREEN IS UP, pure: `[{ id, media, t0 }]` -- each screen tile of the plan's thread from its first read + * line's start less the pan's lead (`lead`), in order. Empty: none read. + */ +export function screenShows(entry, follow, { lead = 0.4 } = {}) { + const tiles = (follow?.thread?.tiles ?? []).filter((t) => isScreenScope(t.scope)); + const out = []; + for (const t of tiles) { + const id = t.scope.slice(7); + const sc = screenOf(entry, id); + if (!sc) continue; + const ts = (follow.blocks ?? []).filter((b) => b.scope === t.scope && fin(b.start)).map((b) => b.start); + if (!ts.length) continue; + out.push({ id, media: sc.media, at: Array.isArray(sc.at) ? sc.at : null, t0: r3(Math.max(0, Math.min(...ts) - lead)) }); + } + return out.sort((a, b) => a.t0 - b.t0); +} + +// --------------------------------------------------------------------------- +// THE DRAWING (post-item.mjs postCardHtml's threaded card calls it). +// --------------------------------------------------------------------------- + +const KIND_WORD = { dm: "DMs", email: "An email", post: "A post", text: "Text" }; +const KIND_SHORT = { dm: "DMs", email: "Email", post: "Post", text: "Text" }; + +/** + * A screen's HEADER, pure: what it is and that it is transcribed -- "DMs shown in Savvy's video · transcribed" (its + * `title` for the kind's word; the author's SHOWN name, an anonymous one's; "the post's" for a blurred author). + */ +export function screenHeader(entry, screen, { authorHidden = false } = {}) { + const m = Array.isArray(entry?.media) ? entry.media[screen?.media] : null; + const where = m?.kind === "image" ? "picture" : "video"; + const who = authorHidden || !str(entry?.author).trim() ? "the post's" : `${str(entry.author).trim()}'s`; + // A title's shapes masked as a line's are (an e-mail, a number in it never drawn). + const title = maskedField(str(screen?.title).trim()); + const what = title || KIND_WORD[screen?.kind] || "Text"; + return { text: `${what} shown in ${who} ${where}`, badge: `${title || KIND_SHORT[screen?.kind] || "Text"} · transcribed` }; +} + +/** + * ONE SCREEN's TILE, as HTML (escaped; the redaction's marks drawn as bars by the page's barsHtml). `blocks`: line -> + * the read-follow block that reads it (`data-post-block`); `shown(lineWho)`: whether a speaker is drawn (the privacy + * rule), else blurred. `h`: the card's helpers (esc, mixHex, rgbaOf). The kinds: a DM as bubbles (the author's on the + * right in the accent, the others on the left), an email or text as a quiet letter block, a post as a post tile marked + * "screenshot". + * + * @param {Record<string, any>} entry + * @param {Record<string, any>} screen + * @param {{ k: number, size: number, blocks: Map<number, number>, shown: (line: Record<string, any>) => boolean, authorHidden?: boolean, h: { esc: (s: any) => string } }} o + */ +export function screenTileHtml(entry, screen, { k, size, blocks, shown, authorHidden = false, h }) { + const { esc } = h; + const id = screen.id; + const scope = screenScope(id); + const head = screenHeader(entry, screen, { authorHidden }); + const excerpt = screenIsExcerpt(screen) ? '<span class="plabel" data-screen-excerpt="">excerpt</span>' : ""; + const rows = screenRows(screen); + const blk = (n) => (blocks.has(n) ? ` data-post-block="${blocks.get(n)}"` : ""); + const words = (r) => `${r.cutBefore ? "…" : ""}${esc(r.text)}${r.cutAfter ? "…" : ""}`; + const nameOf = (l) => { + const w = str(l?.who).trim(); + if (!w) return ""; + // A speaker's shapes masked whatever the privacy rule says (an e-mail or a phone number as a "name"). + return shown(l) ? `<span class="sname">${esc(maskedField(w))}</span>` : '<span class="sname redact">xxxxxxxx</span>'; + }; + const time = (l) => (str(l?.time).trim() ? `<span class="stime">${esc(maskedField(l.time.trim()))}</span>` : ""); + let body; + if (screen.kind === "dm") { + const named = new Set(); + let last = null; + body = rows + .map((r) => { + if (r.gap) { + last = null; + return `<div class="sgap" data-screen-gap="${r.lines}">⋯</div>`; + } + const l = screen.lines[r.n]; + const side = screenSide(l, entry); + const who = str(l.who).trim(); + const key = who.toLowerCase(); + // The speaker's name on first use (and again after a gap or the other side). + const name = who && (!named.has(key) || last !== key) ? `<div class="swho">${nameOf(l)}</div>` : ""; + named.add(key); + last = key; + return `<div class="srow ${side}${r.read ? "" : " sdim"}" data-screen-line="${r.n}">${name}<div class="sbub"${blk(r.n)}>${words(r)}${time(l)}</div></div>`; + }) + .join(""); + } else if (screen.kind === "post") { + // Its author: the speaker of the first line DRAWN (never a redacted or left-out line's). + const first = rows.filter((r) => !r.gap).map((r) => screen.lines[r.n]).find((l) => str(l?.who).trim()); + body = `<div class="spost">${first ? `<div class="sphead">${nameOf(first)}<span class="plabel" data-screen-shot="">screenshot</span></div>` : '<div class="sphead"><span class="plabel" data-screen-shot="">screenshot</span></div>'}${rows + .map((r) => (r.gap ? `<div class="sgap" data-screen-gap="${r.lines}">⋯</div>` : `<p class="sline${r.read ? "" : " sdim"}" data-screen-line="${r.n}"${blk(r.n)}>${words(r)}</p>`)) + .join("")}</div>`; + } else { + let lastWho = null; + body = `<div class="sletter">${rows + .map((r) => { + if (r.gap) return `<div class="sgap" data-screen-gap="${r.lines}">⋯</div>`; + const l = screen.lines[r.n]; + const who = str(l.who).trim(); + const from = who && who !== lastWho ? `<div class="sfrom">${nameOf(l)}${time(l)}</div>` : ""; + if (who) lastWho = who; + return `${from}<p class="sline${r.read ? "" : " sdim"}" data-screen-line="${r.n}"${blk(r.n)}>${words(r)}${from ? "" : time(l)}</p>`; + }) + .join("")}</div>`; + } + return `<div class="tslot" data-thread-slot="${esc(scope)}"><div class="tile tscreen" data-thread-tile="${esc(scope)}" data-thread-mode="full" data-post-screen="${esc(id)}" data-screen-kind="${esc(screen.kind)}" style="font-size:${size}px"><div class="shead" data-screen-head=""><span class="stitle">${esc(head.text)}</span><span class="strans" data-screen-transcribed=""> · transcribed</span>${excerpt}</div>${body}</div></div>`; +} + +/** A screen's BADGE: pinned to the card's top while that screen is up (followStateAt's `screen`) -- "· transcribed" never leaves the screen. */ +export const screenBadgeHtml = (entry, screen, { esc, authorHidden = false }) => + `<div class="sbadge" data-screen-badge="${esc(screen.id)}">${esc(screenHeader(entry, screen, { authorHidden }).badge)}</div>`; + +/** The CSS a page with screens adds (none without). */ +export function screenCss({ k, pal, mixHex, rgbaOf, pad }) { + const px = (v) => `${Math.round(v * k)}px`; + const bub = mixHex(pal.bg, pal.fg, 0.14); + return ` +.tscreen { display: flex; flex-direction: column; gap: ${px(10)}; line-height: 1.32; } +.shead { display: flex; align-items: baseline; gap: ${px(8)}; color: ${pal.muted}; font-size: ${px(20)}; letter-spacing: 0.01em; } +.shead .strans { color: ${pal.muted}; } +.shead .plabel { margin-left: auto; } +.srow { display: flex; flex-direction: column; max-width: 86%; } +.srow.left { align-self: flex-start; align-items: flex-start; } +.srow.right { align-self: flex-end; align-items: flex-end; } +.tscreen[data-screen-kind="dm"] { align-items: stretch; } +.tscreen[data-screen-kind="dm"] > .srow, .tscreen[data-screen-kind="dm"] > .sgap { } +.swho { color: ${pal.muted}; font-size: ${px(19)}; margin: ${px(4)} ${px(6)} ${px(2)}; } +.sbub { padding: ${px(8)} ${px(16)}; border-radius: ${px(20)}; background: ${bub}; color: ${pal.fg}; overflow-wrap: anywhere; } +.srow.right .sbub { background: ${rgbaOf(pal.accent, 0.42)}; } +.stime { color: ${pal.muted}; font-size: ${px(16)}; margin-left: ${px(10)}; white-space: nowrap; } +.sdim { opacity: 0.45; } +.sgap { align-self: center; color: ${pal.muted}; font-size: ${px(22)}; line-height: 1; letter-spacing: 0.2em; } +.sletter, .spost { border: 1px solid ${mixHex(pal.bg, pal.fg, 0.22)}; border-radius: ${px(12)}; padding: ${px(14)} ${px(18)}; display: flex; flex-direction: column; gap: ${px(8)}; } +.sfrom { color: ${pal.muted}; font-size: ${px(19)}; } +.sline { color: ${pal.fg}; overflow-wrap: anywhere; } +.sphead { display: flex; align-items: center; gap: ${px(10)}; font-size: ${px(22)}; } +.sname { font-family: 'PostSansBold', sans-serif; color: ${pal.fg}; } +.swho .sname { color: ${pal.muted}; } +.sbadge { position: absolute; top: ${Math.max(2, Math.round((pad - 22 * k) / 2))}px; right: ${pad}px; font-size: ${px(16)}; line-height: 1; padding: ${px(3)} ${px(9)}; border-radius: ${px(6)}; background: ${rgbaOf(pal.bg, 0.85)}; color: ${pal.muted}; border: 1px solid ${mixHex(pal.bg, pal.fg, 0.22)}; letter-spacing: 0.04em; text-transform: uppercase; opacity: 0; z-index: 3; }`; +} + +// --------------------------------------------------------------------------- +// THE LINT's WARNINGS (lint.mjs; never refused). They NAME a line, never quote a value. +// --------------------------------------------------------------------------- + +const kindWords = (kinds) => kinds.map((k) => (k === "email" ? "an e-mail address" : k === "order" ? "an order or reference number" : "a long number or a phone number")).join(" and "); + +/** + * Post item `entry`'s screens WARNINGS, pure: a transcription no one checked, a line holding a shape the card masks, a + * screen on an item not narrated (not drawn), a screenshot of a post naming an archived one, a speaker the privacy rule + * blurs, read lines the picked take does not read. `takeRoles`: the picked take's roles (post-thread.mjs partRoles), + * `narrated` whether it plays a take. + * + * @param {Record<string, any>} entry + * @param {{ narrated?: boolean, takeRoles?: Array<string | null>, attachAfter?: boolean }} [o] + */ +export function screenWarnings(entry, { narrated = false, takeRoles = [], attachAfter = false } = {}) { + const out = []; + const id = entry?.id ?? "?"; + const w = `timeline ${id}`; + const roles = new Set(takeRoles.filter(Boolean)); + const subjects = new Set((Array.isArray(entry?.subjects) ? entry.subjects : []).map((h) => handleKey(h))); + for (const sc of screensOf(entry)) { + if (!isObj(sc.checked)) out.push(`${w}: screen ${sc.id}'s transcription not checked -- read it against the screenshot, then umtool posts screen <p> ${id} check ${sc.id} (or tick it on the post bench)`); + sc.lines.forEach((l, n) => { + if (!isObj(l) || l.redact === true) return; + const kinds = [...new Set(shapeSpans(str(l.text)).map((s) => s.kind))]; + if (kinds.length) out.push(`${w}: screen ${sc.id} line ${n} holds ${kindWords(kinds)} -- masked on the card and never said; mark the line redact (umtool posts screen <p> ${id} set ${sc.id} line.${n}.redact=on) if the rest of it should go too`); + // Its speaker and its time: masked on the card too. + for (const [f, what] of [["who", "speaker"], ["time", "time"]]) { + const k2 = [...new Set(shapeSpans(str(l[f])).map((x) => x.kind))]; + if (k2.length) out.push(`${w}: screen ${sc.id} line ${n}'s ${what} holds ${kindWords(k2)} -- masked on the card; write it without (umtool posts screen <p> ${id} set ${sc.id} line.${n}.${f}=…)`); + } + }); + // DIGITS SPLIT ACROSS TWO LINES ("my card is 4111 1111" / "1111 1111"): a shape only the two together make. + for (let n = 0; n + 1 < sc.lines.length; n += 1) { + const a = sc.lines[n]; + const b = sc.lines[n + 1]; + if (!isObj(a) || !isObj(b) || a.redact === true || b.redact === true) continue; + const ta = str(a.text); + const joined = `${ta} ${str(b.text)}`; + const across = shapeSpans(joined).filter((sp) => sp.start < ta.length && sp.end > ta.length + 1); + if (across.length) out.push(`${w}: lines ${n} and ${n + 1} of screen ${sc.id} together hold ${kindWords([...new Set(across.map((x) => x.kind))])} split across them -- each alone is drawn and said; mark them redact (umtool posts screen <p> ${id} set ${sc.id} line.${n}.redact=on line.${n + 1}.redact=on) or join them`); + } + const tk = [...new Set(shapeSpans(str(sc.title)).map((x) => x.kind))]; + if (tk.length) out.push(`${w}: screen ${sc.id}'s title holds ${kindWords(tk)} -- masked on the card; write it without (umtool posts screen <p> ${id} set ${sc.id} title=…)`); + if (sc.kind === "post" && sc.ref) out.push(`${w}: screen ${sc.id} pictures ${sc.ref} -- drawn from its transcription; umtool posts set-item <p> ${id} link.add=… draws the archived post itself`); + const reads = screenReadLines(sc); + if (!reads.length) continue; + if (!narrated) { + out.push(`${w}: screen ${sc.id} is drawn and read only on a narrated item -- make its read: umtool posts screen <p> ${id} read`); + continue; + } + // A read over the card first, the attachments after it (`attach: "after"`): the slot does not play the screen's span. + if (attachAfter) out.push(`${w}: screen ${sc.id}'s span is not played while it is read: the item's narration attaches its media after the read (attach: after) -- set attach=under to play it`); + const missing = reads.filter((r) => !roles.has(screenRole(sc.id, r.n))); + if (missing.length === reads.length) out.push(`${w}: its picked take does not read screen ${sc.id} (not drawn until it does) -- umtool posts screen <p> ${id} read`); + else if (missing.length) out.push(`${w}: its picked take does not read line${missing.length === 1 ? "" : "s"} ${missing.map((r) => r.n).join(", ")} of screen ${sc.id} -- umtool posts screen <p> ${id} read`); + const blurred = new Set(); + for (const r of reads) { + const who = str(sc.lines[r.n].who).trim(); + const s = screenWho(who, entry); + if (who && !s.self && entry?.redact !== false && sc.lines[r.n].anonymous !== true && !subjects.has(handleKey(s.handle ?? "")) && !blurred.has(who.toLowerCase())) { + blurred.add(who.toLowerCase()); + out.push(`${w}: screen ${sc.id} line ${r.n}'s speaker is drawn blurred (the privacy rule: not a subject of the item) -- add them to its subjects or set redact: false to show the name`); + } + } + } + return out; +} diff --git a/umtool/report-to-video/post-screens.test.mjs b/umtool/report-to-video/post-screens.test.mjs @@ -0,0 +1,268 @@ +// post-screens.mjs: a post's SCREENS -- its text screenshots, transcribed, drawn on its card and read in the voices of +// the people in them. The data and its validation, the shapes masked (never drawn, never said), what is read and drawn +// of a screen, the read's roles and pieces, the card's tiles and its schedule, the plan's media, the anonymity pass, +// the lint's warnings. +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { postCardHtml, postItemPlan, validatePostItem } from "./post-item.mjs"; +import { chronoPieces, partRoles, threadLayout, threadReadErrors, validateThreadReadWarnings } from "./post-thread.mjs"; +import { followBlocks, followStateAt, followStateKey, isDrawnState } from "./read-follow.mjs"; +import { anonymiseEntry, anonymityProblems } from "./post-anon.mjs"; +import { redactEntry } from "./post-redact.mjs"; +import { + excerptRun, maskShapes, parseScreenRole, screenHeader, screenLineSaid, screenReadLines, screenRows, screenWarnings, screenWho, shapeSpans, tileOfRole, validateScreens, +} from "./post-screens.mjs"; + +const VID = { src: "posts-media/savvy-x/2117/2117_1.mp4", kind: "video", width: 1920, height: 1080, seconds: 61.742, audio: true, start: 3.3, end: 8 }; +const IMG = { src: "posts-media/savvy-x/2117/2117_2.jpg", kind: "image", width: 900, height: 1400 }; +const S1 = { + id: "s1", media: 0, at: [3.5, 8], kind: "dm", read: "all", lines: [ + { who: "TheQuartering", text: "what's your email so I can refund your order", time: "11:32 AM" }, + { who: "MadamSavvy", text: "where is my scale video", time: "11:53 AM" }, + { who: "TheQuartering", text: "you HONESTLY believe that I have lied about weight loss?" }, + { who: "TheQuartering", text: "You can't be this dumb", time: "11:58 AM" }, + ], +}; +const S2 = { + id: "s2", media: 1, kind: "email", title: "Refund email", read: [{ line: 0 }, { line: 1, text: "Total amount refunded: $99.95" }], lines: [ + { who: "coffee brand coffee", text: "Some items in your order have been refunded" }, + { text: "Total amount refunded: $99.95 USD. It may take up to 10 days for this refund to appear in your account." }, + { text: "Order number 4419283 · reply to support@coffeebrand.com" }, + ], +}; +const POST = "Hey, @thequartering You told me your video was ready to go.\n\nYour turn."; +const base = (o = {}) => ({ type: "post", id: "p-2117", post: "savvy-x/2117", platform: "x", author: "Savvy", handle: "MadamSavvy", date: "2026-11-02T01:40:36.000Z", text: POST, subjects: ["MadamSavvy"], media: [VID, IMG], screens: [S1, S2], ...o }); +/** A thread read's take: his words, then each screen line (stored roles), timed by words. */ +function narrated(e, lines = [["s1", 0], ["s1", 1], ["s1", 2], ["s1", 3], ["s2", 0], ["s2", 1]]) { + const parts = []; + let t = 0; + const add = (text, role, piece, gap) => { + t += parts.length ? gap : 0; + const sec = Math.round((text.split(/\s+/).length / 3) * 100) / 100; + parts.push({ n: parts.length + 1, para: piece * 100, text, role, start: Math.round(t * 1000) / 1000, seconds: sec }); + t += sec; + }; + add("Hey, at thequartering You told me your video was ready to go.", "post", 0, 0); + add("Your turn.", "post", 0, 0.6); + lines.forEach(([id, n], i) => { + const sc = e.screens.find((s) => s.id === id); + add(screenLineSaid(sc, n), `screen:${id}:${n}`, 1 + i, i && lines[i - 1][0] === id ? 0.35 : 0.8); + }); + return { ...e, narration: { script: POST, pick: 0, takes: [{ file: "narration/posts/2117/take-1.orpheus-thread.wav", engine: "orpheus", voice: "tara+leo", seconds: Math.round(t * 1000) / 1000, script: "x", parts }] } }; +} + +test("the data: a well-formed item with screens is taken; each wrong field is named", () => { + assert.deepEqual(validatePostItem(narrated(base())), []); + const bad = (sc, re) => assert.ok(validateScreens(base({ screens: [sc] })).some((x) => re.test(x)), `${JSON.stringify(sc).slice(0, 80)} -> ${re}`); + bad({ ...S1, id: "S 1" }, /\.id must be a short name/); + bad({ ...S1, media: 7 }, /\.media must be the index/); + bad({ ...S1, at: undefined }, /\.at must be \[from, to\]: the seconds of the video/); + bad({ ...S1, at: [3, 70] }, /inside 0–61\.742/); + bad({ ...S2, at: [1, 2] }, /only a video or a GIF has a span/); + bad({ ...S1, kind: "chat" }, /\.kind must be one of dm, email, post, text/); + bad({ ...S1, read: [{ line: 0, text: "refund your email" }] }, /is not a run of line 0's words/); + bad({ ...S1, read: [{ line: 0 }, { line: 0 }] }, /line 0 is read twice/); + bad({ ...S1, lines: [{ text: "x", redact: true }, ...S1.lines], read: [{ line: 0 }] }, /line 0 is redacted -- it is never read/); + bad({ ...S1, ref: "a/b" }, /\.ref must be <channel>\/<postId> \(a screenshot of a post only\)/); + bad({ ...S1, checked: { by: "me" } }, /\.checked must be \{ by, at \}/); + bad({ ...S1, lines: [{ who: "x", text: "y", colour: "red" }] }, /\.colour is not a line's field/); + const two = validateScreens(base({ screens: [S1, { ...S2, id: "s1" }] })); + assert.ok(two.some((x) => /is the id of another screen/.test(x))); + // An excerpt names a run of the line's own words; its edge punctuation need not match. + assert.deepEqual(excerptRun("Total amount refunded: $99.95 USD. It may", "total amount refunded: $99.95."), { start: 0, end: 29 }); + assert.equal(excerptRun("hop on the scale fatso", "on scale"), null); +}); + +test("THE SHAPES: an e-mail, a phone number, an order or long number are masked -- absent from the card's page AND from what the part says", () => { + const kinds = (t) => shapeSpans(t).map((s) => s.kind); + assert.deepEqual(kinds("reply to support@coffeebrand.com"), ["email"]); + assert.deepEqual(kinds("call +1 (555) 201-4477 today"), ["number"]); + assert.deepEqual(kinds("Order number 4419283 shipped"), ["order"]); + assert.deepEqual(kinds("your code #88213 is ready"), ["order"]); + assert.deepEqual(kinds("id 2117069332987425196"), ["number"]); + // Amounts, times and small numbers stay. + assert.deepEqual(kinds("Total $104.90 USD, $1,000,000 at 12:18 PM, 400 pounds, Oct 31, 290"), []); + assert.equal(maskShapes("a@b.co").text.includes("a@b.co"), false); + // A line that READS a shape: the card never draws it, the read never says it. + const sc = { ...S2, read: "all" }; + const e = narrated(base({ screens: [S1, sc] }), [["s1", 0], ["s2", 0], ["s2", 1], ["s2", 2]]); + assert.deepEqual(validatePostItem(e), []); + const said = screenLineSaid(sc, 2); + assert.ok(!said.includes("4419283") && !said.includes("support@") && !said.includes("coffeebrand"), said); + assert.ok(/reply to/.test(said)); + const plan = postItemPlan(e, {}); + const html = postCardHtml(e, { width: 1600, height: 900, follow: true, thread: plan.follow.thread }); + assert.ok(html.includes('data-screen-line="2"'), "the line is drawn"); + for (const v of ["4419283", "support@coffeebrand.com", "coffeebrand"]) assert.ok(!html.includes(v), `${v} is not in the page`); + assert.ok(html.includes('data-post-blanked=""'), "a bar stands where it was"); + // The read's piece says it as the part does: the shape left out. + const piece = chronoPieces(e).find((p) => p.role === "screen:s2:2"); + assert.ok(piece && !/4419283|support@/.test(piece.text)); +}); + +test("what is read and drawn: all, a list with an excerpt, none; lines not read left out (a gap row) or drawn dim; a redacted line never", () => { + assert.deepEqual(screenReadLines(S1).map((r) => r.n), [0, 1, 2, 3]); + const r2 = screenReadLines(S2); + assert.deepEqual(r2.map((r) => [r.n, r.cutBefore, r.cutAfter]), [[0, false, false], [1, false, true]]); + assert.equal(screenLineSaid(S2, 1), "Total amount refunded: $99.95"); + const rows = screenRows(S2); + assert.deepEqual(rows.map((r) => (r.gap ? `gap${r.lines}` : `${r.n}:${r.read}`)), ["0:true", "1:true", "gap1"]); + assert.equal(rows[1].text, "Total amount refunded: $99.95"); + const dim = screenRows({ ...S2, unread: "dim" }); + assert.deepEqual(dim.map((r) => (r.gap ? "gap" : `${r.n}:${r.read}`)), ["0:true", "1:true", "2:false"]); + assert.ok(!dim[2].text.includes("4419283"), "a dim line is masked too"); + assert.deepEqual(screenReadLines({ ...S1, read: "none" }), []); + const red = { ...S1, lines: [S1.lines[0], { text: "my address is 12 High St", redact: true }, S1.lines[1]], read: "all" }; + assert.deepEqual(screenReadLines(red).map((r) => r.n), [0, 2]); + assert.ok(!JSON.stringify(screenRows({ ...red, unread: "dim" })).includes("High St"), "a redacted line is never drawn"); +}); + +test("who: the post's author by handle or name; another by handle, or a character's name resolved; the side follows", () => { + const e = base(); + assert.deepEqual(screenWho("MadamSavvy", e), { self: true, handle: "MadamSavvy", name: "MadamSavvy" }); + assert.equal(screenWho("savvy", e).self, true); + assert.deepEqual(screenWho("TheQuartering", e), { self: false, handle: "TheQuartering", name: "TheQuartering" }); + assert.deepEqual(screenWho("Jeremy Hambly", e, { "jeremy hambly": "TheQuartering" }), { self: false, handle: "TheQuartering", name: "Jeremy Hambly" }); + assert.equal(screenWho("coffee brand coffee", e).handle, null); +}); + +test("the read: roles screen:<id>:<n> stored on the take; the card threads -- his post, then each screen the take reads, a tile", () => { + const e = narrated(base()); + const roles = partRoles(e).map((r) => r.role); + assert.deepEqual(roles, ["post", "post", "screen:s1:0", "screen:s1:1", "screen:s1:2", "screen:s1:3", "screen:s2:0", "screen:s2:1"]); + assert.deepEqual(parseScreenRole("screen:s1:3"), { id: "s1", n: 3 }); + assert.equal(tileOfRole("screen:s1:3"), "screen:s1"); + const L = threadLayout(e, {}); + assert.equal(L.on, true); + assert.deepEqual(L.tiles.map((t) => t.scope), ["post", "screen:s1", "screen:s2"]); + // A screen the take does not read is not drawn (a warning says so). + const one = narrated(base(), [["s1", 0], ["s1", 1]]); + assert.deepEqual(threadLayout(one, {}).tiles.map((t) => t.scope), ["post", "screen:s1"]); + // The blocks: one a line, named by its role. + const b = followBlocks(e).blocks.filter((x) => String(x.scope).startsWith("screen:")); + assert.deepEqual(b.map((x) => [x.scope, x.line, x.part]), [["screen:s1", 0, 2], ["screen:s1", 1, 3], ["screen:s1", 2, 4], ["screen:s1", 3, 5], ["screen:s2", 0, 6], ["screen:s2", 1, 7]]); + // The pieces a thread read reads: after his words, in the screens' order. + assert.deepEqual(chronoPieces(e).map((p) => p.role), ["post", "screen:s1:0", "screen:s1:1", "screen:s1:2", "screen:s1:3", "screen:s2:0", "screen:s2:1"]); + assert.equal(chronoPieces(e)[1].who, "TheQuartering"); +}); + +test("the schedule: his post gives way to a strip as the first screen comes in; a screen read collapses as the next comes in; the last stays", () => { + const e = narrated(base()); + const plan = postItemPlan(e, {}); + const rows = Object.fromEntries(plan.follow.thread.tiles.map((t) => [t.scope, t])); + const s1 = plan.follow.blocks.find((b) => b.scope === "screen:s1" && b.line === 0).start; + const s2 = plan.follow.blocks.find((b) => b.scope === "screen:s2" && b.line === 0).start; + assert.deepEqual(rows.post.to, [0.62, 0.5]); + assert.ok(Math.abs(rows.post.t0 - (s1 - 0.4)) < 0.01); + assert.deepEqual([rows["screen:s1"].from, rows["screen:s1"].to, rows["screen:s1"].then.to], [[1, 0], [1, 1], [0, 0]]); + assert.ok(Math.abs(rows["screen:s1"].then.t0 - (s2 - 0.4)) < 0.01); + assert.equal(rows["screen:s2"].then, undefined); + // The state says which screen is up (its badge); none before; part of the key; never "the page as drawn". + const path = { start: 0, segments: [], H: 600, C: 900, tiles: {} }; + assert.equal(followStateAt(plan.follow, path, 1).screen, null); + const mid = followStateAt(plan.follow, path, s1 + 1); + assert.equal(mid.screen, "s1"); + assert.equal(followStateAt(plan.follow, path, s2 + 1).screen, "s2"); + assert.ok(followStateKey(mid).includes('"screen":"s1"')); + assert.equal(isDrawnState({ op: {}, offset: 0, fadeTop: 0, fadeBottom: 0, screen: "s1" }), false); +}); + +test("the media: its own attachments until the first screen is up, then each screen's span -- a video's last frame HELD, an image held", () => { + const e = narrated(base()); + const plan = postItemPlan(e, {}); + const st = plan.steps.map((s) => ({ kind: s.kind, at: s.at, sec: s.seconds, from: s.srcFrom, to: s.srcTo, screen: s.screen ?? null, hold: s.hold ?? false })); + const s1At = st.find((s) => s.screen === "s1"); + const s2At = st.find((s) => s.screen === "s2"); + assert.ok(s1At && s2At); + assert.deepEqual([s1At.kind, s1At.from, s1At.to, s1At.hold], ["video", 3.5, 8, true]); + assert.ok(s1At.sec > 8 - 3.5, "the read outlasts the span: held"); + assert.equal(s2At.kind, "image"); + assert.ok(Math.abs(s2At.at + s2At.sec - plan.total) < 0.01, "the last screen to the item's end"); + const own = st.filter((s) => !s.screen); + assert.ok(own.length >= 1 && Math.abs(own[own.length - 1].at + own[own.length - 1].sec - s1At.at) < 0.01, "its own run up to the first screen"); + assert.equal(plan.held, 0); + // A picture-only post: its picture is in its card, no slot -- no screen step. + const pic = narrated(base({ text: "@thequartering", media: [IMG], screens: [{ ...S2, media: 0 }] }), [["s2", 0]]); + assert.ok(postItemPlan(pic, {}).steps.every((s) => !s.screen)); +}); + +test("the card: the screen typeset -- its header names the author's shown name and says transcribed; a badge pins it; speakers by the privacy rule", () => { + const e = narrated(base()); + const plan = postItemPlan(e, {}); + const html = postCardHtml(e, { width: 1600, height: 900, follow: true, thread: plan.follow.thread }); + assert.ok(html.includes("DMs shown in Savvy&#39;s video") || html.includes("DMs shown in Savvy's video")); + assert.ok(html.includes('data-screen-transcribed=""')); + assert.ok(html.includes('data-screen-badge="s1"') && html.includes("DMs · transcribed")); + assert.ok(html.includes("Refund email shown in Savvy") && html.includes("picture")); + assert.ok(html.includes('data-screen-excerpt=""'), "an excerpted screen says so"); + // Each read line is a block of the read-follow. + for (const n of [0, 1, 2, 3]) assert.ok(new RegExp(`data-screen-line="${n}"><div class="swho">|data-screen-line="${n}"><div class="sbub" data-post-block="\\d+"`).test(html) || html.includes(`data-screen-line="${n}"`)); + assert.equal((html.match(/class="sbub" data-post-block="/g) ?? []).length, 4); + // TheQuartering is not a subject of her item: blurred; hers shown. redact: false shows him. + assert.ok(html.includes('<span class="sname redact">')); + assert.ok(!html.includes(">TheQuartering<")); + const shown = postCardHtml({ ...e, redact: false }, { width: 1600, height: 900, follow: true, thread: plan.follow.thread }); + assert.ok(shown.includes(">TheQuartering<")); + // The header: a blurred author is "the post's". + assert.equal(screenHeader(e, S1, { authorHidden: true }).text, "DMs shown in the post's video"); + assert.equal(screenHeader(e, S1).badge, "DMs · transcribed"); +}); + +test("anonymity: a speaker who is an anonymous handle is drawn under the shown name; the header the author's shown name; a display name refused", () => { + const set = new Map([["thequartering", "Anon 1"], ["madamsavvy", "Anon 2"]]); + const e = anonymiseEntry(narrated(base({ screens: [{ ...S1, lines: [...S1.lines, { who: "TheQuartering", text: "ask @TheQuartering yourself" }] }] }), [["s1", 0]]), set); + const lines = e.screens[0].lines; + assert.equal(lines[0].who, "Anon 1"); + assert.equal(lines[0].anonymous, true); + assert.equal(lines[4].text, "ask @Anon_1 yourself"); + assert.equal(e.author, "Anon 2"); + assert.equal(screenHeader(e, e.screens[0]).text, "DMs shown in Anon 2's video"); + const plan = postItemPlan(e, {}); + const html = postCardHtml(e, { width: 1600, height: 900, follow: true, thread: plan.follow.thread }); + assert.ok(!/TheQuartering|MadamSavvy|Savvy&#39;s|Savvy's/.test(html.replace(/Anon 2/g, "")), "no real name or handle in the page"); + assert.ok(html.includes(">Anon 1<")); + // A stray flag is the pass's alone: stripped on the way in. + const stray = anonymiseEntry(base({ screens: [{ ...S1, lines: [{ ...S1.lines[0], anonymous: true }] }] }), new Map([["someone", "Anon 9"]])); + assert.equal(stray.screens[0].lines[0].anonymous, undefined); + // The lint: a speaker written as an anonymous author's display name is an ERROR. + const doc = { characters: [{ id: "tq", name: "Jeremy", handles: ["TheQuartering"], anonymous: true, shown: "Anon 1" }] }; + const m = { timeline: [base({ screens: [{ ...S1, lines: [{ who: "Jeremy", text: "hi" }] }] }), { type: "post", id: "p-x", post: "tq-x/1", platform: "x", author: "Jeremy", handle: "TheQuartering", date: "2026-11-01T00:00:00Z", text: "x" }] }; + assert.ok(anonymityProblems(m, doc).errors.some((x) => /screen s1 line 0's speaker writes Anon 1's display name/.test(x))); +}); + +test("the guard: a part reading a line the screen does not read, a redacted line, or a screen it does not carry is refused, with the fix", () => { + const e = narrated(base()); + assert.deepEqual(threadReadErrors(e, {}), []); + const unread = { ...e, screens: [{ ...S1, read: [{ line: 0 }, { line: 1 }, { line: 3 }] }, S2] }; + assert.ok(threadReadErrors(unread, {}).some((x) => /part 5 reads line 2 of screen s1, which the screen does not read/.test(x) && /posts screen <p> p-2117 read/.test(x))); + const gone = { ...e, screens: [S1] }; + assert.ok(threadReadErrors(gone, {}).some((x) => /reads screen s2, which the item does not carry/.test(x))); + const redacted = { ...e, screens: [{ ...S1, lines: S1.lines.map((l, n) => (n === 3 ? { ...l, redact: true } : l)) }, S2] }; + assert.ok(threadReadErrors(redacted, {}).some((x) => /line 3 of screen s1, which is redacted/.test(x))); +}); + +test("the redaction's terms mark a screen's words and speakers: the card draws bars, the read leaves them out", () => { + const red = { terms: [{ term: "dumb" }, { term: "TheQuartering" }] }; + const out = redactEntry(base(), red); + assert.ok(!out.screens[0].lines[3].text.includes("dumb")); + assert.ok(!out.screens[0].lines[0].who.includes("TheQuartering")); + const e = narrated(base()); + const plan = postItemPlan(e, {}); + const html = postCardHtml(e, { width: 1600, height: 900, follow: true, thread: plan.follow.thread, redaction: red }); + assert.ok(!html.includes("this dumb")); +}); + +test("the lint's warnings: not checked, a masked shape, a read not made, a speaker blurred; a checked screen read whole is quiet", () => { + const e = narrated(base(), [["s1", 0], ["s1", 1]]); + const w = screenWarnings(e, { narrated: true, takeRoles: partRoles(e).map((r) => r.role) }); + assert.ok(w.some((x) => /screen s1's transcription not checked/.test(x))); + assert.ok(w.some((x) => /screen s2 line 2 holds an e-mail address and an order or reference number/.test(x) || /screen s2 line 2 holds/.test(x))); + assert.ok(w.some((x) => /does not read lines 2, 3 of screen s1/.test(x))); + assert.ok(w.some((x) => /does not read screen s2/.test(x))); + assert.ok(w.some((x) => /screen s1 line 0's speaker is drawn blurred/.test(x))); + const quiet = narrated(base({ redact: false, screens: [{ ...S1, checked: { by: "op", at: "2026-11-12T10:00:00Z" } }] }), [["s1", 0], ["s1", 1], ["s1", 2], ["s1", 3]]); + assert.deepEqual(screenWarnings(quiet, { narrated: true, takeRoles: partRoles(quiet).map((r) => r.role) }), []); + assert.ok(screenWarnings(base(), { narrated: false }).some((x) => /drawn and read only on a narrated item/.test(x))); + // Through the cut's lint warnings. + assert.ok(validateThreadReadWarnings({ timeline: [e] }).some((x) => /transcription not checked/.test(x))); +}); diff --git a/umtool/report-to-video/post-thread.mjs b/umtool/report-to-video/post-thread.mjs @@ -49,12 +49,13 @@ // bench, the writers and the lint all read the same rules from here. import { POST_PARENTS_MAX, cardText, contextText, linksOf, parentsOf, refMediaOf, refShown } from "./post-item.mjs"; -import { draftScript, isNarrated, isOnlyUrls, joinSplitLinks, pickedTake, scriptParts, spokenUrls } from "./post-narration.mjs"; +import { draftScript, isNarrated, isOnlyUrls, joinSplitLinks, pickedTake, postNarrationKnobs, scriptParts, spokenUrls } from "./post-narration.mjs"; import { normWord, scriptWordsOf } from "./word-zoom.mjs"; import { followKnobs } from "./read-follow.mjs"; import { planContext } from "./post-conversation.mjs"; import { branchMapOf, mapKnobs, mapTimes } from "./post-branch-map.mjs"; import { isPictureOnly, pictureBeatSeconds } from "./post-picture.mjs"; +import { isScreenScope, parseScreenRole, readScreens, screenLineProblem, screenLineSaid, screenOrder, screenPieces, screenReadLines, screenRole, screenScope, screenWarnings, screensOf as screensOfEntry, shapeSpans, tileOfRole } from "./post-screens.mjs"; /** What a context tile may be. */ export const THREAD_MODES = Object.freeze(["auto", "full", "excerpt", "context", "carry", "hidden"]); @@ -74,7 +75,7 @@ const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); const fin = (v) => typeof v === "number" && Number.isFinite(v); const str = (v) => (typeof v === "string" ? v : ""); const r3 = (v) => Math.round(v * 1000) / 1000; -const ROLE_RE = /^(post|quoted|parent:\d|media:\d|linked:\d)$/; +const ROLE_RE = /^(post|quoted|parent:\d|media:\d|linked:\d|screen:[a-z0-9][a-z0-9-]{0,23}:\d{1,2})$/; // --------------------------------------------------------------------------- // The knobs. @@ -164,6 +165,8 @@ export function readTexts(entry) { add(`linked:${i}`, [str(l.transcript), spoken(l.transcript)], true); }); add("post", [cardText(entry), str(entry?.narration?.script), spoken(cardText(entry))]); + // ITS SCREENS' read lines (post-screens.mjs): each its own text (a take's stored roles name them; a long line is matched). + for (const sc of readScreens(entry)) for (const r of screenReadLines(sc)) add(screenRole(sc.id, r.n), [screenLineSaid(sc, r.n)]); return out; } @@ -186,6 +189,12 @@ const kindOrder = (role) => (role.startsWith("parent:") ? 2 - Number(role.slice( * at theirs -- else by kind (kindOrder). An attachment's words come last. Ranks from 1. */ export function roleOrderOf(entry) { + const base = roleOrderByDate(entry); + // A SCREEN's line (post-screens.mjs) after every other text, in the screens' order and its lines'. + return readScreens(entry).length ? (role) => screenOrder(entry, role) ?? base(role) : base; +} + +function roleOrderByDate(entry) { const dates = new Map(); parentsOf(entry).forEach((p, i) => dates.set(`parent:${i}`, Date.parse(str(p?.date)))); if (isObj(entry?.quoted)) dates.set("quoted", Date.parse(str(entry.quoted.date))); @@ -346,6 +355,11 @@ export function threadLayout(entry, render = undefined, { prev = null, scene = n // THE READ's ORDER (operator, 4 Nov: "read the whole thread chronologically"): the tiles in the order the take // reads them -- a quote read before the post it answers sits above it -- one not read where it stood before the next. orderByRead(tiles, roles); + // ITS SCREENS (post-screens.mjs): each screen the take reads a line of, a tile after his post's, in the screens' order. + for (const sc of readScreens(entry)) { + if (!roles.some((r) => r?.role && parseScreenRole(r.role)?.id === sc.id)) continue; + tiles.push({ scope: screenScope(sc.id), mode: "full", read: true, screen: true }); + } const quotedAtOut = tiles.some((t) => t.above) ? "above" : "inside"; // THE SCENE (post-conversation.mjs): what the run had on screen, in the tree's order with this item's own tiles. const scened = withRelations(entry, isNarrated(entry) ? sceneTiles(entry, tiles, scene, k) : tiles, { group: !!scene?.group || !!groupOf(entry) }); @@ -531,6 +545,81 @@ function layoutMap(entry, tiles, roles, { prevId, group, knobs }) { return branchMapOf(nodes, { prevId, nowId: now, subject: str(entry?.handle), style: knobs.style, group }); } +/** + * ONE SCREEN PART's errors (part k of the picked take, its role a screen line's), pure: the line the screen does not + * read (left out, redacted, `read: "none"`, gone); the line CHANGED since the read (its words or its speaker: + * screenLineChanged -- judged on the entry it is given: the build judges the cut AS WRITTEN, validateScreenReads); and + * what the part SAYS holding a shape (an e-mail, a number: a recording that says what the card masks). `changed`: the + * roles already said changed (one sentence a line). + */ +export function screenPartErrors(entry, k, roles = partRoles(entry), changed = new Set()) { + const r = roles[k]; + const p = r?.role ? parseScreenRole(r.role) : null; + if (!p) return []; + const w = `timeline ${entry?.id ?? "?"}`; + const id = entry?.id ?? "<item>"; + const n = k + 1; + const out = []; + const why = screenLineProblem(entry, r.role); + if (why) out.push(`${w}: its take's part ${n} reads ${why} -- read it (umtool posts screen <p> ${id} set <screen> read=…) or re-make the read without it (umtool posts screen <p> ${id} read)`); + // The words it says are the line's AS IT IS NOW (operator's rule: nothing said the card does not show): a line edited, + // removed or moved since the read leaves the old audio under new lit text -- refused, never played. + else if (!changed.has(r.role) && screenLineChanged(entry, r.role, roles)) { + changed.add(r.role); + out.push(`${w}: its take's part ${n}: line ${p.n} of screen ${p.id} changed since the read (its words or its speaker are not what the take says) -- make the read again (umtool posts screen <p> ${id} read)`); + } + const part = (pickedTake(entry)?.parts ?? [])[k]; + const kinds = [...new Set(shapeSpans(str(part?.text)).map((x) => x.kind))]; + if (kinds.length) out.push(`${w}: its take's part ${n} (line ${p.n} of screen ${p.id}) says ${kinds.map((x) => (x === "email" ? "an e-mail address" : x === "order" ? "an order or reference number" : "a long number or a phone number")).join(" and ")} -- the card masks it, and a read never says it: re-record the line without it, or make the read again (umtool posts screen <p> ${id} read)`); + return out; +} + +/** + * THE SCREENS' READS over a cut, pure (the build's ENFORCED lint, build-video.mjs enforcedLint, gives it the cut AS + * WRITTEN -- never the anonymised copy it draws): every screen part's errors (screenPartErrors) of every narrated post + * item that carries screens. Empty for a cut with none. + */ +export function validateScreenReads(manifest) { + const tl = Array.isArray(manifest?.timeline) ? manifest.timeline : []; + const out = []; + for (const e of tl) { + if (e?.type !== "post" || !Array.isArray(e.screens) || !isNarrated(e)) continue; + const roles = partRoles(e); + const changed = new Set(); + roles.forEach((r, k) => { + if (r?.role && parseScreenRole(r.role)) out.push(...screenPartErrors(e, k, roles, changed)); + }); + } + return out; +} + +const sayKeys = (t) => str(t).toLowerCase().split(/\s+/).map((x) => x.replace(/^[^\p{L}\p{N}]+|[^\p{L}\p{N}]+$/gu, "")).filter(Boolean); +const normText = (t) => str(t).replace(/\s+/g, " ").trim(); + +/** + * Whether the picked take's parts for a screen line (`role`) say something else than the line says NOW: the line each + * part was made from (`parts[k].line`, stored by the thread read) is compared exactly with the line's words as a read + * would write them (draftScript of screenLineSaid); a part with none stored, by its own words, word for word. + */ +export function screenLineChanged(entry, role, roles = partRoles(entry)) { + const p = parseScreenRole(role); + const sc = p ? screensOfEntry(entry).find((x) => x.id === p.id) : null; + if (!sc) return false; + const said = screenLineSaid(sc, p.n); + const t = pickedTake(entry); + const parts = Array.isArray(t?.parts) && t.parts.length ? t.parts : scriptParts(str(t?.script).trim() ? t.script : str(entry?.narration?.script)).map((q) => ({ text: q.text })); + const mine = roles.map((r, k) => (r?.role === role ? parts[k] : null)).filter(Boolean); + if (!mine.length) return false; + // Its speaker (`speaker`, stored beside the line): a line given to someone else is not the line the voice read. + const spk = mine.find((x) => typeof x.speaker === "string"); + if (spk && normText(spk.speaker).toLowerCase() !== normText(sc.lines[p.n]?.who).toLowerCase()) return true; + const stored = mine.find((x) => typeof x.line === "string"); + if (stored) return normText(stored.line) !== normText(draftScript(said).script); + const a = sayKeys(mine.map((x) => str(x.text)).join(" ")); + const b = sayKeys(said); + return a.length !== b.length || a.some((x, i) => x !== b[i]); +} + /** A tile's mode in a layout (null: no such tile). */ export const tileModeOf = (layout, scope) => layout?.tiles?.find((t) => t.scope === scope)?.mode ?? null; @@ -538,7 +627,7 @@ export const tileModeOf = (layout, scope) => layout?.tiles?.find((t) => t.scope // THE GUARD: never narrate hidden text. // --------------------------------------------------------------------------- -const ROLE_NAME = (r) => (r === "post" ? "his words" : r === "quoted" ? "the post it quotes" : r.startsWith("linked:") ? "the post its words link to" : r.startsWith("parent:") ? (r === "parent:0" ? "the post it answers" : "the post that one answers") : `the words on attachment ${Number(r.slice(6)) + 1}`); +const ROLE_NAME = (r) => (parseScreenRole(r) ? `line ${parseScreenRole(r).n} of screen ${parseScreenRole(r).id}` : r === "post" ? "his words" : r === "quoted" ? "the post it quotes" : r.startsWith("linked:") ? "the post its words link to" : r.startsWith("parent:") ? (r === "parent:0" ? "the post it answers" : "the post that one answers") : `the words on attachment ${Number(r.slice(6)) + 1}`); /** * Every reason post item `entry`'s read narrates text the card does not show, @@ -554,6 +643,7 @@ export function threadReadErrors(entry, render = undefined, { prev = null, scene const w = `timeline ${entry?.id ?? "?"}`; const L = threadLayout(entry, render, { prev, scene }); const errors = []; + const changed = new Set(); const fix = `umtool posts set-item <p> ${entry?.id ?? "<item>"}`; const remake = `or re-make the read without it (umtool posts narrate <p> ${entry?.id ?? "<item>"} --take, a script that leaves it out)`; L.roles.forEach((r, k) => { @@ -562,6 +652,10 @@ export function threadReadErrors(entry, render = undefined, { prev = null, scene errors.push(`${w}: its take's part ${n} reads words the card does not show (no text on it holds them) -- set its role (umtool posts roles <p> ${entry?.id ?? "<item>"} --set ${n}=post|quoted|parent:0|media:0) ${remake}`); return; } + if (parseScreenRole(r.role)) { + errors.push(...screenPartErrors(entry, k, L.roles, changed)); + return; + } if (r.role.startsWith("media:")) { const m = (entry?.media ?? [])[Number(r.role.slice(6))]; if (!m) errors.push(`${w}: its take's part ${n} reads attachment ${Number(r.role.slice(6)) + 1}, which it does not have -- set its role (umtool posts roles)`); @@ -601,7 +695,7 @@ export function threadSchedule(entry, render, { layout, blocks, lead = 0.4, beat for (const b of blocks) if (b.part !== null && b.start !== null && !startOfPart.has(b.part)) startOfPart.set(b.part, b.start); // A PICTURE-ONLY context post's BEAT (pictureBeats) is a piece of its own, before the read's first. const beatOf = new Map((Array.isArray(beats) ? beats : []).map((b) => [b.scope, b])); - const pieces = [...beatOf.values()].map((b) => ({ role: b.scope, parts: [], start: b.t0, beat: b.scope !== "post" })).concat(readPieces(entry, roles).map((p) => { + const pieces = [...beatOf.values()].map((b) => ({ role: b.scope, parts: [], start: b.t0, beat: b.scope !== "post" })).concat(tilePieces(readPieces(entry, roles)).map((p) => { const ts = p.parts.map((n) => startOfPart.get(n)).filter(fin); return { ...p, start: ts.length ? Math.min(...ts) : null }; }).filter((p) => p.start !== null && p.role)); @@ -639,6 +733,15 @@ export function threadSchedule(entry, render, { layout, blocks, lead = 0.4, beat row.from = [1, 0]; Object.assign(row, win(T)); } + // ITS SCREENS read after it (post-screens.mjs): his post gives way to a strip as the first comes in. + const S = pieces.find((p) => !p.beat && isScreenScope(p.role) && (T === null || p.start > T))?.start ?? null; + if (S !== null) { + if (row.t1 > row.t0) row.then = { to: small, ...win(S) }; + else { + row.to = small; + Object.assign(row, win(S)); + } + } } else if (t.mode === "scene") { // A post the run left on screen (post-conversation.mjs): it opens as the item before ended, and as the // read begins an ancestor of this item stays on top as context, any other post collapses away. @@ -681,16 +784,19 @@ export function threadSchedule(entry, render, { layout, blocks, lead = 0.4, beat const T0 = firstRead(t.scope); // A quoted post above his: a top-level tile like a parent (revealed, shrunk); inside his: it only dims. const own = t.scope !== "quoted" || !!t.above; + // A SCREEN (post-screens.mjs) read and done COLLAPSES as the next one comes in: stacked, they would bury it. + const done = t.screen ? [0, 0] : small; if (own && revealed(t.scope, T0)) { // Revealed when its read comes (an older post read before it) -- from where the run had it, when it had it. row.from = t.fromScene ?? [1, 0]; row.to = [1, 1]; Object.assign(row, win(T0)); - if (T !== null) row.then = { to: small, ...win(T) }; + if (T !== null) row.then = { to: done, ...win(T) }; } else if (T !== null) { - row.to = own ? small : [1, k.dim]; + row.to = own ? done : [1, k.dim]; Object.assign(row, win(T)); } + if (t.screen) row.screen = true; } if (t.above) row.above = true; if (t.rel) row.rel = t.rel; @@ -702,6 +808,19 @@ export function threadSchedule(entry, render, { layout, blocks, lead = 0.4, beat return { shrink: k.shrink, dim: k.dim, seconds: k.seconds, pan: k.pan, contextRoom: THREAD_CONTEXT_ROOM, quotedAt: above ? "above" : "inside", tiles, ...(map ? { map } : {}) }; } +/** The read's pieces on their TILES: a screen's lines (post-screens.mjs) are one piece of its tile; any other role its own. */ +function tilePieces(pieces) { + if (!pieces.some((p) => p.role && isScreenScope(p.role))) return pieces; + const out = []; + for (const p of pieces) { + const role = p.role ? tileOfRole(p.role) : p.role; + const last = out[out.length - 1]; + if (last && last.role === role && role) last.parts = [...last.parts, ...p.parts]; + else out.push({ ...p, role }); + } + return out; +} + /** inOut cubic over [0, 1]. */ const ease = (x) => { const v = Math.min(1, Math.max(0, x)); @@ -767,7 +886,7 @@ export function threadGeoAt(geo, scales) { if (y >= t.top + t.height - 0.5) d += (1 - t.s) * t.height; else if (y > t.top) d += (1 - t.s) * (y - t.top); // A scene tile collapsing away (post-conversation.mjs) closes the gap above it too. - if (t.gap > 0 && t.scope.startsWith("conv:") && y >= t.top - 0.5) d += (1 - t.s) * t.gap; + if (t.gap > 0 && (t.scope.startsWith("conv:") || isScreenScope(t.scope)) && y >= t.top - 0.5) d += (1 - t.s) * t.gap; } return y - d; }; @@ -836,10 +955,13 @@ export function isTruncated(text) { return /…$/.test(t) || /\bshow more$/i.test(t); } -/** THE WARNINGS over a cut (the build's lint): every narrated post item's (threadReadWarnings). */ +/** THE WARNINGS over a cut (the build's lint): every narrated post item's (threadReadWarnings), and its screens' (post-screens.mjs). */ export function validateThreadReadWarnings(manifest) { const tl = Array.isArray(manifest?.timeline) ? manifest.timeline : []; - return tl.filter((e) => e?.type === "post").flatMap((e) => threadReadWarnings(e)); + return tl.filter((e) => e?.type === "post").flatMap((e) => [ + ...threadReadWarnings(e), + ...(Array.isArray(e.screens) ? screenWarnings(e, { narrated: isNarrated(e), takeRoles: isNarrated(e) ? partRoles(e).map((r) => r.role) : [], attachAfter: isNarrated(e) && postNarrationKnobs(e, manifest?.render).attach === "after" }) : []), + ]); } /** @@ -1003,5 +1125,8 @@ export function chronoPieces(entry, { skip = [] } = {}) { if (isObj(entry?.quoted)) add("quoted", entry.quoted, contextText(entry.quoted)); linksOf(entry).forEach((l, i) => add(`linked:${i}`, l, [contextText(l), str(l.transcript)].filter((t) => t.trim()).join("\n\n"))); add("post", entry, cardText(entry)); - return out.sort((a, b) => order(a.role) - order(b.role)); + out.sort((a, b) => order(a.role) - order(b.role)); + // ITS SCREENS' read lines (post-screens.mjs), after everything else, in the screens' order: `who` as written. + for (const p of screenPieces(entry)) if (!skip.includes(p.role)) out.push({ role: p.role, date: null, author: null, handle: null, who: p.who, screen: p.screen, text: p.text }); + return out; } diff --git a/umtool/report-to-video/read-follow.mjs b/umtool/report-to-video/read-follow.mjs @@ -50,6 +50,7 @@ import { partRoles, threadGeoAt, threadKnobs, threadLayout, threadSchedule, thre import { sceneLayout, sceneRows, sceneSchedule } from "./post-media-scene.mjs"; import { linkVisits, visitRows, visitStateAt } from "./post-link-visit.mjs"; import { mapStateAt } from "./post-branch-map.mjs"; +import { isScreenScope, parseScreenRole, screenScope } from "./post-screens.mjs"; export const FOLLOW_DEFAULTS = Object.freeze({ on: true, dim: 0.65, ease: 0.25 }); export const FOLLOW_LIMITS = Object.freeze({ dim: [0.2, 1], ease: [0, 2] }); @@ -229,7 +230,16 @@ export function followBlocks(entry) { const byScope = new Map(scopes.map((sc) => [sc.scope, { sc, spans: [], cursor: 0 }])); // A part read off an attachment (a screenshot's words, post-thread.mjs): a block with no words on the card. const media = []; + // A SCREEN's line (post-screens.mjs): a block of its own -- the line, drawn by the screen's tile -- named by its role, + // never matched by words; a line read in several parts is one block (from its first part). + const screenLines = new Set(); parts.forEach((p, pi) => { + const sl = typeof p.scope === "string" ? parseScreenRole(p.scope) : null; + if (sl) { + if (!screenLines.has(p.scope)) media.push({ scope: screenScope(sl.id), line: sl.n, from: null, to: null, part: pi }); + screenLines.add(p.scope); + return; + } if (typeof p.scope === "string" && p.scope.startsWith("media:")) { media.push({ scope: p.scope, from: null, to: null, part: pi }); return; @@ -471,7 +481,7 @@ export function followPath(follow, geo) { } /** The tile a block's scope is drawn in (a quoted post is a tile inside his post's). */ -const tileScopeOf = (scope) => (scope === "quoted" || scope === "post" || String(scope).startsWith("parent:") || String(scope).startsWith("linked:") ? scope : null); +const tileScopeOf = (scope) => (scope === "quoted" || scope === "post" || String(scope).startsWith("parent:") || String(scope).startsWith("linked:") || isScreenScope(scope) ? scope : null); /** * A THREADED card's PAN (post-thread.mjs), pure: `{ thread: true, start, @@ -642,13 +652,15 @@ export function followStateAt(follow, path, s) { for (const [scope, [sc, o]] of Object.entries(ts)) { const h = path?.tiles?.[scope]?.height ?? 0; // A scene tile (post-conversation.mjs) collapsing away takes the gap above it with it. - const gap = scope.startsWith("conv:") ? path?.tiles?.[scope]?.gap ?? 0 : 0; + const gap = scope.startsWith("conv:") || isScreenScope(scope) ? path?.tiles?.[scope]?.gap ?? 0 : 0; tiles[scope] = gap > 0 ? [sc, o, Math.round(h * 100) / 100, Math.round(gap * 100) / 100] : [sc, o, Math.round(h * 100) / 100]; if (sc < 0.9995 && gap > 0) C -= (1 - sc) * gap; // A tile closes the flow up under it as it shrinks -- a quoted post inside his post never shrinks; one above it does. if (sc < 0.9995 && (scope !== "quoted" || follow.thread.quotedAt === "above")) C -= (1 - sc) * h; } const below = C - (path?.H ?? 0) - offset; + // A SCREEN up (post-screens.mjs): the one in full now -- its badge ("· transcribed") pinned to the card while it is. + const scr = screenUpAt(ts); return { op, offset, @@ -657,6 +669,7 @@ export function followStateAt(follow, path, s) { current, tiles, ...jp, + ...(scr !== undefined ? { screen: scr } : {}), }; } return { @@ -669,8 +682,21 @@ export function followStateAt(follow, path, s) { }; } +/** + * The SCREEN up at a thread state (post-screens.mjs): the id of the last screen tile at half its size and strength or + * more, null when none is -- undefined when the card has no screen tile (its state then carries no `screen`). + * @param {Record<string, number[]>} ts + */ +function screenUpAt(ts) { + const scopes = Object.keys(ts).filter(isScreenScope); + if (!scopes.length) return undefined; + let up = null; + for (const sc of scopes) if (ts[sc][0] >= 0.5 && ts[sc][1] >= 0.5) up = sc.slice(7); + return up; +} + /** A state's key: two frames with the same key draw the same card (the build shoots each key once). */ -export const followStateKey = (st) => JSON.stringify([st.op, st.offset, st.fadeTop, st.fadeBottom, ...(st.tiles ? [st.tiles] : []), ...(st.join !== undefined ? [st.join] : []), ...(st.visit ? [st.visit] : []), ...(st.map ? [st.map] : [])]); +export const followStateKey = (st) => JSON.stringify([st.op, st.offset, st.fadeTop, st.fadeBottom, ...(st.tiles ? [st.tiles] : []), ...(st.join !== undefined ? [st.join] : []), ...(st.visit ? [st.visit] : []), ...(st.map ? [st.map] : []), ...(st.screen !== undefined ? [{ screen: st.screen }] : [])]); /** * Whether a state draws the card PAGE AS DRAWN (no state applied): nothing @@ -683,7 +709,7 @@ export const followStateKey = (st) => JSON.stringify([st.op, st.offset, st.fadeT */ export function isDrawnState(st) { if (!st) return true; - if (fin(st.join) || st.visit || st.map) return false; + if (fin(st.join) || st.visit || st.map || (typeof st.screen === "string" && st.screen)) return false; if (Object.values(st.op ?? {}).some((o) => fin(o) && o < 0.9995)) return false; if (fin(st.offset) && Math.abs(st.offset) >= 0.5) return false; if ((st.fadeTop ?? 0) > 0 || (st.fadeBottom ?? 0) > 0) return false; @@ -705,7 +731,7 @@ export function isDrawnState(st) { export const READ_IN_VIEW = Object.freeze({ tol: 2, slack: 0.25, share: 0.5, step: 0.05, size: 0.005 }); const pct = (v) => `${Math.round(v * 100)}%`; -const tileName = (scope) => (scope === "post" ? "his post" : scope === "quoted" ? "the quoted post" : String(scope).startsWith("parent:") ? `the post it answers (${scope})` : String(scope).startsWith("linked:") ? `the post it links (${scope})` : String(scope)); +const tileName = (scope) => (isScreenScope(scope) ? `screen ${String(scope).slice(7)}` : scope === "post" ? "his post" : scope === "quoted" ? "the quoted post" : String(scope).startsWith("parent:") ? `the post it answers (${scope})` : String(scope).startsWith("linked:") ? `the post it links (${scope})` : String(scope)); /** * THE READ IN VIEW, pure: every reason the words being read are not on screen, @@ -948,5 +974,10 @@ export function applyFollowState(state, doc = document) { const el = doc.querySelector(`[data-post-fade="${side}"]`); if (el) el.style.opacity = String(v || 0); } + // A SCREEN's badge (post-screens.mjs): shown while that screen is up. + for (const el of Array.from(doc.querySelectorAll("[data-screen-badge]"))) { + const v = state && state.screen === el.getAttribute("data-screen-badge") ? "1" : ""; + if (el.style.opacity !== v) el.style.opacity = v; + } if (doc.body) doc.body.setAttribute("data-post-follow-block", state && state.current !== null && state.current !== undefined ? String(state.current) : ""); }