// A PROJECT's PRONUNCIATION LEXICON and VOICE MAP (umtool-report-to-video/post-say.mjs; // umtool/docs/knobs.md, "Pronunciation and voices"): the files, their one writer // each, and the CLI. // // umtool posts say

[ls] [--item ] [--json] // umtool posts say

add "" [--case] [--item ] [--note "…"] [--json] // umtool posts say

remove [--item ] [--json] // umtool posts say

try "" [--item ] [--json] what a voice would be asked to say // umtool posts say

stale [--json] picked reads that say an entry the old way // umtool posts voices

[ls] | set | remove [--json] // // The files are the project's own (`narration/lexicon.json`, `narration/voices.json`), written // atomically (a temp file renamed over), refused whole in post-say.mjs's words. They are NOT in the // manifest: a narrated segment's cache key carries render.postNarration, and what a voice says is a // new take's business, never a re-render's. // // Plain ESM: the CLI runs under bare node. import { mkdir, readFile, rename, writeFile } from "node:fs/promises"; import path from "node:path"; import { LEXICON_FILE, VOICES_FILE, VOICE_MAP_OTHER, handleKey, lexiconFor, lexiconKey, staleLexicon, validateLexicon, validateVoiceMap, } from "umtool-report-to-video/post-say"; import { isNarrated, pickedTake } from "umtool-report-to-video/post-narration"; import { readManifest } from "../projects/report.mjs"; import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export class SayError extends Error { constructor(message) { super(message); this.name = "SayError"; } } export const SAY_USAGE = [ "usage: umtool posts say [ls] [--item ] [--json]", " umtool posts say add \"\" [--case] [--item ] [--note \"…\"] [--json]", " umtool posts say remove [--item ] [--json]", " umtool posts say try \"\" [--item ] [--json]", " umtool posts say stale [--json]", " THE PRONUNCIATION LEXICON (narration/lexicon.json): a word or phrase the voice says differently -- \"tbh\" said", " \"T-B-H\", \"@grok\" said \"At grok\" -- in EVERY synthesized read (a script's take, each piece of a thread read,", " the bench's re-take); the scripts and the cards keep their words. A whole-word match without case (--case: with", " it), a phrase across any spaces, regex characters literal; --item: that post item's reads only (it wins over the", " project's). A slur the filter masks and a redacted word are never replaced (the filter and the redaction win).", " add of a word already on the list changes what is said for it. try: what a voice would be asked to say for the", " text. stale: each picked read that still says an entry the old way, with the command that re-reads it.", ].join("\n"); export const VOICES_USAGE = [ "usage: umtool posts voices [ls] [--json]", " umtool posts voices set [--json]", " umtool posts voices remove [--json]", " THE VOICE MAP (narration/voices.json): the stock voice each author's words are read in by a thread read", " (umtool posts narrate

