commit d1a7eb583b8257d15dbfae7c39721adff077b101 parent 56f45d32dd141ad5633c4bf2f29695fc4c009133 Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st> Date: Tue, 3 Nov 2026 17:07:56 -0500 umtool: the slur filter in the render, the reads, the CLI and Play -- a take that says a slur is silenced or beeped over it by its word timings (refused without them), a read is synthesized skipped / with its stand-in / said for a beep; `umtool posts slurs`; the uncensored cut (`umtool take … --uncensored`, build-video --uncensored, Play's Uncensored) The render: post-render covers each slur its take SAYS (take.slurs said, or absent: a recording, a take from before the filter; a derived take reads its source's) with takeSlurBleeps -- the voice muted over the word's span (voice skip) or a 1 kHz tone laid in (beep, placeholder), on the take's clock before the tempo; no word timings refuses the post in the build's words. Captions mask the slurs (shownLine); the segment key carries the filter. The reads: makeTake and the bench synthesize spokenRead (skip, the stand-in, or said); a beep take is word-timed right after (the editor's transcribe op) and, when it cannot be, synthesized again skipped; the bench, which cannot time it, skips. take.slurs records which. The switch: render.posts.slurs.on false in the take's patch (--uncensored; its label "(uncensored)", take.json `slurs: censored|uncensored`), build-video --uncensored, the post-item route's uncensored=1 behind Play's Uncensored (beside As published) -- the redaction and censored attachments stay on. `umtool posts slurs <p> ls|on|off|level|visual|voice|add|except|remove` (updatePostSlurs, one undo point each): ls counts what the cut masks per slur and per post, masks only, and names the reads that need word timings. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Diffstat:
16 files changed, 545 insertions(+), 25 deletions(-)
diff --git a/umtool/app/api/report/post-item/route.ts b/umtool/app/api/report/post-item/route.ts @@ -22,7 +22,9 @@ export const dynamic = "force-dynamic"; // 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 +// (post-redact.mjs), never in the page, its slurs +// masked (post-slurs.mjs); &uncensored=1 the +// slurs as posted (the redaction kept) // 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 @@ -162,7 +164,8 @@ export async function GET(request: Request) { 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); + // uncensored=1: the slur filter off (post-slurs.mjs) -- Play's Uncensored; the redaction stays. + if (q.get("published") === "1") redaction = await projectRedaction(r.project.dir, found.manifest, { uncensored: q.get("uncensored") === "1" }); } catch (e) { return new Response(e instanceof Error ? e.message : String(e), { status: 500 }); } diff --git a/umtool/app/api/report/post-narration/route.ts b/umtool/app/api/report/post-narration/route.ts @@ -14,10 +14,13 @@ 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"; +import { spokenRead } from "umtool-report-to-video/post-redact"; export const dynamic = "force-dynamic"; +/** The slur filter's voice for a take synthesized on the bench: beep falls back to skip (no word timings yet to beep by). */ +const benchVoice = (red: { slurs?: { voice?: string } | null } | null) => (red?.slurs?.voice === "beep" ? "skip" : undefined) as "skip" | undefined; + // A NARRATED POST ITEM's bench (report-to-video/post-narration.mjs; knobs.md, // "A narrated post item"): the recording session, the takes, the mix's knobs. // @@ -100,7 +103,11 @@ export async function GET(request: Request) { const { result } = await withEditNotes(r.project, async () => updatePostNarration(r.project.dir, id, { addTake: derived }, { token: await manifestToken(r.project.dir) })); return Response.json({ state: "done", file: rel, entry: result.entry, token: result.token }, { headers: noStore }); } + // What its audio does with the script's slurs (post-slurs.mjs): as the POST above asked for it. + const red = await projectRedaction(r.project.dir, m); + const slurs = spokenRead(script, e, red, { voice: benchVoice(red) }).slurs; const take = { + ...(slurs ? { slurs } : {}), file: rel, engine: res.engine ?? q.get("engine") ?? "orpheus", voice: res.voice ?? q.get("voice") ?? "zac", seconds: meas.seconds, source: { kind: "tts", engine: res.engine ?? q.get("engine") ?? "orpheus", voice: res.voice ?? q.get("voice") ?? "zac", script }, script, at: new Date().toISOString(), jobId: job, ...(Number.isFinite(meas.lufs) ? { lufs: meas.lufs } : {}), ...(note ? { note } : {}), @@ -169,8 +176,11 @@ export async function POST(request: Request) { await mkdir(dir, { recursive: true }); const rel = takeFileOf(pid, nextTakeNumber(e, await readdir(dir).catch(() => [])), engine, voice); const speed = body.speed === undefined || body.speed === null || engine === "orpheus" ? undefined : Number(body.speed); - // What the voice SAYS: the script with every redacted term left out (post-redact.mjs); the script is kept as written. - const spoken = spokenWithout(script, termsFor(e, await projectRedaction(r.project.dir, m))); + // What the voice SAYS: the script with every redacted term left out (post-redact.mjs) and each slur as the cut's + // filter has it (post-slurs.mjs); the script is kept as written. The bench cannot word-time a take as it is made, + // so a beep falls back to skip here (the CLI's --take times it and beeps). + const red = await projectRedaction(r.project.dir, m); + const spoken = spokenRead(script, e, red, { voice: benchVoice(red) }).text; 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 }); } diff --git a/umtool/components/projects/review/PlayCut.tsx b/umtool/components/projects/review/PlayCut.tsx @@ -171,6 +171,8 @@ const PAUSE_KEY = "umtool.play.pauseWhileWriting"; 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"; +/** And which cut: censored (the slur filter on, post-slurs.mjs) or the uncensored one. Per browser. */ +const UNCENSORED_KEY = "umtool.play.uncensored"; /** 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 }[] = [ @@ -340,9 +342,11 @@ export default function PlayCut({ // (umtool check blocks on a fact error and lists the rest). Remembered per browser. const [showRejected, setShowRejected] = useState(false); const [asPublished, setAsPublished] = useState(false); + const [uncensored, setUncensored] = useState(false); useEffect(() => { try { if (window.localStorage.getItem(AS_PUBLISHED_KEY) === "on") setAsPublished(true); + if (window.localStorage.getItem(UNCENSORED_KEY) === "on") setUncensored(true); } catch { // A preference, not state. } @@ -846,6 +850,7 @@ export default function PlayCut({ playing={ui.playing && !ui.waiting} speed={rate} published={asPublished} + uncensored={uncensored} /> ) : null; const placeholderCard = placeholder ? ( @@ -1060,7 +1065,7 @@ 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)"> + <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), every slur masked (umtool posts slurs)"> <input type="checkbox" data-play-as-published="" @@ -1075,7 +1080,26 @@ export default function PlayCut({ } }} /> - As published + {asPublished ? (uncensored ? "As published (uncensored)" : "As published (censored)") : "As published"} + </label> + )} + {hasPosts && asPublished && ( + <label className="inline-flex items-center gap-1.5 text-[11.5px] text-text-2" title="the UNCENSORED cut: the slurs as posted (umtool take … --uncensored; umtool posts slurs) -- the redacted words stay bars"> + <input + type="checkbox" + data-play-uncensored="" + checked={uncensored} + onChange={(ev) => { + const on = ev.target.checked; + setUncensored(on); + try { + window.localStorage.setItem(UNCENSORED_KEY, on ? "on" : "off"); + } catch { + // A preference, not state. + } + }} + /> + Uncensored </label> )} {item && ( diff --git a/umtool/components/projects/review/PostItemPlayer.tsx b/umtool/components/projects/review/PostItemPlayer.tsx @@ -260,7 +260,7 @@ function MediaEl({ } export default function PostItemPlayer({ - project, take = null, entry, plan, box, s, playing, cardKey = null, speed = 1, published = false, + project, take = null, entry, plan, box, s, playing, cardKey = null, speed = 1, published = false, uncensored = false, }: { project: string; take?: string | null; @@ -276,6 +276,8 @@ export default function PostItemPlayer({ speed?: number; /** AS PUBLISHED (Play's toggle): the card with its redacted words as bars, as the build draws it. */ published?: boolean; + /** With `published`: the UNCENSORED cut -- the slurs as posted (post-slurs.mjs), the redaction kept. */ + uncensored?: boolean; }) { const wrap = useRef<HTMLDivElement | null>(null); const [scale, setScale] = useState(0); @@ -313,7 +315,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)}` : ""}${published ? "&published=1" : ""}`; + `/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${uncensored ? "&uncensored=1" : ""}` : ""}`; const reading = s < plan.reading || !plan.steps.length; const current = stepAt(plan, s); // Beside the card, the first attachment is up (its first frame) while the words are read. diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs @@ -2805,6 +2805,60 @@ export async function updatePostRedact(dir, change, { token = null } = {}) { }); } +// ---- the slur filter (post-slurs.mjs; `umtool posts slurs`) --------------- + +/** + * CHANGE THE CUT's SLUR FILTER (`render.posts.slurs`): `{ set: { on?, level?, + * visual?, voice? } }` sets its knobs (a null: back to the default), `{ add: + * "<word>" }` masks a word of the project's own, `{ except: "<word>" }` never + * masks one (a form, a slur's word or its id), `{ remove: "<word>" }` takes a + * word off both lists. A word already on the list it is added to is refused. + * The posts' words are never touched. Validated with the build's check. + * + * @param {string} dir + * @param {{ set?: Record<string, unknown>, add?: string, except?: string, remove?: string }} change + * @param {{ token?: string | null }} [opts] + */ +export async function updatePostSlurs(dir, change, { token = null } = {}) { + const ops = ["set", "add", "except", "remove"].filter((k) => isObj(change) && change[k] !== undefined); + if (ops.length !== 1) throw new Error("say set, add, except or remove"); + return structural(dir, "post-slurs", token, (m) => { + if (!isObj(m.render)) m.render = {}; + const posts = isObj(m.render.posts) ? m.render.posts : {}; + const sl = isObj(posts.slurs) ? { ...posts.slurs } : {}; + const word = (v) => String(v ?? "").trim().toLowerCase(); + const has = (list, w) => (Array.isArray(list) ? list : []).some((x) => word(typeof x === "string" ? x : x?.word) === w); + if (change.set !== undefined) { + if (!isObj(change.set)) throw new Error("set takes {on?, level?, visual?, voice?}"); + for (const [k, v] of Object.entries(change.set)) { + if (!["on", "level", "visual", "voice", "note"].includes(k)) throw new StructureRefused([`render.posts.slurs.${k} is not a knob a write sets (on, level, visual, voice, note)`]); + if (v === null || v === undefined) delete sl[k]; + else sl[k] = v; + } + } else if (change.add !== undefined || change.except !== undefined) { + const key = change.add !== undefined ? "add" : "except"; + const w = word(change[key]); + if (has(sl[key], w)) throw new Error(`that word is already on the ${key} list`); + sl[key] = [...(Array.isArray(sl[key]) ? sl[key] : []), w]; + // A word is added or excepted, never both. + const other = key === "add" ? "except" : "add"; + if (Array.isArray(sl[other])) sl[other] = sl[other].filter((x) => word(typeof x === "string" ? x : x?.word) !== w); + } else { + const w = word(change.remove); + if (!has(sl.add, w) && !has(sl.except, w)) throw new Error("that word is on neither list (add, except)"); + for (const k of ["add", "except"]) if (Array.isArray(sl[k])) sl[k] = sl[k].filter((x) => word(typeof x === "string" ? x : x?.word) !== w); + } + for (const k of ["add", "except"]) if (Array.isArray(sl[k]) && !sl[k].length) delete sl[k]; + if (Object.keys(sl).length) posts.slurs = sl; + else delete posts.slurs; + 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 { slurs: sl }; + }); +} + // ---- 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,7 +26,7 @@ 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 { spokenRead } from "umtool-report-to-video/post-redact"; import { projectRedaction } from "./postRedaction.mjs"; import { readManifest } from "../projects/report.mjs"; import { withEditNotes } from "./edit-guard.mjs"; @@ -244,7 +244,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, redaction = undefined } = {}) { +export async function makeTake(project, e, { script = null, note = null, engine = null, voice = null, speed = null, render = {}, emit = () => {}, editor = null, ask = null, askOp = 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)`); @@ -259,23 +259,59 @@ export async function makeTake(project, e, { script = null, note = null, engine const rel = takeFileOf(pid, n, eng, vox); const out = path.join(project.dir, ...rel.split("/")); const askTts = ask ?? (await import("umtool-report-to-video/narrate-via-editor")).askEditorTts; - // What the voice SAYS: the script with every redacted term left out (post-redact.mjs) -- the script itself is kept as written. + // What the voice SAYS: the script with every redacted term left out (post-redact.mjs), and each slur as the + // cut's filter has it (post-slurs.mjs: skipped, its stand-in, or said for a beep) -- the script itself is kept as written. 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 }); + const said = spokenRead(words, e, red); + const ttsBody = (text) => ({ text, engine: eng, voice: vox, out, ...(spd !== null && eng !== "orpheus" ? { speed: spd } : {}) }); + let { jobId, result } = await askTts(ttsBody(said.text), { ...(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"})`); + // A BEEP needs the slur's time: the take is word-timed now (the editor's transcription). When that cannot be + // done, the read is synthesized again with the slur left out -- a published take never says one it cannot cover. + let slurs = said.slurs; + let timed = null; + if (slurs === "said" && red?.slurs?.on && red.slurs.voice === "beep") { + try { + timed = await timeTakeWords(project, rel, words, { askOp, emit }); + } catch (err) { + emit("note", { message: `${e.id}: its read could not be word-timed for the beep (${err instanceof Error ? err.message : err}) -- synthesized again with the slur left out` }); + ({ jobId, result } = await askTts(ttsBody(spokenRead(words, e, red, { voice: "skip" }).text), { ...(editor ? { editor } : {}), emit })); + slurs = "skip"; + } + } const m = await measureTake(out); const take = { file: rel, engine: result?.engine ?? eng, voice: result?.voice ?? vox, seconds: m.seconds ?? Number(result?.seconds), source: { kind: "tts", engine: result?.engine ?? eng, voice: result?.voice ?? vox, script: words }, script: words, at: new Date().toISOString(), ...(note ? { note } : {}), ...(spd !== null && eng !== "orpheus" ? { speed: spd } : {}), ...(Number.isFinite(m.lufs) ? { lufs: m.lufs } : {}), jobId, + // What its audio does with the slurs the script holds (post-slurs.mjs), and its words when timed for a beep. + ...(slurs ? { slurs } : {}), ...(timed ? { words: timed } : {}), }; const patch = { addTake: take, ...(script !== null && script !== e.narration?.script ? { script: words } : {}) }; const { result: wrote, editNotes } = await withEditNotes(project, async () => updatePostNarration(project.dir, e.id, patch, { token: await manifestToken(project.dir) })); return { take, result: wrote, editNotes }; } +/** + * A just-made take's WORD TIMINGS (for a beep over a slur it says): the editor's + * transcription of its file, aligned to the script it read (word-zoom.mjs + * scriptWordTimes) -- `posts narrate --words`' way, before the take is kept. + * Throws when the editor cannot, or hears no words. + */ +async function timeTakeWords(project, rel, script, { askOp = null, emit = () => {} } = {}) { + const { recognizedOf, wordsFileOf } = await import("./postFxCli.mjs"); + const { scriptWordTimes } = await import("umtool-report-to-video/word-zoom"); + const ask = askOp ?? (await import("umtool-report-to-video/narrate-via-editor")).askEditorOp; + const abs = path.join(project.dir, ...rel.split("/")); + const outFile = path.join(project.dir, ...wordsFileOf(rel).split("/")); + emit("note", { message: `timing ${rel}'s words for the beep (the editor's transcription)…` }); + await ask("/api/ops/transcribe", { path: abs, words: true, out: outFile }, { emit }); + const heard = recognizedOf(JSON.parse(await readFile(outFile, "utf8")), 0); + if (!heard.length) throw new Error("the transcription came back with no word timings"); + return scriptWordTimes(script, heard).words; +} + /** `umtool posts narrate …` (postsCli.mjs routes it here). */ export async function narrateCommand(project, words, flags, { json = false, dryRun = false, out = (s) => console.log(s), str }) { const manifest = await readManifest(project.dir); diff --git a/umtool/lib/report/postSlurs.test.mjs b/umtool/lib/report/postSlurs.test.mjs @@ -0,0 +1,191 @@ +// The slur filter's writer and CLI (`umtool posts slurs`), a take's read under +// each voice (skip, placeholder, beep -- word-timed, or skipped when it cannot +// be), and the uncensored take (`umtool take … --uncensored`). The slurs come +// from the shipped list; no test spells one out, and no CLI line prints one. +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { readFileSync } from "node:fs"; +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"; +import { takeCommand } from "./takeCli.mjs"; +import { PROJECT_KINDS } from "../projects/kinds.mjs"; + +const LIST = JSON.parse(readFileSync(new URL("../../report-to-video/slurs.json", import.meta.url), "utf8")); +const F = LIST.entries.find((e) => e.id === "f-slur").word; +const N = LIST.entries.find((e) => e.id === "n-word").word; +const ROOT = await mkdtemp(path.join(tmpdir(), "umtool-post-slurs-")); +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)); + await writeFile(path.join(dir, "project.json"), JSON.stringify({ kind: PROJECT_KINDS.find((k) => k.makesTakes).id, title: name }) + "\n"); + 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 slurs ls: what the cut would mask, per slur and per post, masks only -- and each read's state", async () => { + const p = await project("ls", [ + item("1", { text: `you ${F}, and ${F} again` }), + item("2", { text: "clean", quoted: { author: "Q", handle: "q", text: `a ${N}` } }), + item("3", { text: "nothing", narration: { script: `he said ${F}`, takes: [{ file: "narration/posts/3/take-1.orpheus-zac.wav", seconds: 2, script: `he said ${F}` }] } }), + item("4"), + ]); + const r = await cli(["slurs", "ls", "ls"]); + assert.equal(r.code, 0, r.err); + assert.match(r.out, /the slur filter is ON -- level all, visual blackout, voice skip/); + assert.match(r.out, /masks 4 word\(s\) in 3 post item\(s\)/); + assert.match(r.out, /f\*{5} +f-slur +×3 +in 2 post\(s\): p-1, p-3/); + assert.match(r.out, /p-2 +n\*{5} ×1 +\(quoted\.text\)/); + assert.match(r.out, /p-3 +NEEDS WORD TIMINGS/); + assert.ok(!r.out.toLowerCase().includes(F) && !r.out.toLowerCase().includes(N), "ls never prints a slur"); + const j = JSON.parse((await cli(["slurs", "ls", "--json"])).out); + assert.equal(j.total, 4); + assert.deepEqual(j.bySlur["f-slur"].posts, ["p-1", "p-3"]); + assert.equal(j.reads[0].needs, "word timings"); + // Timed: covered (silenced, as voice skip has it). + const m = await manifest(p); + m.timeline[2].narration.takes[0].words = [{ w: "he", start: 0, end: 0.3 }, { w: "said", start: 0.3, end: 0.6 }, { w: F, start: 0.6, end: 1 }]; + await writeFile(path.join(p.dir, "video.manifest.json"), JSON.stringify(m)); + assert.match((await cli(["slurs", "ls", "ls"])).out, /p-3 +silenced \(1 span\(s\)\)/); +}); + +test("posts slurs on|off|level|visual|voice|add|except|remove: one writer, refused in the build's words, the posts untouched", async () => { + const p = await project("w", [item("1", { text: `a ${F} and a zorbo` })]); + const ok = async (...a) => { + const r = await cli(["slurs", "w", ...a]); + assert.equal(r.code, 0, r.err); + assert.ok(!r.out.toLowerCase().includes(F), "no line prints a slur"); + return r.out; + }; + assert.match(await ok("off"), /OFF: this is the uncensored cut/); + assert.deepEqual((await manifest(p)).render.posts.slurs, { on: false }); + await ok("on"); + assert.equal((await manifest(p)).render.posts, undefined, "the defaults leave no key"); + await ok("level", "strong"); + await ok("visual", "placeholder"); + await ok("voice", "beep"); + assert.match(await ok("add", "zorbo"), /z\*{4} is masked in this cut/); + await ok("except", F); + assert.deepEqual((await manifest(p)).render.posts.slurs, { level: "strong", visual: "placeholder", voice: "beep", add: ["zorbo"], except: [F] }); + const red = await projectRedaction(p.dir, await manifest(p)); + assert.equal(red.slurs.visual, "placeholder"); + assert.ok(red.slurs.entries.some((e) => e.word === "zorbo")); + assert.ok(!red.slurs.entries.some((e) => e.forms.includes(F))); + await ok("remove", F); + await ok("level", "all"); + assert.deepEqual((await manifest(p)).render.posts.slurs, { visual: "placeholder", voice: "beep", add: ["zorbo"] }); + assert.equal((await cli(["slurs", "w", "add", "zorbo"])).code, 1, "already on the list"); + assert.equal((await cli(["slurs", "w", "voice", "hum"])).code, 2); + assert.equal((await cli(["slurs", "w", "remove", "nothing"])).code, 1); + assert.equal((await cli(["slurs", "w", "sideways"])).code, 2); + assert.equal((await manifest(p)).timeline[0].text, `a ${F} and a zorbo`, "the snapshot is never rewritten"); + assert.match((await cli(["slurs", "--help"])).err, /THE SLUR FILTER/); +}); + +const asker = (asked) => async (body) => { + asked.push(body); + wav(body.out, 1); + return { jobId: `job-${asked.length}`, result: { wav: body.out, engine: body.engine, voice: body.voice, seconds: 1 } }; +}; + +test("a take's read: skip leaves the slur out, placeholder says its stand-in; the take records which; the script keeps the word", async () => { + const script = `Hello, you ${F}. Welcome.`; + for (const [voice, said, state] of [["skip", "Hello, you. Welcome.", "skip"], ["placeholder", "Hello, you f-slur. Welcome.", "placeholder"]]) { + const p = await project(`r-${voice}`, [item("1", { narration: { script } })], { posts: { slurs: { voice } } }); + const asked = []; + const r = await makeTake(p, (await manifest(p)).timeline[0], { ask: asker(asked) }); + assert.equal(asked[0].text, said); + assert.equal(r.take.slurs, state); + assert.equal(r.take.script, script); + assert.equal((await manifest(p)).timeline[0].narration.takes[0].slurs, state); + } + // The filter off (an uncensored project): said, and recorded so -- a later censored cut will cover it. + const p = await project("r-off", [item("1", { narration: { script } })], { posts: { slurs: { on: false } } }); + const asked = []; + assert.equal((await makeTake(p, (await manifest(p)).timeline[0], { ask: asker(asked) })).take.slurs, "said"); + assert.equal(asked[0].text, script); + // No slur: no state. + const q = await project("r-none", [item("1", { narration: { script: "Hello there." } })]); + assert.equal((await makeTake(q, (await manifest(q)).timeline[0], { ask: asker([]) })).take.slurs, undefined); +}); + +test("a beep take: said, then word-timed so the render can beep it; when it cannot be timed, synthesized again with the slur left out", async () => { + const script = `Hello, you ${F}. Welcome.`; + const p = await project("b", [item("1", { narration: { script } })], { posts: { slurs: { voice: "beep" } } }); + const asked = []; + const ops = []; + const askOp = async (route, body) => { + ops.push(route); + await writeFile(body.out, JSON.stringify({ words: [{ w: "Hello,", start: 0, end: 0.3 }, { w: "you", start: 0.3, end: 0.5 }, { w: `${F}.`, start: 0.5, end: 0.9 }, { w: "Welcome.", start: 1, end: 1.4 }] })); + return { jobId: "t-1", result: {} }; + }; + const r = await makeTake(p, (await manifest(p)).timeline[0], { ask: asker(asked), askOp }); + assert.equal(asked.length, 1); + assert.equal(asked[0].text, script); + assert.deepEqual(ops, ["/api/ops/transcribe"]); + assert.equal(r.take.slurs, "said"); + assert.equal(r.take.words.length, 4); + assert.deepEqual(r.take.words[2], { w: `${F}.`, start: 0.5, end: 0.9 }); + // The editor cannot: the read again, the slur left out. + const q = await project("b2", [item("1", { narration: { script } })], { posts: { slurs: { voice: "beep" } } }); + const asked2 = []; + const notes = []; + const r2 = await makeTake(q, (await manifest(q)).timeline[0], { ask: asker(asked2), askOp: async () => { throw new Error("no parakeet worker"); }, emit: (_e, f) => notes.push(f.message) }); + assert.deepEqual(asked2.map((b) => b.text), [script, "Hello, you. Welcome."]); + assert.equal(r2.take.slurs, "skip"); + assert.equal(r2.take.words, undefined); + assert.match(notes.join("\n"), /could not be word-timed for the beep \(no parakeet worker\)/); +}); + +test("umtool take … --uncensored: the slur filter off in the take's patch, its label and take.json say so", async () => { + const p = await project("u", [item("1", { text: `you ${F}` })]); + await mkdir(path.join(p.dir, "out", "clips-raw"), { recursive: true }); + const seen = []; + const deps = { + render: async (job) => { + seen.push(JSON.parse(await readFile(job.manifestPath, "utf8"))); + const file = path.join(job.outDir, `${job.slug}.mp4`); + await writeFile(file, "render"); + return { file }; + }, + probe: async () => 1, + }; + const errs = []; + const io = { reportsRoot: REPORTS, log: () => {}, err: (s) => errs.push(s), deps }; + assert.equal(await takeCommand(["u", "--id", "unc", "--label", "Cut", "--full", "--uncensored"], io), 0, errs.join("\n")); + const take = JSON.parse(await readFile(path.join(p.dir, "takes", "unc", "take.json"), "utf8")); + assert.equal(take.label, "Cut (uncensored)"); + assert.equal(take.slurs, "uncensored"); + assert.deepEqual(take.patch, { render: { posts: { slurs: { on: false } } } }); + assert.equal(seen[0].render.posts.slurs.on, false); + assert.equal(await takeCommand(["u", "--id", "cen", "--label", "Cut", "--full"], io), 0, errs.join("\n")); + assert.equal(JSON.parse(await readFile(path.join(p.dir, "takes", "cen", "take.json"), "utf8")).slurs, "censored"); + // A censored take is not rebuilt uncensored: that is a take of its own. + assert.equal(await takeCommand(["u", "--id", "cen", "--rebuild", "--uncensored"], io), 2); + assert.match(errs.at(-1), /made censored/); + // The project's manifest is not touched. + assert.equal((await manifest(p)).render.posts, undefined); +}); diff --git a/umtool/lib/report/postSlursCli.mjs b/umtool/lib/report/postSlursCli.mjs @@ -0,0 +1,122 @@ +// `umtool posts slurs` -- THE SLUR FILTER of a cut's post items +// (umtool-report-to-video/post-slurs.mjs; umtool/docs/knobs.md, "The slur +// filter"): what it would mask, and its knobs. +// +// umtool posts slurs <p> [ls] what the cut would mask: per slur, per post, and each read's state +// umtool posts slurs <p> on | off the filter (off: the cut is the uncensored one) +// umtool posts slurs <p> level strong|all only the strong slurs, or the mild ones too +// umtool posts slurs <p> visual blackout|placeholder +// umtool posts slurs <p> voice skip|beep|placeholder +// umtool posts slurs <p> add <word> | except <word> | remove <word> +// +// Every write goes through updatePostSlurs (one undo point each). Nothing +// here prints a slur: a word is shown as its mask. +// +// Plain ESM: the CLI runs under bare node. +import { isNarrated, pickedTake, rootTakeOf } from "umtool-report-to-video/post-narration"; +import { SLURS_DEFAULTS, SLUR_LEVELS, SLUR_VISUALS, SLUR_VOICES, maskOfWord, slurReport, takeBleeps } from "umtool-report-to-video/post-slurs"; +import { cutSlurs } from "umtool-report-to-video/post-redact-files"; +import { readManifest } from "../projects/report.mjs"; +import { withEditNotes } from "./edit-guard.mjs"; +import { manifestToken, updatePostSlurs } from "./manifest.mjs"; + +export const SLURS_USAGE = [ + " umtool posts slurs <project> [ls] | on | off | level strong|all | visual blackout|placeholder", + " | voice skip|beep|placeholder | add <word> | except <word> | remove <word> [--json]", + " THE SLUR FILTER (render.posts.slurs; on by default): every slur on the list (umtool/report-to-video/slurs.json,", + " strong and mild; `level strong` masks only the strong) masked in what the cut PUBLISHES -- matched whole-word,", + " without case, through look-alike letters and a word spelt out. visual: blackout (the redaction's bar) or", + " placeholder (a dark pill with its mask, \"f*****\"); voice: skip (left out of a synthesized read), beep (said, a", + " tone over it by the take's word timings) or placeholder (its stand-in said, \"f-slur\"). A take that SAYS one (a", + " recording, a beep take, a take from before the filter) is silenced or beeped over it by its word timings, and", + " a censored build refuses one with none. `ls` counts what the cut would mask (masks only, never the word), per", + " slur and per post, and says which reads still need word timings. off -- or `umtool take … --uncensored` -- is", + " the uncensored cut; the redaction and censored attachments stay on. add/except/remove: the project's own words.", +].join("\n"); + +export class SlursError extends Error { + constructor(message) { + super(message); + this.name = "SlursError"; + } +} + +const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); + +/** What a cut's filter would mask, and the state of each read that holds a slur. */ +export function slursListing(manifest) { + const s = cutSlurs(manifest); + const on = { ...s, on: true }; + const tl = Array.isArray(manifest?.timeline) ? manifest.timeline : []; + const report = slurReport(tl, s); + const reads = []; + for (const e of tl) { + if (e?.type !== "post" || !isNarrated(e)) continue; + const t = pickedTake(e); + const root = rootTakeOf(e.narration.takes ?? [], t); + const state = t.slurs ?? root?.slurs ?? "said"; + const b = takeBleeps(t, on, { state, script: t.script ?? e.narration?.script }); + if (state !== "said") { + if (reportHas(report, e.id, "script")) reads.push({ id: e.id, take: t.file, state, covered: "left out of the read" }); + continue; + } + if (!b) continue; + reads.push({ id: e.id, take: t.file, state, ...(b.error ? { needs: "word timings", error: b.error } : { covered: b.mode === "beep" ? "beeped" : "silenced", spans: b.spans.length }) }); + } + return { slurs: s, report, reads }; +} + +const reportHas = (report, id, where) => report.posts.some((p) => p.id === id && p.where.includes(where)); + +/** `umtool posts slurs <p> …` */ +export async function slursCommand(project, rest, { json = false, out = (s) => console.log(s) } = {}) { + const [sub = "ls", arg] = rest; + const write = async (change) => withEditNotes(project, async () => updatePostSlurs(project.dir, change, { token: await manifestToken(project.dir) })); + const said = async (change, line) => { + const { result } = await write(change); + out(json ? JSON.stringify({ ok: true, slurs: result.slurs, token: result.token }, null, 2) : `${project.id}: ${line}`); + return 0; + }; + const one = (list, what) => { + if (!arg || !list.includes(arg)) throw new SlursError(`posts slurs ${sub} takes ${list.join(" or ")}${arg ? ` (not ${arg})` : ""}`); + return arg; + }; + if (sub === "on") return said({ set: { on: null } }, "the slur filter is on (the default): the cut publishes its post items censored"); + if (sub === "off") return said({ set: { on: false } }, "the slur filter is OFF: this is the uncensored cut (the redaction and censored attachments stay on)"); + if (sub === "level") return said({ set: { level: one(SLUR_LEVELS) === SLURS_DEFAULTS.level ? null : arg } }, `level ${arg}: ${arg === "strong" ? "only the strong slurs are masked" : "strong and mild slurs are masked"}`); + if (sub === "visual") return said({ set: { visual: one(SLUR_VISUALS) === SLURS_DEFAULTS.visual ? null : arg } }, `visual ${arg}: ${arg === "blackout" ? "a solid bar, as a redacted word" : "a dark pill with the masked form"}`); + if (sub === "voice") return said({ set: { voice: one(SLUR_VOICES) === SLURS_DEFAULTS.voice ? null : arg } }, `voice ${arg}: ${arg === "skip" ? "left out of a synthesized read" : arg === "beep" ? "said, with a beep over it (the take's word timings)" : "its stand-in said in its place"}`); + if (sub === "add" || sub === "except" || sub === "remove") { + if (!arg || !/^[A-Za-z][A-Za-z-]{1,39}$/.test(arg)) throw new SlursError(`posts slurs ${sub} takes a word (letters, 2–40)`); + const what = sub === "add" ? "masked in this cut" : sub === "except" ? "never masked in this cut" : "off the project's lists"; + return said({ [sub]: arg }, `${maskOfWord(arg.toLowerCase())} is ${what}`); + } + if (sub !== "ls") throw new SlursError(`posts slurs: ls, on, off, level, visual, voice, add, except or remove (not ${sub})`); + const manifest = await readManifest(project.dir); + if (!manifest) throw new SlursError(`${project.id} has no manifest`); + const { slurs: s, report, reads } = slursListing(manifest); + const cfg = isObj(manifest.render?.posts?.slurs) ? manifest.render.posts.slurs : {}; + if (json) { + out(JSON.stringify({ ok: true, on: s.on, level: s.level, visual: s.visual, voice: s.voice, listed: s.entries.length, add: (cfg.add ?? []).length, except: (cfg.except ?? []).length, total: report.total, bySlur: report.bySlur, posts: report.posts, reads }, null, 2)); + return 0; + } + out( + `${project.id}: the slur filter is ${s.on ? "ON" : "OFF (the uncensored cut)"} -- level ${s.level}, visual ${s.visual}, voice ${s.voice}` + + ` (${s.entries.length} slur(s) listed${cfg.add?.length ? `, ${cfg.add.length} of its own` : ""}${cfg.except?.length ? `, ${cfg.except.length} excepted` : ""})`, + ); + if (!report.total) { + out(" no post item of the cut holds a slur on the list"); + return 0; + } + out(` it ${s.on ? "masks" : "would mask"} ${report.total} word(s) in ${report.posts.length} post item(s):`); + const rows = Object.entries(report.bySlur).sort((a, b) => b[1].n - a[1].n); + for (const [id, b] of rows) out(` ${b.mask.padEnd(10)} ${id.padEnd(18)} ×${String(b.n).padEnd(4)} in ${b.posts.length} post(s): ${b.posts.slice(0, 8).join(", ")}${b.posts.length > 8 ? ", …" : ""}`); + out(" per post item:"); + for (const p of report.posts) out(` ${p.id.padEnd(22)} ${Object.entries(p.hits).map(([id, n]) => `${report.bySlur[id]?.mask ?? id} ×${n}`).join(", ")} (${p.where.join(", ")})`); + if (reads.length) { + const need = reads.filter((r) => r.needs); + out(` the reads: ${reads.length} narrated post(s) hold a slur in their read -- ${reads.filter((r) => r.covered).length} covered, ${need.length} need word timings`); + for (const r of reads) out(` ${r.id.padEnd(22)} ${r.needs ? `NEEDS WORD TIMINGS (a censored build refuses it): umtool posts narrate ${project.id} ${r.id} --words` : `${r.covered}${r.spans ? ` (${r.spans} span(s))` : ""}`}`); + } + return 0; +} diff --git a/umtool/lib/report/postsCli.mjs b/umtool/lib/report/postsCli.mjs @@ -36,6 +36,15 @@ import { withEditNotes } from "./edit-guard.mjs"; import { PostsRefused, StaleToken, StructureRefused, addArchiveAvatars, manifestToken, setPostAvatar, updatePostItem, updatePostRedact, updatePosts, upsertPost } from "./manifest.mjs"; import { postWarnings } from "./postCards.mjs"; +// `umtool posts slurs` (postSlursCli.mjs SLURS_USAGE): its lines, kept here so the usage is one block. +const SLURS_USAGE_LINES = [ + " umtool posts slurs <project> [ls] | on | off | level strong|all | visual blackout|placeholder", + " | voice skip|beep|placeholder | add <word> | except <word> | remove <word> [--json]", + " THE SLUR FILTER (render.posts.slurs, on by default): the list's slurs masked in what the cut publishes (a bar or", + " a placeholder pill on the card; left out, beeped or a stand-in in the read); `ls` counts what it masks (masks", + " only), off or `umtool take … --uncensored` is the uncensored cut. umtool posts slurs --help: the whole story.", +]; + export const POSTS_USAGE = [ "usage: umtool posts add <project> <archive-channel>/<postId> [--attach <clipId>] [--flag F] [--author A] [--id ID]", " [--thread] [--crop <px>] [--dry-run] [--json]", @@ -87,6 +96,7 @@ export const POSTS_USAGE = [ " 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).", + ...SLURS_USAGE_LINES, " umtool posts context <project> [--dry-run] [--json]", " every post item's CONTEXT from its capture (capture.json's `context`: the post it quotes, the post it answers, as", " its page showed them) where the archive row lacks it -- one write (one undo point). A post whose capture read", @@ -394,6 +404,17 @@ export async function postsCommand(args, { root = REPORTS_ROOT, out = (s) => con 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 === "slurs") { + // The slur filter (postSlursCli.mjs): its own words refused as a usage error. + const { SLURS_USAGE, slursCommand } = await import("./postSlursCli.mjs"); + if (!projectArg || flags.has("--help")) { + err(SLURS_USAGE); + return 2; + } + return await slursCommand(await projectOf(projectArg, root), words.slice(2), { json, out }).catch((e) => { + throw e?.name === "SlursError" ? new CliError(e.message) : e; + }); + } 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 }); diff --git a/umtool/lib/report/takeCli.mjs b/umtool/lib/report/takeCli.mjs @@ -42,7 +42,7 @@ export const TAKE_USAGE = [ "usage: umtool take <project> --id <id> --label \"<label>\" [--group G] [--kind similar|different]", " [--summary S] [--style NAME] [--patch FILE | --patch-json JSON | --set path=value …]", " [--effect NAME] [--at S --dur S | --full] [--quick] [--force] [--progress ndjson]", - " [--from TAKE] [--keep-frames] [--priority]", + " [--from TAKE] [--keep-frames] [--priority] [--uncensored]", " umtool take <project> --id <id> --rebuild [--at S --dur S | --full] [--from TAKE] [--keep-frames] [--priority]", " made again from its own take.json (its stored patch, walked edits included); a window", " flag renders it over that window instead of its own", @@ -71,6 +71,10 @@ export const TAKE_USAGE = [ "and download lanes are held (only the ones not held already), and both end with the take — done,", "failed or stopped. Close Firefox and other heavy apps while it renders. A take started inside a", "`umtool render-mode on` window renders in that window, flag or not.", + "--uncensored renders the UNCENSORED cut: the post items' slur filter off (render.posts.slurs.on false in the", + "take's patch, so a --rebuild keeps it; post-slurs.mjs) -- the slurs drawn and played as posted. The redaction", + "of private words and a censored attachment stay on. Its label says \"(uncensored)\" and take.json's `slurs`", + "records which cut it is (censored | uncensored).", ].join("\n"); export const TAKES_USAGE = [ @@ -104,6 +108,9 @@ export const TAKES_USAGE = [ class CliError extends Error {} +/** A take's patch for the uncensored cut: the slur filter off (post-slurs.mjs). */ +export const UNCENSORED_PATCH = Object.freeze({ render: { posts: { slurs: { on: false } } } }); + /** The flags of one command line. */ function parse(args) { const valued = new Set([ @@ -244,6 +251,7 @@ export async function takeCommand(args, { reportsRoot = REPORTS_ROOT, log = cons let spec; if (fromStored) { if (!prev) throw new CliError(`${project.id} has no take ${id} to rebuild`); + if (p.has("--uncensored") && prev.patch?.render?.posts?.slurs?.on !== false) throw new CliError(`${id} was made censored: --uncensored makes a take of its own (a new --id), not a rebuild of this one`); spec = { id, label: p.one("--label") ?? prev.label, @@ -269,6 +277,11 @@ export async function takeCommand(args, { reportsRoot = REPORTS_ROOT, log = cons quick: p.has("--quick"), }; } + // THE UNCENSORED CUT (post-slurs.mjs): the slur filter off in the take's own patch; the redaction stays. + if (p.has("--uncensored") && !fromStored) { + spec.patch = mergePatch(spec.patch ?? {}, UNCENSORED_PATCH); + if (spec.label && !/uncensored/i.test(spec.label)) spec.label = `${spec.label} (uncensored)`; + } if (draft) { const d = await draftTake(project.dir, spec, { force: p.has("--force"), ...(deps?.styles ? { styles: /** @type {any} */ (deps.styles) } : {}) }); if (p.has("--json")) { diff --git a/umtool/lib/report/takeMaker.mjs b/umtool/lib/report/takeMaker.mjs @@ -49,6 +49,7 @@ import path from "node:path"; import { pathToFileURL } from "node:url"; import { mergePatch } from "umtool-report-to-video/montage-styles"; import { postItemSeconds } from "umtool-report-to-video/post-item"; +import { cutSlurState } from "umtool-report-to-video/post-slurs"; import { applyMontageRulings, readMontageRulings, rulingsLines } from "umtool-report-to-video/montage-rulings"; import { markKeepFrames } from "umtool-report-to-video/prune-frames"; import { PIPELINE_DIR, RENDER_BUDGET, UMTOOL_DIR } from "./driver.mjs"; @@ -739,6 +740,8 @@ async function makeTakeLocked(projectDir, rawSpec, opts) { ...(opts.from ? { from: opts.from } : {}), // The render's own time, for the next take's ETA (takeEta.mjs). renderSeconds, + // Which cut its post items are (post-slurs.mjs): censored, or the uncensored one (`umtool take … --uncensored`). + ...(cutSlurState(manifest) ? { slurs: cutSlurState(manifest) } : {}), }; const tmp = `${takeFile}.tmp-${process.pid}`; await writeFile(tmp, JSON.stringify(doc, null, 2) + "\n", "utf8"); diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs @@ -66,6 +66,10 @@ // --narration-unreviewed Build narrated cards the narration review has not // approved (unreviewed, or edited since); a rejected one // still refuses. Without a review file nothing is held. +// --uncensored The post items' SLUR FILTER off (post-slurs.mjs, +// render.posts.slurs): their slurs drawn and played as +// posted. The redaction and a censored attachment stay on. +// A take does it with its patch (umtool take … --uncensored). // --final The deliverable (the driver's `final` preset passes it): // every DRAFTED field (drafts-review.mjs) must be approved // on its current value -- unapproved or rejected refuses. @@ -6151,7 +6155,12 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly }); 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; + POST_REDACTION = (manifest.timeline ?? []).some((e) => e?.type === "post") ? await readPostRedaction(channelsDir, manifest, { uncensored: opts.uncensored === true }) : null; + // Which cut this is (post-slurs.mjs): censored, or the uncensored one. + if (POST_REDACTION?.slurs) { + const sl = POST_REDACTION.slurs; + EMIT("note", { message: sl.on ? `slur filter: on (level ${sl.level}, visual ${sl.visual}, voice ${sl.voice})` : `slur filter: OFF -- the uncensored cut${sl.uncensored ? " (--uncensored)" : " (render.posts.slurs.on false)"}; the redaction stays on` }); + } // 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); @@ -7063,6 +7072,7 @@ async function main() { " [--lint] [--no-lint] (lint the manifest and stop / build without the lint)\n" + " [--no-rulings] (build as if there were no montage-rulings.json beside the manifest)\n" + " [--narration-unreviewed] (build narrated cards the review has not approved; never a rejected one)\n" + + " [--uncensored] (the post items' slur filter off, render.posts.slurs; the redaction and the censored attachments stay)\n" + " [--final] [--drafts-unreviewed] (the deliverable: drafted fields must be approved / build the unapproved anyway)\n" + " [--site-origin <url>] [--resolve-site-ids] [--cue-source auto|local|http]\n" + " [--thumbnail] (render.brand only: out/<slug>.thumbnail.png and stop)", @@ -7102,6 +7112,7 @@ async function main() { noLint: argv.includes("--no-lint"), noRulings: argv.includes("--no-rulings"), narrationUnreviewed: argv.includes("--narration-unreviewed"), + uncensored: argv.includes("--uncensored"), final: argv.includes("--final"), draftsUnreviewed: argv.includes("--drafts-unreviewed"), short: flag("--short") ?? null, diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json @@ -66,6 +66,7 @@ "./post-censor": "./post-censor.mjs", "./post-redact": "./post-redact.mjs", "./post-redact-files": "./post-redact-files.mjs", + "./post-slurs": "./post-slurs.mjs", "./post-render": "./post-render.mjs", "./word-zoom": "./word-zoom.mjs", "./presets": "./presets.mjs", diff --git a/umtool/report-to-video/post-narration.mjs b/umtool/report-to-video/post-narration.mjs @@ -163,7 +163,7 @@ const MIX_KEYS = ["lead", "tail", "ramp", "linger", "clip", "wet", "lowpassHz", // `attach` is one post's (it decides the card's layout, which is drawn from the entry alone). const RENDER_KEYS = new Set([...MIX_KEYS.filter((k) => k !== "attach"), "engine", "voice"]); const ITEM_KEYS = new Set([...MIX_KEYS, "script", "excerpt", "engine", "voice", "speed", "takes", "pick", "approved", "off", "window"]); -const TAKE_KEYS = new Set(["file", "engine", "voice", "seconds", "script", "at", "note", "speed", "lufs", "jobId", "parts", "label", "source", "steps", "words"]); +const TAKE_KEYS = new Set(["file", "engine", "voice", "seconds", "script", "at", "note", "speed", "lufs", "jobId", "parts", "label", "source", "steps", "words", "slurs"]); const STEP_KEYS = new Set(["op", "engine", "voice", "params", "ranAt", "job"]); const PART_KEYS = new Set(["n", "para", "text", "file", "start", "seconds", "gapBefore", "note", "at", "jobId"]); const VOICE_RE = /^[A-Za-z0-9][A-Za-z0-9_.+-]{0,63}$/; @@ -525,6 +525,8 @@ export function validatePostNarration(e) { ); if (!ok) errors.push(`${tw}.source must be {kind: "tts", engine, voice}, {kind: "recorded", voice} or {kind: "take", from: <one of its takes' id>}`); } + // What its audio does with the slurs its script holds (post-slurs.mjs): said (a beep or a mute covers them), left out, or a stand-in said. + if (t.slurs !== undefined && !["said", "skip", "placeholder"].includes(t.slurs)) errors.push(`${tw}.slurs must be said, skip or placeholder`); if (t.words !== undefined) { // Its script's words, timed in take seconds (the editor's transcription, aligned: word-zoom.mjs scriptWordTimes). const ws = t.words; diff --git a/umtool/report-to-video/post-redact-files.mjs b/umtool/report-to-video/post-redact-files.mjs @@ -78,6 +78,7 @@ async function readJson(file) { export async function readPostRedaction(channelsDir, manifest, { uncensored = false } = {}) { const project = projectRedactOf(manifest?.render); const terms = []; + /** @type {Record<string, any>} */ const markup = {}; if (channelsDir) { const file = corpusRedactionsPath(channelsDir); diff --git a/umtool/report-to-video/post-render.mjs b/umtool/report-to-video/post-render.mjs @@ -19,8 +19,9 @@ import { mkdir, readFile, rename, stat, writeFile } from "node:fs/promises"; import path from "node:path"; import { pathToFileURL } from "node:url"; 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 { redactEntry, redactionOn, spokenWithout, termsFor } from "./post-redact.mjs"; +import { isNarrated, narrationLevelDb, pickedTake, postNarrationFilters, rootTakeOf } from "./post-narration.mjs"; +import { redactEntry, redactionOn, shownLine, termsFor } from "./post-redact.mjs"; +import { bleepFilters, slursOn, takeBleeps } from "./post-slurs.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"; @@ -192,7 +193,10 @@ export function postSegmentArgs({ entry, box, plan, layout, cards, files, render } else parts.push(`[${sil}:a]anull[${media}]`); if (media === "pm") { const vi = add(["-i", narration.file]); - parts.push(...postNarrationFilters({ media: "pm", voice: `${vi}:a`, out: "a", sch: plan.narration, gainDb: narration.gainDb ?? 0, audioRate: render.audioRate ?? 48000 })); + // A take that says a slur the cut masks (post-slurs.mjs takeBleeps): silenced or beeped over it, on the take's own clock. + const bl = narration.bleeps?.spans?.length ? bleepFilters(`${vi}:a`, "pnbl", narration.bleeps, { audioRate: render.audioRate ?? 48000, seconds: narration.bleeps.seconds ?? 600 }) : []; + parts.push(...bl); + parts.push(...postNarrationFilters({ media: "pm", voice: bl.length ? "pnbl" : `${vi}:a`, out: "a", sch: plan.narration, gainDb: narration.gainDb ?? 0, audioRate: render.audioRate ?? 48000 })); } return [ "-nostdin", "-v", "error", "-y", @@ -381,13 +385,15 @@ export async function buildPostSegment(entry, { render, outDir, manifestDir, box const take = isNarrated(entry) ? pickedTake(entry) : null; const takeFile = take ? path.resolve(manifestDir, take.file) : null; if (takeFile && !(await stat(takeFile).catch(() => null))) throw new Error(`${entry.id}: its narration take is not on disk: ${takeFile} (${take.file})`); + // The slurs its take SAYS, covered (post-slurs.mjs): a public render never plays one -- without word timings it is refused. + const bleeps = take ? takeSlurBleeps(entry, take, redaction) : null; const stamps = await Promise.all([...files, ...wordFiles.filter(Boolean), ...Object.values(avatars), ...(takeFile ? [takeFile] : []), ...(entry.parentShot ? [path.resolve(manifestDir, entry.parentShot)] : [])].map(async (f) => { const st = await stat(f).catch(() => null); return st ? `${f}:${st.size}:${Math.round(st.mtimeMs)}` : `${f}:-`; })); const key = createHash("sha256") // 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 } : {}) })) + .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 } : {}), ...(bleeps ? { bleeps } : {}), ...(slursOn(redaction?.slurs) ? { slurs: redaction.slurs } : {}) })) .digest("hex"); const record = postRecordPath(seg); const had = await readFile(record, "utf8").then((t) => JSON.parse(t), () => null); @@ -407,8 +413,8 @@ export async function buildPostSegment(entry, { render, outDir, manifestDir, box const wf = wordFiles[m.i]; if (!wf) continue; 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)) }; + // A redacted term is left out of the burnt-in words, as it is left out of a read; a slur masked (post-slurs.mjs). + const c = { ...c0, text: shownLine(c0.text, entry, redaction) }; if (!c.text.trim()) continue; const textfile = path.join(cardDir, `cue-${si}-${ci}.txt`); await writeFile(textfile, c.text, "utf8"); @@ -419,7 +425,7 @@ export async function buildPostSegment(entry, { render, outDir, manifestDir, box let narration = null; if (take) { const lufs = Number.isFinite(take.lufs) ? take.lufs : await measureLufsOf(takeFile, { exec, ffmpeg }); - narration = { file: takeFile, gainDb: narrationLevelDb(lufs, plan.narration.lufs), lufs }; + narration = { file: takeFile, gainDb: narrationLevelDb(lufs, plan.narration.lufs), lufs, ...(bleeps ? { bleeps } : {}) }; } const argv = postSegmentArgs({ entry, box, plan, layout, cards, files, render, place, encode, captions, fontfile: render.fontBold ?? render.fontRegular ?? null, outPath: tmp, narration, zooms }); try { @@ -429,7 +435,7 @@ export async function buildPostSegment(entry, { render, outDir, manifestDir, box throw new Error(`${entry.id}: ffmpeg failed on the post item\n${detail}`); } await rename(tmp, seg); - await writeFile(record, JSON.stringify({ version: 1, id: entry.id, key, layout: layout.mode, total: plan.total, steps: plan.steps.length, ...(zooms.length ? { zooms: zooms.map((z) => ({ i: z.i, at: z.t, source: z.source, span: z.span, region: z.region, word: z.word })) } : {}), ...(narration ? { narration: { take: take.file, ...plan.narration, gainDb: narration.gainDb, measured: narration.lufs } } : {}) }, null, 2) + "\n", "utf8"); + await writeFile(record, JSON.stringify({ version: 1, id: entry.id, key, layout: layout.mode, total: plan.total, steps: plan.steps.length, ...(zooms.length ? { zooms: zooms.map((z) => ({ i: z.i, at: z.t, source: z.source, span: z.span, region: z.region, word: z.word })) } : {}), ...(narration ? { narration: { take: take.file, ...plan.narration, gainDb: narration.gainDb, measured: narration.lufs, ...(bleeps ? { slurs: { mode: bleeps.mode, spans: bleeps.spans } } : {}) } } : {}) }, null, 2) + "\n", "utf8"); emit("note", { message: narration ? `${entry.id}: post item ${plan.total.toFixed(1)} s, narrated (${take.file}: ${plan.narration.seconds.toFixed(1)} s from ${plan.narration.at} s, muffled to ${plan.narration.voiceEnd.toFixed(1)} s)` @@ -439,6 +445,26 @@ export async function buildPostSegment(entry, { render, outDir, manifestDir, box return seg; } +/** + * The slurs post item `entry`'s take says that the cut masks, as its bleeps + * (`{ mode, spans, seconds }`, post-slurs.mjs takeBleeps), or null. Its + * audio's state is its own `slurs`, else its source take's (a derived take + * reads what its source read). Throws, in the build's words, when the take + * says one it has no word timings to find. + */ +export function takeSlurBleeps(entry, take, redaction) { + const takes = Array.isArray(entry?.narration?.takes) ? entry.narration.takes : []; + const root = rootTakeOf(takes, take); + const b = takeBleeps(take, redaction?.slurs, { state: take.slurs ?? root?.slurs ?? null }); + if (b?.error) { + throw new Error( + `${entry.id}: ${b.error} -- a published cut never plays a slur: time its words (umtool posts narrate <p> ${entry.id} --words), ` + + `synthesize a take without it (umtool posts narrate <p> ${entry.id} --take; the filter's voice skip or placeholder), or render the uncensored cut (--uncensored)`, + ); + } + return b ? { ...b, seconds: take.seconds } : null; +} + /** A sound's integrated loudness (EBU R128, LUFS) by ffmpeg's ebur128 through `exec`; null when silent or unread. */ export async function measureLufsOf(file, { exec, ffmpeg = "ffmpeg" }) { try {