Archilyzer · Source

archilyzer

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

commit acccb9f5cf796c769a15e4e54e01d6763af11be3
parent ac8605851767f6b0b1bd4af7b0f191b66519bae6
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Tue,  3 Nov 2026 17:00:50 -0500

Merge main (lane/post-redact) into lane/read-follow: both kept -- the card page takes the redaction and the follow; the follow blocks are mapped on the words as written (the plan's are), whose indices the redaction's bars keep; the segment key carries both

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

Diffstat:
Mumtool/app/api/report/post-item/route.ts | 14++++++++++++--
Mumtool/app/api/report/post-narration/route.ts | 6+++++-
Mumtool/bin/umtool.mjs | 3+++
Aumtool/components/projects/BlurBoxPad.tsx | 110+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/projects/PostBench.tsx | 63++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mumtool/components/projects/RecordPage.tsx | 5+++++
Mumtool/components/projects/RecordSession.tsx | 26++++++++++++++++++++++++--
Mumtool/components/projects/review/PlayCut.tsx | 31+++++++++++++++++++++++++++++++
Mumtool/components/projects/review/PostItemPlayer.tsx | 30+++++++++++++++++++++++++-----
Mumtool/docs/cli.md | 3++-
Mumtool/docs/knobs.md | 26++++++++++++++++++++++++++
Mumtool/e2e/post-items.spec.ts | 44++++++++++++++++++++++++++++++++++++++++++++
Mumtool/e2e/post-narration.spec.ts | 57+++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/manifest.mjs | 58++++++++++++++++++++++++++++++++++++++++++++++++++++++----
Mumtool/lib/report/postNarrationCli.mjs | 8++++++--
Aumtool/lib/report/postRedaction.mjs | 15+++++++++++++++
Aumtool/lib/report/postRedaction.test.mjs | 108+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/postsCli.mjs | 63++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Mumtool/report-to-video/build-video.mjs | 14++++++++++++++
Mumtool/report-to-video/package.json | 3+++
Aumtool/report-to-video/post-censor.mjs | 144+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/post-censor.test.mjs | 83+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/post-item.mjs | 59+++++++++++++++++++++++++++++++++++++++++++++++++++++------
Aumtool/report-to-video/post-redact-files.mjs | 71+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/post-redact.mjs | 275+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/post-redact.test.mjs | 112+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/post-render.mjs | 49++++++++++++++++++++++++++++++++++++-------------
27 files changed, 1440 insertions(+), 40 deletions(-)

diff --git a/umtool/app/api/report/post-item/route.ts b/umtool/app/api/report/post-item/route.ts @@ -12,6 +12,7 @@ import { recognizedOf, takeWordSources, wordsFileOf } from "@/lib/report/postFxC 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"; @@ -19,8 +20,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 @@ -158,6 +161,12 @@ 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>, @@ -166,6 +175,7 @@ export async function GET(request: Request) { parentShotUrl: parentShot, // Its read-follow (read-follow.mjs): the blocks and the flow Play lights and pans, as the build's page has them. follow: q.get("phase") !== "media" && followKnobs(found.item, (found.manifest.render ?? render) as Record<string, unknown>).on, + 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/bin/umtool.mjs b/umtool/bin/umtool.mjs @@ -115,6 +115,7 @@ // narrate <project> [<item>] --import | --take | --script | --pick | --approve | k=v | --all … narration // fit <project> --all | <item>… narrated posts' videos cut to their best part // avatar <project> <handle> <image> | avatars <project> the authors' pictures +// redact <project> ls | add "<term>" [--substring] | remove <n> words blanked from what is published // umtool candidates <project> [ls | import <sweep.md> | add <json>] proposed clips for the Cut tab's Candidates panel import process from "node:process"; import { @@ -1036,6 +1037,8 @@ function usage() { " | --all --draft-scripts | --all --take | --cut k=v …] a post read aloud (its takes: the editor's tts or yours)", " umtool posts fit <project> [--all | <item> …] [--linger s] [--dry-run] narrated posts' videos cut to their best part", " umtool posts avatar <project> [<handle> <image>|off] · avatars <project> the authors' pictures on the cards", + " umtool posts redact <project> ls | add \"<term>\" [--substring] [--note \"…\"] | remove <n> words blanked from", + " what is published (a bar on the card, left out of a synthesized read); the data never rewritten", " umtool candidates <project> [ls] [--all] [--json] | import <sweep.md> [--dry-run] | add <json|@file>", " the candidates inbox: a sweep's or an agent's proposed clips -> <project>/candidates.json;", " Insert into a section or a group, and Not this, are the Cut tab's Candidates panel's", diff --git a/umtool/components/projects/BlurBoxPad.tsx b/umtool/components/projects/BlurBoxPad.tsx @@ -0,0 +1,110 @@ +"use client"; + +import { useEffect, useRef, useState } from "react"; + +// THE CENSOR BOXES, DRAWN (post-censor.mjs; knobs.md, "A post item"): the +// attachment on a still frame -- a picture as it is, a video paused at the +// bench's playhead (or its in point) -- shown as the cut shows it (its crop), +// each box over it; drag to draw a new one, × to take one away. The boxes are +// fractions of the picture as shown, which is what the render blurs. + +type Box = number[]; +type Props = { + project: string; + media: { src: string; kind: string; width?: number; height?: number; crop?: number[] }; + /** The video's source second to hold still. */ + at: number; + boxes: Box[]; + onChange: (boxes: Box[]) => void; + index: number; +}; + +const r4 = (v: number) => Math.round(v * 10000) / 10000; +const clamp = (v: number) => Math.min(1, Math.max(0, v)); + +export default function BlurBoxPad({ project, media, at, boxes, onChange, index }: Props) { + const pad = useRef<HTMLDivElement | null>(null); + const video = useRef<HTMLVideoElement | null>(null); + const [drag, setDrag] = useState<{ x: number; y: number; x2: number; y2: number } | null>(null); + const crop = Array.isArray(media.crop) && media.crop.length === 4 ? media.crop : [0, 0, 1, 1]; + const aspect = media.width && media.height ? (media.width * crop[2]) / (media.height * crop[3]) : 16 / 9; + const src = `/api/report/post-item?project=${encodeURIComponent(project)}&file=${encodeURIComponent(media.src)}`; + const inner: React.CSSProperties = { + position: "absolute", width: `${100 / crop[2]}%`, height: `${100 / crop[3]}%`, left: `${(-crop[0] / crop[2]) * 100}%`, top: `${(-crop[1] / crop[3]) * 100}%`, maxWidth: "none", objectFit: "fill", + }; + useEffect(() => { + const v = video.current; + if (!v) return; + try { + v.currentTime = at; + } catch { + // not seekable yet + } + }, [at]); + const where = (ev: React.PointerEvent) => { + const r = pad.current!.getBoundingClientRect(); + return { x: clamp((ev.clientX - r.left) / r.width), y: clamp((ev.clientY - r.top) / r.height) }; + }; + const box = (d: { x: number; y: number; x2: number; y2: number }): Box => { + const x = Math.min(d.x, d.x2); + const y = Math.min(d.y, d.y2); + return [r4(x), r4(y), r4(Math.abs(d.x2 - d.x)), r4(Math.abs(d.y2 - d.y))]; + }; + return ( + <div className="space-y-1"> + <div + ref={pad} + className="relative w-full cursor-crosshair touch-none select-none overflow-hidden rounded border border-seam bg-black" + style={{ aspectRatio: String(aspect) }} + data-post-bench-blur-pad={index} + onPointerDown={(ev) => { + if ((ev.target as HTMLElement).closest("button")) return; + (ev.currentTarget as HTMLDivElement).setPointerCapture(ev.pointerId); + const p = where(ev); + setDrag({ x: p.x, y: p.y, x2: p.x, y2: p.y }); + }} + onPointerMove={(ev) => { + if (!drag) return; + const p = where(ev); + setDrag({ ...drag, x2: p.x, y2: p.y }); + }} + onPointerUp={() => { + if (!drag) return; + const b = box(drag); + setDrag(null); + if (b[2] >= 0.01 && b[3] >= 0.01 && boxes.length < 8) onChange([...boxes, b]); + }} + > + {media.kind === "image" ? ( + // eslint-disable-next-line @next/next/no-img-element + <img src={src} alt="" draggable={false} style={inner} /> + ) : ( + <video ref={video} src={src} muted playsInline preload="auto" style={inner} /> + )} + {[...boxes, ...(drag ? [box(drag)] : [])].map((b, j) => ( + <div + key={j} + data-post-bench-blur-box={j < boxes.length ? j : "new"} + className="absolute border-2 border-amber-400 bg-amber-400/15" + style={{ left: `${b[0] * 100}%`, top: `${b[1] * 100}%`, width: `${b[2] * 100}%`, height: `${b[3] * 100}%` }} + > + {j < boxes.length && ( + <button + type="button" + className="absolute right-0 top-0 bg-black/70 px-1 text-[11px] leading-none text-white" + onClick={() => onChange(boxes.filter((_, k) => k !== j))} + aria-label={`remove box ${j + 1}`} + data-post-bench-blur-box-remove={j} + > + × + </button> + )} + </div> + ))} + </div> + <p className="m-0 text-[11.5px] text-text-2"> + drag on the frame to blur a region; no box blurs the whole frame{boxes.length ? ` · ${boxes.length} box${boxes.length === 1 ? "" : "es"}` : ""} + </p> + </div> + ); +} diff --git a/umtool/components/projects/PostBench.tsx b/umtool/components/projects/PostBench.tsx @@ -9,6 +9,7 @@ import { postBenchHref } from "@/lib/hrefs"; import { POST_HOLD, POST_MEDIA_MIN_SPAN, POST_PARAPHRASE_MAX, contextReadSeconds, postItemPlan, readingSeconds, ruleSeconds } from "umtool-report-to-video/post-item"; import PostItemPlayer, { type PostPlan } from "./review/PostItemPlayer"; import PostFollowPanel from "./PostFollowPanel"; +import BlurBoxPad from "./BlurBoxPad"; import PostNarrationPanel from "./PostNarrationPanel"; import PostZoomPanel from "./PostZoomPanel"; import { wordZoomTimes, zoomSpan } from "umtool-report-to-video/word-zoom"; @@ -31,7 +32,8 @@ import { wordZoomTimes, zoomSpan } from "umtool-report-to-video/word-zoom"; // "paraphrased" label (its own text kept, shown beside) // --------------------------------------------------------------------------- -type Media = Record<string, unknown> & { src: string; kind: string; seconds?: number; start?: number; end?: number; mute?: boolean; crop?: number[]; push?: boolean; words?: string; audio?: boolean; width?: number; height?: number }; +type Blur = { on: boolean; strength?: number; boxes?: number[][]; label?: string | false }; +type Media = Record<string, unknown> & { src: string; kind: string; seconds?: number; start?: number; end?: number; mute?: boolean; crop?: number[]; push?: boolean; words?: string; audio?: boolean; width?: number; height?: number; blur?: Blur }; type Ref = Record<string, unknown> & { author?: string; handle?: string; text?: string; paraphrase?: string }; type Entry = Record<string, unknown> & { id: string; media?: Media[]; hold?: number; mediaLayout?: string; redact?: boolean; quoted?: Ref; parents?: Ref[] }; @@ -142,6 +144,10 @@ export default function PostBench({ mute: m.mute === true ? true : null, crop: Array.isArray(m.crop) ? m.crop : null, push: m.push === true ? true : null, + // The censoring blur (post-censor.mjs), every key as it stands (null: cleared). + blur: m.blur + ? { on: m.blur.on === true, strength: m.blur.strength ?? null, boxes: m.blur.boxes?.length ? m.blur.boxes : null, label: m.blur.label === undefined ? null : m.blur.label } + : null, }, ]), ), @@ -463,6 +469,61 @@ export default function PostBench({ </button> ))} </div> + <div className="mt-2 space-y-1.5 text-[12px]" data-post-bench-censor={i}> + <label className="flex items-center gap-2"> + <input + type="checkbox" + checked={m.blur?.on === true} + onChange={(e) => setMedia(i, { blur: { ...(m.blur ?? {}), on: e.target.checked } })} + data-post-bench-blur={i} + /> + censor it (blurred in the video; the file is untouched) + </label> + {m.blur?.on === true && ( + <> + <div className="flex flex-wrap items-center gap-2"> + strength + <input + type="range" + min={1} + max={10} + step={1} + value={m.blur.strength ?? 7} + onChange={(e) => setMedia(i, { blur: { ...m.blur!, strength: Number(e.target.value) === 7 ? undefined : Number(e.target.value) } })} + data-post-bench-blur-strength={i} + /> + <span className="font-mono">{m.blur.strength ?? 7}</span> + label + <input + type="text" + value={m.blur.label === false ? "" : (m.blur.label ?? "")} + placeholder={m.blur.label === false ? "(none)" : "Censored"} + disabled={m.blur.label === false} + onChange={(e) => setMedia(i, { blur: { ...m.blur!, label: e.target.value.trim() ? e.target.value : undefined } })} + className="w-28 rounded border border-seam bg-ground px-1.5 py-0.5" + data-post-bench-blur-label={i} + /> + <label className="flex items-center gap-1"> + <input type="checkbox" checked={m.blur.label === false} onChange={(e) => setMedia(i, { blur: { ...m.blur!, label: e.target.checked ? false : undefined } })} /> + no label + </label> + {!!m.blur.boxes?.length && ( + <button type="button" className={btn} onClick={() => setMedia(i, { blur: { ...m.blur!, boxes: undefined } })} data-post-bench-blur-whole={i}> + Whole frame + </button> + )} + </div> + <BlurBoxPad + project={project} + media={m} + index={i} + at={timed ? (srcNow ?? m.start ?? 0) : 0} + boxes={m.blur.boxes ?? []} + onChange={(boxes) => setMedia(i, { blur: { ...m.blur!, boxes: boxes.length ? boxes : undefined } })} + /> + </> + )} + </div> {m.kind === "video" && m.audio !== false && ( <div className="mt-2 text-[12px]"> {m.words ? ( 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 @@ -4,6 +4,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { POST_PUSH, mediaTimeAt, postLayout, stepAt, stepBoxes } from "umtool-report-to-video/post-item"; import { dryGainAt, mixPhaseAt, pickedTake, wetGainAt } from "umtool-report-to-video/post-narration"; import { applyFollowState, followPath, followStateAt, measureFollow } from "umtool-report-to-video/read-follow"; +import { blurCqw, blurOf } from "umtool-report-to-video/post-censor"; import { WORD_ZOOM_HIGHLIGHT_ALPHA, findMatch, highlightAt, resolveWordZoom, targetScope, targetTextOf, wordZoomTimes, zoomAt, zoomProgressAt, zoomSpan, zoomWindow } from "umtool-report-to-video/word-zoom"; // --------------------------------------------------------------------------- @@ -224,12 +225,16 @@ function MediaEl({ if (!run && !v.paused) v.pause(); }, [target, run, speed]); const progress = inStep ? Math.min(1, Math.max(0, (s - step.at) / Math.max(0.1, step.seconds))) : 0; + // CENSORED (post-censor.mjs): the whole frame blurred, or its boxes -- as the render blurs it. + const blur = blurOf(m) as { strength: number; boxes: number[][]; label: string | null } | null; + const blurCss = blur ? `blur(${blurCqw(blur.strength)}cqw)` : undefined; return ( <div data-post-media={m.i} data-post-media-kind={m.kind} + data-post-blurred={blur ? (blur.boxes.length ? "boxes" : "frame") : undefined} className="absolute overflow-hidden" - style={{ left: pct(b.x, box.width), top: pct(b.y, box.height), width: pct(b.width, box.width), height: pct(b.height, box.height) }} + style={{ left: pct(b.x, box.width), top: pct(b.y, box.height), width: pct(b.width, box.width), height: pct(b.height, box.height), containerType: blur ? "size" : undefined }} > {timed ? ( <video @@ -242,7 +247,7 @@ function MediaEl({ playsInline loop={step.loop} muted={!(step.sound && run)} - style={{ ...inner, objectFit: "fill" }} + style={{ ...inner, objectFit: "fill", filter: blur && !blur.boxes.length ? blurCss : undefined }} /> ) : ( // eslint-disable-next-line @next/next/no-img-element @@ -250,15 +255,28 @@ function MediaEl({ src={postFileUrl(project, String(m.src))} alt="" data-post-image={m.i} - style={{ ...inner, objectFit: "fill", transform: m.push ? `scale(${1 + POST_PUSH * progress})` : undefined, transformOrigin: "center" }} + style={{ ...inner, objectFit: "fill", transform: m.push ? `scale(${1 + POST_PUSH * progress})` : undefined, transformOrigin: "center", filter: blur && !blur.boxes.length ? blurCss : undefined }} /> )} + {blur?.boxes.map((bx, j) => ( + <div + key={j} + data-post-blur-box={j} + className="pointer-events-none absolute" + style={{ left: `${bx[0] * 100}%`, top: `${bx[1] * 100}%`, width: `${bx[2] * 100}%`, height: `${bx[3] * 100}%`, backdropFilter: blurCss, WebkitBackdropFilter: blurCss }} + /> + ))} + {blur?.label && ( + <span data-post-blur-label="" className="pointer-events-none absolute left-[2%] top-[2%] rounded-[3px] bg-black/70 px-[1.2cqw] py-[0.4cqw] text-[2.4cqw] leading-none text-white"> + {blur.label} + </span> + )} </div> ); } 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; @@ -272,6 +290,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); @@ -309,7 +329,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/docs/cli.md b/umtool/docs/cli.md @@ -82,11 +82,12 @@ Inbox cannot disagree about what is wrong with one. | `posts set <project> <post> thread=on\|off [hide=on\|off] [attach=<clipId>\|auto] [crop=<px>\|off] [--json]` | the Posts table's writer (`updatePosts`, `PUT /api/report/posts`) from a terminal: `<post>` is the manifest's id (`x-<postId>`) or the bare `<postId>`; `thread=on` draws a reply with the post it answers above it (`shot-thread.png` beside its `shot`, taken by `capture-posts` `"thread": true`; its own shot while there is none), `off` removes the key.; `crop=<px>` the post's own crop of its screenshot (`shotMaxHeight`, 120–1080: its top that tall, never panned; `off` removes it) ([knobs.md](knobs.md#add-post-a-post-card-from-play-the-cut)). Refused in the build's words (a post with no `shot`, an `attach` that is not a clip) — **exit 1** | | `posts add <project> <archive-channel>/<postId> [--attach <clipId>] [--flag F] [--author A] [--id ID] [--thread] [--crop <px>] [--dry-run] [--json]` | a **post card** from the corpus's posts archive (`channels/<slug>/posts/*.jsonl`): its words, date, link and handle; id `x-<postId>` (`bsky-`, `post-`); the author an earlier post by the same handle carries in the cut, else the archive's. Its capture (`posts-media/<postId>/`: `shot.png`, `capture.json`, the post's pictures) is copied to the project's `posts-media/<slug>/<postId>/` — or used where it is, when that folder links the channel's captures; never copied through a link anywhere else. Then `upsertPost` (a post with the id is replaced, its `attachTo` kept). **Exit 1** with no screenshot, naming the `pnpm ops capture-posts` to run. `--thread`: the entry gets `thread: true` (a reply drawn with the post it answers; `shot-thread.png` is copied with the rest, and with none yet it prints the `"thread": true` capture to run). `--crop <px>`: the post's own crop (`shotMaxHeight`). A post that quotes another, reposts one or carries media is added with a `WARNING:` line (`--json`: `warnings`) — its screenshot shows them, by the post's own data. Play the cut's **Add post** runs this same write ([knobs.md](knobs.md#add-post-a-post-card-from-play-the-cut)) | | `posts reel <project> --channel <slug> [--channel <slug> …] [--since YYYY-MM-DD] [--until YYYY-MM-DD] [--own] [--with-media] [--replies include\|only\|exclude] [--order chrono\|reverse] [--limit N] [--after <id\|->] [--dry-run] [--json]` | **POST ITEMS** ([report-video.md](report-video.md#post-items-a-post-as-an-entry-of-the-cut)): each archived post an entry of the cut -- its card drawn from the archive row (snapshotted), its attachments copied into `posts-media/` and played in it. The channels are read as one archive, merged in time order, de-duplicated by post id (`--channel ObviousRises-x --channel ObviousRises-x-replies`); `--own` the accounts' own posts (their config's `socialHandle`, no reposts); `--with-media` only posts whose capture holds an attachment; `--replies` keeps, keeps only or drops replies (a reply carries the posts it answers from the archive, else the capture's thread shot, else a "Replying to" line; the quoted post and the parent the archive lacks come from the capture's `context`, as `posts context` fills them). A post the cut already plays (by its id, a repost's original, a repost of it) is skipped, so a **re-run adds only what is new**; the rest goes in in ONE write (one undo point: `timeline <p> undo`), at the end unless `--after` | -| `posts set-item <project> <item> [hold=<s>\|off] [layout=sequence\|grid] [redact=on\|off\|auto] [fit=read[:<linger>]] [media.<i>.start=<s>] [media.<i>.end=<s>] [media.<i>.trim=off] [media.<i>.mute=on\|off] [media.<i>.crop=x,y,w,h\|off] [media.<i>.push=on\|off] [quoted.paraphrase="…"\|off] [parent.<i>.paraphrase="…"\|off] [follow=on\|off\|auto] [follow.dim=<0.2-1>] [follow.ease=<s>] [--json]` | a **post item's knobs** (the post bench's writer, `updatePostItem`; [knobs.md](knobs.md#a-post-item-a-post-as-an-entry-of-the-cut)): `<item>` is its id or the post's id; refused in the build's words. `quoted.paraphrase` / `parent.<i>.paraphrase`: your retelling of a long context post (≤ 600 characters), drawn in place of its words with a "paraphrased" label (its text kept); `off` or empty clears it. `follow=`: its read-follow ([knobs.md](knobs.md#read-follow-the-block-being-read-lit-the-card-panned-to-it)) -- `off`, `on`, `auto` (the cut's); `follow.dim=` / `follow.ease=` over the cut's | +| `posts set-item <project> <item> [hold=<s>\|off] [layout=sequence\|grid] [redact=on\|off\|auto] [fit=read[:<linger>]] [media.<i>.start=<s>] [media.<i>.end=<s>] [media.<i>.trim=off] [media.<i>.mute=on\|off] [media.<i>.crop=x,y,w,h\|off] [media.<i>.push=on\|off] [media.<i>.blur=on\|off] [media.<i>.blur.strength=1–10] [media.<i>.blur.label="…"\|off] [media.<i>.blur.boxes=x,y,w,h;…\|off] [quoted.paraphrase="…"\|off] [parent.<i>.paraphrase="…"\|off] [follow=on\|off\|auto] [follow.dim=<0.2-1>] [follow.ease=<s>] [--json]` | a **post item's knobs** (the post bench's writer, `updatePostItem`; [knobs.md](knobs.md#a-post-item-a-post-as-an-entry-of-the-cut)): `<item>` is its id or the post's id; refused in the build's words. `quoted.paraphrase` / `parent.<i>.paraphrase`: your retelling of a long context post (≤ 600 characters), drawn in place of its words with a "paraphrased" label (its text kept); `off` or empty clears it. `follow=`: its read-follow ([knobs.md](knobs.md#read-follow-the-block-being-read-lit-the-card-panned-to-it)) -- `off`, `on`, `auto` (the cut's); `follow.dim=` / `follow.ease=` over the cut's `media.<i>.blur…` CENSORS the attachment in the render (a real blur of the whole frame or of its boxes, labelled "Censored"; the file untouched; merged key by key, `blur=off` keeps the settings) | | `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=]` · `<item> --take [--note "…"] [--voice v] [--engine e] [--speed s] [--script "…"]` · `<item> --derive <n> --op enhance\|convert [--engine e] [--voice v]` · `<item> --delete <n>` · `--all --draft-scripts [--force]` · `--all --take [--limit N]` · `--cut <k=v>…` | a **narrated post item** ([report-video.md](report-video.md#narrated-post-items), [knobs.md](knobs.md#a-narrated-post-item)): `--import` reads `narration/posts/index.json` (`[{id, entry, script, takes: [{file, engine, voice, seconds}], pick}]`, and a take's `take-<n>.parts.json`) into the cut in ONE write, measuring each take (length, loudness); a re-run adds only takes not there. `--take` asks the EDITOR for a new take (`POST /api/ops/tts`, its `out` the next `narration/posts/<postId>/take-<n>.<engine>-<voice>.wav`; a job, waited for; `ARCHILYZER_EDITOR_URL`, `WORKER_TOKEN`) and picks it, its `--note` kept with it; `--pick <n>` is the take's number as `--list` shows it. `--derive <n>` makes a NEW take from take n through the editor's `voice-enhance` / `voice-convert` op (a stock synthetic voice; "not installed" until the editor has the engine), the original kept; `--delete <n>` moves a take's file to the post's `.trash/`. A new script or pick takes the approval away. `--all --draft-scripts` writes every post's words as its script, VERBATIM (cleaned only to be spoken: @handles, links, emoji dropped; `plan(s)` → plans, `w/` → with, `&` → and; paragraphs kept). `--cut` sets `render.postNarration` (and its read-follow: `follow=on\|off`, `follow.dim=`, `follow.ease=`). Refused in the build's words (**exit 1**) | | `posts fx <project> <item> [ls]` · `add word-zoom --match "…" [--target post\|quoted\|parent:<i>] [--occurrence n] [--at s] [--scale s] [--hold s] [--lead s] [--ease out\|inOut\|snap] [--highlight #rrggbb\|off]` · `set <n> [those flags; default clears one]` · `remove <n>` · `posts narrate <project> <item> --words [--worker <id>]` | a post item's **word zoom** ([report-video.md](report-video.md#a-word-zoom), [knobs.md](knobs.md#a-word-zoom-a-post-items-card-pushed-in-on-a-word-as-it-is-read)): the card pushed in on a word as it is read, a highlight under it, then back out -- through `updatePostFx`, refused in the build's words (a match not in the words, a knob out of bounds; **exit 1**). Its time is `--at`, else the word's start in the picked take's word timings; `ls` prints each zoom's time and where it came from. An un-narrated post's `add` fills `at` with the reading estimate. `--words` asks the EDITOR's transcribe op (`words: true`, a job per take or per part file; `ARCHILYZER_EDITOR_URL`, `WORKER_TOKEN`) and keeps the words heard, aligned to the script, on the take (`takes[i].words`) | | `posts fit <project> [--all \| <item> …] [--linger <s>] [--dry-run] [--json]` · `posts set-item <project> <item> fit=read[:<linger>]` | narrated posts' video attachments cut to their **best part** for the read (lead + take + tail + linger): a scored scan of the sound (loudness, its peaks), the speech (a transcript) and the scene cuts, the start snapped to a pause or a cut, recorded with why (`narration.window`) -- ONE write; each post's old and new length printed. A video no longer than the read is left as it is | | `posts avatar <project> [<handle> <image-file> \| <handle> off] [--json]` · `posts avatars <project> [--dry-run] [--json]` | the **authors' pictures** (`postAvatars`): `avatar` copies a picture into `posts-media/_avatars/` for every card that draws that handle (manual; never replaced by the archive's), `off` clears it, no handle lists them; `avatars` copies the archive's (the channels' `posts-media/_avatars/avatars.json`, capture-posts') for every author the cut's cards draw unblurred that it has none of. A blurred author never shows one | +| `posts redact <project> ls \| add "<term>" [--substring] [--note "…"] \| remove <n> [--json]` | **REDACTED WORDS** ([knobs.md](knobs.md#redacted-words-blanked-from-what-is-published)): the project's list (`render.posts.redact`, `updatePostRedact`) of words or phrases blanked from everything the cut publishes -- a solid bar on the rendered card, left out of a synthesized read, a post's 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 and the scripts are never rewritten. `ls` numbers the terms as `remove` takes them, and counts the corpus's (`transcripts/redactions.json`) and the posts marked up in the cut's channels (`posts-markup.json`). A term already listed is refused (**exit 1**) | | `posts context <project> [--dry-run] [--json]` | every **post item's context from its capture** (`postContext.mjs`): the post it quotes and the post it answers, as its page showed them (`capture.json`'s `context`, read by the editor's `capture-posts` -- `"contextOnly": true` reads it alone), filled where the archive row lacks them -- `quoted` where the entry has none (or a named one with no words, the same post), `parents` where it has none (a thread shot stays on the entry; the card draws the parents). What the archive gave is never replaced. ONE write for every entry (`setPostItemsContext`: one undo point, refused whole in the build's words); a re-run with nothing new writes nothing. A post whose capture read no context is listed with the call that reads it (`pnpm ops capture-posts --json '{"slug":…,"ids":[…],"contextOnly":true}' --wait`). The card's blur of other authors is unchanged ([report-video.md](report-video.md#post-items-a-post-as-an-entry-of-the-cut)) | | `new <slug> --from-posts <channel> [--channel <more>…] [--since D] [--until D] [--own] [--with-media] [--replies …] [--order …] [--limit N]` | a **posts reel**: the scaffold with the deck on (no `siteOrigin`: each post's QR opens the post, `deck.qr.links: "original"`), then `posts reel` with the same filters | | `timeline <project> insert (--after <id\|-> \| --to-section N \| --group G) post:<channel>/<postId> [--id ID]` | **one post item** among the cut's entries, made as `posts reel` makes one | diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md @@ -652,6 +652,7 @@ its knobs are one writer, `updatePostItem` (`lib/report/manifest.mjs`), refused | `media[i].mute` — `true`: the video plays silent | post bench, **its sound** | `media.0.mute=on` (`=off`) | same | | `media[i].crop` — `[x, y, w, h]`, fractions of the picture: what of it is shown | post bench, **crop** (none, centre 80%, top half, bottom half) | `media.0.crop=0,0.1,1,0.8` (`=off`) | same | | `media[i].push` — an image's slow push-in (6% over its span) | post bench, **slow push-in** | `media.0.push=on` | same | +| `media[i].blur` — the attachment CENSORED (`post-censor.mjs`): `{on, strength?: 1–10 (7), boxes?: [[x, y, w, h], …], label?: "…" \| false}`. The render blurs it for real (ffmpeg `gblur`, its sigma grown with the strength and the picture's width) -- the whole frame, or only its boxes (fractions of the picture as shown, after its crop, held still over the clip) -- and draws the label ("Censored"; `false`: none) at its corner. The file is never touched; `on: false` keeps the settings. A channel's `posts-markup.json` may censor it for every project (`censor`, below); the item's own `blur` wins | post bench, **censor it**, **strength**, **label** / **no label**, the boxes drawn on a still frame (drag; × removes; **Whole frame**); Play and the bench preview it | `media.0.blur=on` · `media.0.blur.strength=5` · `media.0.blur.label="Censored"` (`=off`: none) · `media.0.blur.boxes=0.2,0.3,0.4,0.4;…` (`=off`) · `media.0.blur=off` | same, `patch: {media: {"0": {blur: {on, strength, boxes, label}}}}` (merged; a null key cleared) | | `media[i].words` — a video's transcript (`{cues: [{start, end, text}]}` beside it), its words shown under it in Play and the render | post bench, **Transcribe its words (the editor)**: the editor's `transcribe` op on the file (a job on a local worker), set when it is done | `pnpm ops transcribe --json '{"path": "<project>/posts-media/…_1.mp4", "words": true, "out": "<project>/posts-media/…_1.words.json"}'`, then set `words` by the bench | `POST {op: "transcribe", id, media}` → `{jobId}` · `GET ?project&id&media&job=` | | | In umtool | From a terminal | Route | @@ -693,6 +694,31 @@ the shape, the mix, recordings, parts, the best part). One writer for a post's n none, approved) and links the next post to record; **N** / **P** walk the cut's posts, **Space** plays the item as the render will (the take over the muffled attachment). +## Redacted words (blanked from what is published) + +A word or a phrase -- a private person's name -- left out of everything a cut PUBLISHES, never out of the data +(`report-to-video/post-redact.mjs`). The archive's rows, the manifest's snapshot of each post and every narration +script keep their words; the redaction is applied where public output is made: the **rendered card** draws each +match as a solid bar of the word's width (no letters in the page or the frame, not a blur that can be undone) in the +post's words, the posts it answers and quotes, a paraphrase, an author's name and handle and the repost line; a +**synthesized read** (`--take`, the bench's re-take) is sent to the editor with the match left out, its spaces and +dangling punctuation tidied; a post's **chapter line** and a video attachment's **burnt-in captions** drop it. +umtool's own views (the bench, Play, the recording page) show the words; Play's **As published** shows the bars, +and the recording teleprompter strikes through the words to leave out of your read. A term matches without regard +to case, as whole words unless `wholeWord: false`, the words of a phrase across any spaces or punctuation (or none, +as a handle runs them together), a possessive `'s` with it. A redaction file that is there and broken FAILS the build +(a render that ignored it would publish what it was told to blank). With a **word zoom** (below): the bars keep the +redacted words' places (a phrase stays as many card words, so a zoom's `occurrence` is counted on the original words +and lands on the same word), Play's **As published** shows the bars and the zoom together, and a zoom whose match +is a redacted word is REFUSED -- the project's list at every write, the corpus's and a post's markup by the build: a +published card never pushes in on a blank. + +| Knob | In umtool | From a terminal | Route | +|---|---|---|---| +| `render.posts.redact` — the project's list, `[{term, wholeWord?, note?}]` (at most 200; one writer, `updatePostRedact`, refused in the build's words) | Play the cut, **As published** (the cards as the video draws them) | `umtool posts redact <p> ls` · `add "<term>" [--substring] [--note "…"]` · `remove <n>` (n as `ls` numbers them) | `GET /api/report/post-item?…&published=1` (the card's page, as published) | +| the corpus's list — `transcripts/redactions.json`, the same shape (or `{terms: […]}`): blanked in every project | — | read by every build; the editor's to write | — | +| one post's markup — `transcripts/channels/<slug>/posts-markup.json`, `{"<postId>": {redact?: [{term, wholeWord?, scope?} \| {start, end, scope?, index?}], censor?: [{media, blur?}]}}`: a term in a `scope` (`text`, `parent`, `quoted`; absent, the whole post), or a span of the archived text in code units (`index`: which parent, nearest first); `censor` blurs the post's attachment `media` (its index; `blur` as `media[i].blur`'s keys, absent the whole frame) in every project | — | read by every build of a cut playing the post; the editor's to write | — | + ## A word zoom (a post item's card pushed in on a word as it is read) `fx: [{kind: "word-zoom", match, …}]` on a post item ([report-video.md](report-video.md#a-word-zoom): the shape, the diff --git a/umtool/e2e/post-items.spec.ts b/umtool/e2e/post-items.spec.ts @@ -104,6 +104,50 @@ test("Play plays a post item: its card, the private parent blurred, its video pl await expect(root(page)).toHaveAttribute("data-play-item", "p-vid"); }); +test("a redacted term: Play shows the words; As published draws blank bars and the term is nowhere in the card's DOM", async ({ page }) => { + // A made-up term on the fixture's words (post-redact.mjs; knobs.md, "Redacted words"). + umtool(["posts", "redact", PROJECT, "add", "here is"]); + expect(umtool(["posts", "redact", PROJECT, "ls"])).toContain("1. here is"); + await page.setViewportSize({ width: 1366, height: 1000 }); + await page.goto(urls.playHref(PROJECT, { bare: true, clip: "p-vid" })); + await page.evaluate(() => window.localStorage.removeItem("umtool.play.asPublished")); + await page.reload(); + await expect(root(page)).toHaveAttribute("data-play-item", "p-vid"); + const card = page.frameLocator('[data-post-card-frame="read"]'); + // umtool's own view: the words as posted. + await expect(card.locator("[data-post-words]")).toContainText("Yes, and here is the video."); + await expect(card.locator("[data-post-blanked]")).toHaveCount(0); + await page.locator("[data-play-as-published]").check(); + // A bar per word of the phrase, each in its own word's slot (a word zoom's indices hold). + await expect(card.locator("[data-post-blanked]")).toHaveCount(2); + await expect(card.locator("[data-post-words]")).toContainText("Yes, and"); + await expect(card.locator("[data-post-words]")).toContainText("the video."); + const dom = await card.locator("html").evaluate((el) => el.outerHTML); + expect(dom.toLowerCase()).not.toContain("here is"); + expect(await card.locator("[data-post-blanked]").evaluateAll((els) => els.map((el) => el.textContent).join(""))).toBe(""); + if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "post-items-as-published.png") }); + // The snapshot is never rewritten. + expect(JSON.stringify(timeline())).toContain("here is the video"); +}); + +test("a censored attachment: set-item blurs it, Play previews the blur and its label, the bench toggles it off and saves", async ({ page }) => { + umtool(["posts", "set-item", PROJECT, "p-vid", "media.0.blur=on"]); + await page.setViewportSize({ width: 1366, height: 1000 }); + await page.goto(urls.playHref(PROJECT, { bare: true, clip: "p-vid" })); + await expect(page.locator('[data-post-media="0"]')).toHaveAttribute("data-post-blurred", "frame"); + await expect(page.locator('[data-post-media="0"] [data-post-blur-label]')).toHaveText("Censored"); + expect(await page.locator('[data-post-video="0"]').evaluate((v) => getComputedStyle(v).filter)).toMatch(/blur\(/); + await page.goto(urls.postBenchHref(PROJECT, "p-vid")); + await expect(page.locator('[data-post-bench-blur="0"]')).toBeChecked(); + await expect(page.locator('[data-post-bench-blur-pad="0"]')).toBeVisible(); + await page.locator('[data-post-bench-blur="0"]').uncheck(); + await page.locator("[data-post-bench-save]").click(); + await expect(page.locator("[data-post-bench-status]")).toBeVisible(); + const vid = timeline().find((e) => e.id === "p-vid") as Entry & { media: Array<{ blur?: { on: boolean }; src: string }> }; + expect(vid.media[0].blur?.on).toBe(false); + expect(vid.media[0].src).toMatch(/\.mp4$/); +}); + test("the post bench trims the video attachment and saves it; the cut's seconds follow", async ({ page }) => { await page.setViewportSize({ width: 1366, height: 1000 }); await page.goto(urls.postBenchHref(PROJECT, "p-vid")); diff --git a/umtool/e2e/post-narration.spec.ts b/umtool/e2e/post-narration.spec.ts @@ -325,6 +325,63 @@ test("A WORD ZOOM: Get word timings (the editor's transcription), click a word - await page.locator("[data-play-toggle]").click(); }); +test("READ-FOLLOW (operator, 3 Nov: \"highlight the current paragraph and panning down as needed\"): a long post read part by part -- the second block brightens at its part's start, the others dim, and the card pans so a late block is in view; the bench shows the block map", async ({ page }) => { + // p-13 made long: ten paragraphs, a take read paragraph by paragraph (a part every 2 s of the take). + const para = (i: number) => `Paragraph ${i + 1} begins here and it goes on for a while, ${"saying the same kind of thing again and again, ".repeat(3)}until it ends with mark ${i + 1}.`; + const paras = Array.from({ length: 10 }, (_, i) => para(i)); + const m = JSON.parse(readFileSync(MANIFEST, "utf8")); + const e = m.timeline.find((x: { id: string }) => x.id === "p-13"); + e.text = paras.join("\n\n"); + e.narration = { + script: e.text, + takes: [{ file: "narration/posts/11/take-1.orpheus-zac.wav", engine: "orpheus", voice: "zac", seconds: 20, script: e.text, parts: paras.map((text, i) => ({ n: i + 1, para: i, text, start: i * 2, seconds: 1.8 })) }], + pick: 0, + }; + writeFileSync(MANIFEST, JSON.stringify(m, null, 2) + "\n"); + await page.setViewportSize({ width: 1500, height: 1100 }); + await page.goto(urls.postBenchHref(PROJECT, "p-13")); + const panel = page.locator("[data-post-follow-panel]"); + await expect(panel.locator("[data-post-follow-summary]")).toHaveText(/10 blocks, 10 read \(the take's parts\)/); + await expect(panel.locator("[data-post-follow-row]")).toHaveCount(10); + const player = page.locator('[data-post-play="p-13"]'); + const frame = page.frameLocator('[data-post-card-frame="read"]'); + await expect(frame.locator("body")).toHaveAttribute("data-post-follow", "10", { timeout: 15_000 }); + const op = (k: number) => frame.locator(`[data-post-block="${k}"]`).evaluate((el) => (el as HTMLElement).style.opacity); + const scrub = page.locator("[data-post-bench-scrub]"); + // Before the second part: the first block lit, the second dimmed. + await scrub.fill("1"); + await expect(player).toHaveAttribute("data-post-follow-block", "0"); + await expect.poll(() => op(0)).toBe(""); + await expect.poll(() => op(1)).toBe("0.65"); + // The second part starts at lead 0.4 + 2 s: past its ease (0.125 s) it is lit and the first is dimmed. + await scrub.fill("2.6"); + await expect(player).toHaveAttribute("data-post-follow-block", "1"); + await expect.poll(() => op(1)).toBe(""); + await expect.poll(() => op(0)).toBe("0.65"); + await expect(panel.locator('[data-post-follow-row="1"]')).toHaveAttribute("data-current", "1"); + if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "post-follow-second-block.png") }); + // The words are taller than the card: a late block is panned into view. + await expect(player).toHaveAttribute("data-post-follow-pans", /^[1-9]/); + await scrub.fill("17.2"); + await expect(player).toHaveAttribute("data-post-follow-block", "8"); + await expect.poll(async () => Number(await player.getAttribute("data-post-follow-offset"))).toBeGreaterThan(0); + const view = await frame.locator("[data-post-words]").evaluate((w) => { + const r = w.getBoundingClientRect(); + const b = (w.querySelector('[data-post-block="8"]') as HTMLElement).getBoundingClientRect(); + return { top: r.top, bottom: r.bottom, bTop: b.top, bBottom: b.bottom, flow: (w.querySelector("[data-post-flow]") as HTMLElement).style.transform }; + }); + expect(view.flow).toMatch(/translateY\(-\d/); + expect(view.bTop).toBeGreaterThanOrEqual(view.top - 1); + expect(view.bBottom).toBeLessThanOrEqual(view.bottom + 1); + if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "post-follow-panned.png") }); + // A row of the map puts the playhead at its block's start. + await panel.locator('[data-post-follow-row="3"] button').click(); + await expect(page.locator("[data-post-bench-clock]")).toHaveText(/^6\.4 \//); + // Off on this post: the card shows its words as they are (no blocks lit, no pan). + await panel.locator("[data-post-follow-mode]").selectOption("off"); + await expect(panel).toContainText("off: the card shows its words as they are"); +}); + test("THE RECORDING SESSION: part by part, a reload resumes, redo one, the last part makes the recorded take and picks it", async ({ page }) => { await page.setViewportSize({ width: 1440, height: 1200 }); await page.goto(urls.projectHref(PROJECT, { tab: "cut" })); 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"; @@ -2351,15 +2352,15 @@ 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", "redact", "follow"]); -/** A post item attachment's knobs: its trim, its sound, its crop, the push-in, its transcript. */ -export const POST_MEDIA_KNOBS = Object.freeze(["start", "end", "mute", "crop", "push", "words"]); +/** 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"]); /** A context post's knobs (`quoted`, `parents[i]`): the operator's paraphrase of its words. */ export const POST_CONTEXT_KNOBS = Object.freeze(["paraphrase"]); /** * SET A POST ITEM's KNOBS (the post bench, `umtool posts set-item`): `patch` * is `{ hold?, mediaLayout?, redact?, follow?: false | { on?, dim?, ease? }, media?: { <i>: { start?, end?, mute?, - * crop?, push?, words? } }, quoted?: { paraphrase? }, parents?: { <i>: + * crop?, push?, words?, blur? } }, quoted?: { paraphrase? }, parents?: { <i>: * { paraphrase? } } }`; a null clears a knob (the default again), and so * does an empty paraphrase (the context's own words again; its `text` is * never touched). One structural write, refused in the build's words @@ -2406,7 +2407,17 @@ export async function updatePostItem(dir, id, patch, { token = null } = {}) { for (const k of POST_MEDIA_KNOBS) { if (!(k in mp)) continue; if (k === "crop" && Array.isArray(mp.crop)) media[n].crop = mp.crop.map((v) => Math.round(Number(v) * 10000) / 10000); - else set(media[n], k, mp[k]); + else if (k === "blur" && isObj(mp.blur)) { + // The censoring blur (post-censor.mjs) MERGES: each key set, a null one cleared; nothing left, none. + const b = isObj(media[n].blur) ? { ...media[n].blur } : {}; + for (const [bk, bv] of Object.entries(mp.blur)) { + if (bv === null || bv === undefined) delete b[bk]; + else if (bk === "boxes" && Array.isArray(bv)) b.boxes = bv.map((box) => (Array.isArray(box) ? box.map((v) => Math.round(Number(v) * 10000) / 10000) : box)); + else b[bk] = bv; + } + if (Object.keys(b).length) media[n].blur = b; + else delete media[n].blur; + } else set(media[n], k, mp[k]); } // A trim back to the whole file is no trim. if (media[n].start === 0) delete media[n].start; @@ -2776,6 +2787,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 @@ -26,6 +26,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"; @@ -245,7 +247,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)`); @@ -260,7 +262,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,108 @@ +// 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."); +}); + +test("posts set-item media.<i>.blur: on, strength, label, boxes -- merged; off keeps the settings; the file's entry otherwise untouched", async () => { + const p = await project("b", [item("1", { media: [{ src: "posts-media/subj-x/1/1.mp4", kind: "video", seconds: 3, width: 320, height: 180 }] })]); + let r = await cli(["set-item", "b", "p-1", "media.0.blur=on", "media.0.blur.strength=4", "media.0.blur.boxes=0,0,0.5,0.5;0.5,0.5,0.25,0.25"]); + assert.equal(r.code, 0, r.err); + assert.deepEqual((await manifest(p)).timeline[0].media[0].blur, { on: true, strength: 4, boxes: [[0, 0, 0.5, 0.5], [0.5, 0.5, 0.25, 0.25]] }); + r = await cli(["set-item", "b", "p-1", "media.0.blur.label=off", "media.0.blur.boxes=off"]); + assert.equal(r.code, 0, r.err); + assert.deepEqual((await manifest(p)).timeline[0].media[0].blur, { on: true, strength: 4, label: false }); + r = await cli(["set-item", "b", "p-1", "media.0.blur=off"]); + assert.deepEqual((await manifest(p)).timeline[0].media[0].blur, { on: false, strength: 4, label: false }); + r = await cli(["set-item", "b", "p-1", "media.0.blur.strength=40"]); + assert.equal(r.code, 1, "refused in the build's words"); + assert.equal((await manifest(p)).timeline[0].media[0].src, "posts-media/subj-x/1/1.mp4"); +}); 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 = [ @@ -59,12 +59,17 @@ export const POSTS_USAGE = [ " umtool posts set-item <project> <item> [hold=<s>|off] [layout=sequence|grid] [redact=on|off|auto] [follow=on|off|auto] [follow.dim=<0.2-1>] [follow.ease=<s>]", " [media.<i>.start=<s>] [media.<i>.end=<s>] [media.<i>.mute=on|off] [media.<i>.crop=x,y,w,h|off]", " [media.<i>.push=on|off] [media.<i>.trim=off] [quoted.paraphrase=\"…\"|off]", + " [media.<i>.blur=on|off] [media.<i>.blur.strength=1–10] [media.<i>.blur.label=\"…\"|off]", + " [media.<i>.blur.boxes=x,y,w,h;…|off]", " [parent.<i>.paraphrase=\"…\"|off] [narration.rate=0.8–1.5|narration.<mix knob>=…] [--json]", " a post item's knobs (the post bench's writer, updatePostItem): its hold, its images' grid, the blur of other authors,", " an attachment's trim, sound, crop (fractions of its picture) and push-in; fit=read[:linger] (a narrated post: its", " video cut to its best part for the read, `posts fit`). quoted.paraphrase / parent.<i>.paraphrase (nearest first):", " your retelling of a long context post (at most 600 characters), drawn in place of its words and labelled", " \"paraphrased\"; its own text is kept; off (or empty) shows its words again.", + " media.<i>.blur=on: the attachment CENSORED in the render -- a real blur (strength 1-10, default 7) of the whole", + " frame, or of its boxes (fractions of the picture as shown: x,y,w,h;…), labelled \"Censored\" (label=… or off);", + " its file is never touched. Play and the bench preview it; the bench draws boxes on a paused frame.", " umtool posts narrate <project> … a post item's narration: script, takes (the editor's tts), pick, approve, mix", " (umtool posts narrate --help)", " umtool posts fit <project> [--all|<item> …] [--linger s] [--dry-run] narrated posts' videos cut to their best part", @@ -76,6 +81,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", @@ -382,6 +393,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 }); @@ -572,9 +584,18 @@ export function postItemPatchOf(pairs) { } else if (k === "quoted.paraphrase") out.quoted = { paraphrase: paraphraseOf(raw) }; else if (/^parents?\.\d+\.paraphrase$/.test(k)) (out.parents ??= {})[k.split(".")[1]] = { paraphrase: paraphraseOf(raw) }; - else { + else if (/^media\.\d+\.blur(\.(strength|label|boxes))?$/.test(k)) { + // The censoring blur (post-censor.mjs): on|off, its strength, its label (off: none), its boxes (x,y,w,h;…|off). + const [, i, , sub] = /^media\.(\d+)\.blur(\.(strength|label|boxes))?$/.exec(k) ?? []; + const blur = (((out.media ??= {})[i] ??= {}).blur ??= {}); + if (!sub) blur.on = onOff(v, k); + else if (sub === "strength") blur.strength = OFF.has(v) || v === "" ? null : Number(raw); + else if (sub === "label") blur.label = v === "off" ? false : raw.trim() === "" ? null : raw; + else blur.boxes = OFF.has(v) || v === "" ? null : raw.split(";").map((b) => b.split(",").map(Number)); + if (typeof blur.strength === "number" && !Number.isFinite(blur.strength)) throw new CliError(`${k}= takes a number (1-10)`); + } else { const m = /^media\.(\d+)\.(start|end|mute|crop|push|trim)$/.exec(k); - if (!m) throw new CliError(`${pair}: not a post item knob (hold=, layout=, redact=, follow=, follow.dim|ease=, media.<i>.start|end|mute|crop|push|trim=, quoted.paraphrase=, parent.<i>.paraphrase=)`); + if (!m) throw new CliError(`${pair}: not a post item knob (hold=, layout=, redact=, follow=, follow.dim|ease=, media.<i>.start|end|mute|crop|push|trim=, media.<i>.blur[.strength|.label|.boxes]=, quoted.paraphrase=, parent.<i>.paraphrase=)`); const media = (out.media ??= {}); const one = (media[m[1]] ??= {}); if (m[2] === "start" || m[2] === "end") one[m[2]] = OFF.has(v) || v === "" ? null : Number(raw); @@ -592,6 +613,42 @@ export function postItemPatchOf(pairs) { return out; } +/** `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; +} + /** `posts context`: every post item's context from its capture (postContext.mjs postsContext). */ async function contextCommand(projectArg, { root, json, dryRun, out }) { const project = await projectOf(projectArg, root); 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,8 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly rawDir: dirs.rawDir, channelsDir, channelSlug: provenance?.channelSlug ?? null, probe: opts.probe, }); FX_CHANNELS_DIR = channelsDir; + // Read only for a cut that plays post items: a cut without them publishes nothing it could blank. + POST_REDACTION = (manifest.timeline ?? []).some((e) => e?.type === "post") ? await readPostRedaction(channelsDir, manifest) : null; // 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 +6415,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,9 @@ "./post-avatars": "./post-avatars.mjs", "./post-item": "./post-item.mjs", "./post-narration": "./post-narration.mjs", + "./post-censor": "./post-censor.mjs", + "./post-redact": "./post-redact.mjs", + "./post-redact-files": "./post-redact-files.mjs", "./post-render": "./post-render.mjs", "./word-zoom": "./word-zoom.mjs", "./read-follow": "./read-follow.mjs", diff --git a/umtool/report-to-video/post-censor.mjs b/umtool/report-to-video/post-censor.mjs @@ -0,0 +1,144 @@ +// A CENSORED ATTACHMENT (operator, 3 Nov: "'it jiggle' will need to be +// censored but I do want to include it"): a post item's picture or video +// played BLURRED -- the whole frame, or only some regions of it -- with a +// small label saying so. umtool/docs/knobs.md, "A post item". +// +// media[i].blur = { on: true, strength?: 1–10 (7), boxes?: [[x, y, w, h], …], label?: "…" | false } +// +// `boxes` are fractions of the picture AS SHOWN (after its crop), held still +// over the clip; none blurs the whole frame. `label` is the caption drawn on +// it ("Censored" by default; false: none). A post's channel markup may censor +// one of its attachments for every project (posts-markup.json's `censor`, +// post-redact.mjs); the item's own `blur` wins. +// +// NOTHING IS REWRITTEN: the attachment's file stays as it was captured. The +// blur is a real one (ffmpeg gblur, sigma grown with the strength and the +// picture's size), drawn where public output is made -- the render. Play and +// the post bench preview it (a CSS blur, the boxes as backdrop blurs). +// +// PURE and dependency-free. + +export const POST_BLUR_DEFAULTS = Object.freeze({ strength: 7, label: "Censored" }); +export const POST_BLUR_BOXES_MAX = 8; +const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); +const fin = (v) => typeof v === "number" && Number.isFinite(v); +const r3 = (v) => Math.round(v * 1000) / 1000; + +/** Is attachment `m` blurred? */ +export const blurOn = (m) => isObj(m?.blur) && m.blur.on === true; + +/** Its blur with the defaults filled: `{ strength, boxes, label }` (label null: none), or null when it is not blurred. */ +export function blurOf(m) { + if (!blurOn(m)) return null; + const b = m.blur; + return { + strength: fin(b.strength) ? Math.min(10, Math.max(1, b.strength)) : POST_BLUR_DEFAULTS.strength, + boxes: Array.isArray(b.boxes) ? b.boxes.filter((x) => Array.isArray(x) && x.length === 4) : [], + label: b.label === false ? null : typeof b.label === "string" && b.label.trim() ? b.label.trim() : POST_BLUR_DEFAULTS.label, + }; +} + +/** The blur's sigma on a picture `width` px wide: 0.4% of the width per step of strength (at 7, ~2.8%). */ +export const blurSigma = (strength, width) => Math.max(2, Math.round(width * strength * 0.004 * 10) / 10); +/** The same as a share of the width, for a preview (CSS `cqw`). */ +export const blurCqw = (strength) => r3(strength * 0.4); + +/** Is `b` a box of fractions inside the picture? */ +export const boxOk = (b) => + Array.isArray(b) && b.length === 4 && b.every((v) => fin(v) && v >= 0 && v <= 1) && b[2] >= 0.01 && b[3] >= 0.01 && b[0] + b[2] <= 1.0001 && b[1] + b[3] <= 1.0001; + +/** Every reason `media[i].blur` is refused. */ +export function blurErrors(blur, where) { + if (blur === undefined) return []; + if (!isObj(blur)) return [`${where} must be {on, strength?, boxes?, label?}`]; + const errors = []; + for (const k of Object.keys(blur)) if (!["on", "strength", "boxes", "label"].includes(k)) errors.push(`${where}.${k} is not a blur knob (on, strength, boxes, label)`); + if (typeof blur.on !== "boolean") errors.push(`${where}.on must be true or false`); + if (blur.strength !== undefined && !(fin(blur.strength) && blur.strength >= 1 && blur.strength <= 10)) errors.push(`${where}.strength must be 1–10`); + if (blur.boxes !== undefined) { + if (!Array.isArray(blur.boxes) || blur.boxes.length > POST_BLUR_BOXES_MAX) errors.push(`${where}.boxes must be a list of at most ${POST_BLUR_BOXES_MAX} [x, y, w, h]`); + else blur.boxes.forEach((b, j) => !boxOk(b) && errors.push(`${where}.boxes[${j}] must be [x, y, w, h] as fractions of the picture (each 0–1, inside it)`)); + } + if (blur.label !== undefined && blur.label !== false && !(typeof blur.label === "string" && blur.label.length <= 40)) errors.push(`${where}.label must be words (at most 40 characters) or false`); + return errors; +} + +/** A label's words as ffmpeg drawtext's `text=` takes them, inside single quotes. */ +const dtText = (s) => String(s).replace(/\\/g, "\\\\").replace(/'/g, "\u2019").replace(/:/g, "\\:").replace(/%/g, "\\%"); + +/** + * The filters that blur attachment `m`, drawn `w` × `h` px: `[inLabel]` → + * `[outLabel]`. The whole frame, or each box: split, cropped, blurred and laid + * back over. A label is drawn by labelFilter, on the composed frame. + */ +export function blurFilters(inLabel, outLabel, m, { width, height }) { + const b = blurOf(m); + if (!b) return [`[${inLabel}]null[${outLabel}]`]; + const sigma = blurSigma(b.strength, width); + if (!b.boxes.length) return [`[${inLabel}]gblur=sigma=${sigma}:steps=3[${outLabel}]`]; + const out = []; + let cur = inLabel; + b.boxes.forEach((box, j) => { + const x = Math.round(box[0] * width); + const y = Math.round(box[1] * height); + const w = Math.max(2, Math.min(width - x, Math.round(box[2] * width))); + const h = Math.max(2, Math.min(height - y, Math.round(box[3] * height))); + const base = `${outLabel}_k${j}`; + out.push(`[${cur}]split[${base}a][${base}b]`); + out.push(`[${base}b]crop=${w}:${h}:${x}:${y},gblur=sigma=${sigma}:steps=3[${base}c]`); + const next = j === b.boxes.length - 1 ? outLabel : `${base}o`; + out.push(`[${base}a][${base}c]overlay=x=${x}:y=${y}[${next}]`); + cur = next; + }); + return out; +} + +/** + * The label's drawtext on the frame `[inLabel]` → `[outLabel]`: the words at + * the attachment's top-left corner (its box `b` on the frame) while it is up, + * or null when it has none (or there is no face to draw it in). + */ +export function labelFilter(inLabel, outLabel, m, b, { from, to, fontfile, scale = 1 }) { + const bl = blurOf(m); + if (!bl?.label || !fontfile) return null; + const size = Math.max(12, Math.round(26 * scale)); + const pad = Math.round(size * 0.5); + return ( + `[${inLabel}]drawtext=fontfile='${fontfile}':text='${dtText(bl.label)}':fontsize=${size}:fontcolor=white:box=1:boxcolor=black@0.7:boxborderw=${Math.round(size * 0.35)}:` + + `x=${b.x + pad}:y=${b.y + pad}:enable='between(t,${r3(from)},${r3(to)})'[${outLabel}]` + ); +} + +/** Every reason a markup's `censor` list is refused (posts-markup.json). */ +export function censorMarkupErrors(list, where) { + if (list === undefined) return []; + if (!Array.isArray(list)) return [`${where} must be a list of {media, blur}`]; + const errors = []; + list.forEach((c, i) => { + if (!isObj(c) || !(Number.isInteger(c.media) && c.media >= 0 && c.media < 8)) errors.push(`${where}[${i}].media must be the attachment's index (0–7)`); + if (isObj(c) && c.blur !== undefined) errors.push(...blurErrors({ on: true, ...(isObj(c.blur) ? c.blur : { bad: c.blur }) }, `${where}[${i}].blur`)); + }); + return errors; +} + +/** + * Post item `entry` with its channel markup's censoring laid on (`censor: + * [{media, blur?}]` in the post's markup; `blur` absent: the whole frame, the + * defaults): an attachment with a `blur` of its own keeps it. Returns the + * entry itself when nothing changes. + * + * @param {Record<string, any>} entry + * @param {{ markup?: Record<string, {censor?: Array<{media: number, blur?: Record<string, any>}>}> } | null | undefined} red + */ +export function censorEntry(entry, red) { + const list = red?.markup?.[String(entry?.post ?? "")]?.censor; + if (!Array.isArray(list) || !list.length || !Array.isArray(entry?.media)) return entry; + let changed = false; + const media = entry.media.map((m, i) => { + const c = list.find((x) => x?.media === i); + if (!c || !isObj(m) || m.blur !== undefined) return m; + changed = true; + return { ...m, blur: { on: true, ...(isObj(c.blur) ? c.blur : {}) } }; + }); + return changed ? { ...entry, media } : entry; +} diff --git a/umtool/report-to-video/post-censor.test.mjs b/umtool/report-to-video/post-censor.test.mjs @@ -0,0 +1,83 @@ +// post-censor.mjs: a censored attachment -- the knob's check, the blur in the +// encode (the whole frame, or its boxes), the label, a channel's markup. +import assert from "node:assert/strict"; +import { execFileSync, spawnSync } from "node:child_process"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { after, test } from "node:test"; +import { blurErrors, blurFilters, blurOf, blurSigma, censorEntry } from "./post-censor.mjs"; +import { postItemPlan, postLayout, validatePostItem } from "./post-item.mjs"; +import { postSegmentArgs } from "./post-render.mjs"; +import { validatePostsMarkup } from "./post-redact.mjs"; + +const box = { width: 1440, height: 810 }; +const entry = (blur) => ({ + type: "post", id: "p1", post: "c-x/1", platform: "x", author: "A", handle: "a", date: "2026-10-30T04:00:00Z", text: "it does a thing", + media: [{ src: "m/v.mp4", kind: "video", seconds: 3, width: 320, height: 180, audio: false, ...(blur ? { blur } : {}) }], +}); +const graphOf = (e, fontfile = null) => { + const argv = postSegmentArgs({ entry: e, box, plan: postItemPlan(e), layout: postLayout(e, box), cards: { read: "/c/read.png" }, files: ["/m/v.mp4"], render: { fps: 30 }, outPath: "/o.mp4", fontfile }); + return argv[argv.indexOf("-filter_complex") + 1]; +}; + +test("the knob: on, a strength 1-10, boxes of fractions, a label or false; validated with the item", () => { + assert.deepEqual(blurErrors({ on: true, strength: 4, boxes: [[0.1, 0.1, 0.5, 0.5]], label: false }, "b"), []); + const bad = blurErrors({ on: "yes", strength: 11, boxes: [[0.8, 0, 0.5, 0.5]], label: 3, extra: 1 }, "b"); + assert.equal(bad.length, 5, bad.join("; ")); + assert.ok(validatePostItem(entry({ on: true, strength: 0 })).some((e) => e.includes("media[0].blur.strength must be 1–10"))); + assert.deepEqual(blurOf({ blur: { on: true } }), { strength: 7, boxes: [], label: "Censored" }); + assert.equal(blurOf({ blur: { on: false, strength: 3 } }), null, "off keeps its settings and blurs nothing"); +}); + +test("the encode: the whole frame gblurred, or each box split, cropped, blurred and laid back; the label drawn on the frame", () => { + const plain = graphOf(entry(null)); + assert.doesNotMatch(plain, /gblur/); + const whole = graphOf(entry({ on: true }), "/f/bold.ttf"); + assert.match(whole, /\[m0_0r\]gblur=sigma=[\d.]+:steps=3\[m0_0\]/); + assert.match(whole, /drawtext=fontfile='\/f\/bold.ttf':text='Censored'/); + const boxes = graphOf(entry({ on: true, strength: 5, boxes: [[0, 0, 0.5, 0.5], [0.5, 0.5, 0.5, 0.5]], label: "It: 100%" }), "/f/bold.ttf"); + assert.equal((boxes.match(/gblur/g) ?? []).length, 2); + assert.match(boxes, /\[m0_0r\]split/); + assert.match(boxes, /text='It\\: 100\\%'/); + assert.doesNotMatch(graphOf(entry({ on: true, label: false }), "/f/bold.ttf"), /drawtext/); + assert.equal(blurSigma(7, 1000), 28); + assert.deepEqual(blurFilters("a", "b", { blur: { on: false } }, { width: 10, height: 10 }), ["[a]null[b]"]); +}); + +test("a channel's markup censors an attachment in every project; the item's own blur wins", () => { + const red = { terms: [], markup: { "c-x/1": { censor: [{ media: 0 }] } } }; + const e = entry(null); + const out = censorEntry(e, red); + assert.deepEqual(out.media[0].blur, { on: true }); + assert.equal(e.media[0].blur, undefined, "the entry is never rewritten"); + const own = entry({ on: false }); + assert.equal(censorEntry(own, red), own); + assert.equal(censorEntry(e, { terms: [] }), e); + assert.deepEqual(validatePostsMarkup({ "1": { censor: [{ media: 0, blur: { strength: 3 } }] } }), []); + assert.equal(validatePostsMarkup({ "1": { censor: [{ media: 9 }, { media: 0, blur: { strength: 30 } }] } }).length, 2); +}); + +const ROOT = mkdtempSync(path.join(tmpdir(), "post-censor-")); +after(() => rmSync(ROOT, { recursive: true, force: true })); + +test("the encode runs: a blurred frame is smoother than the clean one (ffmpeg)", () => { + const src = path.join(ROOT, "v.mp4"); + execFileSync("ffmpeg", ["-v", "error", "-y", "-f", "lavfi", "-i", "testsrc=s=320x180:d=3:r=30", "-c:v", "libx264", "-pix_fmt", "yuv420p", src]); + const png = path.join(ROOT, "card.png"); + execFileSync("ffmpeg", ["-v", "error", "-y", "-f", "lavfi", "-i", "color=c=black:s=1440x810", "-frames:v", "1", png]); + const detail = (blur) => { + const e = entry(blur); + const out = path.join(ROOT, `o-${blur ? "b" : "c"}.mp4`); + const argv = postSegmentArgs({ entry: e, box, plan: postItemPlan(e), layout: postLayout(e, box), cards: { read: png }, files: [src], render: { fps: 30 }, outPath: out, encode: ["-c:v", "libx264", "-preset", "ultrafast"] }); + execFileSync("ffmpeg", argv); + // The frame's edge energy: a blur takes most of it away. + const r = spawnSync("ffmpeg", ["-v", "info", "-ss", "1", "-i", out, "-frames:v", "1", "-vf", "edgedetect,signalstats,metadata=print:key=lavfi.signalstats.YAVG", "-f", "null", "-"], { encoding: "utf8" }); + return `${r.stdout}${r.stderr}`; + }; + const yavg = (s) => Number(/YAVG=([\d.]+)/.exec(s)?.[1] ?? NaN); + const clean = yavg(detail(null)); + const blurred = yavg(detail({ on: true, label: false })); + assert.ok(Number.isFinite(clean) && Number.isFinite(blurred), `${clean} ${blurred}`); + assert.ok(blurred < clean * 0.6, `edges: clean ${clean}, blurred ${blurred}`); +}); diff --git a/umtool/report-to-video/post-item.mjs b/umtool/report-to-video/post-item.mjs @@ -9,7 +9,8 @@ // repostedBy?: { author, handle }, quoted?: <ref>, parents?: [<ref>, …], // replyingTo?: "<handle>", parentShot?: "<file>", // media?: [{ src, kind: "image"|"video"|"gif", seconds?, width?, height?, audio?, -// start?, end?, mute?, crop?: [x, y, w, h], push?, words? }], +// start?, end?, mute?, crop?: [x, y, w, h], push?, words?, +// blur?: { on, strength?, boxes?, label? } }], (post-censor.mjs) // mediaLayout?: "sequence"|"grid", hold?, redact?, onscreen?, // fx?: [{ kind: "word-zoom", match, target?, occurrence?, at?, lead?, hold?, scale?, ease?, highlight? }] } // @@ -31,7 +32,9 @@ import { isNarrated, narrationSchedule, postNarrationFiles, postNarrationKnobs, validatePostNarration, } from "./post-narration.mjs"; -import { WORD_ZOOM_HIGHLIGHT_ALPHA, cardTokens, validatePostFx } from "./word-zoom.mjs"; +import { BAR_CSS, barsHtml, hasMarks, projectRedactOf, redactEntry, redactionOn, validatePostsRender } from "./post-redact.mjs"; +import { blurErrors } from "./post-censor.mjs"; +import { WORD_ZOOM_HIGHLIGHT_ALPHA, cardTokens, cardWordsOf, findMatch, targetTextOf, validatePostFx } from "./word-zoom.mjs"; import { FOLLOW_MIN_SIZE, followBlocks, followSchedule, scopeBlocks, validatePostFollow } from "./read-follow.mjs"; /** The platforms a post item may come from (deck.mjs POST_PLATFORMS). */ @@ -498,6 +501,7 @@ function mediaErrors(m, where) { const er2 = relFileError(m.words, `${where}.words`); if (er2) errors.push(er2); } + errors.push(...blurErrors(m.blur, `${where}.blur`)); return errors; } @@ -506,6 +510,43 @@ 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)); + // A word zoom on a word the project's list blanks (the corpus's and a post's markup are checked by the build). + const own = { terms: projectRedactOf(manifest?.render) }; + for (const e of tl) if (e?.type === "post") errors.push(...fxRedactionErrors(e, own)); + return errors; +} + +/** + * Every word zoom of post item `entry` whose words are (or hold) a REDACTED + * word (post-redact.mjs): refused -- a published card never pushes in on a + * blank. The match is found on the ORIGINAL text (its `occurrence` as the + * manifest counts it); the redacted text keeps its spaces, so the same word + * indices name the same words on the published card. + * + * @param {Record<string, any>} entry + * @param {{ terms: any[], markup?: Record<string, any> } | null | undefined} red + */ +export function fxRedactionErrors(entry, red) { + if (!Array.isArray(entry?.fx) || !entry.fx.length || !redactionOn(red)) return []; + const shown = redactEntry(entry, red); + const errors = []; + entry.fx.forEach((fx, i) => { + if (!isObj(fx) || fx.kind !== "word-zoom" || typeof fx.match !== "string") return; + const target = fx.target ?? "post"; + const text = targetTextOf(entry, target); + const published = targetTextOf(shown, target); + if (text === null || published === null) return; + const m = findMatch(text, fx.match, fx.occurrence ?? 1); + if (m.error) return; + const words = cardWordsOf(published); + for (let w = m.from; w <= m.to; w += 1) { + if (hasMarks(words[w])) { + errors.push(`timeline ${entry.id}.fx[${i}]: its match "${fx.match}" is a redacted word (render.posts.redact, the corpus's redactions.json or the post's markup) -- a published card never zooms on a blank; zoom on another word`); + break; + } + } + }); return errors; } @@ -767,13 +808,18 @@ 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>, - * highlight?: { scope: string, from: number, to: number, color: string } | null, follow?: boolean }} o + * highlight?: { scope: string, from: number, to: number, color: string } | null, + * redaction?: { terms: Array<{term: string, wholeWord?: boolean}>, markup?: Record<string, any> } | null, follow?: boolean }} o */ -export function postCardHtml(entry, { width, height, palette = {}, fonts = {}, phase = "read", parentShotUrl = null, transparent = false, avatars = {}, highlight = null, follow = false }) { +export function postCardHtml(entry, { width, height, palette = {}, fonts = {}, phase = "read", parentShotUrl = null, transparent = false, avatars = {}, highlight = null, redaction = null, follow = false }) { const hlOf = (scope) => (highlight && highlight.scope === scope ? highlight : null); - // READ-FOLLOW (read-follow.mjs): the read's blocks wrapped on the card, the post's words in a flow that pans. + // READ-FOLLOW (read-follow.mjs): the read's blocks wrapped on the card, the post's words in a flow that pans -- + // mapped on the words as written (the plan's are), whose indices the redaction's bars keep. const fmap = follow ? followBlocks(entry) : null; const blk = (scope) => (fmap ? scopeBlocks(fmap, scope) : null); + // AS PUBLISHED (post-redact.mjs): every redacted match drawn as a bar, its letters never in the page. The + // marks keep the text's length and its spaces, so the card's word indices (a word zoom's) are the original's. + 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 }); @@ -876,8 +922,9 @@ b, .name, .mark { font-family: 'PostSansBold', sans-serif; font-weight: 400; } .wfade[data-post-fade="top"] { top: 0; background: linear-gradient(${cardBg}, ${rgbaOf(cardBg, 0)}); } .wfade[data-post-fade="bottom"] { bottom: 0; background: linear-gradient(${rgbaOf(cardBg, 0)}, ${cardBg}); }` : ""}${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> -<body data-post-item="${esc(entry.id)}" data-post-layout="${L.mode}" data-post-phase="${strip ? "media" : "read"}"${fmap ? ` data-post-follow="${fmap.blocks.length}"` : ""}>${body} +<body data-post-item="${esc(entry.id)}" data-post-layout="${L.mode}" data-post-phase="${strip ? "media" : "read"}"${fmap ? ` data-post-follow="${fmap.blocks.length}"` : ""}>${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,275 @@ +// 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? }], +// censor?: [{ media: <i>, blur?: {strength?, boxes?, label?} }] } } +// 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); `censor` blurs an +// attachment of the post in every project (post-censor.mjs) +// +// 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 (the build, the route, Play and the writers). +import { censorMarkupErrors } from "./post-censor.mjs"; + +/** 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 spaces kept + * -- its length, every offset and its words (runs of non-space) kept, so a + * layout measured on it and a word index counted on it are 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) { + // Every code unit marked but the spaces: a phrase stays as many card words as it was (a word zoom's indices hold). + out += s.slice(at, a) + s.slice(a, b).replace(/\S/g, REDACT_MARK); + 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) { + // A phrase's marks with its spaces between them are one run to drop. + const parts = str(marked).split(/\uE000(?:[\s\uE000]*\uE000)?/); + 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?: […], censor?: […]}}`]; + 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) || (m.redact !== undefined && !Array.isArray(m.redact)) || Object.keys(m).some((k) => !["redact", "censor", "note"].includes(k))) { + errors.push(`${w} must be {redact?: […], censor?: […]}`); + continue; + } + errors.push(...censorMarkupErrors(m.censor, `${w}.censor`)); + (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,112 @@ +// 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 }]); + // Its spaces kept: as many card words as before (a word zoom's indices hold). + assert.equal(r.text, `Signed, ${marks(8)}\n ${marks(7)} -- 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. + const plain = postCardHtml(entry, { width: 1280, height: 720 }); + assert.match(plain, />QUENTIN</); + assert.match(plain, />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": {}, "8": { other: 1 } }); + 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"))); +}); + +test("with a word zoom: the redacted text keeps its card words (the zoom's indices hold), a zoom on a redacted word is refused", async () => { + const { fxRedactionErrors, validatePostItems: vpi } = await import("./post-item.mjs"); + const { cardWordsOf } = await import("./word-zoom.mjs"); + const text = "So Quentin Example said barbecue twice, barbecue!"; + assert.equal(cardWordsOf(redactText(text, NAME).text).length, cardWordsOf(text).length); + const e = { type: "post", id: "z1", post: "c-x/1", platform: "x", text, date: "2026-10-30T04:00:00Z", fx: [{ kind: "word-zoom", match: "barbecue", occurrence: 2, at: 1 }] }; + assert.deepEqual(fxRedactionErrors(e, { terms: NAME }), []); + // The published card: the bars in the redacted words' slots, the zoom's word where it was. + const html = postCardHtml(e, { width: 1280, height: 720, redaction: { terms: NAME }, highlight: { scope: "post", from: 6, to: 6, color: "#ffd84d" } }); + assert.match(html, /data-w="post:6" data-w-hl="">barbecue!/); + assert.match(html, /data-w="post:1"><span class="rbar"/); + const onName = { ...e, fx: [{ kind: "word-zoom", match: "Example", at: 1 }] }; + assert.equal(fxRedactionErrors(onName, { terms: NAME }).length, 1); + assert.ok(vpi({ timeline: [onName], render: { posts: { redact: NAME } } }).some((x) => x.includes("is a redacted word"))); + assert.deepEqual(vpi({ timeline: [onName], render: {} }), []); +}); diff --git a/umtool/report-to-video/post-render.mjs b/umtool/report-to-video/post-render.mjs @@ -18,9 +18,11 @@ import { createHash } from "node:crypto"; import { mkdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises"; import path from "node:path"; import { pathToFileURL } from "node:url"; -import { POST_PICTURE_XFADE, POST_PUSH, postCardHtml, postItemPlan, postLayout, stepBoxes } from "./post-item.mjs"; +import { POST_PICTURE_XFADE, POST_PUSH, fxRedactionErrors, postCardHtml, postItemPlan, postLayout, stepBoxes } from "./post-item.mjs"; import { isNarrated, narrationLevelDb, pickedTake, postNarrationFilters } from "./post-narration.mjs"; import { applyFollowState, followPath, followStateAt, followStateKey, measureFollow } from "./read-follow.mjs"; +import { redactEntry, redactionOn, spokenWithout, termsFor } from "./post-redact.mjs"; +import { blurFilters, blurOn, censorEntry, labelFilter } from "./post-censor.mjs"; import { WORD_ZOOM_DEFAULTS, findMatch, overlappingZooms, resolveWordZoom, targetScope, targetTextOf, wordZoomTimes, zoomSpan, zoomTarget, zoompanExprs } from "./word-zoom.mjs"; const r3 = (v) => Math.round(v * 1000) / 1000; @@ -137,6 +139,8 @@ export function postSegmentArgs({ entry, box, plan, layout, cards, files, render const file = files[m.i]; const crop = Array.isArray(m.crop) ? `crop=iw*${num(m.crop[2])}:ih*${num(m.crop[3])}:iw*${num(m.crop[0])}:ih*${num(m.crop[1])},` : ""; const label = `m${si}_${j}`; + // A censored attachment (post-censor.mjs): its chain ends in a raw label, blurred into `label`. + const raw = blurOn(m) ? `${label}r` : label; if (step.kind === "image" || step.kind === "grid") { if (m.push === true) { const frames = Math.max(1, Math.round((until - shownFrom) * fps)); @@ -144,11 +148,11 @@ export function postSegmentArgs({ entry, box, plan, layout, cards, files, render parts.push( `[${k}:v]${crop}scale=${b.width * 2}:${b.height * 2},setsar=1,` + `zoompan=z='1+${POST_PUSH}*on/${frames}':x='iw/2-(iw/zoom/2)':y='ih/2-(ih/zoom/2)':d=${frames}:s=${b.width}x${b.height}:fps=${fps},` + - `setpts=PTS-STARTPTS+${num(shownFrom)}/TB${fadeIn(shownFrom)}[${label}]`, + `setpts=PTS-STARTPTS+${num(shownFrom)}/TB${fadeIn(shownFrom)}[${raw}]`, ); } else { const k = add(["-loop", "1", "-framerate", String(fps), "-t", num(until), "-i", file]); - parts.push(`[${k}:v]${crop}scale=${b.width}:${b.height},setsar=1,fps=${fps}${fadeIn(shownFrom)}[${label}]`); + 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. @@ -156,7 +160,7 @@ export function postSegmentArgs({ entry, box, plan, layout, cards, files, render const k = add([...(step.loop ? ["-stream_loop", "-1"] : []), "-ss", num(step.srcFrom), "-t", num(len), "-i", file]); parts.push( `[${k}:v]${crop}scale=${b.width}:${b.height},setsar=1,fps=${fps},setpts=PTS-STARTPTS,` + - `tpad=start_duration=${num(step.at)}:start_mode=clone:stop_mode=clone:stop_duration=${num(T)}[${label}]`, + `tpad=start_duration=${num(step.at)}:start_mode=clone:stop_mode=clone:stop_duration=${num(T)}[${raw}]`, ); if (step.sound) { const ms = Math.round(step.at * 1000); @@ -164,7 +168,14 @@ export function postSegmentArgs({ entry, box, plan, layout, cards, files, render 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}]` }); } } + if (raw !== label) parts.push(...blurFilters(raw, label, m, b)); lay(label, b.x, b.y, shownFrom, until); + // Its label ("Censored") on the frame, at the attachment's corner, while it is up. + const lf = blurOn(m) ? labelFilter(cur, `b${n + 1}`, m, b, { from: shownFrom, to: until, fontfile, scale: box.height / 1080 }) : null; + if (lf) { + parts.push(lf); + cur = `b${++n}`; + } }); }); // A video attachment's words (its transcript), at the slot's foot. @@ -221,7 +232,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 = {}, zooms = [], follow = null, total = 0 }) { +export async function renderPostCards(entry, { box, render, dir, manifestDir, layout, avatars = {}, zooms = [], redaction = null, follow = null, total = 0 }) { await mkdir(dir, { recursive: true }); const fonts = { regular: render.fontRegular ? pathToFileURL(render.fontRegular).href : "", @@ -240,6 +251,7 @@ export async function renderPostCards(entry, { box, render, dir, manifestDir, la 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])), follow: !!follow && phase === "read", + redaction, }); const file = path.join(dir, `${phase}.html`); await writeFile(file, html, "utf8"); @@ -251,7 +263,7 @@ export async function renderPostCards(entry, { box, render, dir, manifestDir, la if (phase === "read" && follow) out.follow = await shootFollow(page, { follow, total, fps: render.fps ?? 30, box, dir }); } await ctx.close(); - if (zooms.length) out.zooms = await shootZooms(browser, entry, { box, render, dir, fonts, parentShotUrl, avatars, zooms, follow }); + if (zooms.length) out.zooms = await shootZooms(browser, entry, { box, render, dir, fonts, parentShotUrl, avatars, zooms, redaction, follow }); } finally { await browser.close(); } @@ -320,14 +332,14 @@ export const zoomShotScale = (zooms) => Math.min(4, Math.max(2, Math.ceil(Math.m * and the region shot plain and with the zoom's highlight under the words. * `zooms`: `[{ i, scope, from, to, scale, highlight }]`. */ -async function shootZooms(browser, entry, { box, render, dir, fonts, parentShotUrl, avatars, zooms, follow = null }) { +async function shootZooms(browser, entry, { box, render, dir, fonts, parentShotUrl, avatars, zooms, redaction = null, follow = null }) { const k = zoomShotScale(zooms); const ctx = await browser.newContext({ viewport: { width: box.width, height: box.height }, deviceScaleFactor: k, offline: true, serviceWorkers: "block" }); const page = await ctx.newPage(); const av = Object.fromEntries(Object.entries(avatars).map(([h, f]) => [h, pathToFileURL(f).href])); const load = async (name, highlight) => { const file = path.join(dir, `${name}.html`); - await writeFile(file, postCardHtml(entry, { width: box.width, height: box.height, palette: render.palette, fonts, phase: "read", parentShotUrl, avatars: av, highlight, follow: !!follow }), "utf8"); + await writeFile(file, postCardHtml(entry, { width: box.width, height: box.height, palette: render.palette, fonts, phase: "read", parentShotUrl, avatars: av, highlight, redaction, follow: !!follow }), "utf8"); await page.goto(pathToFileURL(file).href, { waitUntil: "load" }); await page.waitForSelector("body[data-post-ready='1']", { timeout: 15000 }); }; @@ -420,9 +432,16 @@ export function postZoomPlan(entry, render, total = Infinity) { * 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 }) { + // A channel's markup may censor an attachment for every project (post-censor.mjs); the item's own blur wins. + entry = censorEntry(entry, redaction); + // A word zoom on a redacted word is refused in the build's words (the corpus's terms and the markup included). + const fxRed = fxRedactionErrors(entry, redaction); + if (fxRed.length) throw new Error(fxRed.join("; ")); const seg = path.join(outDir, "segments", `${entry.id}.mp4`); const plan = postItemPlan(entry, render); const layout = postLayout(entry, box); @@ -440,7 +459,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 } : {}), ...(plan.follow ? { follow: plan.follow } : {}) })) + // 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 } : {}), ...(plan.follow ? { follow: plan.follow } : {}) })) .digest("hex"); const record = postRecordPath(seg); const had = await readFile(record, "utf8").then((t) => JSON.parse(t), () => null); @@ -450,7 +470,7 @@ export async function buildPostSegment(entry, { render, outDir, manifestDir, box } const cardDir = path.join(outDir, "cards", `post-${entry.id}`); const zoomPlan = postZoomPlan(entry, render, plan.total); - const cards = await renderPostCards(entry, { box, render, dir: cardDir, manifestDir, layout, avatars, zooms: zoomPlan, follow: plan.follow ?? null, total: plan.total }); + const cards = await renderPostCards(entry, { box, render, dir: cardDir, manifestDir, layout, avatars, zooms: zoomPlan, redaction, follow: plan.follow ?? null, total: plan.total }); const zooms = (cards.zooms ?? []).map((z) => ({ ...z, target: zoomTarget(z.region, { ...z.word }, z.span.scale) })); // Its video attachments' words, when transcribed: one textfile per cue. const captions = []; @@ -459,7 +479,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 });