commit 6a5f22ec04c2781d8abf0f3fbb8b261f9bf4c883 parent 36b1b1c040a8010f7911c102b5bc15c5f8f77639 Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st> Date: Tue, 3 Nov 2026 14:17:59 -0500 umtool: a REDACTION list for post items -- words blanked from what is published, never from the data (operator: "Leave out his real name ... blank and skip it"; "don't manipulate original data, just don't show it in the public views") render.posts.redact [{term, wholeWord?, note?}] (case-insensitive, whole words by default, a phrase across any spaces or punctuation or none, a possessive 's with it), merged with the corpus's redactions.json and a channel's posts-markup.json (a term per scope, or a span of the archived text) by post-redact-files.mjs. Applied only where public output is made: the rendered card draws each match as a solid bar of its width (no letters in the page, not a blur), a synthesized read (CLI --take and the bench) leaves it out with its spaces and dangling punctuation tidied, a post's chapter line and an attachment's burnt-in captions drop it. The archive rows, the manifest's snapshot and every script keep their words. Play gets an "As published" toggle (the card page's published=1); the recording teleprompter strikes the words to skip. Writer updatePostRedact + `umtool posts redact <p> ls | add "<term>" [--substring] [--note] | remove <n>`. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Diffstat:
18 files changed, 748 insertions(+), 19 deletions(-)
diff --git a/umtool/app/api/report/post-item/route.ts b/umtool/app/api/report/post-item/route.ts @@ -8,6 +8,7 @@ import { StaleToken, StructureRefused, manifestToken, updatePostItem } from "@/l import { rangeResponse, resolveReport } from "@/lib/report/serve.mjs"; import { resolveTakeManifest } from "@/lib/report/takeManifest.mjs"; import { refuseCaller } from "@/lib/report/caller"; +import { projectRedaction } from "@/lib/report/postRedaction.mjs"; export const dynamic = "force-dynamic"; @@ -15,8 +16,10 @@ export const dynamic = "force-dynamic"; // umtool/docs/knobs.md, "A post item"): what Play the cut and the post bench // draw a post item with, and the bench's writer. // -// GET ?project&id&w&h[&phase=read|media][&take] the card's page, the HTML the build -// screenshots, at w × h (the footage box) +// GET ?project&id&w&h[&phase=read|media][&take][&published=1] the card's page, the HTML the +// build screenshots, at w × h (the footage box); +// published=1 AS PUBLISHED: its redacted words bars +// (post-redact.mjs), never in the page // GET ?project&file=posts-media/… an attachment (byte ranges): only a file // under the project's posts-media/ // GET ?project&font=regular|bold the cut's faces, for the page @@ -120,12 +123,19 @@ export async function GET(request: Request) { const parentShot = typeof found.item.parentShot === "string" ? `${base}&file=${encodeURIComponent(found.item.parentShot)}` : null; // The authors' pictures (post-avatars.mjs), served as the project's files. const avatars = avatarUrls(found.manifest, (src: string) => `${base}&file=${encodeURIComponent(src)}`) as Record<string, string>; + let redaction = null; + try { + if (q.get("published") === "1") redaction = await projectRedaction(r.project.dir, found.manifest); + } catch (e) { + return new Response(e instanceof Error ? e.message : String(e), { status: 500 }); + } const html = postCardHtml(found.item, { width: w, height: h, avatars, palette: (render.palette ?? {}) as Record<string, string>, fonts: { regular: `${base}&font=regular`, bold: `${base}&font=bold` }, phase: q.get("phase") === "media" ? "media" : "read", parentShotUrl: parentShot, + redaction, }); return new Response(html, { headers: { "content-type": "text/html; charset=utf-8", ...noStore } }); } diff --git a/umtool/app/api/report/post-narration/route.ts b/umtool/app/api/report/post-narration/route.ts @@ -13,6 +13,8 @@ import { refuseCaller } from "@/lib/report/caller"; import { deleteTake, measureTake } from "@/lib/report/postNarrationCli.mjs"; import { keepRecording, RECORD_LABEL_RE } from "@/lib/report/postRecord.mjs"; import { fitPostItem } from "@/lib/report/postFit.mjs"; +import { projectRedaction } from "@/lib/report/postRedaction.mjs"; +import { spokenWithout, termsFor } from "umtool-report-to-video/post-redact"; export const dynamic = "force-dynamic"; @@ -167,7 +169,9 @@ export async function POST(request: Request) { await mkdir(dir, { recursive: true }); const rel = takeFileOf(pid, nextTakeNumber(e, await readdir(dir).catch(() => [])), engine, voice); const speed = body.speed === undefined || body.speed === null || engine === "orpheus" ? undefined : Number(body.speed); - const jobId = await startJob("/api/ops/tts", { text: script, engine, voice, out: path.join(r.project.dir, ...rel.split("/")), ...(speed ? { speed } : {}) }); + // What the voice SAYS: the script with every redacted term left out (post-redact.mjs); the script is kept as written. + const spoken = spokenWithout(script, termsFor(e, await projectRedaction(r.project.dir, m))); + const jobId = await startJob("/api/ops/tts", { text: spoken, engine, voice, out: path.join(r.project.dir, ...rel.split("/")), ...(speed ? { speed } : {}) }); return Response.json({ ok: true, jobId, file: rel, engine, voice, script }, { headers: noStore }); } if (body.op === "derive") { diff --git a/umtool/components/projects/RecordPage.tsx b/umtool/components/projects/RecordPage.tsx @@ -10,6 +10,8 @@ import { draftScript, pickedTake, takeSourceOf } from "umtool-report-to-video/po import { normalizeParts, partsFileOf } from "@/lib/report/postNarrationCli.mjs"; import { avatarEntryOf } from "umtool-report-to-video/post-avatars"; import type { ProjectRef } from "@/lib/project-types"; +import { projectRedaction } from "@/lib/report/postRedaction.mjs"; +import { termsFor } from "umtool-report-to-video/post-redact"; // THE RECORDING SESSION (operator, 3 Nov: "I need to do a dramatic reading of // this starting tomorrow"): /projects/<p>/narration/record walks the cut's @@ -29,6 +31,8 @@ export default async function RecordPage({ project, search = {} }: { project: Pr const posts = ((Array.isArray(m.timeline) ? m.timeline : []) as Entry[]).filter((e) => e?.type === "post"); if (!posts.length) notFound(); const items: RecordItem[] = []; + // The words to leave out of the read (post-redact.mjs): marked on the teleprompter, never removed from the script. + const redaction = await projectRedaction(project.dir, m); for (const [i, e] of posts.entries()) { const takes = e.narration?.takes ?? []; const picked = pickedTake(e) as (Take & { index: number }) | null; @@ -49,6 +53,7 @@ export default async function RecordPage({ project, search = {} }: { project: Pr placeholder: placeholder ? { file: placeholder.file, seconds: placeholder.seconds, parts: (parts ?? []).map((p) => ({ n: p.n, para: p.para ?? 0, text: p.text ?? "", start: p.start, seconds: p.seconds, ...(p.file ? { file: p.file } : {}) })) } : null, media: (e.media ?? []).slice(0, 1).map((x) => ({ src: x.src, kind: x.kind }))[0] ?? null, avatar: av ? String((av[1] as { src?: string }).src ?? "") || null : null, + skip: termsFor(e, redaction) as RecordItem["skip"], }); } const box = deckOn(render) ? deckGeometry(render).footage : { width: Number(render.width ?? 1920), height: Number(render.height ?? 1080) }; diff --git a/umtool/components/projects/RecordSession.tsx b/umtool/components/projects/RecordSession.tsx @@ -1,10 +1,11 @@ "use client"; -import { useCallback, useEffect, useMemo, useRef, useState } from "react"; +import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react"; import { buttonVariants } from "@/components/ui/button"; import { cn } from "@/lib/utils"; import { postBenchHref } from "@/lib/hrefs"; import { scriptParts } from "umtool-report-to-video/post-narration"; +import { redactText } from "umtool-report-to-video/post-redact"; import { MIC_KEY, ls, useMic } from "./useMic"; // --------------------------------------------------------------------------- @@ -38,7 +39,28 @@ export type RecordItem = { placeholder: { file: string; seconds: number; parts: Part[] } | null; media: { src: string; kind: string } | null; avatar: string | null; + /** Redacted terms (post-redact.mjs): marked on the teleprompter as words to leave out of the read. */ + skip?: Array<{ term: string; wholeWord?: boolean }>; }; + +/** A part's words with each redacted term struck through: say everything but those. */ +function SkipMarked({ text, skip }: { text: string; skip?: RecordItem["skip"] }) { + const { spans } = redactText(text, skip ?? []) as { spans: Array<{ start: number; end: number }> }; + if (!spans.length) return <>{text}</>; + const out: ReactNode[] = []; + let at = 0; + for (const sp of spans) { + out.push(text.slice(at, sp.start)); + out.push( + <s key={sp.start} className="text-muted-2" title="redacted: leave this out of the read" data-record-skip=""> + {text.slice(sp.start, sp.end)} + </s>, + ); + at = sp.end; + } + out.push(text.slice(at)); + return <>{out}</>; +} type Session = { count: number | null; parts: Record<string, { file: string; text: string; at: string }> }; const COUNT_KEY = "umtool.record.count-in"; @@ -339,7 +361,7 @@ export default function RecordSession({ project, items: initial, start, box }: { data-record-prompt-kept={kept(p.n) ? "1" : undefined} > {parts.length > 1 && <span className="micro mr-2 align-middle">{p.n}/{parts.length}</span>} - {p.text} + <SkipMarked text={p.text} skip={item.skip} /> {i === cur && ( <span className="mt-1 flex flex-wrap gap-1.5 text-[12px]"> {kept(p.n) && ( diff --git a/umtool/components/projects/review/PlayCut.tsx b/umtool/components/projects/review/PlayCut.tsx @@ -169,6 +169,8 @@ const PAUSE_KEY = "umtool.play.pauseWhileWriting"; /** "on": play the clips the walk rejected too (for re-review); absent or "off": skip them. */ // The key keeps its old name: a browser that chose "show" before rejections had reasons still has. const SHOW_REJECTED_KEY = "umtool.play.showIncorrect"; +/** Play's "As published": post cards drawn with their redacted words as bars (post-redact.mjs). Per browser. */ +const AS_PUBLISHED_KEY = "umtool.play.asPublished"; /** The dailies' kinds of note: what it asks for, and its key (with Alt, in the composer). */ const ASKS: { id: CutAsk; label: string; key: string }[] = [ @@ -337,6 +339,15 @@ export default function PlayCut({ // unless asked for: the cut the operator means to ship does not hold them // (umtool check blocks on a fact error and lists the rest). Remembered per browser. const [showRejected, setShowRejected] = useState(false); + const [asPublished, setAsPublished] = useState(false); + useEffect(() => { + try { + if (window.localStorage.getItem(AS_PUBLISHED_KEY) === "on") setAsPublished(true); + } catch { + // A preference, not state. + } + }, []); + const hasPosts = useMemo(() => view.entries.some((e) => e.type === "post"), [view.entries]); useEffect(() => { try { // The URL first (Back from the bench lands on the URL Play left), then this browser's choice. @@ -834,6 +845,7 @@ export default function PlayCut({ s={Math.max(0, t - postNow.item.start)} playing={ui.playing && !ui.waiting} speed={rate} + published={asPublished} /> ) : null; const placeholderCard = placeholder ? ( @@ -1047,6 +1059,25 @@ export default function PlayCut({ ))} </select> </label> + {hasPosts && ( + <label className="inline-flex items-center gap-1.5 text-[11.5px] text-text-2" title="the post cards as the video draws them: every redacted word a blank bar (umtool posts redact)"> + <input + type="checkbox" + data-play-as-published="" + checked={asPublished} + onChange={(ev) => { + const on = ev.target.checked; + setAsPublished(on); + try { + window.localStorage.setItem(AS_PUBLISHED_KEY, on ? "on" : "off"); + } catch { + // A preference, not state. + } + }} + /> + As published + </label> + )} {item && ( <span className="min-w-0 truncate font-mono text-[11.5px] text-muted" data-play-readout=""> {ui.cur + 1}/{plan.items.length} · {item.id} diff --git a/umtool/components/projects/review/PostItemPlayer.tsx b/umtool/components/projects/review/PostItemPlayer.tsx @@ -195,7 +195,7 @@ function MediaEl({ } export default function PostItemPlayer({ - project, take = null, entry, plan, box, s, playing, cardKey = null, speed = 1, + project, take = null, entry, plan, box, s, playing, cardKey = null, speed = 1, published = false, }: { project: string; take?: string | null; @@ -209,6 +209,8 @@ export default function PostItemPlayer({ cardKey?: string | null; /** The clock's speed (Play's 0.75-3x): the attachments and the voice play at it, not seeked along. */ speed?: number; + /** AS PUBLISHED (Play's toggle): the card with its redacted words as bars, as the build draws it. */ + published?: boolean; }) { const wrap = useRef<HTMLDivElement | null>(null); const [scale, setScale] = useState(0); @@ -246,7 +248,7 @@ export default function PostItemPlayer({ }, [box.width]); const layout = useMemo(() => postLayout(entry, box), [entry, box]); const pageUrl = (phase: "read" | "media") => - `/api/report/post-item?project=${encodeURIComponent(project)}&id=${encodeURIComponent(entry.id)}&w=${Math.round(box.width)}&h=${Math.round(box.height)}&phase=${phase}${take ? `&take=${encodeURIComponent(take)}` : ""}${cardKey ? `&v=${encodeURIComponent(cardKey)}` : ""}`; + `/api/report/post-item?project=${encodeURIComponent(project)}&id=${encodeURIComponent(entry.id)}&w=${Math.round(box.width)}&h=${Math.round(box.height)}&phase=${phase}${take ? `&take=${encodeURIComponent(take)}` : ""}${cardKey ? `&v=${encodeURIComponent(cardKey)}` : ""}${published ? "&published=1" : ""}`; const reading = s < plan.reading || !plan.steps.length; const current = stepAt(plan, s); // Beside the card, the first attachment is up (its first frame) while the words are read. diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs @@ -60,6 +60,7 @@ import { validateNarration } from "umtool-report-to-video/narration"; import { validatePostItem, validatePostItems } from "umtool-report-to-video/post-item"; import { AVATARS_DIR, avatarEntryOf, handleKey, validatePostAvatars } from "umtool-report-to-video/post-avatars"; import { POST_NARRATION_DEFAULTS, validatePostNarrationRender } from "umtool-report-to-video/post-narration"; +import { termWords, validatePostsRender } from "umtool-report-to-video/post-redact"; import { parseMuteFrom } from "./playback.mjs"; import { LINK_POLICY_KEY, linkPolicyOf, normalizeLinkPolicy, policyCiteUrl, webpageReader } from "./linkPolicy.mjs"; import { SHADOW_CHANNELS as POLICY_SHADOW, channelsDirFor as policyChannelsDirFor } from "umtool-report-to-video/sources"; @@ -2687,6 +2688,45 @@ export async function updatePostNarrationRender(dir, patch, { token = null } = { }); } +// ---- the redaction list (post-redact.mjs; `umtool posts redact`) --------- + +/** + * CHANGE THE PROJECT's REDACTION LIST (`render.posts.redact`): `{ add: {term, + * wholeWord?, note?} }` appends a term (one already there, the same words + * and the same wholeWord, is refused), `{ remove: <index> }` takes one out. + * The words of the posts are never touched: the list is applied where a + * public output is made. Validated with the build's check. + * + * @param {string} dir + * @param {{ add?: {term: string, wholeWord?: boolean, note?: string}, remove?: number }} change + * @param {{ token?: string | null }} [opts] + */ +export async function updatePostRedact(dir, change, { token = null } = {}) { + if (!isObj(change) || (change.add === undefined) === (change.remove === undefined)) throw new Error("say add or remove"); + return structural(dir, "post-redact", token, (m) => { + if (!isObj(m.render)) m.render = {}; + const posts = isObj(m.render.posts) ? m.render.posts : {}; + const list = Array.isArray(posts.redact) ? [...posts.redact] : []; + if (change.add !== undefined) { + const t = change.add; + const key = (x) => `${termWords(x?.term).join(" ").toLowerCase()}|${x?.wholeWord !== false}`; + if (list.some((x) => key(x) === key(t))) throw new Error("that term is already on the list"); + list.push({ term: String(t?.term ?? "").trim(), ...(t?.wholeWord === false ? { wholeWord: false } : {}), ...(typeof t?.note === "string" && t.note ? { note: t.note } : {}) }); + } else { + const i = change.remove; + if (!Number.isInteger(i) || i < 0 || i >= list.length) throw new Error(`no term ${typeof i === "number" ? i + 1 : i} on the list (it holds ${list.length})`); + list.splice(i, 1); + } + if (list.length) posts.redact = list; + else delete posts.redact; + if (Object.keys(posts).length) m.render.posts = posts; + else delete m.render.posts; + const errors = validatePostsRender(m.render); + if (errors.length) throw new StructureRefused(errors); + return { redact: list }; + }); +} + // ---- the link policy (UI notes 2026-10-30, #10; linkPolicy.mjs) ----------- /** diff --git a/umtool/lib/report/postNarrationCli.mjs b/umtool/lib/report/postNarrationCli.mjs @@ -25,6 +25,8 @@ import { NARRATION_INDEX, POST_DERIVE_OPS, POST_DERIVE_ROUTES, derivedFileOf, draftScript, takeIdOf, isNarrated, nextTakeNumber, pickedTake, postIdOf, postNarrationKnobs, takeFileOf, takesDirOf, } from "umtool-report-to-video/post-narration"; import { postItemPlan } from "umtool-report-to-video/post-item"; +import { spokenWithout, termsFor } from "umtool-report-to-video/post-redact"; +import { projectRedaction } from "./postRedaction.mjs"; import { readManifest } from "../projects/report.mjs"; import { withEditNotes } from "./edit-guard.mjs"; import { manifestToken, updatePostNarration, updatePostNarrationRender, updatePostNarrations } from "./manifest.mjs"; @@ -238,7 +240,7 @@ export function mixPatchOf(pairs, { cut = false } = {}) { * the project, measured, appended (and picked) through the writer. Returns * the take and the write's result. */ -export async function makeTake(project, e, { script = null, note = null, engine = null, voice = null, speed = null, render = {}, emit = () => {}, editor = null, ask = null } = {}) { +export async function makeTake(project, e, { script = null, note = null, engine = null, voice = null, speed = null, render = {}, emit = () => {}, editor = null, ask = null, redaction = undefined } = {}) { const k = postNarrationKnobs(e, render); const words = String(script ?? e.narration?.script ?? "").trim(); if (!words) throw new NarrateError(`${e.id} has no script to read (--script "…", or --all --draft-scripts)`); @@ -253,7 +255,9 @@ export async function makeTake(project, e, { script = null, note = null, engine const rel = takeFileOf(pid, n, eng, vox); const out = path.join(project.dir, ...rel.split("/")); const askTts = ask ?? (await import("umtool-report-to-video/narrate-via-editor")).askEditorTts; - const body = { text: words, engine: eng, voice: vox, out, ...(spd !== null && eng !== "orpheus" ? { speed: spd } : {}) }; + // What the voice SAYS: the script with every redacted term left out (post-redact.mjs) -- the script itself is kept as written. + const red = redaction !== undefined ? redaction : await projectRedaction(project.dir, (await readManifest(project.dir)) ?? {}); + const body = { text: spokenWithout(words, termsFor(e, red)), engine: eng, voice: vox, out, ...(spd !== null && eng !== "orpheus" ? { speed: spd } : {}) }; const { jobId, result } = await askTts(body, { ...(editor ? { editor } : {}), emit }); if (!(await stat(out).catch(() => null))?.isFile()) throw new NarrateError(`the editor's job ${jobId} finished but ${rel} is not there (its result names ${result?.wav ?? "no file"})`); const m = await measureTake(out); diff --git a/umtool/lib/report/postRedaction.mjs b/umtool/lib/report/postRedaction.mjs @@ -0,0 +1,15 @@ +// A PROJECT's REDACTION (umtool-report-to-video/post-redact.mjs): the corpus's +// terms, its channels' post markup and the project's own `render.posts.redact`, +// read from the channels tree the project's clip bench reads. What a take's +// synthesized read, Play's "As published" and the post item route blank. +import { readPostRedaction } from "umtool-report-to-video/post-redact-files"; +import { channelsDirFor, hasShadowChannels } from "../projects/report.mjs"; + +/** + * @param {string} dir the project's folder + * @param {Record<string, any>} manifest + */ +export async function projectRedaction(dir, manifest) { + const channelsDir = channelsDirFor(dir, manifest, { shadowExists: await hasShadowChannels(dir) }); + return readPostRedaction(channelsDir, manifest); +} diff --git a/umtool/lib/report/postRedaction.test.mjs b/umtool/lib/report/postRedaction.test.mjs @@ -0,0 +1,93 @@ +// The redaction list's writer and CLI (`umtool posts redact`), the corpus's +// files read beside it (post-redact-files.mjs), and a take's synthesized read +// with the terms left out while its script is kept. Made-up terms only. +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { after, test } from "node:test"; +import { postsCommand } from "./postsCli.mjs"; +import { makeTake } from "./postNarrationCli.mjs"; +import { projectRedaction } from "./postRedaction.mjs"; + +const ROOT = await mkdtemp(path.join(tmpdir(), "umtool-post-redact-")); +after(() => rm(ROOT, { recursive: true, force: true })); +const REPORTS = path.join(ROOT, "reports"); +const CH = path.join(ROOT, "channels"); +const wav = (f, secs) => execFileSync("ffmpeg", ["-v", "error", "-y", "-f", "lavfi", "-i", `sine=f=220:d=${secs}`, "-ar", "48000", "-ac", "1", f]); + +const item = (id, o = {}) => ({ + type: "post", id: `p-${id}`, post: `subj-x/${id}`, platform: "x", author: "THE SUBJECT", handle: "Subject", date: "2026-10-30T10:00:00.000Z", + text: `post ${id}`, ...o, +}); +async function project(name, timeline, render = {}) { + const dir = path.join(REPORTS, name); + await mkdir(dir, { recursive: true }); + await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify({ + schemaVersion: 1, slug: name, title: name, provenance: { siteOrigin: "", channelSlug: "subj-x", channelsDir: CH }, + render: { width: 1920, height: 1080, fps: 30, ...render }, timeline, + }, null, 2)); + return { id: name, dir }; +} +const manifest = async (p) => JSON.parse(await readFile(path.join(p.dir, "video.manifest.json"), "utf8")); +const cli = async (args) => { + const lines = []; + const errs = []; + const code = await postsCommand(args, { root: REPORTS, out: (s) => lines.push(s), err: (s) => errs.push(s) }); + return { code, out: lines.join("\n"), err: errs.join("\n") }; +}; + +test("posts redact: add, ls (numbered, as remove takes them), remove -- the posts' words untouched", async () => { + const p = await project("r", [item("1", { text: "I am Quentin Example" })]); + let r = await cli(["redact", "r", "add", "Quentin Example", "--note", "a made-up name"]); + assert.equal(r.code, 0, r.err); + r = await cli(["redact", "r", "add", "Exam", "--substring"]); + assert.equal(r.code, 0, r.err); + const m = await manifest(p); + assert.deepEqual(m.render.posts.redact, [{ term: "Quentin Example", note: "a made-up name" }, { term: "Exam", wholeWord: false }]); + assert.equal(m.timeline[0].text, "I am Quentin Example", "the snapshot is never rewritten"); + r = await cli(["redact", "r", "ls"]); + assert.match(r.out, /r: 2 term\(s\) of its own; 0 from the corpus, 0 post\(s\) marked up/); + assert.match(r.out, /1\. Quentin Example {2}-- a made-up name/); + assert.match(r.out, /2\. Exam {2}\(inside words too\)/); + // The same term twice is refused. + r = await cli(["redact", "r", "add", "quentin example"]); + assert.equal(r.code, 1); + r = await cli(["redact", "r", "remove", "1"]); + assert.equal(r.code, 0, r.err); + assert.deepEqual((await manifest(p)).render.posts.redact, [{ term: "Exam", wholeWord: false }]); + assert.equal((await cli(["redact", "r", "remove", "5"])).code, 1); + await cli(["redact", "r", "remove", "1"]); + assert.equal((await manifest(p)).render.posts, undefined, "an empty list leaves no key"); +}); + +test("the corpus's terms and a channel's markup are read with the project's list; a broken file fails the read", async () => { + const p = await project("c", [item("1")], { posts: { redact: [{ term: "Zed" }] } }); + await mkdir(path.join(CH, "subj-x"), { recursive: true }); + await writeFile(path.join(ROOT, "redactions.json"), JSON.stringify([{ term: "Quentin Example", note: "everywhere" }])); + await writeFile(path.join(CH, "subj-x", "posts-markup.json"), JSON.stringify({ "1": { redact: [{ start: 0, end: 4 }] } })); + const red = await projectRedaction(p.dir, await manifest(p)); + assert.deepEqual(red.terms.map((t) => t.term), ["Quentin Example", "Zed"]); + assert.deepEqual(Object.keys(red.markup), ["subj-x/1"]); + assert.match((await cli(["redact", "c", "ls"])).out, /1 term\(s\) of its own; 1 from the corpus, 1 post\(s\) marked up/); + await writeFile(path.join(ROOT, "redactions.json"), "{ not json"); + await assert.rejects(projectRedaction(p.dir, await manifest(p)), /does not parse/); + await rm(path.join(ROOT, "redactions.json")); + await rm(path.join(CH, "subj-x", "posts-markup.json")); +}); + +test("a take's synthesized read leaves the term out; the script and the take's record keep it", async () => { + const p = await project("t", [item("1", { narration: { script: "Hello, I am Quentin Example. Welcome." } })], { posts: { redact: [{ term: "Quentin Example" }] } }); + const asked = []; + const ask = async (body) => { + asked.push(body); + wav(body.out, 1); + return { jobId: "job-1", result: { wav: body.out, engine: body.engine, voice: body.voice, seconds: 1 } }; + }; + const r = await makeTake(p, (await manifest(p)).timeline[0], { ask }); + assert.equal(asked[0].text, "Hello, I am. Welcome."); + assert.doesNotMatch(asked[0].text, /quentin/i); + assert.equal(r.take.script, "Hello, I am Quentin Example. Welcome."); + assert.equal((await manifest(p)).timeline[0].narration.script, "Hello, I am Quentin Example. Welcome."); +}); diff --git a/umtool/lib/report/postsCli.mjs b/umtool/lib/report/postsCli.mjs @@ -33,7 +33,7 @@ import path from "node:path"; import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs"; import { channelsDirFor, readManifest } from "../projects/report.mjs"; import { withEditNotes } from "./edit-guard.mjs"; -import { PostsRefused, StaleToken, StructureRefused, addArchiveAvatars, manifestToken, setPostAvatar, updatePostItem, updatePosts, upsertPost } from "./manifest.mjs"; +import { PostsRefused, StaleToken, StructureRefused, addArchiveAvatars, manifestToken, setPostAvatar, updatePostItem, updatePostRedact, updatePosts, upsertPost } from "./manifest.mjs"; import { postWarnings } from "./postCards.mjs"; export const POSTS_USAGE = [ @@ -74,6 +74,12 @@ export const POSTS_USAGE = [ " umtool posts avatars <project> [--dry-run] [--json]", " every author the cut's cards draw unblurred, their picture from the archive's store (the channels' posts-media/", " _avatars/, capture-posts') copied in where the cut has none; a manual one is never replaced.", + " umtool posts redact <project> ls | add \"<term>\" [--substring] [--note \"…\"] | remove <n> [--json]", + " REDACTED WORDS (render.posts.redact): a word or phrase blanked from everything PUBLISHED -- a solid bar on the", + " rendered card, left out of a synthesized read, a chapter line and an attachment's captions. Matched without case,", + " as whole words (--substring: inside words too), a phrase across any spaces or punctuation. The posts' words are", + " never rewritten; Play's \"As published\" shows the bars. `ls` lists the project's terms (n as `remove` takes it)", + " and counts the corpus's (transcripts/redactions.json, channels/<slug>/posts-markup.json).", " umtool posts context <project> [--dry-run] [--json]", " every post item's CONTEXT from its capture (capture.json's `context`: the post it quotes, the post it answers, as", " its page showed them) where the archive row lacks it -- one write (one undo point). A post whose capture read", @@ -372,6 +378,7 @@ export async function postsCommand(args, { root = REPORTS_ROOT, out = (s) => con if (lingerRaw !== null && !(Number.isFinite(linger) && linger >= 0 && linger <= 30)) throw new CliError("--linger takes seconds, 0-30"); return await fitCommand(await projectOf(projectArg, root), words.slice(2), { all: flags.has("--all"), linger, json, dryRun, out }); } + if (verb === "redact" && projectArg && !flags.has("--help")) return await redactCommand(projectArg, words.slice(2), { root, json, out, flags, str }); if (verb === "avatar" && projectArg && !flags.has("--help")) return await avatarCommand(projectArg, words.slice(2), { root, json, out }); if (verb === "avatars" && projectArg && !flags.has("--help")) return await avatarsCommand(projectArg, { root, json, dryRun, out }); if (verb === "context" && projectArg && !flags.has("--help")) return await contextCommand(projectArg, { root, json, dryRun, out }); @@ -576,6 +583,42 @@ export function postItemPatchOf(pairs) { } /** `posts context`: every post item's context from its capture (postContext.mjs postsContext). */ +/** `umtool posts redact <p> ls | add "<term>" [--substring] [--note …] | remove <n>`: the project's redaction list. */ +async function redactCommand(projectArg, rest, { root, json, out, flags, str }) { + const project = await projectOf(projectArg, root); + const [sub, arg] = rest; + const write = async (change) => withEditNotes(project, async () => updatePostRedact(project.dir, change, { token: await manifestToken(project.dir) })); + const line = (t, i) => ` ${i + 1}. ${t.term}${t.wholeWord === false ? " (inside words too)" : ""}${t.note ? ` -- ${t.note}` : ""}`; + if (sub === "add") { + if (!arg || !String(arg).trim()) throw new CliError('posts redact add takes the term: add "<word or phrase>"'); + const { result } = await write({ add: { term: arg, ...(flags.has("--substring") ? { wholeWord: false } : {}), ...(str("--note") ? { note: str("--note") } : {}) } }); + out(json ? JSON.stringify({ ok: true, redact: result.redact, token: result.token }, null, 2) : `added; ${project.id} blanks ${result.redact.length} term(s) from what it publishes`); + return 0; + } + if (sub === "remove") { + const n = Number(arg); + if (!Number.isInteger(n) || n < 1) throw new CliError("posts redact remove takes the term's number, as `ls` shows it"); + const { result } = await write({ remove: n - 1 }); + out(json ? JSON.stringify({ ok: true, redact: result.redact, token: result.token }, null, 2) : `removed term ${n}; ${project.id} blanks ${result.redact.length} term(s)`); + return 0; + } + if (sub !== "ls" && sub !== undefined) throw new CliError(`posts redact: ls, add "<term>" or remove <n> (not ${sub})`); + const manifest = await readManifest(project.dir); + if (!manifest) throw new CliError(`${project.id} has no manifest`); + const list = Array.isArray(manifest.render?.posts?.redact) ? manifest.render.posts.redact : []; + const { projectRedaction } = await import("./postRedaction.mjs"); + const all = await projectRedaction(project.dir, manifest); + const corpus = all.terms.length - list.length; + const marked = Object.keys(all.markup ?? {}).length; + if (json) { + out(JSON.stringify({ ok: true, redact: list, corpusTerms: corpus, markedPosts: marked }, null, 2)); + return 0; + } + out(`${project.id}: ${list.length} term(s) of its own${list.length ? "" : " (umtool posts redact <p> add \"<term>\")"}; ${corpus} from the corpus, ${marked} post(s) marked up in its channels`); + list.forEach((t, i) => out(line(t, i))); + return 0; +} + async function contextCommand(projectArg, { root, json, dryRun, out }) { const project = await projectOf(projectArg, root); const { postsContext } = await import("./postContext.mjs"); diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs @@ -212,6 +212,8 @@ import { // The snap itself (a montage's window snaps with it too), re-exported for the tests. import { snap } from "./snap.mjs"; import { buildPostSegment } from "./post-render.mjs"; +import { readPostRedaction } from "./post-redact-files.mjs"; +import { dropMarks, redactEntry } from "./post-redact.mjs"; import { avatarUrls } from "./post-avatars.mjs"; export { snap }; // The lint a build runs before it renders, and the prune after its final mux. @@ -285,6 +287,8 @@ let LOCAL = null; // The channels tree the build reads local media from (sources.mjs // channelsDirFor), for the effects' words: set by buildVideo() beside CUES. let FX_CHANNELS_DIR = null; +// What this build blanks from its post items (post-redact.mjs): the corpus's terms, the channels' markup, the project's list. +let POST_REDACTION = null; const exists = (p) => access(p).then(() => true, () => false); @@ -5527,6 +5531,13 @@ export async function chapterTitle(entry, index, provenance, { deck = false } = } // A post item: who posted it, and the first words. if (entry.type === "post") { + // As published: a redacted term is left out of the chapter line (post-redact.mjs). + const shown = redactEntry(entry, POST_REDACTION); + if (shown !== entry) { + const words = dropMarks(String(shown.text ?? "").replace(/^RT @[A-Za-z0-9_]+:\s*/, "")).replace(/\s+/g, " ").trim(); + const who = dropMarks(String(shown.author ?? "")) || (dropMarks(String(shown.handle ?? "")) ? `@${dropMarks(String(shown.handle))}` : "Post"); + return `${who}: ${words.length > 60 ? `${words.slice(0, 57)}…` : words || "(no words)"}`; + } const words = String(entry.text ?? "").replace(/^RT @[A-Za-z0-9_]+:\s*/, "").replace(/\s+/g, " ").trim(); return `${entry.author ?? (entry.handle ? `@${entry.handle}` : "Post")}: ${words.length > 60 ? `${words.slice(0, 57)}…` : words || "(no words)"}`; } @@ -6139,6 +6150,7 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly rawDir: dirs.rawDir, channelsDir, channelSlug: provenance?.channelSlug ?? null, probe: opts.probe, }); FX_CHANNELS_DIR = channelsDir; + POST_REDACTION = await readPostRedaction(channelsDir, manifest); // Speaker captions read the project's reactions.json and words beside the // manifest (readLookSources); a short is framed by its clip's crop. if (captionsOn(render)) dirs.look = await readLookSources(manifestDir); @@ -6402,6 +6414,7 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly encode: encodeArgs(render), exec: execFileP, ffmpeg: FFMPEG, emit: (ev, f) => EMIT(ev, f), // The authors' pictures (post-avatars.mjs), as files of the project. avatars: avatarUrls(manifest, (src) => path.resolve(manifestDir, src)), + redaction: POST_REDACTION, }); if (fr) await writeCutRecord(seg, { version: 1, id: entry.id, framing: fr }); return seg; diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json @@ -63,6 +63,8 @@ "./post-avatars": "./post-avatars.mjs", "./post-item": "./post-item.mjs", "./post-narration": "./post-narration.mjs", + "./post-redact": "./post-redact.mjs", + "./post-redact-files": "./post-redact-files.mjs", "./post-render": "./post-render.mjs", "./presets": "./presets.mjs", "./prune-frames": "./prune-frames.mjs", diff --git a/umtool/report-to-video/post-item.mjs b/umtool/report-to-video/post-item.mjs @@ -28,6 +28,7 @@ import { isNarrated, narrationSchedule, postNarrationFiles, postNarrationKnobs, validatePostNarration, } from "./post-narration.mjs"; +import { BAR_CSS, barsHtml, redactEntry, validatePostsRender } from "./post-redact.mjs"; /** The platforms a post item may come from (deck.mjs POST_PLATFORMS). */ export const POST_ITEM_PLATFORMS = Object.freeze(["x", "bluesky", "web"]); @@ -495,6 +496,7 @@ export function validatePostItems(manifest) { const errors = []; const tl = Array.isArray(manifest?.timeline) ? manifest.timeline : []; for (const e of tl) if (e?.type === "post") errors.push(...validatePostItem(e)); + errors.push(...validatePostsRender(manifest?.render)); return errors; } @@ -731,9 +733,12 @@ export function nameHtml(who, { redact, cls = "" }) { * * @param {Record<string, any>} entry * @param {{ width: number, height: number, palette?: Record<string, string>, fonts?: { regular?: string, bold?: string }, - * phase?: "read"|"media", parentShotUrl?: string|null, transparent?: boolean, avatars?: Record<string, string> }} o + * phase?: "read"|"media", parentShotUrl?: string|null, transparent?: boolean, avatars?: Record<string, string>, + * redaction?: { terms: Array<{term: string, wholeWord?: boolean}>, markup?: Record<string, any> } | null }} o */ -export function postCardHtml(entry, { width, height, palette = {}, fonts = {}, phase = "read", parentShotUrl = null, transparent = false, avatars = {} }) { +export function postCardHtml(entry, { width, height, palette = {}, fonts = {}, phase = "read", parentShotUrl = null, transparent = false, avatars = {}, redaction = null }) { + // AS PUBLISHED (post-redact.mjs): every redacted match drawn as a bar, its letters never in the page. + entry = redactEntry(entry, redaction); const pic = (who) => avatarUrlOf(avatars, who?.handle); const pal = { bg: "#12100c", fg: "#f6f1e6", muted: "#a2957f", accent: "#c8752a", ...palette }; const L = postLayout(entry, { width, height }); @@ -828,8 +833,9 @@ b, .name, .mark { font-family: 'PostSansBold', sans-serif; font-weight: 400; } .redact { filter: blur(${Math.round(9 * k)}px); color: ${pal.muted}; } .avatar.redact { background: ${rgbaOf(pal.muted, 0.6)} !important; } .slot { background: ${rgbaOf("#000000", 0.32)}; border-radius: ${Math.round(14 * k)}px; } +${BAR_CSS(pal.fg)} </style></head> -<body data-post-item="${esc(entry.id)}" data-post-layout="${L.mode}" data-post-phase="${strip ? "media" : "read"}">${body} +<body data-post-item="${esc(entry.id)}" data-post-layout="${L.mode}" data-post-phase="${strip ? "media" : "read"}">${barsHtml(body)} <script> // The words at the layout's size, shrunk while they overflow (the browser // knows how they wrap; the layout only estimated it). Then say so. diff --git a/umtool/report-to-video/post-redact-files.mjs b/umtool/report-to-video/post-redact-files.mjs @@ -0,0 +1,71 @@ +// THE REDACTION A BUILD PUBLISHES WITH (post-redact.mjs): the corpus's terms, +// each post's channel markup and the project's own list, read together. Read +// only -- the corpus's two files are the editor's to write. +// +// <transcripts>/redactions.json [{ term, wholeWord?, note? }] (or { terms: […] }) +// <transcripts>/channels/<slug>/posts-markup.json { "<postId>": { redact: […] } } +// +// A file that is there and does not parse, or is refused by its validator, +// FAILS the read: a public render that silently ignored its redaction would +// publish what it was told to blank. A file that is not there is nothing. +import { readFile } from "node:fs/promises"; +import path from "node:path"; +import { normalizeTerms, projectRedactOf, validatePostsMarkup, validateRedactTerms } from "./post-redact.mjs"; + +export const CORPUS_REDACTIONS_FILE = "redactions.json"; +export const POSTS_MARKUP_FILE = "posts-markup.json"; + +/** The corpus's terms file beside a channels dir. */ +export const corpusRedactionsPath = (channelsDir) => path.join(path.dirname(path.resolve(channelsDir)), CORPUS_REDACTIONS_FILE); +/** A channel's markup file. */ +export const postsMarkupPath = (channelsDir, slug) => path.join(path.resolve(channelsDir), slug, POSTS_MARKUP_FILE); + +async function readJson(file) { + let text; + try { + text = await readFile(file, "utf8"); + } catch (e) { + if (e?.code === "ENOENT" || e?.code === "ENOTDIR") return undefined; + throw e; + } + try { + return JSON.parse(text); + } catch (e) { + throw new Error(`${file} does not parse (${e instanceof Error ? e.message : e}) -- a public render does not run without its redaction`); + } +} + +/** + * The redaction for `manifest`'s post items: `{ terms, markup }`. `channelsDir` + * null reads only the project's list (no corpus at hand). + * + * @param {string|null} channelsDir + * @param {Record<string, any>} manifest + */ +export async function readPostRedaction(channelsDir, manifest) { + const project = projectRedactOf(manifest?.render); + const terms = []; + const markup = {}; + if (channelsDir) { + const file = corpusRedactionsPath(channelsDir); + const doc = await readJson(file); + if (doc !== undefined) { + const list = Array.isArray(doc) ? doc : doc?.terms; + const errors = validateRedactTerms(list, CORPUS_REDACTIONS_FILE); + if (errors.length) throw new Error(`${file} is refused: ${errors.join("; ")}`); + terms.push(...normalizeTerms(list)); + } + const posts = (Array.isArray(manifest?.timeline) ? manifest.timeline : []).filter((e) => e?.type === "post" && typeof e.post === "string"); + const slugs = [...new Set(posts.map((e) => e.post.split("/")[0]).filter((s) => /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(s)))]; + for (const slug of slugs) { + const mf = postsMarkupPath(channelsDir, slug); + const doc2 = await readJson(mf); + if (doc2 === undefined) continue; + const errors = validatePostsMarkup(doc2, `${slug}/${POSTS_MARKUP_FILE}`); + if (errors.length) throw new Error(`${mf} is refused: ${errors.join("; ")}`); + for (const [id, m] of Object.entries(doc2)) markup[`${slug}/${id}`] = m; + } + } + terms.push(...normalizeTerms(project)); + return { terms, markup }; +} diff --git a/umtool/report-to-video/post-redact.mjs b/umtool/report-to-video/post-redact.mjs @@ -0,0 +1,268 @@ +// WORDS BLANKED FROM WHAT IS PUBLISHED (operator, 3 Nov: "Leave out his real +// name since we don't really need it, even if he says it himself blank and +// skip it"; "don't manipulate original data, just don't show it in the +// public views"). umtool/docs/knobs.md, "Redacted words". +// +// A REDACTION is a list of terms -- a word or a phrase -- matched without +// regard to case, as whole words unless `wholeWord: false`, the words of a +// phrase across any run of spaces or punctuation ("Quentin Example" matches +// "quentin, EXAMPLE", and "QuentinExample" as a handle runs them together), a +// possessive 's taken with it. Its sources, merged by +// the reader (post-redact-files.mjs): +// +// render.posts.redact [{ term, wholeWord?, note? }] the project's own list +// <transcripts>/redactions.json the same shape every project's (the corpus's) +// channels/<slug>/posts-markup.json one post's MARKUP: +// { "<postId>": { redact: [{ term, wholeWord?, scope? } | { start, end, scope?, index? }] } } +// a term (in `scope` -- "text", "parent", "quoted" -- or the whole post), or a span of the +// archived text, in code units (`index`: which parent, nearest first) +// +// NOTHING IS REWRITTEN: the archive's rows, the manifest's snapshot and a +// narration's script keep their words. Redaction happens only where PUBLIC +// output is made -- the rendered card (each match a solid bar of the word's +// width: no letters, not a blur), the read a voice synthesizes (the match +// dropped, its spaces and dangling punctuation tidied), a video's chapter +// line and an attachment's burnt-in captions. umtool's own views show the +// words; Play's "As published" shows the bars. +// +// PURE and dependency-free (the build, the route, Play and the writers). + +/** The mark a redacted code unit becomes (a private-use character: never typed, never drawn as a letter). */ +export const REDACT_MARK = ""; +const MARKS_RE = /+/g; +export const POST_REDACT_MAX = 200; +export const POST_REDACT_TERM_MAX = 120; +export const POST_MARKUP_SCOPES = Object.freeze(["text", "parent", "quoted"]); + +const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); +const str = (v) => (typeof v === "string" ? v : ""); +const WORD = "[\\p{L}\\p{N}]"; +const escRe = (s) => s.replace(/[.*+?^${}()|[\]\\/-]/g, "\\$&"); + +/** A term's words (letters and digits): what it matches, across any punctuation. */ +export const termWords = (term) => str(term).split(/[^\p{L}\p{N}]+/u).filter(Boolean); + +/** A list's terms as `{ term, wholeWord }`, a bare string read as a term. */ +export function normalizeTerms(list) { + return (Array.isArray(list) ? list : []) + .map((t) => (typeof t === "string" ? { term: t } : t)) + .filter((t) => isObj(t) && termWords(t.term).length) + .map((t) => ({ term: t.term, wholeWord: t.wholeWord !== false })); +} + +/** One term's pattern source, or null when it has no word to match. */ +export function termPattern(t) { + const words = termWords(t?.term); + if (!words.length) return null; + // Between a phrase's words, any run of spaces or punctuation -- or none, as a handle writes it ("QuentinExample"). + const body = `${words.map(escRe).join("[^\\p{L}\\p{N}]*")}(?:['’]s)?`; + return t?.wholeWord === false ? body : `(?<!${WORD})${body}(?!${WORD})`; +} + +/** The terms' one pattern (longest first, so a phrase wins over a word inside it), or null. */ +export function redactPattern(terms) { + const src = normalizeTerms(terms) + .sort((a, b) => b.term.length - a.term.length) + .map(termPattern) + .filter(Boolean); + return src.length ? new RegExp(src.join("|"), "giu") : null; +} + +/** + * `text` with every match of `terms` (and every `spans` range, `{start, end}` + * in code units) turned into REDACT_MARKs, one per code unit -- its length and + * every offset kept, so a layout measured on it is the original's. Returns + * `{ text, spans }`: the merged ranges, sorted. + * + * @param {string} text + * @param {Array<string|{term: string, wholeWord?: boolean}>|RegExp|null} terms + * @param {{ spans?: Array<{start: number, end: number}> }} [o] + */ +export function redactText(text, terms, { spans: extra = [] } = {}) { + const s = str(text); + const re = terms instanceof RegExp ? new RegExp(terms.source, terms.flags) : redactPattern(terms); + const ranges = []; + if (re && s) for (const m of s.matchAll(re)) if (m[0]) ranges.push([m.index, m.index + m[0].length]); + for (const sp of Array.isArray(extra) ? extra : []) { + const a = Math.max(0, Math.floor(Number(sp?.start))); + const b = Math.min(s.length, Math.floor(Number(sp?.end))); + if (Number.isFinite(a) && Number.isFinite(b) && b > a) ranges.push([a, b]); + } + if (!ranges.length) return { text: s, spans: [] }; + ranges.sort((x, y) => x[0] - y[0]); + const merged = []; + for (const r of ranges) { + const last = merged[merged.length - 1]; + if (last && r[0] <= last[1]) last[1] = Math.max(last[1], r[1]); + else merged.push([...r]); + } + let out = ""; + let at = 0; + for (const [a, b] of merged) { + out += s.slice(at, a) + REDACT_MARK.repeat(b - a); + at = b; + } + return { text: out + s.slice(at), spans: merged.map(([start, end]) => ({ start, end })) }; +} + +/** Does `text` hold a redacted match? */ +export const hasMarks = (text) => str(text).includes(REDACT_MARK); + +/** + * Marked text with the marks DROPPED, as a read or a line of text says it: + * the spaces either side collapsed to one, a bracket left empty removed, and + * punctuation left dangling -- a comma before a full stop, a clause's comma + * at a sentence's start -- taken away. Only around a mark; the rest verbatim. + */ +export function dropMarks(marked) { + const parts = str(marked).split(MARKS_RE); + if (parts.length === 1) return parts[0]; + let out = parts[0]; + for (let i = 1; i < parts.length; i += 1) { + let L = out.replace(/[ \t]+$/, ""); + let R = parts[i].replace(/^[ \t]+/, ""); + if (/[(\[]$/.test(L) && /^[)\]]/.test(R)) { + L = L.slice(0, -1).replace(/[ \t]+$/, ""); + R = R.slice(1).replace(/^[ \t]+/, ""); + } + if ((L === "" || /[.!?…\n,;:(\[]$/.test(L)) && /^[,;:]/.test(R)) R = R.replace(/^[,;:][ \t]*/, ""); + if (/[,;:]$/.test(L) && /^[.!?…,;:]/.test(R)) L = L.slice(0, -1); + const glue = L === "" || /\n$/.test(L) || R === "" || /^[\n,.!?;:…)\]]/.test(R) ? "" : " "; + out = L + glue + R; + } + return out.trim(); +} + +/** `text` as SAID with `terms` left out (a synthesized read; a chapter line). */ +export const spokenWithout = (text, terms) => { + const r = redactText(text, terms); + return r.spans.length ? dropMarks(r.text) : str(text); +}; + +/** The width a run of `n` marks is drawn at, in em (a sans face's average letter). */ +export const barEm = (n) => Math.round(n * 0.52 * 100) / 100; + +/** HTML (already escaped) with each run of marks drawn as a solid bar of its width -- no letters inside. */ +export const barsHtml = (html) => + str(html).replace(MARKS_RE, (m) => `<span class="rbar" data-post-blanked="" style="width:${barEm(m.length)}em"></span>`); + +/** The bar's CSS, for a page that draws them. */ +export const BAR_CSS = (fg) => `.rbar { display: inline-block; height: 0.92em; vertical-align: -0.12em; background: ${fg}; border-radius: 0.12em; }`; + +// --------------------------------------------------------------------------- +// The project's list and a post's markup. +// --------------------------------------------------------------------------- + +/** The project's own list (`render.posts.redact`). */ +export const projectRedactOf = (render) => (Array.isArray(render?.posts?.redact) ? render.posts.redact : []); + +/** Every reason a list of terms (the project's, or the corpus's file) is refused. */ +export function validateRedactTerms(list, where = "render.posts.redact") { + if (list === undefined) return []; + if (!Array.isArray(list)) return [`${where} must be a list of {term, wholeWord?}`]; + const errors = []; + if (list.length > POST_REDACT_MAX) errors.push(`${where} holds at most ${POST_REDACT_MAX} terms`); + list.forEach((t, i) => { + const w = `${where}[${i}]`; + if (!isObj(t)) return errors.push(`${w} must be {term, wholeWord?}`); + for (const k of Object.keys(t)) if (!["term", "wholeWord", "note"].includes(k)) errors.push(`${w}.${k} is not a key of a term (term, wholeWord, note)`); + if (typeof t.term !== "string" || !termWords(t.term).length) errors.push(`${w}.term must hold a word (letters or digits)`); + else if (t.term.length > POST_REDACT_TERM_MAX) errors.push(`${w}.term is longer than ${POST_REDACT_TERM_MAX} characters`); + if (t.wholeWord !== undefined && typeof t.wholeWord !== "boolean") errors.push(`${w}.wholeWord must be true or false`); + if (t.note !== undefined && typeof t.note !== "string") errors.push(`${w}.note must be words`); + }); + return errors; +} + +/** Every reason `render.posts` cannot be built (its `redact` list). */ +export function validatePostsRender(render) { + const p = render?.posts; + if (p === undefined) return []; + if (!isObj(p)) return ["render.posts must be an object ({redact})"]; + return validateRedactTerms(p.redact); +} + +/** Every reason a channel's posts-markup.json is refused. */ +export function validatePostsMarkup(doc, where = "posts-markup.json") { + if (!isObj(doc)) return [`${where} must be {"<postId>": {redact: […]}}`]; + const errors = []; + for (const [id, m] of Object.entries(doc)) { + const w = `${where} ${id}`; + if (!/^[A-Za-z0-9_-]{1,128}$/.test(id)) errors.push(`${w}: not a post id`); + if (!isObj(m) || !Array.isArray(m.redact)) { + errors.push(`${w} must be {redact: […]}`); + continue; + } + m.redact.forEach((r, i) => { + const wi = `${w}.redact[${i}]`; + if (!isObj(r)) return errors.push(`${wi} must be {term} or {start, end}`); + if (r.scope !== undefined && !POST_MARKUP_SCOPES.includes(r.scope)) errors.push(`${wi}.scope must be one of ${POST_MARKUP_SCOPES.join(", ")}`); + if (r.index !== undefined && !(Number.isInteger(r.index) && r.index >= 0 && r.index < 2)) errors.push(`${wi}.index must be 0 or 1 (a parent, nearest first)`); + if (r.term !== undefined) { + if (typeof r.term !== "string" || !termWords(r.term).length) errors.push(`${wi}.term must hold a word`); + if (r.wholeWord !== undefined && typeof r.wholeWord !== "boolean") errors.push(`${wi}.wholeWord must be true or false`); + } else if (!(Number.isInteger(r.start) && Number.isInteger(r.end) && r.start >= 0 && r.end > r.start)) { + errors.push(`${wi} must name a term, or a span {start, end} of the text (code units, end after start)`); + } + }); + } + return errors; +} + +/** + * A REDACTION as the readers resolve it: `{ terms, markup }` -- every term + * that applies everywhere (the corpus's and the project's) and each post's + * markup by `<channel>/<postId>` (the entry's `post`). + * + * @typedef {{ terms: Array<{term: string, wholeWord?: boolean}>, markup?: Record<string, {redact: any[]}> }} Redaction + */ + +/** Is there anything to blank? */ +export const redactionOn = (red) => !!red && (normalizeTerms(red.terms).length > 0 || Object.keys(red.markup ?? {}).length > 0); + +/** The terms that apply to post item `entry` in `scope` (everywhere, then its markup's). */ +export function termsFor(entry, red, scope = null) { + const mine = red?.markup?.[str(entry?.post)]?.redact ?? []; + const local = mine.filter((r) => isObj(r) && typeof r.term === "string" && (!scope || !r.scope || r.scope === scope)); + return [...normalizeTerms(red?.terms), ...normalizeTerms(local)]; +} + +const spansFor = (entry, red, scope, index = 0) => + (red?.markup?.[str(entry?.post)]?.redact ?? []).filter( + (r) => isObj(r) && r.term === undefined && (r.scope ?? "text") === scope && (scope !== "parent" || (r.index ?? 0) === index), + ); + +/** + * Post item `entry` AS PUBLISHED: a copy with every match marked (redactText) + * in what its card draws -- its words, its author's name and handle, the + * posts it answers and quotes (their words, a paraphrase, their names), the + * repost line, a "replying to" handle and the subjects the authors' rule + * reads (so a subject marked is still the subject). The entry itself is + * never touched; with nothing to blank, it is returned as it is. + * + * @param {Record<string, any>} entry + * @param {Redaction|null|undefined} red + */ +export function redactEntry(entry, red) { + if (!redactionOn(red) || !isObj(entry)) return entry; + const all = redactPattern(termsFor(entry, red)); + const scoped = (scope) => redactPattern(termsFor(entry, red, scope)); + const mark = (v, re, spans = []) => (typeof v === "string" ? redactText(v, re, { spans }).text : v); + const ref = (r, scope, index = 0) => { + if (!isObj(r)) return r; + const re = scoped(scope); + const out = { ...r }; + for (const k of ["author", "handle"]) if (k in out) out[k] = mark(out[k], all); + if ("text" in out) out.text = mark(out.text, re, spansFor(entry, red, scope, index)); + if ("paraphrase" in out) out.paraphrase = mark(out.paraphrase, re); + return out; + }; + const out = { ...entry }; + for (const k of ["author", "handle", "replyingTo"]) if (k in out) out[k] = mark(out[k], all); + out.text = mark(entry.text, scoped("text"), spansFor(entry, red, "text")); + if (Array.isArray(entry.subjects)) out.subjects = entry.subjects.map((h) => mark(h, all)); + if (isObj(entry.repostedBy)) out.repostedBy = { ...entry.repostedBy, author: mark(entry.repostedBy.author, all), handle: mark(entry.repostedBy.handle, all) }; + if (Array.isArray(entry.parents)) out.parents = entry.parents.map((p, i) => ref(p, "parent", i)); + if (isObj(entry.quoted)) out.quoted = ref(entry.quoted, "quoted"); + return out; +} diff --git a/umtool/report-to-video/post-redact.test.mjs b/umtool/report-to-video/post-redact.test.mjs @@ -0,0 +1,92 @@ +// post-redact.mjs: words blanked from what is published -- the matcher, the +// marks, the read without them, the card that never holds them. Made-up +// terms only ("Quentin Example"). +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { + REDACT_MARK, barsHtml, dropMarks, redactEntry, redactPattern, redactText, spokenWithout, termsFor, validatePostsMarkup, validatePostsRender, +} from "./post-redact.mjs"; +import { postCardHtml, validatePostItems } from "./post-item.mjs"; + +const NAME = [{ term: "Quentin Example" }]; +const marks = (n) => REDACT_MARK.repeat(n); + +test("a term matches without case, as whole words; --substring inside words too", () => { + assert.equal(redactText("quentin is here", [{ term: "Quentin" }]).text, `${marks(7)} is here`); + // Whole word: not inside another word. + assert.equal(redactText("Quentinesque", [{ term: "Quentin" }]).text, "Quentinesque"); + assert.equal(redactText("Quentinesque", [{ term: "Quentin", wholeWord: false }]).text, `${marks(7)}esque`); + // A possessive goes with it. + assert.equal(redactText("QUENTIN's mic", [{ term: "Quentin" }]).text, `${marks(9)} mic`); + // A bare string is a term. + assert.equal(redactText("hi Quentin", ["quentin"]).spans.length, 1); + assert.equal(redactPattern([]), null); +}); + +test("a phrase matches across any spaces or punctuation; its length and offsets are kept", () => { + const s = "Signed, quentin.\n EXAMPLE -- for real"; + const r = redactText(s, NAME); + assert.equal(r.text.length, s.length); + assert.deepEqual(r.spans, [{ start: 8, end: 25 }]); + assert.equal(r.text, `Signed, ${marks(17)} -- for real`); + assert.equal(redactText("Quentin alone", NAME).spans.length, 0, "a phrase is all its words"); + assert.equal(redactText("@QuentinExample", NAME).text, `@${marks(14)}`); + // A span of the archived text (markup), merged with a match it overlaps. + assert.deepEqual(redactText("ab Quentin Example cd", NAME, { spans: [{ start: 0, end: 2 }, { start: 10, end: 20 }] }).spans, [{ start: 0, end: 2 }, { start: 3, end: 20 }]); +}); + +test("the read drops the match: spaces collapsed, dangling punctuation and an empty bracket taken away", () => { + assert.equal(spokenWithout("My name is Quentin Example.", NAME), "My name is."); + assert.equal(spokenWithout("Quentin Example, the author, said so", NAME), "the author, said so"); + assert.equal(spokenWithout("Thanks, Quentin Example!", NAME), "Thanks!"); + assert.equal(spokenWithout("hello (Quentin Example) there", NAME), "hello there"); + assert.equal(spokenWithout("I, Quentin Example, swear", NAME), "I, swear"); + // Paragraphs kept; nothing else touched. + assert.equal(spokenWithout("One , two.\n\nQuentin Example: three", NAME), "One , two.\n\nthree"); + assert.equal(spokenWithout("no match , here", NAME), "no match , here"); + assert.equal(dropMarks(`a ${marks(3)} b`), "a b"); +}); + +test("the card AS PUBLISHED never holds a term: words, names, handles, context, paraphrase -- solid bars instead", () => { + const entry = { + type: "post", id: "p1", post: "subj-x/1", platform: "x", author: "Quentin Example", handle: "QuentinExample", date: "2026-10-30T04:00:00.000Z", + text: "Hi, I'm QUENTIN example and this is my channel", url: "https://x.com/s/status/1", + parents: [{ author: "Fan", handle: "fan", badge: "gold", text: "is that quentin, example?", date: "2026-10-30T03:00:00.000Z" }], + quoted: { author: "Other", handle: "other", badge: "gold", text: "long words", paraphrase: "He said Quentin Example out loud" }, + redact: false, + }; + // The phrase alone covers the handle that runs its words together. + const red = { terms: NAME }; + const html = postCardHtml(entry, { width: 1280, height: 720, redaction: red }); + assert.doesNotMatch(html, /quentin/i, "not even hidden"); + assert.doesNotMatch(html, new RegExp(REDACT_MARK)); + assert.ok((html.match(/data-post-blanked=""/g) ?? []).length >= 5, "the post, the parent, the paraphrase, the name and the handle"); + assert.match(html, /\.rbar \{ display: inline-block/); + // Without a redaction, the card is the words. + assert.match(postCardHtml(entry, { width: 1280, height: 720 }), /QUENTIN example/); + // The entry itself is never rewritten. + assert.equal(entry.text, "Hi, I'm QUENTIN example and this is my channel"); + assert.equal(redactEntry(entry, { terms: [] }), entry); + assert.equal(barsHtml(`x${marks(4)}y`), `x<span class="rbar" data-post-blanked="" style="width:2.08em"></span>y`); +}); + +test("a post's markup: a term in one scope, or a span of its archived text", () => { + const entry = { type: "post", id: "p1", post: "subj-x/7", text: "abc Zed def", parents: [{ text: "Zed in a parent" }], quoted: { text: "Zed quoted" } }; + const red = { terms: [], markup: { "subj-x/7": { redact: [{ term: "Zed", scope: "parent" }, { start: 8, end: 11, scope: "text" }] } } }; + const out = redactEntry(entry, red); + assert.equal(out.text, `abc Zed ${marks(3)}`); + assert.equal(out.parents[0].text, `${marks(3)} in a parent`); + assert.equal(out.quoted.text, "Zed quoted"); + assert.deepEqual(termsFor(entry, red).map((t) => t.term), ["Zed"]); + assert.deepEqual(termsFor({ post: "other/1" }, red), []); + assert.deepEqual(validatePostsMarkup({ "7": { redact: [{ term: "Zed" }, { start: 1, end: 3, scope: "quoted" }] } }), []); + const bad = validatePostsMarkup({ "7": { redact: [{ start: 3, end: 1 }, { term: "Zed", scope: "elsewhere" }] }, "a/b": {} }); + assert.equal(bad.length, 4, bad.join("; ")); +}); + +test("render.posts.redact is validated with the build's check", () => { + assert.deepEqual(validatePostsRender({ posts: { redact: [{ term: "Quentin Example" }, { term: "Q", wholeWord: false, note: "a note" }] } }), []); + const bad = validatePostsRender({ posts: { redact: [{ term: " !! " }, { term: "x", wholeWord: "yes" }, { term: "y", extra: 1 }, "bare"] } }); + assert.equal(bad.length, 4, bad.join("; ")); + assert.ok(validatePostItems({ timeline: [], render: { posts: { redact: "nope" } } }).some((e) => e.includes("render.posts.redact must be a list"))); +}); diff --git a/umtool/report-to-video/post-render.mjs b/umtool/report-to-video/post-render.mjs @@ -20,6 +20,7 @@ import path from "node:path"; import { pathToFileURL } from "node:url"; import { POST_PICTURE_XFADE, POST_PUSH, postCardHtml, postItemPlan, postLayout, stepBoxes } from "./post-item.mjs"; import { isNarrated, narrationLevelDb, pickedTake, postNarrationFilters } from "./post-narration.mjs"; +import { redactEntry, redactionOn, spokenWithout, termsFor } from "./post-redact.mjs"; const r3 = (v) => Math.round(v * 1000) / 1000; const num = (v) => String(r3(v)); @@ -186,7 +187,7 @@ async function loadChromium() { * stack layout. The page is a file beside them, so its faces and the parent * shot load from disk (an about:blank page may not read file: urls). */ -export async function renderPostCards(entry, { box, render, dir, manifestDir, layout, avatars = {} }) { +export async function renderPostCards(entry, { box, render, dir, manifestDir, layout, avatars = {}, redaction = null }) { await mkdir(dir, { recursive: true }); const fonts = { regular: render.fontRegular ? pathToFileURL(render.fontRegular).href : "", @@ -204,6 +205,7 @@ export async function renderPostCards(entry, { box, render, dir, manifestDir, la const html = postCardHtml(entry, { width: box.width, height: box.height, palette: render.palette, fonts, phase, parentShotUrl, avatars: Object.fromEntries(Object.entries(avatars).map(([h, f]) => [h, pathToFileURL(f).href])), + redaction, }); const file = path.join(dir, `${phase}.html`); await writeFile(file, html, "utf8"); @@ -225,9 +227,11 @@ export async function renderPostCards(entry, { box, render, dir, manifestDir, la * box, place, encode, exec, ffmpeg, emit, avatars }` -- the box it fills (the * deck's footage box, or the frame), the deck's framing after it, * build-video's encode args and ffmpeg runner, the authors' pictures - * (`{ <handle>: absolute file }`, post-avatars.mjs). Returns the segment's path. + * (`{ <handle>: absolute file }`, post-avatars.mjs), the redaction it is + * published with (`{ terms, markup }`, post-redact-files.mjs: its matches + * drawn as bars, dropped from its captions). Returns the segment's path. */ -export async function buildPostSegment(entry, { render, outDir, manifestDir, box, place = [], encode = [], exec, ffmpeg = "ffmpeg", emit = () => {}, avatars = {} }) { +export async function buildPostSegment(entry, { render, outDir, manifestDir, box, place = [], encode = [], exec, ffmpeg = "ffmpeg", emit = () => {}, avatars = {}, redaction = null }) { const seg = path.join(outDir, "segments", `${entry.id}.mp4`); const plan = postItemPlan(entry, render); const layout = postLayout(entry, box); @@ -245,7 +249,8 @@ export async function buildPostSegment(entry, { render, outDir, manifestDir, box return st ? `${f}:${st.size}:${Math.round(st.mtimeMs)}` : `${f}:-`; })); const key = createHash("sha256") - .update(JSON.stringify({ v: 1, entry, box, place, palette: render.palette, fonts: [render.fontRegular, render.fontBold], fps: render.fps, encode, stamps, ...(Object.keys(avatars).length ? { avatars } : {}), ...(take ? { narration: plan.narration, postNarration: render.postNarration ?? null } : {}) })) + // A redaction that changes what the card draws changes the key; none leaves it as it was. + .update(JSON.stringify({ v: 1, entry, ...(redactionOn(redaction) ? { published: redactEntry(entry, redaction), blank: termsFor(entry, redaction) } : {}), box, place, palette: render.palette, fonts: [render.fontRegular, render.fontBold], fps: render.fps, encode, stamps, ...(Object.keys(avatars).length ? { avatars } : {}), ...(take ? { narration: plan.narration, postNarration: render.postNarration ?? null } : {}) })) .digest("hex"); const record = postRecordPath(seg); const had = await readFile(record, "utf8").then((t) => JSON.parse(t), () => null); @@ -254,7 +259,7 @@ export async function buildPostSegment(entry, { render, outDir, manifestDir, box return seg; } const cardDir = path.join(outDir, "cards", `post-${entry.id}`); - const cards = await renderPostCards(entry, { box, render, dir: cardDir, manifestDir, layout, avatars }); + const cards = await renderPostCards(entry, { box, render, dir: cardDir, manifestDir, layout, avatars, redaction }); // Its video attachments' words, when transcribed: one textfile per cue. const captions = []; for (const [si, step] of plan.steps.entries()) { @@ -262,7 +267,10 @@ export async function buildPostSegment(entry, { render, outDir, manifestDir, box const m = step.items[0]; const wf = wordFiles[m.i]; if (!wf) continue; - for (const [ci, c] of stepCaptions(step, await readMediaCues(wf)).entries()) { + for (const [ci, c0] of stepCaptions(step, await readMediaCues(wf)).entries()) { + // A redacted term is left out of the burnt-in words, as it is left out of a read. + const c = { ...c0, text: spokenWithout(c0.text, termsFor(entry, redaction)) }; + if (!c.text.trim()) continue; const textfile = path.join(cardDir, `cue-${si}-${ci}.txt`); await writeFile(textfile, c.text, "utf8"); captions.push({ ...c, textfile });