--take --thread) and a single post's read -- set kirscheverstahl tara, or with its", " engine set thequartering kokoro:am_michael; `*` is everyone it does not name (default leo on Orpheus). The map is", " the project's OVERRIDE over the cast (umtool cast: the characters across projects). The item's own author reads in", " the item's narrator voice unless the map or the cast names them.", " ls: the map, and every author the cut's post items carry with the voice each would get.", ].join("\n"); const abs = (project, rel) => path.join(project.dir, ...rel.split("/")); async function readJson(file) { let text; try { text = await readFile(file, "utf8"); } catch (e) { if (e?.code === "ENOENT") return undefined; throw e; } try { return JSON.parse(text); } catch (e) { throw new SayError(`${file} is not JSON: ${e instanceof Error ? e.message : e}`); } } async function writeJsonAtomic(file, value) { await mkdir(path.dirname(file), { recursive: true }); const tmp = tmpPathFor(file); await writeFile(tmp, `${JSON.stringify(value, null, 1)}\n`); await rename(tmp, file); } /** The project's lexicon as its file holds it (`[]` with none); a broken file throws. */ export async function readLexicon(dir) { const doc = await readJson(path.join(dir, ...LEXICON_FILE.split("/"))); if (doc === undefined) return []; const errors = validateLexicon(doc); if (errors.length) throw new SayError(`${LEXICON_FILE} is refused: ${errors.join("; ")}`); return doc; } /** The project's voice map (`{}` with none); a broken file throws. */ export async function readVoiceMap(dir) { const doc = await readJson(path.join(dir, ...VOICES_FILE.split("/"))); if (doc === undefined) return {}; const errors = validateVoiceMap(doc); if (errors.length) throw new SayError(`${VOICES_FILE} is refused: ${errors.join("; ")}`); return doc; } /** * CHANGE THE LEXICON (its one writer): `{ add: {word, say, case?, item?, note?} }` -- an entry with the same * word (and case, and item) is REPLACED -- or `{ remove: {word, item?} | }`. Refused whole. * Returns `{ lexicon, changed: "added" | "updated" | "removed", entry }`. */ export async function updateLexicon(dir, change) { const list = [...(await readLexicon(dir))]; let changed; let entry; if (change?.add) { const a = change.add; entry = { word: String(a.word ?? "").replace(/\s+/g, " ").trim(), say: String(a.say ?? "").trim(), ...(a.case === true ? { case: true } : {}), ...(a.item ? { item: String(a.item) } : {}), ...(a.note ? { note: String(a.note) } : {}), }; const k = list.findIndex((x) => lexiconKey(x) === lexiconKey(entry)); if (k >= 0) { list[k] = entry; changed = "updated"; } else { list.push(entry); changed = "added"; } } else if (change?.remove !== undefined) { const r = change.remove; let k = -1; if (Number.isInteger(r)) k = r >= 0 && r < list.length ? r : -1; else { const w = String(r?.word ?? "").replace(/\s+/g, " ").trim().toLowerCase(); const it = r?.item ? String(r.item) : null; const hits = list.map((x, i) => ({ x, i })).filter(({ x }) => String(x.word).replace(/\s+/g, " ").trim().toLowerCase() === w && (x.item ?? null) === it); if (hits.length > 1) throw new SayError(`"${r.word}" is on the list ${hits.length} times (with and without --case): remove it by its number, as ls shows it`); k = hits[0]?.i ?? -1; } if (k < 0) throw new SayError(`no entry ${Number.isInteger(r) ? r + 1 : `"${r?.word}"${r?.item ? ` for ${r.item}` : ""}`} on the lexicon (umtool posts say

ls)`); [entry] = list.splice(k, 1); changed = "removed"; } else throw new SayError("a lexicon change is {add} or {remove}"); const errors = validateLexicon(list); if (errors.length) throw new SayError(`refused: ${errors.join("; ")}`); await writeJsonAtomic(path.join(dir, ...LEXICON_FILE.split("/")), list); return { lexicon: list, changed, entry }; } /** CHANGE THE VOICE MAP (its one writer): `{ set: {handle, voice} }` or `{ remove: handle }`. */ export async function updateVoiceMap(dir, change) { const map = { ...(await readVoiceMap(dir)) }; if (change?.set) { const h = handleKey(change.set.handle); if (!h) throw new SayError("posts voices set takes a handle (or *) and a voice"); map[h] = String(change.set.voice ?? ""); } else if (change?.remove !== undefined) { const h = handleKey(change.remove); if (!(h in map)) throw new SayError(`${h} is not on the voice map`); delete map[h]; } else throw new SayError("a voice map change is {set} or {remove}"); const errors = validateVoiceMap(map); if (errors.length) throw new SayError(`refused: ${errors.join("; ")}`); await writeJsonAtomic(path.join(dir, ...VOICES_FILE.split("/")), map); return { voices: map }; } /** The post item `ref` names (its id, its post's id, p-), or null. */ function itemOf(manifest, ref) { const r = String(ref ?? ""); return (manifest?.timeline ?? []).find((e) => e?.type === "post" && (e.id === r || String(e.post ?? "").split("/")[1] === r || e.id === `p-${r}`)) ?? null; } /** * THE PICKED READS THAT SAY AN ENTRY THE OLD WAY, pure: `[{ id, take, thread, entries: [{word, say, item?, was?}], * fix }]` -- every narrated post item whose picked take is synthesized and matches an entry it did not apply. */ export function staleReads(manifest, lexicon, project = "

") { const out = []; for (const e of manifest?.timeline ?? []) { if (e?.type !== "post" || !isNarrated(e)) continue; const t = pickedTake(e); if (!t) continue; const entries = staleLexicon(e, t, lexicon); if (!entries.length) continue; const thread = t.read?.kind === "thread" || /-thread\.wav$/.test(String(t.file ?? "")) || (Array.isArray(t.parts) && new Set(t.parts.map((p) => p?.voice).filter(Boolean)).size > 1); out.push({ id: e.id, take: t.file, thread, entries, fix: `umtool posts narrate ${project} ${e.id} --take${thread ? ` --thread${threadArgsOf(t.read)}` : ""}` }); } return out; } /** A thread take's `read` record as the flags that ask for it again. */ export function threadArgsOf(read) { if (!read || read.kind !== "thread") return ""; const q = (s) => (/^[A-Za-z0-9_.:=+-]+$/.test(s) ? s : `'${String(s).replace(/'/g, "'\\''")}'`); const a = []; if (read.parents !== undefined && String(read.parents) !== "0") a.push(`--parents ${read.parents}`); for (const s of read.skip ?? []) a.push(`--skip-parent ${q(s)}`); if (read.quoted === false) a.push("--no-quoted"); if (read.linked === false) a.push("--no-linked"); if (read.seen === true) a.push("--read-seen"); for (const [h, v] of Object.entries(read.voiceFor ?? {})) a.push(`--voice-for ${q(`${h}=${v}`)}`); if (read.voice) a.push(`--voice ${q(read.voice)}`); // Its screens (post-screens.mjs): left out, or lines from takes -- by their numbers then (the files are in the record). if (read.screens === false) a.push("--no-screens"); for (const [r, x] of Object.entries(read.lineTakes ?? {})) if (Number.isInteger(x?.n)) a.push(`--line-take ${q(`${r}=${x.n}`)}`); return a.length ? ` ${a.join(" ")}` : ""; } /** `umtool posts say …` (postsCli.mjs routes it here). */ export async function sayCommand(project, rest, { flags, str, json = false, out = (s) => console.log(s) }) { const [sub = "ls", ...args] = rest; const manifest = (await readManifest(project.dir)) ?? {}; const itemRef = flags.has("--item") ? str("--item") : null; const item = itemRef === null ? null : itemOf(manifest, itemRef); if (itemRef !== null && !item) throw new SayError(`no post item ${itemRef} in ${project.id} (its id, or the post's id)`); const line = (x, i) => ` ${i + 1}. ${JSON.stringify(x.word)} -> ${JSON.stringify(x.say)}${x.case ? " (with case)" : ""}${x.item ? ` (${x.item} only)` : ""}${x.note ? ` -- ${x.note}` : ""}`; if (sub === "add") { const [word, say] = args; if (!word || say === undefined) throw new SayError('posts say add takes the word and what to say: add tbh "T-B-H"'); const r = await updateLexicon(project.dir, { add: { word, say, case: flags.has("--case"), item: item?.id ?? null, note: flags.has("--note") ? str("--note") : null } }); if (json) out(JSON.stringify({ ok: true, changed: r.changed, entry: r.entry, lexicon: r.lexicon }, null, 2)); else { out(`${r.changed} ${JSON.stringify(r.entry.word)} -> ${JSON.stringify(r.entry.say)}${r.entry.item ? ` for ${r.entry.item}` : ""}; ${project.id}'s lexicon holds ${r.lexicon.length} entr${r.lexicon.length === 1 ? "y" : "ies"}`); const n = staleReads(manifest, r.lexicon, project.id).length; if (n) out(` ${n} picked read(s) say an entry the old way: umtool posts say ${project.id} stale`); } return 0; } if (sub === "remove") { const [w] = args; if (!w) throw new SayError("posts say remove takes the word (or its number, as ls shows it)"); const list = await readLexicon(project.dir); const byNumber = /^\d+$/.test(w) && !list.some((x) => String(x.word).toLowerCase() === w.toLowerCase()); const r = await updateLexicon(project.dir, { remove: byNumber ? Number(w) - 1 : { word: w, item: item?.id ?? null } }); out(json ? JSON.stringify({ ok: true, changed: r.changed, entry: r.entry, lexicon: r.lexicon }, null, 2) : `removed ${JSON.stringify(r.entry.word)}${r.entry.item ? ` (${r.entry.item})` : ""}; ${r.lexicon.length} left`); return 0; } if (sub === "try") { const [text] = args; if (text === undefined) throw new SayError('posts say try takes the text: try "tbh atm"'); const { projectRedaction } = await import("./postRedaction.mjs"); const { spokenRead } = await import("umtool-report-to-video/post-redact"); const red = await projectRedaction(project.dir, manifest); const said = spokenRead(text, item ?? { id: null }, red); out(json ? JSON.stringify({ ok: true, text, said: said.text, lexicon: said.lexicon ?? [], slurs: said.slurs }, null, 2) : `${said.text}${said.lexicon?.length ? `\n (${said.lexicon.map((x) => `${x.word} -> ${x.say}`).join(", ")})` : ""}`); return 0; } if (sub === "stale") { const list = await readLexicon(project.dir); const rows = staleReads(manifest, list, project.id); if (json) out(JSON.stringify({ ok: true, stale: rows.length, reads: rows }, null, 2)); else { out(rows.length ? `${rows.length} picked read(s) say a lexicon entry the old way:` : `no picked read says a lexicon entry the old way (${list.length} entr${list.length === 1 ? "y" : "ies"})`); for (const r of rows) { out(` ${r.id} ${r.take}`); out(` ${r.entries.map((x) => `${JSON.stringify(x.word)} (now ${JSON.stringify(x.say)}${x.was ? `, was ${JSON.stringify(x.was)}` : ""})`).join(", ")}`); out(` ${r.fix}`); } } return 0; } if (sub !== "ls") throw new SayError(`posts say: ls, add, remove, try or stale (not ${sub})`); const list = await readLexicon(project.dir); const shown = item ? lexiconFor(list, item.id).map((x) => list.find((y) => lexiconKey(y) === lexiconKey(x))).filter(Boolean) : list; if (json) out(JSON.stringify({ ok: true, file: LEXICON_FILE, lexicon: shown }, null, 2)); else { out(`${project.id}: ${shown.length} lexicon entr${shown.length === 1 ? "y" : "ies"}${item ? ` that apply to ${item.id}` : ""} (${LEXICON_FILE})${shown.length ? "" : ` -- umtool posts say ${project.id} add tbh "T-B-H"`}`); shown.forEach((x) => out(line(x, list.indexOf(x)))); } return 0; } /** `umtool posts voices …` (postsCli.mjs routes it here). */ export async function voicesCommand(project, rest, { json = false, out = (s) => console.log(s) }) { const [sub = "ls", ...args] = rest; if (sub === "set") { const [h, v] = args; if (!h || !v) throw new SayError("posts voices set takes a handle (or *) and a voice: set kirscheverstahl tara"); const r = await updateVoiceMap(project.dir, { set: { handle: h, voice: v } }); out(json ? JSON.stringify({ ok: true, voices: r.voices }, null, 2) : `${handleKey(h) === VOICE_MAP_OTHER ? "everyone else" : `@${handleKey(h)}`} reads in ${v}`); return 0; } if (sub === "remove") { const [h] = args; if (!h) throw new SayError("posts voices remove takes a handle (or *)"); const r = await updateVoiceMap(project.dir, { remove: h }); out(json ? JSON.stringify({ ok: true, voices: r.voices }, null, 2) : `${handleKey(h)} off the voice map`); return 0; } if (sub !== "ls") throw new SayError(`posts voices: ls, set or remove (not ${sub})`); const map = await readVoiceMap(project.dir); const manifest = (await readManifest(project.dir)) ?? {}; const { voiceSourceOf } = await import("umtool-report-to-video/post-say"); const { postNarrationKnobs } = await import("umtool-report-to-video/post-narration"); const { castForProject } = await import("./castStore.mjs"); const { castVoiceMap, characterOf } = await import("umtool-report-to-video/cast"); const k = postNarrationKnobs({}, manifest.render ?? {}); const castRead = await castForProject(project.dir); const cast = castVoiceMap(castRead.cast); // The layers a read asks (characterLayers.mjs): this video's own characters over this map, then the cast -- so the // table says what a read would say, and why. const L = await (await import("./characterLayers.mjs")).readLayers(project.dir); // Every author a thread read could voice: the items' own, their parents', quoted and linked posts'. const authors = new Map(); const count = (h, own) => { const key = handleKey(h); if (!key) return; const a = authors.get(key) ?? { handle: key, items: 0, context: 0 }; if (own) a.items += 1; else a.context += 1; authors.set(key, a); }; for (const e of manifest.timeline ?? []) { if (e?.type !== "post") continue; count(e.handle, true); for (const p of Array.isArray(e.parents) ? e.parents : []) count(p?.handle, false); if (e.quoted) count(e.quoted.handle, false); for (const l of Array.isArray(e.links) ? e.links : []) count(l?.handle, false); } // Each author's voice as a context post, and WHERE it comes from: the project's map, the cast, the default. const rows = [...authors.values()].sort((a, b) => b.items + b.context - (a.items + a.context)).map((a) => { const v = voiceSourceOf({ handle: a.handle, role: "parent:0" }, { map: L.map, cast: L.castMap, narrator: k.voice, engine: k.engine }); const c = characterOf(castRead.cast, a.handle); // `own`: this video's own character that answers for the handle (narration/characters.json), before the map. const own = v.from === "project" && v.character ? v.character : null; return { ...a, voice: v.spec, from: v.from, ...(typeof v.speed === "number" ? { speed: v.speed } : {}), mapped: a.handle in map, ...(own ? { own } : {}), ...(c ? { character: c.id, castVoice: c.voice } : {}) }; }); if (json) out(JSON.stringify({ ok: true, file: VOICES_FILE, voices: map, narrator: k.voice, engine: k.engine, cast: { file: castRead.file, characters: Object.keys(cast).length, ...(castRead.error ? { error: castRead.error } : {}) }, authors: rows }, null, 2)); else { out(`${project.id}: ${Object.keys(map).length} voice(s) on the map (${VOICES_FILE}); the narrator ${k.engine} · ${k.voice}`); for (const [h, v] of Object.entries(map)) out(` ${h === VOICE_MAP_OTHER ? "* (everyone else)" : `@${h}`} -> ${v}${cast[h] && cast[h] !== v ? ` (the cast says ${cast[h]}: overridden here)` : ""}`); if (castRead.error) out(` the cast is not read: ${castRead.error}`); if (rows.length) out(" the cut's authors, as a context post (their own items read in the narrator's voice unless mapped or cast):"); if (L.projectRead.error) out(` this video's own characters are not read: ${L.projectRead.error}`); for (const r of rows) out(` @${r.handle} ${r.voice}${r.speed !== undefined ? ` ×${r.speed}` : ""} (${r.from === "project" ? (r.own ? `this video's character: ${r.own}${r.mapped ? "; the map's entry is under it" : ""}` : "project") : r.from === "cast" ? `cast: ${r.character}` : "default"}) -- ${r.items} item(s), ${r.context} context post(s)`); } return 0; }