// WHAT A SYNTHESIZED READ SAYS, AND IN WHOSE VOICE (operator, 4 Nov 2026: "we // want the plain apps to do as much heavy lifting as possible so cheaper // models can more easily do these tasks without having to improvise shell // scripts"). umtool/docs/knobs.md, "Pronunciation and voices". // // THE LEXICON -- a project's pronunciation list, `narration/lexicon.json` in // the project (never the manifest: the narrated segments' cache keys carry // render.postNarration, and a word said differently is a new TAKE, not a new // card) -- `[{ word, say, case?, item?, note? }]`: // // word a word or a phrase as the posts write it ("tbh", "@grok", "at the moment") // say what the voice is asked to say for it ("T-B-H", "At grok") // case true: matched with its case (default: without) // item a post item's id: only that item's read (default: every read) // // A match is a WHOLE word: no letter, digit or underscore either side, and no // apostrophe-and-letter after it ("can" is not the "can" of "can't"); the // words of a phrase across any run of spaces. Regex characters in a word are // literal ("C++", "(sic)"). An item's own entry wins over the project's for // the same text; a longer match wins over a shorter one inside it; a // replacement is never matched again. // // It is applied where the words are turned into the text a voice SAYS // (post-redact.mjs spokenRead): every synthesized read -- a script's take, // each piece of a thread read, the bench's re-take. The slur filter and the // redaction WIN: a span the filter masks or the redaction blanks is never // replaced (the slur is left out, beeped or its stand-in said; a blanked name // is dropped, even when an entry's spoken form would say it). // // A take records what it applied (`takes[i].lexicon`: `[{ word, say, item? }]`), // so a read SAID THE OLD WAY is known (staleLexicon): an entry that matches // the words the take read and that the take did not apply with the same // spoken form. // // THE VOICE MAP -- `narration/voices.json` in the project, `{ "": // "", "*": "" }`: the stock voice each author's words are read // in by a read (a single post's take, each piece of a thread read: // lib/report/postThreadRead.mjs). Handles without "@", any case. A voice is // bare ("tara": the read's engine) or names its engine ("kokoro:am_michael"). // "*" is everyone the map does not name (default: CONTEXT_VOICE_DEFAULTS for // the engine). The map is the project's OVERRIDE LAYER over THE CAST // (cast.mjs: the characters that recur across projects, each with its voice): // the read's own override, the item's own character, the map (and the // project's own characters: cast.mjs projectPresetMap), the cast, the // narrator's (the item's own author), the map's "*", the default -- // voiceSourceOf, the one function every read goes through. // // PURE and dependency-free. /** At most this many entries; a word, a spoken form at most this long. */ export const LEXICON_MAX = 500; export const LEXICON_WORD_MAX = 120; export const LEXICON_SAY_MAX = 300; export const LEXICON_KEYS = Object.freeze(["word", "say", "case", "item", "note"]); /** The project files (relative to the project's folder). */ export const LEXICON_FILE = "narration/lexicon.json"; export const VOICES_FILE = "narration/voices.json"; /** The voice map's key for everyone it does not name. */ export const VOICE_MAP_OTHER = "*"; export const VOICE_MAP_MAX = 200; /** The voice a context post's author reads in when the map names neither them nor "*", by engine. */ export const CONTEXT_VOICE_DEFAULTS = Object.freeze({ orpheus: "leo" }); const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); const str = (v) => (typeof v === "string" ? v : ""); const VOICE_RE = /^(?:(?:orpheus|kokoro|espeak-ng):)?[A-Za-z0-9][A-Za-z0-9_.+-]{0,63}$/; const BARE_VOICE_RE = /^[A-Za-z0-9][A-Za-z0-9_.+-]{0,63}$/; /** The tts engines a voice may name (the editor's tts op). */ export const TTS_ENGINE_IDS = Object.freeze(["orpheus", "kokoro", "espeak-ng"]); const ITEM_RE = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/; const HANDLE_RE = /^[A-Za-z0-9_.-]{1,64}$/; // (No `-` or `/` escaped: under the `u` flag an escape outside a class must be a syntax character.) const escRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); const W = "[\\p{L}\\p{N}_]"; /** A word as written, its spaces collapsed. */ const tidy = (w) => str(w).replace(/\s+/g, " ").trim(); /** Every reason a lexicon is refused (empty: it is fine). */ export function validateLexicon(list, where = LEXICON_FILE) { if (list === undefined || list === null) return []; if (!Array.isArray(list)) return [`${where} must be a list of {word, say, case?, item?, note?}`]; if (list.length > LEXICON_MAX) return [`${where}: at most ${LEXICON_MAX} entries`]; const errors = []; const seen = new Set(); list.forEach((x, i) => { const w = `${where}[${i}]`; if (!isObj(x)) return errors.push(`${w} must be {word, say}`); for (const k of Object.keys(x)) if (!LEXICON_KEYS.includes(k)) errors.push(`${w}.${k} is not a lexicon key (${LEXICON_KEYS.join(", ")})`); const word = tidy(x.word); if (!word || !/[\p{L}\p{N}]/u.test(word)) errors.push(`${w}.word must hold a letter or a digit`); else if (word.length > LEXICON_WORD_MAX) errors.push(`${w}.word: at most ${LEXICON_WORD_MAX} characters`); if (typeof x.say !== "string" || !x.say.trim()) errors.push(`${w}.say must be what the voice says for it (a redaction leaves a word out: umtool posts redact)`); else if (x.say.length > LEXICON_SAY_MAX) errors.push(`${w}.say: at most ${LEXICON_SAY_MAX} characters`); else if (/<(?!\/?(?:laugh|chuckle|sigh|cough|sniffle|groan|yawn|gasp)>)[^>]*>/i.test(x.say)) errors.push(`${w}.say: only Orpheus's tags may be in angle brackets`); if (x.case !== undefined && typeof x.case !== "boolean") errors.push(`${w}.case must be true or false`); if (x.item !== undefined && !(typeof x.item === "string" && ITEM_RE.test(x.item))) errors.push(`${w}.item must be a post item's id`); if (x.note !== undefined && typeof x.note !== "string") errors.push(`${w}.note must be a string`); const key = lexiconKey(x); if (word && seen.has(key)) errors.push(`${w}: "${word}" is on the list twice${x.item ? ` for ${x.item}` : ""}`); seen.add(key); }); return errors; } /** The identity of an entry: its words (in its case when `case`), and its item. */ export function lexiconKey(x) { const w = tidy(x?.word); return `${x?.case === true ? w : w.toLowerCase()}|${x?.case === true ? "c" : "i"}|${str(x?.item)}`; } /** A list as `{ word, say, case, item }` -- the invalid ones dropped. */ export function normalizeLexicon(list) { return (Array.isArray(list) ? list : []) .filter((x) => isObj(x) && tidy(x.word) && /[\p{L}\p{N}]/u.test(x.word) && typeof x.say === "string" && x.say.trim()) .map((x) => ({ word: tidy(x.word), say: x.say.trim(), case: x.case === true, item: typeof x.item === "string" && x.item ? x.item : null })); } /** One entry's pattern source: the word's characters literal, its spaces any run of spaces, whole-word edges. */ export function lexiconPattern(x) { const w = tidy(x?.word); if (!w) return null; const body = w.split(" ").map(escRe).join("\\s+"); return `(? x.item && x.item === item); const all = list.filter((x) => !x.item); const byLen = (a, b) => b.word.length - a.word.length; return [...own.sort(byLen), ...all.sort(byLen)]; } const overlaps = (a, b) => a.start < b.end && b.start < a.end; /** * Every place `lexicon` replaces in `text` for item `item`: `[{ start, end, entry }]`, in order, none * overlapping another or a `protect` span (`{start, end}` code units: a slur, a redacted term). */ export function lexiconHits(text, lexicon, { item = null, protect = [] } = {}) { const t = str(text); const entries = lexiconFor(lexicon, item); if (!t || !entries.length) return []; const taken = (Array.isArray(protect) ? protect : []).filter((s) => Number.isFinite(s?.start) && Number.isFinite(s?.end) && s.end > s.start).map((s) => ({ start: s.start, end: s.end })); const hits = []; for (const x of entries) { const re = new RegExp(lexiconPattern(x), x.case ? "gu" : "giu"); for (const m of t.matchAll(re)) { if (!m[0]) continue; const h = { start: m.index, end: m.index + m[0].length, entry: x }; if (taken.some((s) => overlaps(s, h))) continue; taken.push(h); hits.push(h); } } return hits.sort((a, b) => a.start - b.start); } /** An entry as a take records it. */ export const appliedOf = (x) => ({ word: x.word, say: x.say, ...(x.item ? { item: x.item } : {}) }); /** * `text` with the lexicon applied for item `item`, never inside a `protect` span. Returns `{ text, applied }`: * `applied` the entries it replaced, once each, as a take records them. */ export function applyLexicon(text, lexicon, { item = null, protect = [] } = {}) { const t = str(text); const hits = lexiconHits(t, lexicon, { item, protect }); if (!hits.length) return { text: t, applied: [] }; let out = ""; let at = 0; const applied = new Map(); for (const h of hits) { out += t.slice(at, h.start) + h.entry.say; at = h.end; applied.set(lexiconKey(h.entry), appliedOf(h.entry)); } return { text: out + t.slice(at), applied: [...applied.values()] }; } /** The words a take read, as its record has them: its script, else its parts' words, else the item's script. */ export function takeReadText(take, entry = null) { if (typeof take?.script === "string" && take.script.trim()) return take.script; const parts = Array.isArray(take?.parts) ? take.parts : []; if (parts.some((p) => typeof p?.text === "string")) return parts.map((p) => str(p.text)).join("\n\n"); return str(entry?.narration?.script); } /** * THE ENTRIES A TAKE STILL SAYS THE OLD WAY, pure: each entry of the lexicon that applies to the item and matches * the words the take read (takeReadText), unless the take applied it with the same spoken form -- * `[{ word, say, item?, was? }]` (`was`: the spoken form the take used, when it used another). A recorded take is * a person's own read: never stale. */ export function staleLexicon(entry, take, lexicon) { if (!take || take.engine === "recorded" || take?.source?.kind === "recorded") return []; const text = takeReadText(take, entry); const done = new Map((Array.isArray(take.lexicon) ? take.lexicon : []).filter(isObj).map((x) => [lexiconKey({ word: x.word, item: x.item, case: false }), str(x.say)])); const out = []; const seen = new Set(); for (const h of lexiconHits(text, lexicon, { item: entry?.id ?? null })) { const x = h.entry; const k = lexiconKey(x); if (seen.has(k)) continue; seen.add(k); const was = done.get(lexiconKey({ word: x.word, item: x.item, case: false })); if (was === x.say) continue; out.push({ ...appliedOf(x), ...(was !== undefined ? { was } : {}) }); } return out; } /** A take's lexicon record is fine (empty: it is). */ export function takeLexiconErrors(v, where) { if (v === undefined) return []; if (!Array.isArray(v) || v.length > LEXICON_MAX || !v.every((x) => isObj(x) && typeof x.word === "string" && typeof x.say === "string" && (x.item === undefined || typeof x.item === "string") && Object.keys(x).every((k) => ["word", "say", "item"].includes(k)))) { return [`${where} must be the lexicon entries it applied, [{word, say, item?}]`]; } return []; } // --------------------------------------------------------------------------- // The voice map. // --------------------------------------------------------------------------- /** A handle as the map keys it: no "@", lower case ("*" stays). */ export const handleKey = (h) => (str(h).trim() === VOICE_MAP_OTHER ? VOICE_MAP_OTHER : str(h).trim().replace(/^@+/, "").toLowerCase()); /** Every reason a voice map is refused. */ export function validateVoiceMap(map, where = VOICES_FILE) { if (map === undefined || map === null) return []; if (!isObj(map)) return [`${where} must be {"": "", "*": ""}`]; const keys = Object.keys(map); if (keys.length > VOICE_MAP_MAX) return [`${where}: at most ${VOICE_MAP_MAX} handles`]; const errors = []; for (const k of keys) { if (k !== VOICE_MAP_OTHER && (!HANDLE_RE.test(k) || k !== handleKey(k))) errors.push(`${where}: "${k}" is not a handle as the map keys it (lower case, no @), or "*"`); if (typeof map[k] !== "string" || !VOICE_RE.test(map[k])) errors.push(`${where}.${k} must be a stock voice's id ("tara", or with its engine "kokoro:am_michael")`); } return errors; } /** * A voice as written -- `"kokoro:am_michael"`, or bare `"tara"` (the read's engine, `engine`) -- as `{ engine, * voice }`; null when it is neither (a path, a URL, an engine the editor has not). */ export function voiceRefOf(spec, engine = null) { const s = str(spec).trim(); if (!s) return null; const at = s.indexOf(":"); if (at < 0) return BARE_VOICE_RE.test(s) ? { engine: engine ?? null, voice: s } : null; const e = s.slice(0, at); const v = s.slice(at + 1); if (!TTS_ENGINE_IDS.includes(e) || !BARE_VOICE_RE.test(v)) return null; return { engine: e, voice: v }; } /** `{engine, voice}` as `engine:voice` (bare when there is no engine). */ export const voiceSpecOf = (r) => (r?.engine ? `${r.engine}:${r.voice}` : str(r?.voice)); /** A layer's entry as `{ voice, speed?, tuning?, character? }`: a voice as written ("tara"), or a character's preset; null when it names no voice. */ function entryOf(v) { if (typeof v === "string") return v ? { voice: v } : null; return isObj(v) && typeof v.voice === "string" && v.voice ? v : null; } const hit = (entry, from) => ({ spec: entry.voice, from, ...(typeof entry.speed === "number" && Number.isFinite(entry.speed) ? { speed: entry.speed } : {}), // A character's Orpheus tuning (cast.mjs presetEntryOf: only when it has one). ...(isObj(entry.tuning) && Object.keys(entry.tuning).length ? { tuning: entry.tuning } : {}), ...(typeof entry.character === "string" && entry.character ? { character: entry.character } : {}), }); /** * The voice one piece of a read is said in, and WHERE IT CAME FROM, pure: `{ spec, from, speed?, tuning?, character? }` -- * `spec` as written (bare or `engine:voice`), `from` one of "override" (`--voice-for`, `--voice`), "item" (the item's * own character: `narration.character`), "project" (the project's character for the author, or its voice map), * "cast" (the cast's character for the handle), "narrator" (the item's own author: the narrator's voice), "default"; * `speed` the preset's (a character's `synthetic.speed`) and `character` its id, when the layer that answered is a * character's. FIRST HIT WINS, in order: the run's own `overrides` (`--voice-for`), the item's `voice` for its own * post (`--voice`), the item's own character for its author's words (`item`), the project's for the author (`map`), * the CAST's, the narrator's for the item's own author, the map's "*", the engine's context default, the narrator's. * * A layer's entry (`map[h]`, `cast[h]`, `item`) is a voice as written or a character's synthetic preset * `{ voice, speed?, character }` (cast.mjs presetEntryOf, projectPresetMap, castPresetMap). * * @param {{ handle?: string | null, role: string }} piece * @param {{ map?: Record, cast?: Record, item?: any, overrides?: Record, * self?: string | null, voice?: string | null, narrator: string, engine?: string }} o */ export function voiceSourceOf(piece, { map = {}, cast = {}, item = null, overrides = {}, self = null, voice = null, narrator, engine = "orpheus" }) { const h = handleKey(piece?.handle); const mine = piece?.role === "post" || (!!h && h === handleKey(self)); if (h && overrides[h]) return { spec: overrides[h], from: "override" }; if (piece?.role === "post" && voice) return { spec: voice, from: "override" }; const own = mine ? entryOf(item) : null; if (own) return hit(own, "item"); const named = h && h !== VOICE_MAP_OTHER; const p = named ? entryOf(map?.[h]) : null; if (p) return hit(p, "project"); const c = named ? entryOf(cast?.[h]) : null; if (c) return hit(c, "cast"); if (mine) return { spec: narrator, from: "narrator" }; const other = entryOf(map?.[VOICE_MAP_OTHER]); if (other) return { spec: other.voice, from: "project" }; return { spec: CONTEXT_VOICE_DEFAULTS[engine] ?? narrator, from: "default" }; } /** The voice one piece of a read is said in, as written (voiceSourceOf's `spec`). */ export function voiceForPiece(piece, o) { return voiceSourceOf(piece, o).spec; } /** * The voice one piece is said in, RESOLVED: `{ engine, voice, from, speed?, tuning?, character? }` -- a bare voice in * the read's `engine`, one that names its own engine in that one; `speed`, `tuning` and `character` as voiceSourceOf * says them. The thread read and a single post's take both ask this. */ export function resolvePieceVoice(piece, o) { const { spec, from, speed, tuning, character } = voiceSourceOf(piece, o); const ref = voiceRefOf(spec, o.engine ?? "orpheus") ?? { engine: o.engine ?? "orpheus", voice: String(spec) }; return { engine: ref.engine ?? o.engine ?? "orpheus", voice: ref.voice, from, ...(speed !== undefined ? { speed } : {}), ...(tuning ? { tuning } : {}), ...(character ? { character } : {}) }; } /** * THE TUNING A READ IS ASKED WITH, pure (lane character-tuning): the line's own (`flag`: the take's --temperature … * flags, a line's "use for this line only") beats its character's (`preset`: the synthetic preset's that answered for * the voice) -- `{ tuning, asked: true | "preset" }`, the take's `tuningAsked` -- or null: none to ask (no tuning * either way, or an engine that has no sampler: Kokoro, eSpeak NG). An empty tuning is none. */ /** * THE TUNING ONE READ IS ASKED WITH, AND WHOSE IT IS -- the one rule a post's take (makeTake, the bench's take op) and * every piece of a thread read follow (lane character-tuning, review 2): `own` the line's own values AS ASKED (the * flags, the bench's Tune, a `--for`/`--tuned` piece; never normalised first: an explicit default is the line's own), * `preset` its character's. Returns `{ tuning, asked, own }`: `tuning` the line's values over the character's, field * by field (null: none); `asked` true when the line names a sampler value of its own (or asks any value with no * character tuning to lay it over), "preset" when the sampler is the character's (a line asking only its takes keeps * the character's sampler), null when nothing is asked; `own` the line's values as asked (null: none). An engine with no * sampler is asked the line's own as it is (the editor says it ignores them) and none of the character's. * @param {{ own?: Record | null, preset?: Record | null, engine?: string | null }} [o] * @returns {{ tuning: Record | null, asked: true | "preset" | null, own: Record | null }} */ export function tuningAskOf({ own = null, preset = null, engine = null } = {}) { const mine = isObj(own) ? Object.fromEntries(Object.entries(own).filter(([, v]) => typeof v === "number" && Number.isFinite(v))) : {}; const hasOwn = Object.keys(mine).length > 0; if (engine !== "orpheus") return { tuning: hasOwn ? mine : null, asked: null, own: hasOwn ? mine : null }; const pre = isObj(preset) && Object.keys(preset).length ? preset : null; const tuning = pre ? { ...pre, ...mine } : hasOwn ? mine : null; const ownSampler = Object.keys(mine).some((k) => k !== "takes"); const asked = !tuning ? null : ownSampler || !pre ? true : "preset"; return { tuning, asked, own: hasOwn ? mine : null }; } export function readTuningOf({ flag = null, preset = null, engine = null } = {}) { if (engine !== "orpheus") return null; if (isObj(flag) && Object.keys(flag).length) return { tuning: flag, asked: true }; if (isObj(preset) && Object.keys(preset).length) return { tuning: preset, asked: "preset" }; return null; } /** * THE SPEED A PART IS ASKED AT, pure: the command's (`flag`), else the item's own (`own`: `narration.speed`, for its * own words -- set on that one item, it beats a character's), else the preset's (`preset`: the character's that * answered for the voice) -- and none (null) for an engine that has no speed (Orpheus), or at 1. */ export function readSpeedOf({ flag = null, preset = null, own = null, engine = null } = {}) { const v = [flag, own, preset].find((x) => typeof x === "number" && Number.isFinite(x)); return v === undefined || engine === "orpheus" || v === 1 ? null : v; } /** `--voice-for h=v` words as `{ handle: voice }` (handles keyed as the map keys them); throws naming a bad one. */ export function voiceOverridesOf(list) { const out = {}; for (const raw of (Array.isArray(list) ? list : []).flatMap((x) => String(x).split(",")).map((x) => x.trim()).filter(Boolean)) { const eq = raw.lastIndexOf("="); const h = eq > 0 ? handleKey(raw.slice(0, eq)) : ""; const v = eq > 0 ? raw.slice(eq + 1).trim() : ""; if (!h || (h !== VOICE_MAP_OTHER && !HANDLE_RE.test(h)) || !VOICE_RE.test(v)) throw new Error(`--voice-for takes = (got ${raw})`); out[h] = v; } return out; }