Archilyzer · Source

archilyzer

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

commit 56f45d32dd141ad5633c4bf2f29695fc4c009133
parent 47386ef525a5a7fbdac0d521f3339d99050e4157
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Tue,  3 Nov 2026 16:59:08 -0500

umtool: a SLUR FILTER on top of the redaction -- a default list as data (slurs.json: each slur's forms, strong or mild, its mask and its spoken stand-in), matched whole-word without case through look-alike letters (@, 0, * for a vowel) and a word spelt out letter by letter; masked only where a cut is published (operator: "add a censor-slurs feature ... that can be turned off for an uncensored cut")

render.posts.slurs {on (default true), level all|strong, add, except, visual blackout|placeholder,
voice skip|beep|placeholder}, resolved over the list by post-redact-files.mjs (readPostRedaction's
`slurs`; `{uncensored: true}` turns it off and leaves the redaction on). redactEntry masks a post's
words, names and context with it: blackout draws the redaction's bar, placeholder a dark pill with
the mask ("f*****", first letter in the text's case) -- the word never in the card's HTML; a slur
spelt apart keeps its tokens (the card's word indices hold). spokenRead says what a voice reads
(skip / the stand-in / said, for the render's beep); shownLine a caption's words; takeBleeps the
spans of a take that says one (from its word timings; refused without them) and bleepFilters the
mute or tone over them. slurReport counts what a cut would mask. The data is never rewritten.

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

Diffstat:
Mumtool/lib/report/postRedaction.mjs | 5+++--
Mumtool/report-to-video/post-redact-files.mjs | 39++++++++++++++++++++++++++++++++++++---
Mumtool/report-to-video/post-redact.mjs | 95+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------
Aumtool/report-to-video/post-slurs.mjs | 414+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/post-slurs.test.mjs | 184+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/slurs.json | 21+++++++++++++++++++++
6 files changed, 744 insertions(+), 14 deletions(-)

diff --git a/umtool/lib/report/postRedaction.mjs b/umtool/lib/report/postRedaction.mjs @@ -8,8 +8,9 @@ import { channelsDirFor, hasShadowChannels } from "../projects/report.mjs"; /** * @param {string} dir the project's folder * @param {Record<string, any>} manifest + * @param {{ uncensored?: boolean }} [o] the slur filter off (post-slurs.mjs), the redaction kept */ -export async function projectRedaction(dir, manifest) { +export async function projectRedaction(dir, manifest, { uncensored = false } = {}) { const channelsDir = channelsDirFor(dir, manifest, { shadowExists: await hasShadowChannels(dir) }); - return readPostRedaction(channelsDir, manifest); + return readPostRedaction(channelsDir, manifest, { uncensored }); } diff --git a/umtool/report-to-video/post-redact-files.mjs b/umtool/report-to-video/post-redact-files.mjs @@ -1,5 +1,6 @@ // 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 +// each post's channel markup and the project's own list, read together, and +// the cut's slur filter. Read // only -- the corpus's two files are the editor's to write. // // <transcripts>/redactions.json [{ term, wholeWord?, note? }] (or { terms: […] }) @@ -8,9 +9,40 @@ // 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. +// +// And the SLUR FILTER (post-slurs.mjs): the default list shipped beside this +// module (slurs.json) under the project's `render.posts.slurs` -- off for an +// uncensored cut (`{ uncensored: true }`: build-video's --uncensored, Play's +// Uncensored), the redaction itself untouched by it. +import { readFileSync } from "node:fs"; import { readFile } from "node:fs/promises"; import path from "node:path"; +import { fileURLToPath } from "node:url"; import { normalizeTerms, projectRedactOf, validatePostsMarkup, validateRedactTerms } from "./post-redact.mjs"; +import { resolveSlurs, slurListErrors } from "./post-slurs.mjs"; + +const HERE = path.dirname(/* turbopackIgnore: true */ fileURLToPath(import.meta.url)); +/** The slur filter's default list. */ +export const SLURS_FILE = path.join(/* turbopackIgnore: true */ HERE, "slurs.json"); +let SLUR_LIST = null; + +/** The default slur list (slurs.json), read once; a list that does not parse or is refused FAILS (a public render does not run without its filter). */ +export function defaultSlurList() { + if (SLUR_LIST) return SLUR_LIST; + let doc; + try { + doc = JSON.parse(readFileSync(/* turbopackIgnore: true */ SLURS_FILE, "utf8")); + } catch (e) { + throw new Error(`${SLURS_FILE} does not read (${e instanceof Error ? e.message : e}) -- a public render does not run without its slur filter`); + } + const errors = slurListErrors(doc); + if (errors.length) throw new Error(`${SLURS_FILE} is refused: ${errors.join("; ")}`); + SLUR_LIST = doc; + return doc; +} + +/** The cut's slur filter: its `render.posts.slurs` over the default list. */ +export const cutSlurs = (manifest, { uncensored = false } = {}) => resolveSlurs(manifest?.render?.posts?.slurs, defaultSlurList(), { uncensored }); export const CORPUS_REDACTIONS_FILE = "redactions.json"; export const POSTS_MARKUP_FILE = "posts-markup.json"; @@ -41,8 +73,9 @@ async function readJson(file) { * * @param {string|null} channelsDir * @param {Record<string, any>} manifest + * @param {{ uncensored?: boolean }} [o] the slur filter off (the redaction kept) */ -export async function readPostRedaction(channelsDir, manifest) { +export async function readPostRedaction(channelsDir, manifest, { uncensored = false } = {}) { const project = projectRedactOf(manifest?.render); const terms = []; const markup = {}; @@ -67,5 +100,5 @@ export async function readPostRedaction(channelsDir, manifest) { } } terms.push(...normalizeTerms(project)); - return { terms, markup }; + return { terms, markup, slurs: cutSlurs(manifest, { uncensored }) }; } diff --git a/umtool/report-to-video/post-redact.mjs b/umtool/report-to-video/post-redact.mjs @@ -29,6 +29,7 @@ // // PURE (the build, the route, Play and the writers). import { censorMarkupErrors } from "./post-censor.mjs"; +import { BLACKOUT_MARK, SLUR_CSS, decodePlaceholder, hasSlurMarks, maskSlurs, placeholdersHtml, sayFor, slurMatches, slursOn, validateSlursRender } from "./post-slurs.mjs"; /** The mark a redacted code unit becomes (a private-use character: never typed, never drawn as a letter). */ export const REDACT_MARK = ""; @@ -110,8 +111,8 @@ export function redactText(text, terms, { spans: extra = [] } = {}) { 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); +/** Does `text` hold a redacted match (or a masked slur, post-slurs.mjs)? */ +export const hasMarks = (text) => str(text).includes(REDACT_MARK) || hasSlurMarks(text); /** * Marked text with the marks DROPPED, as a read or a line of text says it: @@ -120,8 +121,10 @@ export const hasMarks = (text) => str(text).includes(REDACT_MARK); * at a sentence's start -- taken away. Only around a mark; the rest verbatim. */ export function dropMarks(marked) { + // A masked slur (post-slurs.mjs): its placeholder read as its mask, the gaps of one spelt apart gone. + const unmasked = decodePlaceholder(str(marked).replace(/[ \t]*\uE0FF/g, "")); // A phrase's marks with its spaces between them are one run to drop. - const parts = str(marked).split(/\uE000(?:[\s\uE000]*\uE000)?/); + const parts = unmasked.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) { @@ -150,10 +153,10 @@ 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>`); + placeholdersHtml(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; }`; +export const BAR_CSS = (fg) => `.rbar { display: inline-block; height: 0.92em; vertical-align: -0.12em; background: ${fg}; border-radius: 0.12em; }\n${SLUR_CSS(fg)}`; // --------------------------------------------------------------------------- // The project's list and a post's markup. @@ -184,8 +187,8 @@ export function validateRedactTerms(list, where = "render.posts.redact") { 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); + if (!isObj(p)) return ["render.posts must be an object ({redact, slurs})"]; + return [...validateRedactTerms(p.redact), ...validateSlursRender(p.slurs)]; } /** Every reason a channel's posts-markup.json is refused. */ @@ -221,11 +224,13 @@ export function validatePostsMarkup(doc, where = "posts-markup.json") { * 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 + * and `slurs`, the cut's SLUR FILTER (post-slurs.mjs resolveSlurs: its list, on or off). + * + * @typedef {{ terms: Array<{term: string, wholeWord?: boolean}>, markup?: Record<string, {redact: any[]}>, slurs?: ReturnType<typeof import("./post-slurs.mjs").resolveSlurs> | null }} Redaction */ /** Is there anything to blank? */ -export const redactionOn = (red) => !!red && (normalizeTerms(red.terms).length > 0 || Object.keys(red.markup ?? {}).length > 0); +export const redactionOn = (red) => !!red && (normalizeTerms(red.terms).length > 0 || Object.keys(red.markup ?? {}).length > 0 || slursOn(red.slurs)); /** The terms that apply to post item `entry` in `scope` (everywhere, then its markup's). */ export function termsFor(entry, red, scope = null) { @@ -271,5 +276,77 @@ export function redactEntry(entry, red) { 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 slurEntry(out, red?.slurs); +} + +/** + * A post item's words with every SLUR masked (post-slurs.mjs maskSlurs) as + * the filter's `visual` draws them: its words, its author's name, the repost + * line's, the posts it answers and quotes (their words, a paraphrase, their + * names). Handles are left as they are (they are what the card's rules match + * on). A copy; the entry itself when the filter is off. + */ +export function slurEntry(entry, slurs) { + if (!slursOn(slurs) || !isObj(entry)) return entry; + const m = (v) => (typeof v === "string" ? maskSlurs(v, slurs).text : v); + const ref = (r) => (isObj(r) ? { ...r, ...("author" in r ? { author: m(r.author) } : {}), ...("text" in r ? { text: m(r.text) } : {}), ...("paraphrase" in r ? { paraphrase: m(r.paraphrase) } : {}) } : r); + const out = { ...entry, text: m(entry.text) }; + if ("author" in out) out.author = m(out.author); + if (isObj(entry.repostedBy)) out.repostedBy = { ...entry.repostedBy, author: m(entry.repostedBy.author) }; + if (Array.isArray(entry.parents)) out.parents = entry.parents.map(ref); + if (isObj(entry.quoted)) out.quoted = ref(entry.quoted); return out; } + +// --------------------------------------------------------------------------- +// What is SAID and what a line of text SHOWS, the redaction and the slur filter together. +// --------------------------------------------------------------------------- + +/** + * The words a voice is asked to SAY for `text` (a post item's script): every + * redacted term left out, and each slur as the filter's voice has it -- skip, + * left out as a redacted term is; placeholder, its stand-in said ("f-slur"); + * beep, said (the render lays the beep over it by the take's word timings, + * post-render.mjs). Returns `{ text, slurs }`: `slurs` is what the take's + * audio will do with them (take.slurs: "said" | "skip" | "placeholder"), null + * when the text holds none. + * + * @param {string} text + * @param {Record<string, any>} entry + * @param {Redaction|null|undefined} red + * @param {{ voice?: "skip"|"beep"|"placeholder" }} [o] the voice to use (default the filter's) + */ +export function spokenRead(text, entry, red, { voice = undefined } = {}) { + const s = red?.slurs; + const terms = termsFor(entry, red); + const t = str(text); + const hits = s ? slurMatches(t, s) : []; + if (!hits.length) return { text: spokenWithout(t, terms), slurs: null }; + const v = voice ?? s.voice; + if (!slursOn(s) || v === "beep") return { text: spokenWithout(t, terms), slurs: "said" }; + if (v === "placeholder") { + let said = ""; + let at = 0; + for (const h of hits) { + said += t.slice(at, h.start) + sayFor(s, h); + at = h.end; + } + return { text: spokenWithout(said + t.slice(at), terms), slurs: "placeholder" }; + } + const marked = redactText(t, terms, { spans: hits }); + return { text: marked.spans.length ? dropMarks(marked.text) : t, slurs: "skip" }; +} + +/** + * A line of text as published (an attachment's burnt-in caption): a + * redacted term left out; a slur, blacked out, left out too, or drawn as its + * mask (placeholder). + */ +export function shownLine(text, entry, red) { + const r = redactText(text, termsFor(entry, red)); + const masked = slursOn(red?.slurs) ? maskSlurs(r.text, red.slurs).text : r.text; + return masked === str(text) ? str(text) : dropMarks(masked); +} + +/** The redaction's mark is the blackout's (post-slurs.mjs draws a blacked-out slur with the redaction's bar). */ +export const MARKS_AGREE = BLACKOUT_MARK === REDACT_MARK; diff --git a/umtool/report-to-video/post-slurs.mjs b/umtool/report-to-video/post-slurs.mjs @@ -0,0 +1,414 @@ +// THE SLUR FILTER (operator, 3 Nov: "add a censor-slurs feature ... that can +// be turned off for an uncensored cut -- black out the visual and skip the +// word in narration, or maybe replace it with a TOS friendly but similar +// placeholder visually distinct on the tweet"). umtool/docs/knobs.md, "The +// slur filter". +// +// Built on the REDACTION (post-redact.mjs): like it, it changes only what is +// PUBLISHED -- the rendered card, the read a voice synthesizes or the take +// that plays, a chapter line, an attachment's burnt-in captions -- and never +// the archive's rows, the manifest's snapshot or a script. Unlike it, it is a +// LIST OF SLURS shipped as data (slurs.json: each slur's forms, a level, its +// masked form and its spoken stand-in), matched whole-word and without case, +// through the common ways of writing one past a filter (a letter swapped for +// a look-alike -- "@" for a, "0" for o, "*" for a vowel -- or the word spelt +// out letter by letter with a space, dot, dash or underscore between). +// +// render.posts.slurs = { +// on?: true (default) | false false: the uncensored cut +// level?: "all" (default) | "strong" strong: only the strong slurs +// add?: ["<word>" | {word, forms?, mask?, say?}] the project's own (always masked) +// except?: ["<form or word>"] never masked in this project +// visual?: "blackout" (default) the redaction's solid bar +// | "placeholder" a dark pill with the masked form ("f*****") +// voice?: "skip" (default) left out of a synthesized read +// | "beep" said, and a tone laid over it at its time +// | "placeholder" its stand-in said instead ("f-slur") +// } +// +// THE SWITCH: `on: false` -- a take's patch (`umtool take <p> … --uncensored`) +// or build-video's --uncensored -- renders the same cut with the slurs left as +// they are. The redaction (private words) and an attachment's censoring are +// NOT part of it: they stay on. +// +// PURE and dependency-free (post-redact.mjs builds on it; the readers hand it +// the list, post-redact-files.mjs). + +export const SLUR_LEVELS = Object.freeze(["all", "strong"]); +export const SLUR_VISUALS = Object.freeze(["blackout", "placeholder"]); +export const SLUR_VOICES = Object.freeze(["skip", "beep", "placeholder"]); +export const SLURS_DEFAULTS = Object.freeze({ on: true, level: "all", visual: "blackout", voice: "skip" }); +export const SLUR_LIST_LEVELS = Object.freeze(["strong", "mild"]); +export const SLURS_ADD_MAX = 100; +export const SLUR_KEYS = Object.freeze(["on", "level", "add", "except", "visual", "voice", "note"]); + +/** The redaction's mark (post-redact.mjs REDACT_MARK): a blacked-out slur is drawn as its bar. */ +export const BLACKOUT_MARK = ""; +/** A slur's second and later letters spelt apart ("f a g …"): kept as a token so the card's word indices hold, drawn as nothing. */ +export const SLUR_GAP = ""; +/** A placeholder's characters, each moved into the private-use area (U+E100 + its ASCII code): never typed, decoded only where drawn. */ +const PH_BASE = 0xe100; +export const PLACEHOLDER_RE = /[-]+/g; + +const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); +const str = (v) => (typeof v === "string" ? v : ""); +const lc = (v) => str(v).trim().toLowerCase(); +const WORD_RE = /^[a-z]{2,40}$/; +const MASK_RE = /^[\x21-\x7E]{1,40}$/; + +// --------------------------------------------------------------------------- +// The list. +// --------------------------------------------------------------------------- + +/** Every reason a slur list document (slurs.json's shape) is refused. */ +export function slurListErrors(doc, where = "slurs.json") { + if (!isObj(doc) || !Array.isArray(doc.entries)) return [`${where} must be {entries: [{id, level, word, forms, say}]}`]; + const errors = []; + const ids = new Set(); + doc.entries.forEach((e, i) => { + const w = `${where} entries[${i}]`; + if (!isObj(e)) return errors.push(`${w} must be an object`); + if (typeof e.id !== "string" || !/^[a-z0-9-]{1,40}$/.test(e.id) || ids.has(e.id)) errors.push(`${w}.id must be a unique short id`); + ids.add(e.id); + if (!SLUR_LIST_LEVELS.includes(e.level)) errors.push(`${w}.level must be ${SLUR_LIST_LEVELS.join(" or ")}`); + if (!WORD_RE.test(str(e.word))) errors.push(`${w}.word must be lower-case letters`); + if (!Array.isArray(e.forms) || !e.forms.length || !e.forms.every((f) => WORD_RE.test(str(f)))) errors.push(`${w}.forms must be a list of lower-case words`); + if (e.mask !== undefined && !MASK_RE.test(str(e.mask))) errors.push(`${w}.mask must be printable ASCII, no spaces`); + if (typeof e.say !== "string" || !e.say.trim() || e.say.length > 40) errors.push(`${w}.say must be the words said in its place`); + }); + return errors; +} + +/** A project's added slur as an entry of the list (a bare word: that word alone, its default mask, said "slur"). */ +function addedEntry(a) { + const x = typeof a === "string" ? { word: a } : a; + const word = lc(x?.word); + const forms = Array.isArray(x?.forms) && x.forms.length ? x.forms.map(lc) : [word]; + return { id: `add:${word}`, level: "strong", word, forms: forms.includes(word) ? forms : [word, ...forms], ...(x?.mask ? { mask: x.mask } : {}), say: str(x?.say).trim() || "slur", added: true }; +} + +/** + * THE FILTER this cut publishes with: `render.posts.slurs` over the list -- + * `{ on, level, visual, voice, entries }`, the entries those of the level + * (strong, or strong and mild), the project's additions, the exceptions taken + * out (a form, a slur's word or its id). `uncensored` turns it off (the + * entries kept: what WOULD be masked is still known). + * + * @param {Record<string, any>|undefined} cfg render.posts.slurs + * @param {{ entries: any[] }|null|undefined} list the default list (slurs.json) + * @param {{ uncensored?: boolean }} [o] + */ +export function resolveSlurs(cfg, list, { uncensored = false } = {}) { + const c = isObj(cfg) ? cfg : {}; + const level = SLUR_LEVELS.includes(c.level) ? c.level : SLURS_DEFAULTS.level; + const ex = new Set((Array.isArray(c.except) ? c.except : []).map(lc).filter(Boolean)); + const base = (Array.isArray(list?.entries) ? list.entries : []).filter((e) => level === "all" || e.level === "strong"); + const added = (Array.isArray(c.add) ? c.add : []).filter((a) => WORD_RE.test(lc(typeof a === "string" ? a : a?.word))).map(addedEntry); + const entries = [...base, ...added] + .filter((e) => !ex.has(e.id) && !ex.has(e.word)) + .map((e) => ({ id: e.id, level: e.level, word: e.word, forms: e.forms.filter((f) => !ex.has(f)), mask: e.mask ?? maskOfWord(e.word), say: e.say, ...(e.added ? { added: true } : {}) })) + .filter((e) => e.forms.length); + return { + on: !uncensored && c.on !== false, + level, + visual: SLUR_VISUALS.includes(c.visual) ? c.visual : SLURS_DEFAULTS.visual, + voice: SLUR_VOICES.includes(c.voice) ? c.voice : SLURS_DEFAULTS.voice, + entries, + ...(uncensored ? { uncensored: true } : {}), + }; +} + +/** Does the filter mask anything? */ +export const slursOn = (s) => !!s && s.on === true && Array.isArray(s.entries) && s.entries.length > 0; + +/** Every reason `render.posts.slurs` is refused. */ +export function validateSlursRender(s, where = "render.posts.slurs") { + if (s === undefined) return []; + if (!isObj(s)) return [`${where} must be {on?, level?, add?, except?, visual?, voice?}`]; + const errors = []; + for (const k of Object.keys(s)) if (!SLUR_KEYS.includes(k)) errors.push(`${where}.${k} is not a knob of the slur filter (${SLUR_KEYS.join(", ")})`); + if (s.on !== undefined && typeof s.on !== "boolean") errors.push(`${where}.on must be true or false`); + if (s.level !== undefined && !SLUR_LEVELS.includes(s.level)) errors.push(`${where}.level must be one of ${SLUR_LEVELS.join(", ")}`); + if (s.visual !== undefined && !SLUR_VISUALS.includes(s.visual)) errors.push(`${where}.visual must be one of ${SLUR_VISUALS.join(", ")}`); + if (s.voice !== undefined && !SLUR_VOICES.includes(s.voice)) errors.push(`${where}.voice must be one of ${SLUR_VOICES.join(", ")}`); + if (s.note !== undefined && typeof s.note !== "string") errors.push(`${where}.note must be words`); + for (const key of ["add", "except"]) { + const list = s[key]; + if (list === undefined) continue; + if (!Array.isArray(list) || list.length > SLURS_ADD_MAX) { + errors.push(`${where}.${key} must be a list of at most ${SLURS_ADD_MAX} words`); + continue; + } + list.forEach((a, i) => { + const w = `${where}.${key}[${i}]`; + if (key === "except" || typeof a === "string") { + if (typeof a !== "string" || !/^[a-z0-9-]{2,40}$/.test(lc(a))) errors.push(`${w} must be a word (letters, 2–40)`); + return; + } + if (!isObj(a)) return errors.push(`${w} must be a word or {word, forms?, mask?, say?}`); + for (const k of Object.keys(a)) if (!["word", "forms", "mask", "say"].includes(k)) errors.push(`${w}.${k} is not a key of an added slur (word, forms, mask, say)`); + if (!WORD_RE.test(lc(a.word))) errors.push(`${w}.word must be a word (letters, 2–40)`); + if (a.forms !== undefined && !(Array.isArray(a.forms) && a.forms.length <= 20 && a.forms.every((f) => WORD_RE.test(lc(f))))) errors.push(`${w}.forms must be a list of words`); + if (a.mask !== undefined && !MASK_RE.test(str(a.mask))) errors.push(`${w}.mask must be printable ASCII, no spaces`); + if (a.say !== undefined && !(typeof a.say === "string" && a.say.length <= 40)) errors.push(`${w}.say must be words (at most 40 characters)`); + }); + } + return errors; +} + +// --------------------------------------------------------------------------- +// The matcher. +// --------------------------------------------------------------------------- + +/** The look-alikes a letter may be written as (a filter-dodger's spellings): "*" stands in for a vowel only. */ +const SWAPS = Object.freeze({ a: "a@4*", e: "e3*", i: "i1!*", o: "o0*", u: "u*", s: "s$5", t: "t7", l: "l1" }); +/** What may sit between the letters of a word spelt out ("f a g …", "f.a.g", "f-a-g"): one, between every pair. */ +const SPELT_SEP = "[ .\\-_]"; +const escRe = (s) => s.replace(/[.*+?^${}()|[\]\\/-]/g, "\\$&"); +const letterRe = (c) => (SWAPS[c] ? `[${SWAPS[c].replace(/[\]\\^-]/g, "\\$&")}]` : escRe(c)); + +/** One form's pattern: its letters (each with its look-alikes), together or spelt out (three letters or more). */ +export function formPattern(form) { + const letters = [...lc(form)].map(letterRe); + const together = letters.join(""); + return letters.length >= 3 ? `(?:${together}|${letters.join(SPELT_SEP)})` : together; +} + +const COMPILED = new WeakMap(); +/** The filter's one pattern (a capture group per slur, its forms longest first), or null. */ +function compiled(s) { + if (!s || !Array.isArray(s.entries) || !s.entries.length) return null; + const hit = COMPILED.get(s); + if (hit) return hit; + const groups = s.entries.map((e) => `(${[...e.forms].sort((a, b) => b.length - a.length).map(formPattern).join("|")})`); + const re = new RegExp(`(?<![\\p{L}\\p{N}])(?:${groups.join("|")})(?![\\p{L}\\p{N}])`, "giu"); + COMPILED.set(s, re); + return re; +} + +/** + * Every slur in `text`: `[{ start, end, id }]` (code units), in order. Whole + * words only -- a letter or digit either side refuses a match ("Scunthorpe", + * "niggardly", "retardant"). + * + * @param {string} text + * @param {{ entries: any[] } | null | undefined} s resolveSlurs' filter (on or off) + */ +export function slurMatches(text, s) { + const re = compiled(s); + const t = str(text); + if (!re || !t) return []; + const out = []; + for (const m of t.matchAll(new RegExp(re.source, re.flags))) { + if (!m[0]) continue; + const g = m.slice(1).findIndex((x) => x !== undefined); + out.push({ start: m.index, end: m.index + m[0].length, id: s.entries[g]?.id ?? null }); + } + return out; +} + +/** A slur's entry in the filter. */ +export const slurEntryOf = (s, id) => (Array.isArray(s?.entries) ? s.entries.find((e) => e.id === id) ?? null : null); + +/** A word's default masked form: its first letter, an asterisk for each other. */ +export const maskOfWord = (word) => (str(word) ? `${str(word)[0]}${"*".repeat(Math.max(1, str(word).length - 1))}` : "*"); + +/** The masked form a hit is drawn as: the slur's mask, its first letter in the case the text wrote it. */ +export function maskFor(s, hit, matched) { + const e = slurEntryOf(s, hit.id); + const mask = e?.mask ?? "*****"; + const first = str(matched)[0] ?? ""; + return first && first !== first.toLowerCase() && /\p{L}/u.test(first) ? mask[0].toUpperCase() + mask.slice(1) : mask; +} + +/** The words a read says in a hit's place (voice placeholder). */ +export const sayFor = (s, hit) => slurEntryOf(s, hit.id)?.say ?? "slur"; + +/** A mask moved into the private-use area (one character each), decoded only where it is drawn. */ +export const encodePlaceholder = (mask) => [...str(mask)].map((c) => String.fromCharCode(PH_BASE + Math.min(0x7e, Math.max(0x21, c.charCodeAt(0))))).join(""); +/** And back. */ +export const decodePlaceholder = (marked) => str(marked).replace(PLACEHOLDER_RE, (run) => [...run].map((c) => String.fromCharCode(c.charCodeAt(0) - PH_BASE)).join("")); + +/** Does `text` hold a masked slur (a placeholder or a gap)? */ +export const hasSlurMarks = (text) => /[-]/.test(str(text)); + +/** + * `text` with every slur MASKED as the card draws it: `visual` blackout, the + * redaction's mark for each letter (a bar of its width); placeholder, the + * mask in the private-use area. A slur spelt apart keeps its tokens (the + * card's word indices hold): the first holds the mark, the others a gap + * drawn as nothing. Returns `{ text, hits }`. + */ +export function maskSlurs(text, s, visual = s?.visual ?? SLURS_DEFAULTS.visual) { + const t = str(text); + const hits = slursOn(s) ? slurMatches(t, s) : []; + if (!hits.length) return { text: t, hits }; + let out = ""; + let at = 0; + for (const h of hits) { + out += t.slice(at, h.start); + const seg = t.slice(h.start, h.end); + let first = true; + for (const p of seg.split(/(\s+)/)) { + if (!p) continue; + if (/^\s+$/.test(p)) out += p; + else if (first) { + out += visual === "placeholder" ? encodePlaceholder(maskFor(s, h, seg)) : BLACKOUT_MARK.repeat(seg.replace(/\s/g, "").length); + first = false; + } else out += SLUR_GAP; + } + at = h.end; + } + return { text: out + t.slice(at), hits }; +} + +/** HTML (already escaped) with each placeholder drawn as the censor pill and each gap as nothing. */ +export const placeholdersHtml = (html) => + str(html) + .replace(//g, "") + .replace(PLACEHOLDER_RE, (run) => `<span class="slur" data-post-slur="">${decodePlaceholder(run).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;")}</span>`); + +/** The pill's CSS: a dark capsule, the mask in the card's colour, spaced a little -- not to be read as the post's own letters. */ +export const SLUR_CSS = (fg) => + `.slur { display: inline-block; padding: 0 0.32em; border-radius: 0.5em; background: #0b0b0b; color: ${fg}; box-shadow: inset 0 0 0 0.06em rgba(255,255,255,0.28); letter-spacing: 0.08em; font-size: 0.86em; line-height: 1.25; vertical-align: 0.04em; }`; + +// --------------------------------------------------------------------------- +// The voice. +// --------------------------------------------------------------------------- + +/** A word reduced as word-zoom.mjs normWord does (lower case, its edge punctuation gone). */ +const normWord = (w) => str(w).toLowerCase().normalize("NFKC").replace(/[‘’]/g, "'").replace(/^[^\p{L}\p{N}]+|[^\p{L}\p{N}]+$/gu, ""); + +/** A script's spoken words with their offsets: word-zoom.mjs scriptWordsOf's words (a take's `words` are one per each), in order. */ +export function scriptTokens(script) { + const clean = str(script).replace(/<[^<>]*>/g, (m) => " ".repeat(m.length)); + const out = []; + for (const m of clean.matchAll(/\S+/g)) if (normWord(m[0])) out.push({ w: m[0], start: m.index, end: m.index + m[0].length }); + return out; +} + +/** Each take's slur state: what its audio does with the slurs its script holds. Absent: it says them (a recording; a take from before the filter). */ +export const TAKE_SLUR_STATES = Object.freeze(["said", "skip", "placeholder"]); + +/** The before/after pad of a beep or a mute around the word, seconds. */ +export const SLUR_BLEEP_PAD = Object.freeze({ before: 0.04, after: 0.06 }); +/** The beep: a sine at this pitch and amplitude, under the narrator's chain. */ +export const SLUR_BEEP = Object.freeze({ hz: 1000, amp: 0.18 }); + +/** + * A TAKE's slurs to cover, in take seconds: `{ mode: "beep" | "mute", spans: + * [[from, to]] }` (beep: the voice's choice beep or placeholder -- a + * recorded take cannot say a stand-in; mute: skip), null when there is none + * (the filter off, the take's audio leaves them out, its script holds none), + * or `{ error }` when the take says one and has no word timings to find it by. + * + * @param {{ script?: string, words?: Array<{w: string, start: number, end: number}>, slurs?: string, file?: string, seconds?: number }} take + * @param {ReturnType<typeof resolveSlurs> | null | undefined} s + * @param {{ script?: string, state?: string | null }} [o] the script it read (default its own), its state (default its own) + */ +export function takeBleeps(take, s, { script = undefined, state = undefined } = {}) { + if (!slursOn(s) || !take) return null; + const st = state ?? take.slurs ?? "said"; + if (st !== "said") return null; + const text = str(script ?? take.script); + const hits = slurMatches(text, s); + if (!hits.length) return null; + const words = Array.isArray(take.words) ? take.words : []; + const toks = scriptTokens(text); + const masks = [...new Set(hits.map((h) => maskFor(s, h, "")))].join(", "); + if (!words.length) return { error: `its take ${take.file ?? ""} says ${hits.length} slur(s) (${masks}) and has no word timings to ${s.voice === "skip" ? "silence" : "beep"} them by` }; + if (words.length !== toks.length) return { error: `its take ${take.file ?? ""}'s word timings are not of its script (${words.length} timed, ${toks.length} in the script)` }; + const spans = []; + for (const h of hits) { + const ks = toks.map((t, k) => (t.end > h.start && t.start < h.end ? k : -1)).filter((k) => k >= 0); + if (!ks.length) continue; + const a = Math.max(0, Math.min(...ks.map((k) => words[k].start)) - SLUR_BLEEP_PAD.before); + const b = Math.max(...ks.map((k) => words[k].end)) + SLUR_BLEEP_PAD.after; + spans.push([Math.round(a * 1000) / 1000, Math.round(b * 1000) / 1000]); + } + spans.sort((x, y) => x[0] - y[0]); + const merged = []; + for (const sp of spans) { + const last = merged[merged.length - 1]; + if (last && sp[0] <= last[1]) last[1] = Math.max(last[1], sp[1]); + else merged.push([...sp]); + } + return merged.length ? { mode: s.voice === "skip" ? "mute" : "beep", spans: merged } : null; +} + +/** + * The narrator's filters that cover the spans (before its levelling and + * tempo, on the take's own clock): `[inLabel]` → `[outLabel]`, the voice + * silenced over each span and, for a beep, a tone mixed in over it. + */ +export function bleepFilters(inLabel, outLabel, bleeps, { audioRate = 48000, seconds = 600 } = {}) { + const gate = bleeps.spans.map(([a, b]) => `between(t,${a},${b})`).join("+"); + const out = [`[${inLabel}]aresample=${audioRate},aformat=sample_fmts=fltp:channel_layouts=stereo,volume=0:enable='${gate}'[${outLabel}_m]`]; + if (bleeps.mode !== "beep") return [...out, `[${outLabel}_m]anull[${outLabel}]`]; + const tone = `${SLUR_BEEP.amp}*sin(2*PI*${SLUR_BEEP.hz}*t)*(${gate})`; + return [ + ...out, + `aevalsrc=exprs='${tone}|${tone}':s=${audioRate}:d=${Math.ceil(seconds + 1)}[${outLabel}_t]`, + `[${outLabel}_m][${outLabel}_t]amix=inputs=2:normalize=0:duration=first[${outLabel}]`, + ]; +} + +// --------------------------------------------------------------------------- +// What a cut would mask (`umtool posts slurs ls`). +// --------------------------------------------------------------------------- + +/** The words of a post item a slur may be in, by where: its words, its authors' names, the posts it answers and quotes, its read. */ +export function postSlurTexts(entry) { + const out = []; + const add = (where, v) => typeof v === "string" && v && out.push({ where, text: v }); + add("text", entry?.text); + add("author", entry?.author); + if (isObj(entry?.repostedBy)) add("repostedBy", entry.repostedBy.author); + (Array.isArray(entry?.parents) ? entry.parents : []).forEach((p, i) => { + add(`parents[${i}].text`, p?.text); + add(`parents[${i}].paraphrase`, p?.paraphrase); + add(`parents[${i}].author`, p?.author); + }); + if (isObj(entry?.quoted)) { + add("quoted.text", entry.quoted.text); + add("quoted.paraphrase", entry.quoted.paraphrase); + add("quoted.author", entry.quoted.author); + } + add("script", entry?.narration?.script); + return out; +} + +/** + * The slurs a cut's post items hold: `{ total, posts: [{ id, hits: {<slur id>: n}, where: [...] }], bySlur: {<slur id>: { mask, n, posts: [ids] }} }`. + * The filter's state does not matter (an uncensored cut is counted as if on). + */ +export function slurReport(timeline, s) { + const on = { ...s, on: true }; + const posts = []; + const bySlur = {}; + let total = 0; + for (const e of Array.isArray(timeline) ? timeline : []) { + if (e?.type !== "post") continue; + const hits = {}; + const where = new Set(); + for (const { where: w, text } of postSlurTexts(e)) { + for (const h of slurMatches(text, on)) { + hits[h.id] = (hits[h.id] ?? 0) + 1; + where.add(w.replace(/\[\d+\]/, "")); + total += 1; + const b = (bySlur[h.id] ??= { mask: slurEntryOf(on, h.id)?.mask ?? "*", n: 0, posts: [] }); + b.n += 1; + if (!b.posts.includes(e.id)) b.posts.push(e.id); + } + } + if (Object.keys(hits).length) posts.push({ id: e.id, hits, where: [...where] }); + } + return { total, posts, bySlur }; +} + +/** A take's record of the cut's slur state (take.json `slurs`): the cut has post items, and whether it publishes them censored. */ +export function cutSlurState(manifest) { + const tl = Array.isArray(manifest?.timeline) ? manifest.timeline : []; + if (!tl.some((e) => e?.type === "post")) return null; + return manifest?.render?.posts?.slurs?.on === false ? "uncensored" : "censored"; +} diff --git a/umtool/report-to-video/post-slurs.test.mjs b/umtool/report-to-video/post-slurs.test.mjs @@ -0,0 +1,184 @@ +// post-slurs.mjs: the slur filter -- the list, the matcher (its spellings and +// no substring matches), the masks on the card, the read (skip, stand-in, +// beep), the switch -- and its place in the redaction (post-redact.mjs). +// The words come from slurs.json: no test spells one out. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; + +import { + BLACKOUT_MARK, SLUR_GAP, bleepFilters, cutSlurState, decodePlaceholder, encodePlaceholder, maskSlurs, placeholdersHtml, resolveSlurs, scriptTokens, + slurListErrors, slurMatches, slurReport, slursOn, takeBleeps, validateSlursRender, +} from "./post-slurs.mjs"; +import { REDACT_MARK, barsHtml, dropMarks, redactEntry, redactionOn, shownLine, spokenRead, validatePostsRender } from "./post-redact.mjs"; +import { cutSlurs, defaultSlurList } from "./post-redact-files.mjs"; +import { postCardHtml } from "./post-item.mjs"; +import { scriptWordsOf } from "./word-zoom.mjs"; + +const LIST = JSON.parse(readFileSync(new URL("./slurs.json", import.meta.url), "utf8")); +const byId = (id) => LIST.entries.find((e) => e.id === id); +const F = byId("f-slur").word; // the f-slur, six letters +const FS = byId("f-slur").forms.find((f) => f === `${F}s`); +const R = byId("r-word").word; // a mild one +const N = byId("n-word").word; +const ON = resolveSlurs(undefined, LIST); +const spaced = (w, sep = " ") => [...w].join(sep); +const leet = (w) => w.replace("a", "@").replace("o", "0"); + +test("the shipped list is well formed, and every entry has forms, a level and a stand-in", () => { + assert.deepEqual(slurListErrors(LIST), []); + assert.equal(defaultSlurList().entries.length, LIST.entries.length); + assert.ok(LIST.entries.some((e) => e.level === "mild") && LIST.entries.some((e) => e.level === "strong")); + assert.match(slurListErrors({ entries: [{ id: "x", level: "loud", word: "X1", forms: [], say: "" }] }).join(" "), /level.*word.*forms.*say/); +}); + +test("matching: whole words, without case, through look-alike letters and a word spelt out", () => { + const hit = (t) => slurMatches(t, ON).map((h) => t.slice(h.start, h.end)); + assert.deepEqual(hit(`you ${F}`), [F]); + assert.deepEqual(hit(`${F.toUpperCase()}!`), [F.toUpperCase()]); + assert.deepEqual(hit(`two ${FS}, ok`), [FS]); + assert.deepEqual(hit(`a ${leet(F)} here`), [leet(F)]); + assert.deepEqual(hit(`${F[0]}*${F.slice(2)}`), [`${F[0]}*${F.slice(2)}`]); + assert.deepEqual(hit(`a ${spaced(F)} b`), [spaced(F)]); + assert.deepEqual(hit(`a ${spaced(F, ".")} b`), [spaced(F, ".")]); + assert.deepEqual(hit(`a ${spaced(F, "-")}.`), [spaced(F, "-")]); + assert.deepEqual(hit(`#${F} @x_${F}`), [F, F]); + assert.deepEqual(hit(`${F}'s thing`), [F]); + // The id says which slur it was. + assert.equal(slurMatches(`${N}s`, ON)[0].id, "n-word"); +}); + +test("no substring matches: a slur inside a longer word, or a word that only looks like one, is left alone", () => { + const none = (t) => assert.deepEqual(slurMatches(t, ON), [], t); + none("Scunthorpe"); + none("niggardly praise"); + none("fire retardant"); + none(`${R}ant`); + none("raccoon, spice, spicy, Fagin, faggio, kiker, troonish, gooky, tardis"); + none(`x${F}`); + none(`${F}2`); + // Spelt apart only with a separator between EVERY letter: "it's pic" is not one. + none("it's pic, the s pic, s pi c"); + // Mixed spacing (some letters together) is not a spelling the filter reads. + none(`${N.slice(0, 3)} ${N.slice(3)}`); +}); + +test("the level, the project's additions and exceptions", () => { + const strong = resolveSlurs({ level: "strong" }, LIST); + assert.equal(slurMatches(R, strong).length, 0); + assert.equal(slurMatches(R, ON).length, 1); + assert.equal(slurMatches(F, strong).length, 1); + const own = resolveSlurs({ add: ["zorbo", { word: "blerg", forms: ["blergs"], mask: "b***", say: "b-word" }], except: [FS, "r-word"] }, LIST); + assert.equal(slurMatches("a zorbo and two blergs", own).length, 2); + assert.equal(slurMatches(FS, own).length, 0, "an excepted form"); + assert.equal(slurMatches(F, own).length, 1, "the rest of its slur"); + assert.equal(slurMatches(R, own).length, 0, "an excepted slur, by its id"); + assert.equal(slursOn(resolveSlurs({ on: false }, LIST)), false); + assert.equal(slursOn(resolveSlurs({}, LIST, { uncensored: true })), false); + assert.equal(resolveSlurs({}, LIST, { uncensored: true }).entries.length, ON.entries.length, "what would be masked is still known"); +}); + +test("validateSlursRender refuses what the filter cannot use; render.posts carries it", () => { + assert.deepEqual(validateSlursRender({ on: false, level: "strong", visual: "placeholder", voice: "beep", add: ["zorbo"], except: ["n-word"] }), []); + const errs = validateSlursRender({ on: "yes", level: "loud", visual: "blur", voice: "hum", add: [3], except: [""], nope: 1 }).join(" | "); + for (const k of ["nope", ".on", ".level", ".visual", ".voice", "add[0]", "except[0]"]) assert.ok(errs.includes(k), k); + assert.match(validatePostsRender({ posts: { slurs: { visual: "blur" } } }).join(" "), /slurs\.visual/); +}); + +test("the card's masks: a blackout is the redaction's bar; a placeholder is a pill with the mask, never the word", () => { + assert.equal(BLACKOUT_MARK, REDACT_MARK); + const b = maskSlurs(`you ${F}!`, ON).text; + assert.equal(b, `you ${REDACT_MARK.repeat(F.length)}!`); + const p = maskSlurs(`you ${F}! ${F[0].toUpperCase()}${F.slice(1)}`, { ...ON, visual: "placeholder" }).text; + assert.equal(decodePlaceholder(p), `you ${F[0]}*****! ${F[0].toUpperCase()}*****`); + assert.ok(!p.toLowerCase().includes(F)); + // Spelt apart: as many tokens as before (the card's word indices hold), the first the mask, the rest gaps. + const sp = maskSlurs(`a ${spaced(F)} b`, { ...ON, visual: "placeholder" }).text; + assert.equal(sp.split(/\s+/).length, `a ${spaced(F)} b`.split(/\s+/).length); + assert.equal(sp.split(SLUR_GAP).length - 1, F.length - 1); + assert.equal(placeholdersHtml(sp), `a <span class="slur" data-post-slur="">${F[0]}*****</span>${" ".repeat(F.length - 1)} b`); + assert.equal(decodePlaceholder(encodePlaceholder("n*****")), "n*****"); + assert.equal(dropMarks(sp), `a ${F[0]}***** b`); + // Off: untouched. + assert.equal(maskSlurs(F, resolveSlurs({ on: false }, LIST)).text, F); +}); + +const post = (text, extra = {}) => ({ + id: "p1", type: "post", platform: "x", post: "chan/1", author: "Some One", handle: "someone", date: "2026-01-01T00:00:00Z", text, ...extra, +}); + +test("redactEntry masks the slurs with the redaction, and the card's HTML never holds the word", () => { + const e = post(`what a ${F}, said the ${leet(F)}`, { quoted: { author: "Q", handle: "q", text: `${FS} again` }, parents: [{ author: "P", handle: "p", text: `${spaced(F)} indeed` }] }); + const red = { terms: [{ term: "said" }], slurs: { ...ON, visual: "placeholder" } }; + assert.ok(redactionOn({ terms: [], slurs: ON })); + const shown = redactEntry(e, red); + for (const v of [shown.text, shown.quoted.text, shown.parents[0].text]) assert.equal(slurMatches(decodePlaceholder(v), ON).length, 0, v); + const html = postCardHtml(e, { width: 1280, height: 720, redaction: red }); + const low = html.toLowerCase(); + for (const w of [F, FS, leet(F), spaced(F)]) assert.ok(!low.includes(w), `the page holds ${w.length}-letter form`); + assert.ok(!low.includes(">said<"), "the redaction still applies"); + assert.ok((html.match(/data-post-slur=""/g) ?? []).length >= 4); + assert.ok(html.includes(`${F[0]}*****`)); + assert.ok(html.includes("data-post-blanked"), "the redacted term's bar"); + // Blackout: bars, no pill. + const bhtml = postCardHtml(e, { width: 1280, height: 720, redaction: { terms: [], slurs: ON } }); + assert.ok(!bhtml.toLowerCase().includes(F) && !bhtml.includes('data-post-slur=""') && bhtml.includes("data-post-blanked")); + // UNCENSORED: the words, the redaction still on. + const u = postCardHtml(e, { width: 1280, height: 720, redaction: { terms: [{ term: "said" }], slurs: resolveSlurs({}, LIST, { uncensored: true }) } }); + assert.ok(u.includes(F) && !u.includes(">said<")); + // The entry itself is never touched. + assert.ok(e.text.includes(F)); +}); + +test("the read: skip leaves the slur out, placeholder says its stand-in, beep says it (the render covers it); off says it", () => { + const e = post("x"); + const red = (o) => ({ terms: [{ term: "Quentin" }], slurs: resolveSlurs(o, LIST) }); + const text = `Quentin called him a ${F}, twice.`; + assert.deepEqual(spokenRead(text, e, red({})), { text: "called him a, twice.", slurs: "skip" }); + assert.deepEqual(spokenRead(text, e, red({ voice: "placeholder" })), { text: "called him a f-slur, twice.", slurs: "placeholder" }); + assert.deepEqual(spokenRead(text, e, red({ voice: "beep" })), { text: `called him a ${F}, twice.`, slurs: "said" }); + assert.deepEqual(spokenRead(text, e, red({ on: false })), { text: `called him a ${F}, twice.`, slurs: "said" }); + assert.deepEqual(spokenRead("nothing here", e, red({})), { text: "nothing here", slurs: null }); + // A caption: left out (blackout), or its mask (placeholder); the redaction too. + assert.equal(shownLine(`Quentin, you ${F}`, e, red({})), "you"); + assert.equal(shownLine(`Quentin, you ${F}`, e, red({ visual: "placeholder" })), `you ${F[0]}*****`); +}); + +test("takeBleeps: a take that says a slur is covered at its words' times; without timings it is refused", () => { + const script = `<sigh> He said ${F} and then ${spaced(F)} again.`; + const toks = scriptTokens(script); + assert.deepEqual(toks.map((t) => t.w), scriptWordsOf(script), "the take's words are one per these"); + const words = toks.map((t, i) => ({ w: t.w, start: i, end: i + 0.5 })); + const take = { file: "narration/posts/1/take-1.orpheus-zac.wav", script, words, seconds: 20 }; + const s = resolveSlurs({ voice: "beep" }, LIST); + const b = takeBleeps(take, s); + // "He"(0) "said"(1) F(2) "and"(3) "then"(4) f,a,g,g,o,t (5..10) "again."(11) + assert.deepEqual(b, { mode: "beep", spans: [[1.96, 2.56], [4.96, 10.56]] }); + assert.equal(takeBleeps(take, resolveSlurs({}, LIST)).mode, "mute"); + assert.equal(takeBleeps(take, resolveSlurs({ on: false }, LIST)), null); + assert.equal(takeBleeps({ ...take, slurs: "skip" }, s), null, "its audio left them out"); + assert.match(takeBleeps({ ...take, words: undefined }, s).error, /no word timings/); + assert.match(takeBleeps({ ...take, words: words.slice(1) }, s).error, /not of its script/); + const f = bleepFilters("v", "vb", b, { seconds: 20 }).join(";"); + assert.match(f, /volume=0:enable='between\(t,1\.96,2\.56\)\+between\(t,4\.96,10\.56\)'/); + assert.match(f, /aevalsrc=exprs='0\.18\*sin\(2\*PI\*1000\*t\)/); + assert.doesNotMatch(bleepFilters("v", "vb", { mode: "mute", spans: [[1, 2]] }).join(";"), /aevalsrc/); +}); + +test("slurReport counts what the cut would mask, per slur and per post; cutSlurState says which a take is", () => { + const tl = [post(`${F} ${F}`, { id: "a" }), post("clean", { id: "b", narration: { script: `${N}` } }), { id: "c", type: "clip" }]; + const r = slurReport(tl, resolveSlurs({ on: false }, LIST)); + assert.equal(r.total, 3); + assert.deepEqual(r.bySlur["f-slur"], { mask: `${F[0]}*****`, n: 2, posts: ["a"] }); + assert.deepEqual(r.posts.map((p) => p.id), ["a", "b"]); + assert.deepEqual(r.posts[1].where, ["script"]); + assert.equal(cutSlurState({ timeline: tl }), "censored"); + assert.equal(cutSlurState({ timeline: tl, render: { posts: { slurs: { on: false } } } }), "uncensored"); + assert.equal(cutSlurState({ timeline: [{ type: "clip" }] }), null); + assert.equal(cutSlurs({ render: { posts: { slurs: { level: "strong" } } } }).level, "strong"); +}); + +test("barsHtml draws placeholders and gaps with the redaction's bars", () => { + const html = barsHtml(`${REDACT_MARK.repeat(3)} ${encodePlaceholder("k***")}${SLUR_GAP}`); + assert.equal(html, `<span class="rbar" data-post-blanked="" style="width:1.56em"></span> <span class="slur" data-post-slur="">k***</span>`); +}); diff --git a/umtool/report-to-video/slurs.json b/umtool/report-to-video/slurs.json @@ -0,0 +1,21 @@ +{ + "version": 1, + "about": "The slur filter's default list (post-slurs.mjs; umtool/docs/knobs.md, \"The slur filter\"). Each entry is one slur: the forms it is written in (matched whole-word, case-insensitive, with common letter swaps and letter-by-letter spacing), its level (strong: always masked when the filter is on; mild: only at level all), the masked form a card draws in place of it (default: its first letter and an asterisk for every other letter of `word`), and the words a synthesized read says for it under voice placeholder. A project adds to it and excepts from it in render.posts.slurs. Kept tight: no word that is also an ordinary English word in common use.", + "entries": [ + { "id": "n-word", "level": "strong", "word": "nigger", "forms": ["nigger", "niggers", "niggerz", "nigga", "niggas", "niggaz", "niggah", "niggahs"], "say": "n-word" }, + { "id": "f-slur", "level": "strong", "word": "faggot", "forms": ["faggot", "faggots", "faggotry", "faggoty", "faggy"], "say": "f-slur" }, + { "id": "f-slur-short", "level": "strong", "word": "fag", "forms": ["fag", "fags"], "say": "f-slur" }, + { "id": "t-slur", "level": "strong", "word": "tranny", "forms": ["tranny", "trannies", "trannys"], "say": "t-slur" }, + { "id": "t-slur-troon", "level": "strong", "word": "troon", "forms": ["troon", "troons", "troony"], "say": "t-slur" }, + { "id": "k-slur", "level": "strong", "word": "kike", "forms": ["kike", "kikes"], "say": "k-slur" }, + { "id": "s-slur", "level": "strong", "word": "spic", "forms": ["spic", "spics"], "say": "s-slur" }, + { "id": "w-slur", "level": "strong", "word": "wetback", "forms": ["wetback", "wetbacks"], "say": "w-slur" }, + { "id": "g-slur", "level": "strong", "word": "gook", "forms": ["gook", "gooks"], "say": "g-slur" }, + { "id": "b-slur", "level": "strong", "word": "beaner", "forms": ["beaner", "beaners"], "say": "b-slur" }, + { "id": "r-slur-raghead", "level": "strong", "word": "raghead", "forms": ["raghead", "ragheads"], "say": "slur" }, + { "id": "t-slur-towelhead", "level": "strong", "word": "towelhead", "forms": ["towelhead", "towelheads"], "say": "slur" }, + { "id": "r-word", "level": "mild", "word": "retard", "forms": ["retard", "retards", "retarded"], "say": "r-word" }, + { "id": "r-word-short", "level": "mild", "word": "tard", "forms": ["tard", "tards"], "say": "r-word" }, + { "id": "s-slur-shemale", "level": "mild", "word": "shemale", "forms": ["shemale", "shemales"], "say": "slur" } + ] +}