Archilyzer · Source

archilyzer

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

commit d1fd7a1cc9302219e4b47c6d4439939437dc05d7
parent ab3d1cb460938e5d190ab6ea3fb131c9a07470d4
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Wed,  4 Nov 2026 22:39:36 -0500

umtool: a project pronunciation lexicon and thread reads as a real command

`umtool posts say <p> add|ls|remove|try|stale` keeps a project's
pronunciation lexicon (narration/lexicon.json: "tbh" said "T-B-H",
"@grok" said "At grok"), applied in spokenRead to every synthesized
read -- a script's take, each piece of a thread read, the bench's
re-take. Whole words, case-insensitive unless --case, phrases across
spaces, regex characters literal, --item for one item's reads (it wins
over the project's). A masked slur and a redacted word are never
replaced: the slur filter and the redaction win, and a spoken form that
says either is masked or dropped too. A take records the entries it
applied (takes[i].lexicon); `stale` lists the picked reads that still
say an entry the old way, with the command that re-reads each.

`umtool posts narrate <p> <item> --take --thread [--parents 0|all|none|<n>]
[--skip-parent <id>]... [--no-quoted] [--no-linked] [--read-seen]
[--voice-for <handle>=<voice>]... [--dry-run] [--json]` does what the
operator-session narrate-v8 script did: the pieces in date order
(chronoPieces), a post the item before already shows not read again, a
voice per author from the project's voice map (`umtool posts voices <p>
set <handle> <voice>`, narration/voices.json, `*` for everyone else),
each part synthesized once by the editor's tts op into
narration/parts-cache/<sha1(voice|text)>.wav with the transcription lane
held meanwhile (only if it was not; released after, on failure and on a
signal), joined with 0.8 / 0.6 / 0.25 s pauses, its take-<n>.parts.json
beside it, saved with its parts' roles and picked in one write. Exit 0
made or already up to date, 1 a part failed (parts made stay cached),
2 usage; --json for the queue.

Both files live in the project, not 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.

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

Diffstat:
Mumtool/app/api/report/post-item/route.ts | 2+-
Mumtool/app/api/report/post-narration/route.ts | 8+++++---
Mumtool/bin/umtool.mjs | 8++++++++
Mumtool/lib/report/postNarrationCli.mjs | 36+++++++++++++++++++++++++++++++++---
Mumtool/lib/report/postRedaction.mjs | 14++++++++++----
Aumtool/lib/report/postSay.mjs | 317+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/postThreadRead.mjs | 434+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/postThreadRead.test.mjs | 346+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/postsCli.mjs | 42++++++++++++++++++++++++++++++++++++++----
Mumtool/report-to-video/package.json | 1+
Mumtool/report-to-video/post-narration.mjs | 10+++++++---
Mumtool/report-to-video/post-redact.mjs | 34++++++++++++++++++++++++----------
Aumtool/report-to-video/post-say.mjs | 266+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/post-say.test.mjs | 136+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
14 files changed, 1626 insertions(+), 28 deletions(-)

diff --git a/umtool/app/api/report/post-item/route.ts b/umtool/app/api/report/post-item/route.ts @@ -183,7 +183,7 @@ export async function GET(request: Request) { let redaction = null; try { // 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" }); + if (q.get("published") === "1") redaction = await projectRedaction(r.project.dir, found.manifest, { uncensored: q.get("uncensored") === "1", say: false }); } 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 @@ -109,9 +109,11 @@ export async function GET(request: Request) { } // 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 { slurs, lexicon } = spokenRead(script, e, red, { voice: benchVoice(red) }); const take = { ...(slurs ? { slurs } : {}), + // The pronunciation entries it said (post-say.mjs), as the POST above applied them. + ...(lexicon ? { lexicon } : {}), 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 } : {}), @@ -180,8 +182,8 @@ 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) 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, + // What the voice SAYS: the script with every redacted term left out (post-redact.mjs), each slur as the cut's + // filter has it (post-slurs.mjs) and the project's pronunciation lexicon applied (post-say.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; diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs @@ -115,6 +115,8 @@ // reel <project> --channel <slug>… [--since/--until/--own/--with-media/--replies/--order/--limit] post items // set-item <project> <item> hold=… media.<i>.start=… a post item's knobs // narrate <project> [<item>] --import | --take | --script | --pick | --approve | k=v | --all … narration +// narrate <project> <item> --take --thread [--parents 0|all] … a thread read (postThreadRead.mjs) +// say <project> ls | add | remove | try | stale · voices <project> ls | set | remove lexicon, voice map // fit <project> --all | <item>… narrated posts' videos cut to their best part // avatar <project> <handle> <image> | avatars <project> the authors' pictures // redact <project> ls | add "<term>" [--substring] | remove <n> words blanked from what is published @@ -1044,6 +1046,12 @@ function usage() { " [media.<i>.end=<s>] [media.<i>.mute=on|off] [media.<i>.crop=x,y,w,h|off] [media.<i>.push=on|off] [--json]", " umtool posts narrate <project> [--import | --list | <item> [--script \"…\"] [--take [--note \"…\"]] [--pick n] [--approve] [k=v …]", " | --all --draft-scripts | --all --take | --cut k=v …] a post read aloud (its takes: the editor's tts or yours)", + " umtool posts narrate <project> <item> --take --thread [--parents 0|all] [--skip-parent <id>]… [--no-quoted]", + " [--voice-for <handle>=<voice>]… [--dry-run] [--json] a THREAD READ: its context and his words in date", + " order, each in its author's voice, parts cached, one take saved and picked (exit 0 / 1)", + " umtool posts say <project> ls | add <word> \"<spoken>\" [--case] [--item <id>] | remove <word> | try \"<text>\" | stale", + " the PRONUNCIATION LEXICON every synthesized read applies (stale: picked reads that say it the old way)", + " umtool posts voices <project> ls | set <handle|*> <voice> | remove <handle> the voice map a thread read uses", " umtool posts fit <project> [--all | <item> …] [--linger s] [--dry-run] narrated posts' videos cut to their best part", " umtool posts avatar <project> [<handle> <image>|off] · avatars <project> the authors' pictures on the cards", " umtool posts redact <project> ls | add \"<term>\" [--substring] [--note \"…\"] | remove <n> words blanked from", diff --git a/umtool/lib/report/postNarrationCli.mjs b/umtool/lib/report/postNarrationCli.mjs @@ -16,6 +16,7 @@ // umtool posts narrate <p> --all --take [--limit N] every missing take, one at a time (resumable) // umtool posts narrate <p> --cut k=v … the cut's mix (render.postNarration) // umtool posts narrate <p> <item> --words [--worker <id>] its take's word timings (the editor's transcription, aligned; postFxCli.mjs) +// umtool posts narrate <p> <item> --take --thread [...] a THREAD READ, each piece in its author's voice (postThreadRead.mjs) // // Plain ESM: the CLI runs under bare node. import { execFile } from "node:child_process"; @@ -43,6 +44,8 @@ export const NARRATE_USAGE = [ " umtool posts narrate <project> <item> [--script \"…\"] [--take [--note \"…\"] [--voice v] [--engine e] [--speed s]]", " [--pick <n>] [--approve|--unapprove] [--off|--on] [lead=… tail=… ramp=… linger=… clip=read|full", " wet=… lowpass=… duck=on|off short=hold|loop attach=under|after lufs=… rate=… pace=fast|normal] [--json]", + " umtool posts narrate <project> <item> --take --thread [--parents 0|all|none|<n>] [--skip-parent <id>]… [--no-quoted]", + " [--no-linked] [--read-seen] [--voice-for <handle>=<voice>]… [--voice v] [--force] [--dry-run]", " umtool posts narrate <project> --all --draft-scripts [--force] | --all --take [--limit N]", " umtool posts narrate <project> --cut lead=… tail=… ramp=… linger=… clip=read|full wet=… lowpass=… duck=on|off short=hold|loop lufs=… rate=… pace=fast|normal engine=… voice=… follow=on|off follow.dim=… follow.ease=…", " --cut thread.parent=auto|full|excerpt|context|carry|hidden thread.quoted=… thread.carry=auto|on|off thread.reveal=on|off thread.shrink=… thread.dim=… thread.seconds=… thread.pan=…", @@ -51,6 +54,11 @@ export const NARRATE_USAGE = [ " writes (`pnpm ops tts`, a job on its tts queue; ARCHILYZER_EDITOR_URL + WORKER_TOKEN) -- umtool never synthesizes.", " --import reads narration/posts/index.json ([{id, entry, script, takes: [{file, engine, voice, seconds}], pick}]).", " <item>: the post item's id or its post's id. --pick <n>: the take's number as --list shows it (1 = the first).", + " Every synthesized read says the project's PRONUNCIATION LEXICON's words its way (umtool posts say <p> --help).", + " --take --thread: a THREAD READ -- the post it answers (--parents all: every ancestor), the post it quotes, the", + " posts it links to and his words in date order, each in its author's voice (umtool posts voices), each part", + " synthesized once into narration/parts-cache/, joined, saved and picked in one write (exit 0 also when it is", + " already up to date; 1 when a part could not be synthesized). --dry-run lists the pieces and parts, asks nothing.", " A new take is picked; a new script or pick takes the approval away. Scripts are the post VERBATIM (cleaned", " for pronunciation only); add emotion with Orpheus's tags <sigh> <laugh> <chuckle> <groan> <gasp> ….", " --delete <n>: the take out of the list, its file moved to narration/posts/<postId>/.trash/ (soft).", @@ -295,8 +303,9 @@ export async function makeTake(project, e, { script = null, note = null, engine const rel = takeFileOf(pid, n, eng, vox); const out = path.join(project.dir, ...rel.split("/")); const askTts = ask ?? (await import("umtool-report-to-video/narrate-via-editor")).askEditorTts; - // 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. + // What the voice SAYS: the script with every redacted term left out (post-redact.mjs), each slur as the cut's + // filter has it (post-slurs.mjs: skipped, its stand-in, or said for a beep), and each word of the project's + // pronunciation lexicon said its way (post-say.mjs) -- the script itself is kept as written. const red = redaction !== undefined ? redaction : await projectRedaction(project.dir, (await readManifest(project.dir)) ?? {}); const said = spokenRead(words, e, red); const ttsBody = (text) => ({ text, engine: eng, voice: vox, out, ...(spd !== null && eng !== "orpheus" ? { speed: spd } : {}) }); @@ -323,6 +332,8 @@ export async function makeTake(project, e, { script = null, note = null, engine ...(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 } : {}), + // The pronunciation entries it said (post-say.mjs; `umtool posts say <p> stale` reads them). + ...(said.lexicon ? { lexicon: said.lexicon } : {}), }; 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) })); @@ -349,7 +360,7 @@ async function timeTakeWords(project, rel, script, { askOp = null, emit = () => } /** `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 }) { +export async function narrateCommand(project, words, flags, { json = false, dryRun = false, out = (s) => console.log(s), str, multi = () => [] }) { const manifest = await readManifest(project.dir); if (!manifest) throw new NarrateError(`${project.id} has no manifest`); const render = manifest.render ?? {}; @@ -480,6 +491,25 @@ export async function narrateCommand(project, words, flags, { json = false, dryR } return 0; } + if (flags.has("--take") && flags.has("--thread")) { + // A THREAD READ (postThreadRead.mjs): its context and his words, each in its author's voice, one take picked. + const { threadCommand, parentsSelector } = await import("./postThreadRead.mjs"); + const { voiceOverridesOf } = await import("umtool-report-to-video/post-say"); + let overrides; + let parents; + try { + overrides = voiceOverridesOf(multi("--voice-for")); + parents = parentsSelector(str("--parents")); + } catch (err) { + throw new NarrateError(err instanceof Error ? err.message : String(err)); + } + return threadCommand(project, e, { + manifest, json, out, overrides, parents, skip: multi("--skip-parent").flatMap((x) => x.split(",")).map((x) => x.trim()).filter(Boolean), + quoted: !flags.has("--no-quoted"), linked: !flags.has("--no-linked"), readSeen: flags.has("--read-seen"), + voice: str("--voice"), engine: str("--engine"), note: str("--note"), force: flags.has("--force"), hold: !flags.has("--no-hold"), dryRun, + }); + } + if (flags.has("--thread")) throw new NarrateError("--thread goes with --take (umtool posts narrate <p> <item> --take --thread)"); if (flags.has("--take")) { const speedRaw = str("--speed"); const r = await makeTake(project, e, { diff --git a/umtool/lib/report/postRedaction.mjs b/umtool/lib/report/postRedaction.mjs @@ -1,16 +1,22 @@ // A PROJECT's REDACTION (umtool-report-to-video/post-redact.mjs): the corpus's // terms, its channels' post markup and the project's own `render.posts.redact`, // read from the channels tree the project's clip bench reads. What a take's -// synthesized read, Play's "As published" and the post item route blank. +// synthesized read, Play's "As published" and the post item route blank -- +// and, for a read only, the project's pronunciation lexicon (`say`). import { readPostRedaction } from "umtool-report-to-video/post-redact-files"; import { channelsDirFor, hasShadowChannels } from "../projects/report.mjs"; +import { readLexicon } from "./postSay.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 + * @param {{ uncensored?: boolean, say?: boolean }} [o] the slur filter off (post-slurs.mjs), the redaction kept; `say: false` + * leaves the lexicon out (a view of the card, which never reads it) */ -export async function projectRedaction(dir, manifest, { uncensored = false } = {}) { +export async function projectRedaction(dir, manifest, { uncensored = false, say: withSay = true } = {}) { const channelsDir = channelsDirFor(dir, manifest, { shadowExists: await hasShadowChannels(dir) }); - return readPostRedaction(channelsDir, manifest, { uncensored }); + const red = await readPostRedaction(channelsDir, manifest, { uncensored }); + // The project's pronunciation lexicon (postSay.mjs): what spokenRead says in a word's place -- a read's only. + const say = withSay ? await readLexicon(dir) : []; + return say.length ? { ...red, say } : red; } diff --git a/umtool/lib/report/postSay.mjs b/umtool/lib/report/postSay.mjs @@ -0,0 +1,317 @@ +// 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 <p> [ls] [--item <id>] [--json] +// umtool posts say <p> add <word|phrase> "<spoken>" [--case] [--item <id>] [--note "…"] [--json] +// umtool posts say <p> remove <word|n> [--item <id>] [--json] +// umtool posts say <p> try "<text>" [--item <id>] [--json] what a voice would be asked to say +// umtool posts say <p> stale [--json] picked reads that say an entry the old way +// umtool posts voices <p> [ls] | set <handle|*> <voice> | remove <handle|*> [--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"; + +export class SayError extends Error { + constructor(message) { + super(message); + this.name = "SayError"; + } +} + +export const SAY_USAGE = [ + "usage: umtool posts say <project> [ls] [--item <id>] [--json]", + " umtool posts say <project> add <word|phrase> \"<spoken>\" [--case] [--item <id>] [--note \"…\"] [--json]", + " umtool posts say <project> remove <word|n> [--item <id>] [--json]", + " umtool posts say <project> try \"<text>\" [--item <id>] [--json]", + " umtool posts say <project> 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 <project> [ls] [--json]", + " umtool posts voices <project> set <handle|*> <voice> [--json]", + " umtool posts voices <project> remove <handle|*> [--json]", + " THE VOICE MAP (narration/voices.json): the stock voice each author's words are read in by a thread read", + " (umtool posts narrate <p> <item> --take --thread) -- set kirscheverstahl tara; `*` is everyone it does not name", + " (default leo on Orpheus). The item's own author reads in the item's narrator voice unless the map 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 = `${file}.${process.pid}.${Date.now()}.tmp`; + 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?} | <index> }`. 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 <p> 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-<id>), 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 = "<p>") { + 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)}`); + 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 { voiceForPiece } = await import("umtool-report-to-video/post-say"); + const { postNarrationKnobs } = await import("umtool-report-to-video/post-narration"); + const k = postNarrationKnobs({}, manifest.render ?? {}); + // 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); + } + const rows = [...authors.values()].sort((a, b) => b.items + b.context - (a.items + a.context)).map((a) => ({ + ...a, voice: voiceForPiece({ handle: a.handle, role: "parent:0" }, { map, narrator: k.voice, engine: k.engine }), mapped: a.handle in map, + })); + if (json) out(JSON.stringify({ ok: true, file: VOICES_FILE, voices: map, narrator: k.voice, engine: k.engine, 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}`); + if (rows.length) out(" the cut's authors, as a context post (their own items read in the narrator's voice unless mapped):"); + for (const r of rows) out(` @${r.handle} ${r.voice}${r.mapped ? "" : " (default)"} -- ${r.items} item(s), ${r.context} context post(s)`); + } + return 0; +} diff --git a/umtool/lib/report/postThreadRead.mjs b/umtool/lib/report/postThreadRead.mjs @@ -0,0 +1,434 @@ +// A THREAD READ AS A REAL COMMAND (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 and instead +// call real tools"): a post item read WITH ITS CONTEXT -- the post it answers +// (or every ancestor), the post it quotes, the posts its words link to, and +// his words -- each piece in its author's voice, in date order, made into one +// take, saved and picked in ONE write (one undo point). +// +// umtool posts narrate <p> <item> --take --thread [--parents 0|all|none|<n>] [--skip-parent <id|parent:i>]… +// [--no-quoted] [--no-linked] [--read-seen] [--voice-for <handle>=<voice>]… [--voice v] [--engine e] +// [--note "…"] [--force] [--no-hold] [--dry-run] [--json] +// +// THE PIECES (post-thread.mjs chronoPieces): every context post the card draws with words, and his post, oldest +// first (each at its own date; without dates: the parents oldest first, the quoted post, the linked posts, his). +// --parents 0 (default) the post it answers only; all: every ancestor; <n>: parents 0..n; none: no parent +// --skip-parent <id> leave one ancestor out (its post id, or its role parent:<i>); repeatable +// --no-quoted / --no-linked leave the quoted post / the linked posts out +// a parent or quoted post ON SCREEN FROM THE ITEM BEFORE (the item before in the cut, its parents, the scene its +// run leaves) is not read again -- --read-seen reads it anyway (a read for another cut, whose item before differs) +// A context piece reads its paraphrase when it has one, else its words, cleaned to be spoken (draftScript); his +// piece reads his script (drafted from his words, and set, when he has none). Every piece is what a voice SAYS +// (post-redact.mjs spokenRead): the redaction left out, the slur filter's voice (a beep cannot be timed on a joined +// read: such a slur is skipped), the project's pronunciation lexicon applied (post-say.mjs, `umtool posts say`). +// +// THE VOICES (post-say.mjs voiceForPiece): --voice-for, --voice (his post), the project's voice map +// (`umtool posts voices`), the narrator's for the item's own author, the map's "*", leo (Orpheus). +// +// THE PARTS: each piece split as a long read is (post-narration.mjs scriptParts: its paragraphs, a paragraph over +// 60 words at a sentence end), each part synthesized ONCE and kept in the project's PARTS CACHE -- +// narration/parts-cache/<sha1(voice|text)>.wav (another engine than Orpheus: sha1(engine|voice|text)) -- so a part +// read once is never asked again, in this read or any other. A part not in the cache is asked of the EDITOR's tts op +// (askEditorTts: `POST /api/ops/tts`, a job on its tts queue; the GPU and the heavy slot are its to arbitrate), one +// at a time; the transcription lane is held while they are asked (only when it was not held; released after, on a +// failure and on a signal too; --no-hold: left alone). +// +// THE TAKE: the parts joined with the pauses (POST_PART_GAP: 0.8 s between pieces, 0.6 between paragraphs, 0.25 +// inside one) by ffmpeg into narration/posts/<postId>/take-<n>.<engine>-thread.wav, its parts meta beside it +// (take-<n>.parts.json: each part's text, voice, role, piece, file, start, seconds, gap), measured, and added with +// its parts (each part's ROLE stored), the lexicon it applied, its slur state and how it was asked (`read`) -- +// picked, in one write. A read whose words and voices are what the picked take already says is left alone +// (--force makes it again). +// +// Exit codes: 0 made (or already up to date, `upToDate: true`); 1 a part could not be synthesized, the join +// failed or the write was refused (`--json`: `{ok: false, error}` on stdout too); 2 a usage error. +// +// Plain ESM: the CLI runs it under bare node. +import { execFile } from "node:child_process"; +import { createHash } from "node:crypto"; +import { mkdir, readdir, stat, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { promisify } from "node:util"; +import { POST_PART_GAP, draftScript, nextTakeNumber, pickedTake, postIdOf, postNarrationKnobs, scriptParts, takeFileOf, takesDirOf } from "umtool-report-to-video/post-narration"; +import { chronoPieces } from "umtool-report-to-video/post-thread"; +import { cardText, parentsOf } from "umtool-report-to-video/post-item"; +import { planContext } from "umtool-report-to-video/post-conversation"; +import { spokenRead } from "umtool-report-to-video/post-redact"; +import { voiceForPiece } from "umtool-report-to-video/post-say"; +import { readManifest } from "../projects/report.mjs"; +import { withEditNotes } from "./edit-guard.mjs"; +import { manifestToken, updatePostNarration } from "./manifest.mjs"; + +const execFileP = promisify(execFile); +const FFMPEG = () => process.env.FFMPEG_BIN ?? "ffmpeg"; +const r3 = (v) => Math.round(v * 1000) / 1000; +const str = (v) => (typeof v === "string" ? v : ""); +const norm = (t) => str(t).replace(/\s+/g, " ").trim(); + +/** The project's parts cache (relative to its folder). */ +export const PARTS_CACHE = "narration/parts-cache"; +/** The rate the parts are joined at (the editor's tts cache: 48 kHz mono). */ +const JOIN_RATE = 48000; + +export class ThreadReadError extends Error { + constructor(message) { + super(message); + this.name = "ThreadReadError"; + } +} + +export const THREAD_READ_USAGE = [ + " umtool posts narrate <project> <item> --take --thread [--parents 0|all|none|<n>] [--skip-parent <id|parent:i>]…", + " [--no-quoted] [--no-linked] [--read-seen] [--voice-for <handle>=<voice>]… [--voice v] [--engine e]", + " [--note \"…\"] [--force] [--no-hold] [--dry-run] [--json]", + " A THREAD READ: the post it answers (--parents all: every ancestor; none: no parent), the post it quotes, the posts", + " its words link to and his words, in DATE order, each in its author's voice (the project's voice map, umtool posts", + " voices; --voice-for handle=voice for this read), the redaction, the slur filter and the pronunciation lexicon", + " (umtool posts say) applied. A parent or quoted post the item before already shows is not read again (--read-seen:", + " it is). Each part is synthesized once by the editor (its tts op, a job) into narration/parts-cache/ and reused by", + " every read after; the take (take-<n>.<engine>-thread.wav + take-<n>.parts.json) is saved with its parts' roles and", + " PICKED in one write (one undo point). --dry-run: the pieces, voices and parts (cached or to synthesize), nothing", + " asked. Up to date already (same words, same voices): left alone, exit 0 (--force: made again). Exit 1: a part", + " could not be synthesized (the parts already made stay cached: run it again).", +].join("\n"); + +/** A part's cache key: sha1 of `voice|text` (an engine other than Orpheus: `engine|voice|text`). */ +export const partKey = (engine, voice, text) => createHash("sha1").update(engine === "orpheus" ? `${voice}|${text}` : `${engine}|${voice}|${text}`).digest("hex"); + +/** `--parents` as a selector: "0" (default), "all", "none", or a whole number n (parents 0..n). */ +export function parentsSelector(v) { + const s = v === null || v === undefined || v === "" ? "0" : String(v).trim().toLowerCase(); + if (s === "all" || s === "none") return s; + if (/^\d$/.test(s)) return s; + throw new ThreadReadError(`--parents takes 0, all, none or a parent's index (0-7) (got ${v})`); +} + +/** The ids of the posts already on screen as item `e` opens (the item before, its parents, its run's scene). */ +export function seenIds(manifest, e) { + const tl = Array.isArray(manifest?.timeline) ? manifest.timeline : []; + const i = tl.findIndex((x) => x?.id === e?.id); + if (i <= 0) return new Set(); + const { prev, scene } = planContext(tl, i, manifest?.render ?? {}); + const out = new Set(); + if (prev?.type === "post") { + for (const id of [postIdOf(prev), str(prev.originalId)]) if (id) out.add(id); + for (const p of parentsOf(prev)) if (str(p.id)) out.add(str(p.id)); + } + for (const t of Array.isArray(scene?.tiles) ? scene.tiles : []) if (str(t?.id)) out.add(str(t.id)); + return out; +} + +/** + * THE READ, PIECE BY PIECE, pure: `{ engine, narrator, pieces: [{ role, handle, date, voice, written, text, + * lexicon, slurs }], skipped: [{ role, id?, why }], want, voice, script, lexicon, slurs }` -- `text` what the voice + * says (spokenRead), `want` the whole read (pieces joined by a blank line), `voice` the take's label (its voices + * joined by "+"), `script` his script when he had none (set with the take). + * + * @param {Record<string, any>} manifest + * @param {Record<string, any>} e the post item + * @param {{ red?: any, map?: Record<string, string>, overrides?: Record<string, string>, parents?: string, + * skip?: string[], quoted?: boolean, linked?: boolean, readSeen?: boolean, voice?: string | null, engine?: string | null }} [o] + */ +export function threadReadPlan(manifest, e, { red = null, map = {}, overrides = {}, parents = "0", skip = [], quoted = true, linked = true, readSeen = false, voice = null, engine = null } = {}) { + const render = manifest?.render ?? {}; + const k = postNarrationKnobs(e, render); + const eng = engine ?? e.narration?.engine ?? k.engine; + const narrator = e.narration?.voice ?? k.voice; + const sel = parentsSelector(parents); + const seen = readSeen ? new Set() : seenIds(manifest, e); + const skips = new Set((skip ?? []).map((s) => String(s).trim()).filter(Boolean)); + const ps = parentsOf(e); + // A beep needs the slur's time in the take; a joined read is not word-timed as it is made -- skip it there. + const slurVoice = red?.slurs?.voice === "beep" ? "skip" : undefined; + const own = str(e.narration?.script).trim(); + const script = own ? null : draftScript(cardText(e)).script || null; + const pieces = []; + const skipped = []; + for (const p of chronoPieces(e)) { + const m = /^parent:(\d)$/.exec(p.role); + if (m) { + const at = Number(m[1]); + const id = str(ps[at]?.id); + if (sel === "none" || (sel !== "all" && at > Number(sel))) { + skipped.push({ role: p.role, ...(id ? { id } : {}), why: `--parents ${sel}` }); + continue; + } + if (skips.has(p.role) || (id && skips.has(id))) { + skipped.push({ role: p.role, ...(id ? { id } : {}), why: "--skip-parent" }); + continue; + } + if (id && seen.has(id)) { + skipped.push({ role: p.role, id, why: "on screen from the item before (--read-seen reads it)" }); + continue; + } + } + if (p.role === "quoted") { + const id = str(e.quoted?.id); + if (!quoted) { + skipped.push({ role: p.role, ...(id ? { id } : {}), why: "--no-quoted" }); + continue; + } + if (id && seen.has(id)) { + skipped.push({ role: p.role, id, why: "on screen from the item before (--read-seen reads it)" }); + continue; + } + } + if (p.role.startsWith("linked:") && !linked) { + skipped.push({ role: p.role, why: "--no-linked" }); + continue; + } + const written = p.role === "post" ? own || script || "" : draftScript(p.text).script; + if (!norm(written)) { + skipped.push({ role: p.role, why: "no words to read" }); + continue; + } + const said = spokenRead(written, e, red, { voice: slurVoice }); + if (!norm(said.text)) { + skipped.push({ role: p.role, why: "nothing left to say (all of it redacted)" }); + continue; + } + const v = voiceForPiece({ handle: p.handle, role: p.role }, { map, overrides, self: str(e.handle), voice, narrator, engine: eng }); + pieces.push({ role: p.role, handle: p.handle, date: p.date, voice: v, written, text: said.text.trim(), lexicon: said.lexicon ?? [], slurs: said.slurs }); + } + if (!pieces.some((p) => p.role === "post")) throw new ThreadReadError(`${e.id} has no words of his own to read (--script "…" first)`); + const lexicon = [...new Map(pieces.flatMap((p) => p.lexicon).map((x) => [`${x.word.toLowerCase()}|${x.item ?? ""}`, x])).values()]; + const states = pieces.map((p) => p.slurs).filter(Boolean); + return { + engine: eng, narrator, pieces, skipped, script, + want: pieces.map((p) => p.text).join("\n\n"), + voice: [...new Set(pieces.map((p) => p.voice))].join("+"), + lexicon, slurs: states.includes("said") ? "said" : states[0] ?? null, + }; +} + +/** The read's PARTS, pure: each piece's parts (scriptParts) with its voice, role and cache key, in order. */ +export function readParts(plan) { + return plan.pieces.flatMap((pc, piece) => + scriptParts(pc.text).map((q) => ({ piece, para: q.para, role: pc.role, voice: pc.voice, text: q.text, key: partKey(plan.engine, pc.voice, q.text) })), + ); +} + +/** + * THE JOIN's TIMES, pure: each part's start in the take, its length, the gap before it (POST_PART_GAP: a new piece, + * a new paragraph, inside one) -- the parts meta as `take-<n>.parts.json` holds it -- and the take's length. + * `para` is the piece × 100 + the paragraph (post-thread.mjs reads a piece as `para` div 100). + */ +export function joinTimes(parts, seconds, { fileOf = (p) => `${PARTS_CACHE}/${p.key}.wav` } = {}) { + let t = 0; + const meta = parts.map((p, i) => { + const prev = i > 0 ? parts[i - 1] : null; + const gap = !prev ? 0 : p.piece !== prev.piece ? POST_PART_GAP.piece : p.para !== prev.para ? POST_PART_GAP.para : POST_PART_GAP.inside; + t += gap; + const s = Number(seconds[i]); + const row = { n: i + 1, para: p.piece * 100 + p.para, text: p.text, voice: p.voice, role: p.role, piece: p.piece, file: fileOf(p), start: r3(t), seconds: r3(s), gapBefore: gap }; + t += s; + return row; + }); + return { meta, seconds: r3(t) }; +} + +/** The `read` record of a take: how it was asked for (only what differs from the defaults). */ +export function readRecordOf({ parents = "0", skip = [], quoted = true, linked = true, readSeen = false, overrides = {}, voice = null }) { + return { + kind: "thread", parents: parentsSelector(parents), + ...(skip?.length ? { skip: [...skip] } : {}), ...(quoted ? {} : { quoted: false }), ...(linked ? {} : { linked: false }), + ...(readSeen ? { seen: true } : {}), ...(Object.keys(overrides ?? {}).length ? { voiceFor: { ...overrides } } : {}), ...(voice ? { voice } : {}), + }; +} + +/** Is the picked take this read already (the same words, voices and engine)? */ +export function upToDate(e, plan) { + const t = pickedTake(e); + return !!t && norm(t.script) === norm(plan.want) && str(t.voice) === plan.voice && (t.engine ?? "orpheus") === plan.engine; +} + +const fileThere = async (f) => !!(await stat(f).catch(() => null))?.isFile(); + +/** A file's length, seconds (ffprobe). */ +async function durationOf(file) { + const { measureTake } = await import("./postNarrationCli.mjs"); + const m = await measureTake(file); + if (!(m.seconds > 0)) throw new ThreadReadError(`${file} has no length (not a sound file?)`); + return m.seconds; +} + +/** + * MAKE A THREAD READ of post item `e` and keep it, picked: see the head of this file. `ask` (askEditorTts's shape: + * `(body, { emit }) => { jobId, result }`, writing `body.out`) and `lanes` (renderMode.mjs editorLanes' shape, or + * null: none held) are the tests' to stub. Returns `{ upToDate, plan, parts, take?, result?, fresh, cached, jobs, + * lane, dryRun }`. + */ +export async function threadTake(project, e, opts = {}) { + const { + manifest: m0 = null, red: red0 = undefined, map: map0 = undefined, overrides = {}, parents = "0", skip = [], quoted = true, linked = true, + readSeen = false, voice = null, engine = null, note = null, force = false, hold = true, dryRun = false, + ask = null, lanes: lanes0 = undefined, emit = () => {}, editor = null, signals = false, + } = opts; + const manifest = m0 ?? (await readManifest(project.dir)); + if (!manifest) throw new ThreadReadError(`${project.id} has no manifest`); + const red = red0 !== undefined ? red0 : await (await import("./postRedaction.mjs")).projectRedaction(project.dir, manifest); + const map = map0 !== undefined ? map0 : await (await import("./postSay.mjs")).readVoiceMap(project.dir); + const plan = threadReadPlan(manifest, e, { red, map, overrides, parents, skip, quoted, linked, readSeen, voice, engine }); + const parts = readParts(plan); + const cacheDir = path.join(project.dir, ...PARTS_CACHE.split("/")); + const wavOf = (p) => path.join(cacheDir, `${p.key}.wav`); + const have = await Promise.all(parts.map((p) => fileThere(wavOf(p)))); + const base = { plan, parts: parts.map((p, i) => ({ ...p, cached: have[i] })), fresh: 0, cached: have.filter(Boolean).length, jobs: [], lane: null, dryRun }; + if (!force && upToDate(e, plan)) return { ...base, upToDate: true }; + if (dryRun) return { ...base, upToDate: false }; + + // The parts not in the cache, asked of the editor one at a time -- the transcription lane held meanwhile. + await mkdir(cacheDir, { recursive: true }); + const todo = parts.map((p, i) => ({ p, i })).filter(({ i }) => !have[i]); + const jobs = []; + let fresh = 0; + let lane = todo.length ? "not held" : null; + let release = async () => {}; + const off = []; + if (todo.length && hold) { + let lanes = lanes0; + if (lanes === undefined) { + const { editorLanes } = await import("./renderMode.mjs"); + const { editorConfig } = await import("./fetchWindows.mjs"); + lanes = editorLanes(editorConfig(process.env)); + } + if (!lanes) lane = "not held (no editor token to ask with)"; + else { + try { + if (await lanes.isHeld("transcription")) lane = "already held (left alone)"; + else { + await lanes.hold("transcription"); + lane = "held, released after"; + let done = false; + release = async () => { + if (done) return; + done = true; + try { + await lanes.release("transcription"); + } catch (err) { + emit("note", { message: `the transcription lane could NOT be released (${err instanceof Error ? err.message : err}): pnpm ops lane --json '{"lane":"transcription","held":false}'` }); + } + }; + if (signals) { + for (const sig of ["SIGINT", "SIGTERM"]) { + const h = () => { + release().finally(() => process.exit(sig === "SIGINT" ? 130 : 143)); + }; + process.once(sig, h); + off.push(() => process.removeListener(sig, h)); + } + } + } + } catch (err) { + lane = `not held (${err instanceof Error ? err.message : err})`; + } + } + emit("note", { message: `the transcription lane: ${lane}` }); + } + try { + const askTts = ask ?? (await import("umtool-report-to-video/narrate-via-editor")).askEditorTts; + for (const [n, { p }] of todo.entries()) { + emit("note", { message: `part ${n + 1}/${todo.length} (${p.role}, ${p.voice}): asking the editor…` }); + await writeFile(path.join(cacheDir, `${p.key}.txt`), p.text); + try { + const { jobId } = await askTts({ text: p.text, engine: plan.engine, voice: p.voice, out: wavOf(p) }, { ...(editor ? { editor } : {}), emit }); + if (jobId) jobs.push(jobId); + } catch (err) { + throw new ThreadReadError(`part ${p.role} "${p.text.slice(0, 60)}${p.text.length > 60 ? "…" : ""}" (${p.voice}) was not synthesized: ${err instanceof Error ? err.message : err} -- the ${fresh + base.cached} part(s) made are cached; run it again`); + } + if (!(await fileThere(wavOf(p)))) throw new ThreadReadError(`the editor's job ${jobs.at(-1) ?? "?"} finished but ${PARTS_CACHE}/${p.key}.wav is not there`); + fresh += 1; + } + } finally { + await release(); + for (const f of off) f(); + } + + // The join: each part resampled to one rate, the gap before it laid in as silence, all concatenated. + const seconds = []; + for (const p of parts) seconds.push(await durationOf(wavOf(p))); + const { meta, seconds: total } = joinTimes(parts, seconds); + const pid = postIdOf(e); + const dir = path.join(project.dir, ...takesDirOf(pid).split("/")); + await mkdir(dir, { recursive: true }); + const n = nextTakeNumber(e, await readdir(dir).catch(() => [])); + const rel = takeFileOf(pid, n, plan.engine, "thread"); + const out = path.join(project.dir, ...rel.split("/")); + const inputs = parts.flatMap((p) => ["-i", wavOf(p)]); + const filt = meta.map((row, i) => `[${i}:a]aresample=${JOIN_RATE},aformat=channel_layouts=mono,adelay=${Math.round(row.gapBefore * 1000)}:all=1[a${i}]`); + filt.push(`${meta.map((_, i) => `[a${i}]`).join("")}concat=n=${meta.length}:v=0:a=1[out]`); + try { + await execFileP(FFMPEG(), ["-nostdin", "-v", "error", "-y", ...inputs, "-filter_complex", filt.join(";"), "-map", "[out]", "-ar", String(JOIN_RATE), "-ac", "1", out], { maxBuffer: 1 << 24 }); + } catch (err) { + throw new ThreadReadError(`the join failed: ${String(err?.stderr || err?.message || err).trim().split("\n").slice(-2).join(" | ")}`); + } + // Beside it, as the importer and the recording page read a take's parts (postNarrationCli.mjs partsFileOf). + const { measureTake, partsFileOf } = await import("./postNarrationCli.mjs"); + await writeFile(path.join(project.dir, ...partsFileOf(rel).split("/")), `${JSON.stringify(meta, null, 1)}\n`); + const mt = await measureTake(out); + const take = { + file: rel, engine: plan.engine, voice: plan.voice, seconds: mt.seconds ?? total, + source: { kind: "tts", engine: plan.engine, voice: plan.voice, script: plan.want }, + script: plan.want, at: new Date().toISOString(), + note: note ?? `thread read: ${plan.pieces.map((p) => `${p.role} (${p.voice})`).join(" + ")}`, + ...(Number.isFinite(mt.lufs) ? { lufs: mt.lufs } : {}), + parts: meta, + ...(plan.slurs ? { slurs: plan.slurs } : {}), + ...(plan.lexicon.length ? { lexicon: plan.lexicon } : {}), + read: readRecordOf({ parents, skip, quoted, linked, readSeen, overrides, voice }), + }; + const patch = { addTake: take, ...(plan.script ? { script: plan.script } : {}) }; + const { result, editNotes } = await withEditNotes(project, async () => updatePostNarration(project.dir, e.id, patch, { token: await manifestToken(project.dir) })); + return { ...base, upToDate: false, fresh, jobs, lane, take, result, editNotes }; +} + +/** The guard on the item as it is now (postThreadCli.mjs readListing): what the card would refuse, and its warnings. */ +async function guardOf(project, id) { + const { readListing } = await import("./postThreadCli.mjs"); + const manifest = await readManifest(project.dir); + const tl = manifest?.timeline ?? []; + const i = tl.findIndex((x) => x?.id === id); + if (i < 0) return { errors: [], warnings: [] }; + const L = readListing(tl[i], manifest.render ?? {}, planContext(tl, i, manifest.render ?? {})); + return { errors: L.errors ?? [], warnings: L.warnings ?? [], pieces: L.pieces }; +} + +/** `umtool posts narrate <p> <item> --take --thread …` (postNarrationCli.mjs routes it here). */ +export async function threadCommand(project, e, o) { + const { json = false, out = (s) => console.log(s) } = o; + const say = (s) => !json && out(s); + let r; + try { + r = await threadTake(project, e, { ...o, signals: true, emit: (_ev, f) => f?.message && say(f.message) }); + } catch (err) { + if (json && err instanceof ThreadReadError) { + out(JSON.stringify({ ok: false, id: e.id, error: err.message }, null, 2)); + return 1; + } + throw err; + } + const pieces = r.plan.pieces.map((p) => ({ role: p.role, handle: p.handle, date: p.date, voice: p.voice, words: p.text.split(/\s+/).filter(Boolean).length, ...(p.lexicon.length ? { lexicon: p.lexicon } : {}) })); + const guard = r.take ? await guardOf(project, e.id) : null; + if (json) { + out(JSON.stringify({ + ok: true, id: e.id, upToDate: r.upToDate, dryRun: r.dryRun, engine: r.plan.engine, voice: r.plan.voice, pieces, skipped: r.plan.skipped, + parts: r.parts.map((p) => ({ role: p.role, voice: p.voice, key: p.key, cached: p.cached, text: p.text })), + fresh: r.fresh, cached: r.cached, jobs: r.jobs, lane: r.lane, + ...(r.take ? { take: r.take, pick: r.result.narration?.pick ?? null, token: r.result.token, snapshot: r.result.snapshot ?? null, guard } : {}), + }, null, 2)); + return 0; + } + out(`${e.id}: a thread read of ${pieces.length} piece(s), ${r.parts.length} part(s) (${r.cached} cached${r.dryRun ? `, ${r.parts.length - r.cached} to synthesize` : ""})`); + for (const p of pieces) out(` ${p.role.padEnd(9)} ${p.voice.padEnd(6)} ${p.handle ? `@${p.handle}` : ""}${p.date ? ` ${p.date.slice(0, 16)}` : ""} ${p.words} words${p.lexicon ? ` (said: ${p.lexicon.map((x) => `${x.word} -> ${x.say}`).join(", ")})` : ""}`); + for (const s of r.plan.skipped) out(` (not read: ${s.role}${s.id ? ` ${s.id}` : ""} -- ${s.why})`); + if (r.upToDate) { + out(` up to date: the picked take already reads this, in these voices (--force makes it again)`); + return 0; + } + if (r.dryRun) return 0; + out(` ${r.take.file} ${r.take.seconds} s, ${r.fresh} part(s) synthesized${r.jobs.length ? ` (editor jobs ${r.jobs.join(", ")})` : ""}, picked`); + if (r.result.snapshot?.rel && !r.result.snapshot.skipped) out(` undo point: ${r.result.snapshot.rel} (umtool timeline ${project.id} undo)`); + if (guard?.errors?.length) out(` the card would REFUSE it:\n${guard.errors.map((x) => ` ${x}`).join("\n")}\n (umtool posts roles ${project.id} ${e.id})`); + for (const w of guard?.warnings ?? []) out(` warning: ${w}`); + return 0; +} diff --git a/umtool/lib/report/postThreadRead.test.mjs b/umtool/lib/report/postThreadRead.test.mjs @@ -0,0 +1,346 @@ +// A thread read as a command (postThreadRead.mjs): the pieces in date order, what is +// skipped (--parents, --skip-parent, a post the item before shows), the voices (the +// map, --voice-for), the parts cache and its keys, the join's times, the take +// (its parts meta, roles, lexicon, read record; picked in one write), up to date, +// a failure; the lexicon and the voice map through the CLI; and a re-take through +// the CLI against a stub editor (no real editor: ARCHILYZER_EDITOR_URL points at +// a server this test runs). +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { createHash } from "node:crypto"; +import { createServer } from "node:http"; +import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises"; +import { existsSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { after, before, test } from "node:test"; +import { joinTimes, partKey, readParts, seenIds, threadReadPlan, threadTake, upToDate } from "./postThreadRead.mjs"; +import { staleReads, threadArgsOf, updateLexicon } from "./postSay.mjs"; +import { postsCommand } from "./postsCli.mjs"; +import { partRoles } from "umtool-report-to-video/post-thread"; + +const ROOT = await mkdtemp(path.join(tmpdir(), "umtool-thread-read-")); +after(() => rm(ROOT, { recursive: true, force: true })); +const REPORTS = path.join(ROOT, "reports"); +const CH = path.join(ROOT, "channels"); +const ff = (args) => execFileSync("ffmpeg", ["-v", "error", "-y", ...args]); +/** A part: `secs` of a tone. */ +const tone = (f, secs = 0.5) => ff(["-f", "lavfi", "-i", `sine=f=220:d=${secs}`, "-ar", "48000", "-ac", "1", f]); + +const KIRSCHE = { id: "101", handle: "KirscheVerstahl", author: "Kirsche", date: "2026-10-30T09:00:00.000Z", text: "parent zero words, honestly" }; +const GRAND = { id: "100", handle: "Someone", author: "Someone", date: "2026-10-30T08:00:00.000Z", text: "the grandparent's words" }; +const QUOTED = { id: "102", handle: "Movail2", author: "Mo", date: "2026-10-30T09:30:00.000Z", text: "quoted words tbh" }; +const item = (id, o = {}) => ({ + type: "post", id: `p-${id}`, post: `subj-x/${id}`, platform: "x", author: "THE SUBJECT", handle: "ObviousRises", date: "2026-10-30T10:00:00.000Z", + text: `his words ${id}`, ...o, +}); +const threaded = (id, o = {}) => item(id, { parents: [KIRSCHE, GRAND], quoted: QUOTED, narration: { script: "his words tbh, atm" }, ...o }); + +async function project(name, timeline) { + 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, palette: { bg: "#000000", fg: "#ffffff", muted: "#888888", accent: "#c8752a" } }, + timeline, + }, null, 2)); + return { id: name, dir }; +} +const manifest = async (p) => JSON.parse(await readFile(path.join(p.dir, "video.manifest.json"), "utf8")); +const cli = async (args) => { + const lines = []; + const errs = []; + const code = await postsCommand(args, { root: REPORTS, out: (s) => lines.push(s), err: (s) => errs.push(s) }); + return { code, out: lines.join("\n"), err: errs.join("\n") }; +}; +/** A stubbed tts: each ask recorded and its `out` written as a tone. */ +const stubAsk = (asked) => async (body) => { + asked.push(body); + tone(body.out, 0.4 + (asked.length % 3) * 0.1); + return { jobId: `job-${asked.length}`, result: { wav: body.out, engine: body.engine, voice: body.voice } }; +}; +const stubLanes = (log, { held = false } = {}) => ({ + isHeld: async () => held, + hold: async (l) => log.push(`hold ${l}`), + release: async (l) => log.push(`release ${l}`), +}); +const NO_RED = { terms: [], markup: {}, slurs: null }; + +test("the plan: his context in DATE order, parent 0 by default; every ancestor with --parents all; voices by author", () => { + const e = threaded("1"); + const m = { render: {}, timeline: [e] }; + const plan = threadReadPlan(m, e, { red: NO_RED, map: { kirscheverstahl: "tara" } }); + assert.deepEqual(plan.pieces.map((p) => [p.role, p.voice]), [["parent:0", "tara"], ["quoted", "leo"], ["post", "zac"]]); + assert.deepEqual(plan.skipped.map((s) => [s.role, s.why]), [["parent:1", "--parents 0"]]); + assert.equal(plan.voice, "tara+leo+zac"); + assert.equal(plan.want, "parent zero words, honestly\n\nquoted words tbh\n\nhis words tbh, atm"); + const all = threadReadPlan(m, e, { red: NO_RED, parents: "all" }); + assert.deepEqual(all.pieces.map((p) => p.role), ["parent:1", "parent:0", "quoted", "post"]); + assert.deepEqual(threadReadPlan(m, e, { red: NO_RED, parents: "none" }).pieces.map((p) => p.role), ["quoted", "post"]); + assert.deepEqual(threadReadPlan(m, e, { red: NO_RED, parents: "1" }).pieces.map((p) => p.role), ["parent:1", "parent:0", "quoted", "post"]); + // --skip-parent by its id or its role; --no-quoted; --voice-for; --voice for his post. + const sk = threadReadPlan(m, e, { red: NO_RED, parents: "all", skip: ["101"], quoted: false, overrides: { someone: "dan" }, voice: "leah" }); + assert.deepEqual(sk.pieces.map((p) => [p.role, p.voice]), [["parent:1", "dan"], ["post", "leah"]]); + assert.deepEqual(sk.skipped.map((s) => s.why), ["--skip-parent", "--no-quoted"]); + assert.deepEqual(threadReadPlan(m, e, { red: NO_RED, parents: "all", skip: ["parent:1"] }).skipped.map((s) => s.role), ["parent:1"]); + assert.throws(() => threadReadPlan(m, e, { parents: "some" }), /--parents takes/); + // No dates: the parents oldest first, the quoted post, his. + const nd = threaded("2", { date: undefined, parents: [{ ...KIRSCHE, date: undefined }, { ...GRAND, date: undefined }], quoted: { ...QUOTED, date: undefined } }); + assert.deepEqual(threadReadPlan({ timeline: [nd] }, nd, { red: NO_RED, parents: "all" }).pieces.map((p) => p.role), ["parent:1", "parent:0", "quoted", "post"]); +}); + +test("a post the item before already shows is not read again (its post, its parents); --read-seen reads it", () => { + const before = item("101", { parents: [GRAND] }); + const e = threaded("3"); + const m = { render: {}, timeline: [before, e] }; + assert.ok(seenIds(m, e).has("101")); + const plan = threadReadPlan(m, e, { red: NO_RED, parents: "all" }); + assert.deepEqual(plan.pieces.map((p) => p.role), ["quoted", "post"]); + assert.match(plan.skipped.map((s) => s.why).join(), /on screen from the item before/); + assert.deepEqual(threadReadPlan(m, e, { red: NO_RED, parents: "all", readSeen: true }).pieces.map((p) => p.role), ["parent:1", "parent:0", "quoted", "post"]); +}); + +test("the lexicon and the redaction are applied to every piece; a beep is skipped on a joined read; parts, keys and times", () => { + const e = threaded("4", { parents: [{ ...KIRSCHE, text: "Quentin said tbh. ".repeat(1) + "x ".repeat(70) }] }); + const red = { terms: [{ term: "Quentin" }], markup: {}, slurs: null, say: [{ word: "tbh", say: "T-B-H" }, { word: "atm", say: "A-T-M", item: "p-4" }] }; + const plan = threadReadPlan({ timeline: [e] }, e, { red }); + assert.match(plan.pieces[0].text, /^said T-B-H\./); + assert.equal(plan.pieces[1].text, "quoted words T-B-H"); + assert.equal(plan.pieces[2].text, "his words T-B-H, A-T-M"); + assert.deepEqual(plan.lexicon, [{ word: "tbh", say: "T-B-H" }, { word: "atm", say: "A-T-M", item: "p-4" }]); + const parts = readParts(plan); + // The parent's 70+ words split at its sentence end: two parts of piece 0. + assert.deepEqual(parts.map((p) => [p.piece, p.para]), [[0, 0], [0, 0], [1, 0], [2, 0]]); + assert.equal(parts[2].key, createHash("sha1").update("leo|quoted words T-B-H").digest("hex"), "the cache key: sha1(voice|text)"); + assert.equal(partKey("kokoro", "af_heart", "hi"), createHash("sha1").update("kokoro|af_heart|hi").digest("hex")); + const { meta, seconds } = joinTimes(parts, [1, 1, 2, 3]); + assert.deepEqual(meta.map((r) => r.gapBefore), [0, 0.25, 0.8, 0.8]); + assert.deepEqual(meta.map((r) => r.start), [0, 1.25, 3.05, 5.85]); + assert.deepEqual(meta.map((r) => r.para), [0, 0, 100, 200]); + assert.deepEqual(meta.map((r) => r.role), ["parent:0", "parent:0", "quoted", "post"]); + assert.equal(seconds, 8.85); +}); + +test("threadTake: the parts asked once into the cache (the lane held, then released), joined, saved and PICKED with roles in one write; again: up to date", async () => { + const p = await project("tr", [item("0"), threaded("5")]); + const m = await manifest(p); + const asked = []; + const lanes = []; + const r = await threadTake(p, m.timeline[1], { red: { ...NO_RED, say: [{ word: "tbh", say: "T-B-H" }] }, map: { kirscheverstahl: "tara" }, ask: stubAsk(asked), lanes: stubLanes(lanes) }); + assert.equal(asked.length, 3); + assert.deepEqual(asked.map((a) => [a.voice, a.engine]), [["tara", "orpheus"], ["leo", "orpheus"], ["zac", "orpheus"]]); + assert.equal(asked[1].text, "quoted words T-B-H"); + assert.ok(asked[0].out.startsWith(path.join(p.dir, "narration", "parts-cache"))); + assert.deepEqual(lanes, ["hold transcription", "release transcription"]); + assert.equal(r.lane, "held, released after"); + assert.equal(r.take.file, "narration/posts/5/take-1.orpheus-thread.wav"); + assert.ok(existsSync(path.join(p.dir, r.take.file))); + const meta = JSON.parse(await readFile(path.join(p.dir, "narration/posts/5/take-1.parts.json"), "utf8")); + assert.deepEqual(meta.map((x) => [x.role, x.voice, x.piece]), [["parent:0", "tara", 0], ["quoted", "leo", 1], ["post", "zac", 2]]); + assert.ok(meta.every((x) => x.file.startsWith("narration/parts-cache/") && existsSync(path.join(p.dir, x.file)))); + const n = (await manifest(p)).timeline[1].narration; + assert.equal(n.takes.length, 1); + assert.equal(n.pick, 0); + const t = n.takes[0]; + assert.equal(t.voice, "tara+leo+zac"); + assert.deepEqual(t.lexicon, [{ word: "tbh", say: "T-B-H" }]); + assert.deepEqual(t.read, { kind: "thread", parents: "0" }); + assert.deepEqual(t.parts.map((x) => x.role), ["parent:0", "quoted", "post"]); + assert.deepEqual(partRoles((await manifest(p)).timeline[1]).map((x) => [x.role, x.source]), [["parent:0", "stored"], ["quoted", "stored"], ["post", "stored"]]); + assert.ok(Math.abs(t.seconds - (meta.at(-1).start + meta.at(-1).seconds)) < 0.06, "the take's length is the join's"); + const revs = await readdir(path.join(p.dir, "revisions")); + assert.equal(revs.filter((f) => f.includes("post-narration")).length, 1, "one undo point"); + // Again: the picked take already reads it -- nothing asked, nothing written. + const again = await threadTake(p, (await manifest(p)).timeline[1], { red: { ...NO_RED, say: [{ word: "tbh", say: "T-B-H" }] }, map: { kirscheverstahl: "tara" }, ask: stubAsk(asked), lanes: stubLanes(lanes) }); + assert.equal(again.upToDate, true); + assert.equal(asked.length, 3); + // --force: made again from the cache (no ask, no lane), a second take picked. + const forced = await threadTake(p, (await manifest(p)).timeline[1], { red: { ...NO_RED, say: [{ word: "tbh", say: "T-B-H" }] }, map: { kirscheverstahl: "tara" }, ask: stubAsk(asked), lanes: stubLanes(lanes), force: true }); + assert.equal(asked.length, 3); + assert.equal(forced.fresh, 0); + assert.equal(forced.cached, 3); + assert.equal(lanes.length, 2, "nothing to synthesize: the lane is not touched"); + assert.equal(forced.take.file, "narration/posts/5/take-2.orpheus-thread.wav"); + assert.equal((await manifest(p)).timeline[1].narration.pick, 1); + // Another voice for one author: only that piece is asked; the rest come from the cache. + const v2 = await threadTake(p, (await manifest(p)).timeline[1], { red: { ...NO_RED, say: [{ word: "tbh", say: "T-B-H" }] }, map: { kirscheverstahl: "mia" }, ask: stubAsk(asked), lanes: stubLanes(lanes, { held: true }) }); + assert.deepEqual(asked.slice(3).map((a) => a.voice), ["mia"]); + assert.equal(v2.lane, "already held (left alone)"); + assert.ok(!lanes.slice(2).includes("release transcription"), "a lane it did not hold is never released"); +}); + +test("threadTake: a part that fails is a ThreadReadError, the lane released, the parts made kept in the cache; --dry-run asks nothing", async () => { + const p = await project("trf", [threaded("6")]); + const m = await manifest(p); + const dry = await threadTake(p, m.timeline[0], { red: NO_RED, map: {}, ask: async () => assert.fail("asked"), lanes: stubLanes([]), dryRun: true }); + assert.equal(dry.dryRun, true); + assert.equal(dry.parts.length, 3); + assert.ok(dry.parts.every((x) => !x.cached)); + const asked = []; + const lanes = []; + const ok = stubAsk(asked); + const ask = async (body) => { + if (asked.length === 1) throw new Error("editor job job-2 failed — out of memory"); + return ok(body); + }; + await assert.rejects(threadTake(p, m.timeline[0], { red: NO_RED, map: {}, ask, lanes: stubLanes(lanes) }), (err) => err.name === "ThreadReadError" && /was not synthesized: editor job job-2 failed/.test(err.message)); + assert.deepEqual(lanes, ["hold transcription", "release transcription"]); + assert.equal((await manifest(p)).timeline[0].narration.takes, undefined, "nothing written"); + const cached = (await readdir(path.join(p.dir, "narration", "parts-cache"))).filter((f) => f.endsWith(".wav")); + assert.equal(cached.length, 1); + // Run again: the cached part is not asked again. + const r = await threadTake(p, m.timeline[0], { red: NO_RED, map: {}, ask: ok, lanes: stubLanes(lanes) }); + assert.equal(r.fresh, 2); + assert.equal(r.cached, 1); + assert.equal(upToDate((await manifest(p)).timeline[0], r.plan), true); +}); + +test("posts say: add (and update), ls, try, remove; an item's own entry; posts voices set / ls; refusals are usage errors", async () => { + const p = await project("say", [threaded("7"), item("8", { narration: { script: "tbh hi" } })]); + let r = await cli(["say", "say", "add", "tbh", "T-B-H"]); + assert.equal(r.code, 0, r.err); + assert.match(r.out, /added "tbh" -> "T-B-H"/); + r = await cli(["say", "say", "add", "tbh", "tee bee aitch"]); + assert.match(r.out, /updated "tbh"/); + r = await cli(["say", "say", "add", "atm", "at the moment", "--item", "7"]); + assert.equal(r.code, 0, r.err); + const lex = JSON.parse(await readFile(path.join(p.dir, "narration", "lexicon.json"), "utf8")); + assert.deepEqual(lex, [{ word: "tbh", say: "tee bee aitch" }, { word: "atm", say: "at the moment", item: "p-7" }]); + r = await cli(["say", "say", "try", "tbh, atm", "--item", "p-7", "--json"]); + assert.equal(JSON.parse(r.out).said, "tee bee aitch, at the moment"); + r = await cli(["say", "say", "try", "tbh, atm"]); + assert.match(r.out, /^tee bee aitch, atm/); + r = await cli(["say", "say", "ls", "--item", "p-8"]); + assert.match(r.out, /1 lexicon entry that apply to p-8/); + r = await cli(["say", "say", "remove", "atm"]); + assert.equal(r.code, 2, "atm is p-7's: name the item"); + r = await cli(["say", "say", "remove", "atm", "--item", "p-7"]); + assert.equal(r.code, 0, r.err); + assert.equal((await cli(["say", "say", "add", "!!", "x"])).code, 2); + assert.equal((await cli(["say", "say", "add", "x", "<b>"])).code, 2); + assert.equal((await cli(["say", "say", "add", "x", "y", "--item", "p-nope"])).code, 2); + // The voice map. + r = await cli(["voices", "say", "set", "@KirscheVerstahl", "tara"]); + assert.equal(r.code, 0, r.err); + r = await cli(["voices", "say", "set", "*", "dan"]); + assert.equal(r.code, 0, r.err); + assert.deepEqual(JSON.parse(await readFile(path.join(p.dir, "narration", "voices.json"), "utf8")), { kirscheverstahl: "tara", "*": "dan" }); + r = await cli(["voices", "say", "ls", "--json"]); + const j = JSON.parse(r.out); + assert.equal(j.authors.find((a) => a.handle === "kirscheverstahl").voice, "tara"); + assert.equal(j.authors.find((a) => a.handle === "movail2").voice, "dan"); + assert.equal((await cli(["voices", "say", "set", "x", "not a voice"])).code, 2); + assert.equal((await cli(["voices", "say", "remove", "nobody"])).code, 2); +}); + +test("posts say stale: the picked reads that say an entry the old way, with the command that re-reads each", async () => { + const p = await project("stale", [ + item("9", { narration: { script: "tbh one", takes: [{ file: "narration/posts/9/take-1.orpheus-zac.wav", seconds: 1, script: "tbh one" }], pick: 0 } }), + item("10", { narration: { script: "tbh two", takes: [{ file: "narration/posts/10/take-1.orpheus-zac.wav", seconds: 1, script: "tbh two", lexicon: [{ word: "tbh", say: "T-B-H" }] }], pick: 0 } }), + item("11", { narration: { script: "T-B-H three", takes: [{ file: "narration/posts/11/take-1.orpheus-thread.wav", seconds: 1, voice: "leo+zac", script: "tbh x\n\nT-B-H three", read: { kind: "thread", parents: "all", skip: ["5"], voiceFor: { a: "dan" } } }], pick: 0 } }), + item("12", { narration: { script: "tbh", takes: [{ file: "narration/posts/12/take-1.recorded-operator.wav", engine: "recorded", seconds: 1, script: "tbh" }], pick: 0 } }), + ]); + await updateLexicon(p.dir, { add: { word: "tbh", say: "T-B-H" } }); + const r = await cli(["say", "stale", "stale", "--json"]); + assert.equal(r.code, 0, r.err); + const j = JSON.parse(r.out); + assert.deepEqual(j.reads.map((x) => x.id), ["p-9", "p-11"]); + assert.equal(j.reads[0].fix, "umtool posts narrate stale p-9 --take"); + assert.equal(j.reads[1].fix, "umtool posts narrate stale p-11 --take --thread --parents all --skip-parent 5 --voice-for a=dan"); + assert.equal(threadArgsOf({ kind: "thread", parents: "0", quoted: false, seen: true }), " --no-quoted --read-seen"); + assert.equal(staleReads(await manifest(p), [], "stale").length, 0); +}); + +// --------------------------------------------------------------------------- +// Through the CLI, against a stub editor: the re-take applies the lexicon. +// --------------------------------------------------------------------------- + +const stub = { asks: [], lanes: [], held: false, server: null, url: "" }; +before(async () => { + let next = 1; + const jobs = new Map(); + stub.server = createServer(async (req, res) => { + const json = (code, v) => { + res.writeHead(code, { "content-type": "application/json" }); + res.end(JSON.stringify(v)); + }; + const url = new URL(req.url, "http://x"); + let body = ""; + for await (const c of req) body += c; + const b = body ? JSON.parse(body) : null; + if (req.headers.authorization !== "Bearer test-token") return json(401, { ok: false, error: "no" }); + if (req.method === "POST" && url.pathname === "/api/ops/tts") { + stub.asks.push(b); + const id = `stub-${next++}`; + tone(b.out, 0.6); + jobs.set(id, { wav: b.out, engine: b.engine, voice: b.voice, seconds: 0.6 }); + return json(200, { ok: true, jobId: id }); + } + const m = /^\/api\/ops\/job\/(.+)$/.exec(url.pathname); + if (req.method === "GET" && m && jobs.has(m[1])) return json(200, { ok: true, job: { id: m[1], status: "done" }, tail: [`@@tts-result ${JSON.stringify(jobs.get(m[1]))}`] }); + if (req.method === "GET" && url.pathname === "/api/ops/settings") return json(200, { ok: true, value: { transcription: { held: stub.held } } }); + if (req.method === "POST" && url.pathname === "/api/ops/lane") { + stub.lanes.push(`${b.lane}:${b.held}`); + return json(200, { ok: true }); + } + return json(404, { ok: false, error: `no ${url.pathname}` }); + }); + await new Promise((r) => stub.server.listen(0, "127.0.0.1", r)); + stub.url = `http://127.0.0.1:${stub.server.address().port}`; + process.env.ARCHILYZER_EDITOR_URL = stub.url; + process.env.WORKER_TOKEN = "test-token"; + process.env.NARRATE_VIA_EDITOR_POLL_MS = "20"; +}); +after(() => new Promise((r) => (stub.server ? stub.server.close(r) : r()))); + +test("CLI: `posts narrate --take` asks the editor to SAY the lexicon's words, records them, and the read is no longer stale", async () => { + const p = await project("cli-take", [item("20", { narration: { script: "tbh, @grok is this true" } })]); + assert.equal((await cli(["say", "cli-take", "add", "tbh", "T-B-H"])).code, 0); + assert.equal((await cli(["say", "cli-take", "add", "@grok", "At grok"])).code, 0); + stub.asks.length = 0; + const r = await cli(["narrate", "cli-take", "p-20", "--take", "--json"]); + assert.equal(r.code, 0, r.err); + assert.equal(stub.asks.length, 1); + assert.equal(stub.asks[0].text, "T-B-H, At grok is this true"); + const t = (await manifest(p)).timeline[0].narration.takes[0]; + assert.equal(t.script, "tbh, @grok is this true", "the script is kept as written"); + assert.deepEqual(t.lexicon, [{ word: "tbh", say: "T-B-H" }, { word: "@grok", say: "At grok" }]); + assert.equal(JSON.parse((await cli(["say", "cli-take", "stale", "--json"])).out).stale, 0); + // The spoken form changed: the read is stale (said the old way), and says what it said. + assert.equal((await cli(["say", "cli-take", "add", "tbh", "to be honest"])).code, 0); + const st = JSON.parse((await cli(["say", "cli-take", "stale", "--json"])).out); + assert.deepEqual(st.reads[0].entries, [{ word: "tbh", say: "to be honest", was: "T-B-H" }]); +}); + +test("CLI: `posts narrate --take --thread --json` -- a thread read through the editor, the lane held and released, a clear JSON result", async () => { + const p = await project("cli-thread", [threaded("21")]); + assert.equal((await cli(["voices", "cli-thread", "set", "kirscheverstahl", "tara"])).code, 0); + assert.equal((await cli(["say", "cli-thread", "add", "tbh", "T-B-H"])).code, 0); + stub.asks.length = 0; + stub.lanes.length = 0; + const dry = await cli(["narrate", "cli-thread", "p-21", "--take", "--thread", "--parents", "all", "--dry-run", "--json"]); + assert.equal(dry.code, 0, dry.err); + assert.equal(JSON.parse(dry.out).parts.length, 4); + assert.equal(stub.asks.length, 0); + const r = await cli(["narrate", "cli-thread", "p-21", "--take", "--thread", "--parents", "all", "--skip-parent", "100", "--voice-for", "Movail2=leah", "--json"]); + assert.equal(r.code, 0, r.err); + const j = JSON.parse(r.out); + assert.equal(j.ok, true); + assert.equal(j.upToDate, false); + assert.deepEqual(j.pieces.map((x) => [x.role, x.voice]), [["parent:0", "tara"], ["quoted", "leah"], ["post", "zac"]]); + assert.deepEqual(stub.asks.map((a) => a.text), ["parent zero words, honestly", "quoted words T-B-H", "his words T-B-H, atm"]); + assert.deepEqual(stub.lanes, ["transcription:true", "transcription:false"]); + assert.equal(j.take.file, "narration/posts/21/take-1.orpheus-thread.wav"); + assert.deepEqual(j.take.read, { kind: "thread", parents: "all", skip: ["100"], voiceFor: { movail2: "leah" } }); + assert.equal(j.pick, 0); + assert.deepEqual(j.guard.errors, []); + // Again: up to date, exit 0, nothing asked. + const again = await cli(["narrate", "cli-thread", "p-21", "--take", "--thread", "--parents", "all", "--skip-parent", "100", "--voice-for", "Movail2=leah", "--json"]); + assert.equal(again.code, 0); + assert.equal(JSON.parse(again.out).upToDate, true); + assert.equal(stub.asks.length, 3); + // Usage errors are exit 2. + assert.equal((await cli(["narrate", "cli-thread", "p-21", "--thread"])).code, 2); + assert.equal((await cli(["narrate", "cli-thread", "p-21", "--take", "--thread", "--parents", "most"])).code, 2); + assert.equal((await cli(["narrate", "cli-thread", "p-21", "--take", "--thread", "--voice-for", "tara"])).code, 2); +}); diff --git a/umtool/lib/report/postsCli.mjs b/umtool/lib/report/postsCli.mjs @@ -66,6 +66,17 @@ const SLURS_USAGE_LINES = [ " only), off or `umtool take … --uncensored` is the uncensored cut. umtool posts slurs --help: the whole story.", ]; +// `umtool posts say` / `posts voices` (postSay.mjs SAY_USAGE, VOICES_USAGE): its lines, kept here so the usage is one block. +const SAY_LINES = [ + " umtool posts say <project> [ls] | add <word|phrase> \"<spoken>\" [--case] [--item <id>] [--note \"…\"] | remove <word|n>", + " | try \"<text>\" [--item <id>] | stale [--json]", + " THE PRONUNCIATION LEXICON (narration/lexicon.json): \"tbh\" said \"T-B-H\" in every synthesized read (a take, a thread", + " read's pieces, the bench's re-take) -- whole words, without case unless --case, --item for one item's reads; a", + " masked slur and a redacted word are never replaced. stale: the picked reads that still say one the old way.", + " umtool posts voices <project> [ls] | set <handle|*> <voice> | remove <handle|*> [--json]", + " THE VOICE MAP (narration/voices.json): the voice a thread read gives each author (* everyone else; default leo).", +]; + 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]", @@ -128,8 +139,8 @@ export const POSTS_USAGE = [ " panel=: where the attachments sit -- beside the card, or at full width above (top) or below it (a wide one: auto).", ...ROLES_LINES, ...REREAD_LINES, - " umtool posts narrate <project> … a post item's narration: script, takes (the editor's tts), pick, approve, mix", - " (umtool posts narrate --help)", + " umtool posts narrate <project> … a post item's narration: script, takes (the editor's tts), pick, approve, mix,", + " a thread read (--take --thread) (umtool posts narrate --help)", " umtool posts fit <project> [--all|<item> …] [--linger s] [--dry-run] narrated posts' videos cut to their best part", " umtool posts fx <project> <item> [ls] | add word-zoom --match \"…\" [--at s] … | add caption --match \"…\" --text \"…\" | set <n> … | remove <n>", " a WORD ZOOM (the card pushed in on a word) or a CAPTION (a chip explaining a phrase) as it is read,", @@ -150,6 +161,7 @@ export const POSTS_USAGE = [ " 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, + ...SAY_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", @@ -160,7 +172,9 @@ export const POSTS_USAGE = [ " umtool posts scenes <project> [on|off] [--json] the MEDIA SCENES: neighbours with the same attachment", ].join("\n"); -const VALUED = new Set(["--set", "--attach", "--flag", "--author", "--id", "--crop", "--since", "--until", "--replies", "--order", "--limit", "--after", "--script", "--note", "--voice", "--engine", "--speed", "--pick", "--linger", "--derive", "--op", "--delete", "--match", "--target", "--occurrence", "--at", "--scale", "--hold", "--lead", "--ease", "--highlight", "--worker", "--without", "--drop-parts", "--text", "--place", "--rewind", "--zone", "--gap", "--from-scale", "--color", "--outline", "--outline-width", "--size", "--face", "--sfx", "--volume", "--bar", "--bar-style", "--tempo-for", "--tempo", "--parts", "--stretch", "--yell-gain", "--yell-style"]); +const VALUED = new Set(["--set", "--attach", "--flag", "--author", "--id", "--crop", "--since", "--until", "--replies", "--order", "--limit", "--after", "--script", "--note", "--voice", "--engine", "--speed", "--pick", "--linger", "--derive", "--op", "--delete", "--match", "--target", "--occurrence", "--at", "--scale", "--hold", "--lead", "--ease", "--highlight", "--worker", "--without", "--drop-parts", "--text", "--place", "--rewind", "--zone", "--gap", "--from-scale", "--color", "--outline", "--outline-width", "--size", "--face", "--sfx", "--volume", "--bar", "--bar-style", "--tempo-for", "--tempo", "--parts", "--stretch", "--yell-gain", "--yell-style", "--parents", "--skip-parent", "--voice-for", "--item"]); +/** The valued flags that may be given more than once (each value kept, in order). */ +const MULTI = new Set(["--skip-parent", "--voice-for"]); const SLUG_RE = /^[A-Za-z0-9._-]+$/; const POST_ID_RE = /^[A-Za-z0-9_-]{1,64}$/; @@ -410,6 +424,7 @@ export async function addPostFromArchive(project, { slug, postId, attach = null, export async function postsCommand(args, { root = REPORTS_ROOT, out = (s) => console.log(s), err = (s) => console.error(s) } = {}) { const words = []; const flags = new Map(); + const multis = new Map(); const channels = []; for (let i = 0; i < args.length; i += 1) { const a = args[i]; @@ -418,6 +433,7 @@ export async function postsCommand(args, { root = REPORTS_ROOT, out = (s) => con i += 1; } else if (VALUED.has(a)) { flags.set(a, args[i + 1] ?? ""); + if (MULTI.has(a)) multis.set(a, [...(multis.get(a) ?? []), args[i + 1] ?? ""]); i += 1; } else if (a.startsWith("--")) flags.set(a, true); else words.push(a); @@ -430,6 +446,11 @@ export async function postsCommand(args, { root = REPORTS_ROOT, out = (s) => con if (v === true || v === "") throw new CliError(`${name} needs a value`); return String(v); }; + const multi = (name) => { + const vs = multis.get(name) ?? []; + if (vs.some((v) => v === "")) throw new CliError(`${name} needs a value`); + return vs.map(String); + }; try { const [verb, projectArg, ref] = words; if (verb === "reel" && projectArg && !flags.has("--help")) return await reelCommand(projectArg, { channels, flags, str, root, json, dryRun, out }); @@ -469,7 +490,7 @@ export async function postsCommand(args, { root = REPORTS_ROOT, out = (s) => con err(NARRATE_USAGE); return 2; } - return await narrateCommand(await projectOf(projectArg, root), words.slice(2), flags, { json, dryRun, out, str }); + return await narrateCommand(await projectOf(projectArg, root), words.slice(2), flags, { json, dryRun, out, str, multi }); } if (verb === "fx") { const { FX_USAGE, fxCommand } = await import("./postFxCli.mjs"); @@ -518,6 +539,19 @@ export async function postsCommand(args, { root = REPORTS_ROOT, out = (s) => con }); } if (verb === "redact" && projectArg && !flags.has("--help")) return await redactCommand(projectArg, words.slice(2), { root, json, out, flags, str }); + if (verb === "say" || verb === "voices") { + // The pronunciation lexicon and the voice map (postSay.mjs): a refusal in its words is a usage error. + const { SAY_USAGE, VOICES_USAGE, sayCommand, voicesCommand } = await import("./postSay.mjs"); + if (!projectArg || flags.has("--help")) { + err(verb === "say" ? SAY_USAGE : VOICES_USAGE); + return 2; + } + const project = await projectOf(projectArg, root); + const run = verb === "say" ? sayCommand(project, words.slice(2), { flags, str, json, out }) : voicesCommand(project, words.slice(2), { json, out }); + return await run.catch((e) => { + throw e?.name === "SayError" ? new CliError(e.message) : e; + }); + } if (verb === "slurs") { // The slur filter (postSlursCli.mjs): its own words refused as a usage error. const { SLURS_USAGE, slursCommand } = await import("./postSlursCli.mjs"); diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json @@ -72,6 +72,7 @@ "./post-censor": "./post-censor.mjs", "./post-media-scene": "./post-media-scene.mjs", "./post-redact": "./post-redact.mjs", + "./post-say": "./post-say.mjs", "./post-redact-files": "./post-redact-files.mjs", "./post-slurs": "./post-slurs.mjs", "./post-thread": "./post-thread.mjs", diff --git a/umtool/report-to-video/post-narration.mjs b/umtool/report-to-video/post-narration.mjs @@ -33,6 +33,7 @@ import { followKnobErrors } from "./read-follow.mjs"; import { threadKnobErrors } from "./post-thread.mjs"; +import { takeLexiconErrors } from "./post-say.mjs"; /** The engines a post's narration may name (the editor's tts op). */ export const POST_NARRATION_ENGINES = Object.freeze(["orpheus", "kokoro", "espeak-ng"]); @@ -186,7 +187,7 @@ const MIX_KEYS = ["lead", "tail", "ramp", "linger", "clip", "wet", "lowpassHz", // `thread`: the cut's thread reads (post-thread.mjs) -- what each context post is on screen, the shrink and dim. const RENDER_KEYS = new Set([...MIX_KEYS.filter((k) => k !== "attach"), "engine", "voice", "follow", "thread"]); 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", "slurs"]); +const TAKE_KEYS = new Set(["file", "engine", "voice", "seconds", "script", "at", "note", "speed", "lufs", "jobId", "parts", "label", "source", "steps", "words", "slurs", "lexicon", "read"]); const STEP_KEYS = new Set(["op", "engine", "voice", "params", "ranAt", "job", "drop", "tempo", "spans"]); // `role` (post-thread.mjs): the text a part reads -- "post", "quoted", "parent:<i>", "media:<i>"; `voice`, `piece`: the batch's. // `tempo`: the part's reading speed in the take's file against its first read (a `tempo` step's; absent: 1). @@ -635,6 +636,9 @@ export function validatePostNarration(e) { } // 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`); + // The pronunciation entries its read applied (post-say.mjs), and how a thread read was asked for (postThreadRead.mjs). + errors.push(...takeLexiconErrors(t.lexicon, `${tw}.lexicon`)); + if (t.read !== undefined && !(isObj(t.read) && t.read.kind === "thread" && JSON.stringify(t.read).length <= 4000)) errors.push(`${tw}.read must be {kind: "thread", …} (how the thread read was asked for)`); 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; @@ -719,8 +723,8 @@ export function postNarrationDisclosure(entry) { /** A part reads at most this many words (a paragraph longer than it is split at a sentence end). */ export const POST_PART_WORDS = 60; -/** The pause the parts are joined with: between paragraphs, and inside one. */ -export const POST_PART_GAP = Object.freeze({ para: 0.6, inside: 0.25 }); +/** The pause the parts are joined with: between paragraphs, inside one, and between the pieces of a thread read (lib/report/postThreadRead.mjs). */ +export const POST_PART_GAP = Object.freeze({ para: 0.6, inside: 0.25, piece: 0.8 }); const wordsOf = (t) => (String(t).trim() ? String(t).trim().split(/\s+/).length : 0); diff --git a/umtool/report-to-video/post-redact.mjs b/umtool/report-to-video/post-redact.mjs @@ -31,6 +31,7 @@ import { censorMarkupErrors } from "./post-censor.mjs"; import { BLACKOUT_MARK, SLUR_CSS, decodePlaceholder, hasSlurMarks, maskSlurs, placeholdersHtml, sayFor, slurMatches, slursOn, validateSlursRender } from "./post-slurs.mjs"; import { validateClockRender } from "./post-clock.mjs"; +import { applyLexicon } from "./post-say.mjs"; import { validateProgressRender } from "./post-progress.mjs"; /** The mark a redacted code unit becomes (a private-use character: never typed, never drawn as a letter). */ @@ -230,7 +231,10 @@ export function validatePostsMarkup(doc, where = "posts-markup.json") { * * 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 + * and `say`, the project's PRONUNCIATION LEXICON (post-say.mjs: `narration/lexicon.json`, read by the umtool + * side's projectRedaction) -- applied by spokenRead only, never to anything drawn. + * + * @typedef {{ terms: Array<{term: string, wholeWord?: boolean}>, markup?: Record<string, {redact: any[]}>, slurs?: ReturnType<typeof import("./post-slurs.mjs").resolveSlurs> | null, say?: Array<Record<string, any>> | null }} Redaction */ /** Is there anything to blank? */ @@ -343,9 +347,15 @@ export function slurEntry(entry, slurs) { * 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 + * post-render.mjs). Returns `{ text, slurs, lexicon? }`: `slurs` is what the take's * audio will do with them (take.slurs: "said" | "skip" | "placeholder"), null - * when the text holds none. + * when the text holds none; `lexicon` the pronunciation entries applied + * (post-say.mjs, `red.say`), present only when one was -- what the take records. + * + * The LEXICON is applied first, but never inside a slur (whatever the filter's + * voice) or a redacted term: those spans keep their words for the filter and + * the redaction, which then run over the result -- so a spoken form that says a + * slur or a blanked name is masked or dropped too. * * @param {string} text * @param {Record<string, any>} entry @@ -355,22 +365,26 @@ export function slurEntry(entry, slurs) { export function spokenRead(text, entry, red, { voice = undefined } = {}) { const s = red?.slurs; const terms = termsFor(entry, red); - const t = str(text); + const lex = Array.isArray(red?.say) && red.say.length && str(text) + ? applyLexicon(str(text), red.say, { item: str(entry?.id) || null, protect: [...(s ? slurMatches(str(text), s) : []), ...redactText(str(text), terms).spans] }) + : { text: str(text), applied: [] }; + const said = (r) => (lex.applied.length ? { ...r, lexicon: lex.applied } : r); + const t = lex.text; const hits = s ? slurMatches(t, s) : []; - if (!hits.length) return { text: spokenWithout(t, terms), slurs: null }; + if (!hits.length) return said({ text: spokenWithout(t, terms), slurs: null }); const v = voice ?? s.voice; - if (!slursOn(s) || v === "beep") return { text: spokenWithout(t, terms), slurs: "said" }; + if (!slursOn(s) || v === "beep") return said({ text: spokenWithout(t, terms), slurs: "said" }); if (v === "placeholder") { - let said = ""; + let out = ""; let at = 0; for (const h of hits) { - said += t.slice(at, h.start) + sayFor(s, h); + out += t.slice(at, h.start) + sayFor(s, h); at = h.end; } - return { text: spokenWithout(said + t.slice(at), terms), slurs: "placeholder" }; + return said({ text: spokenWithout(out + t.slice(at), terms), slurs: "placeholder" }); } const marked = redactText(t, terms, { spans: hits }); - return { text: marked.spans.length ? dropMarks(marked.text) : t, slurs: "skip" }; + return said({ text: marked.spans.length ? dropMarks(marked.text) : t, slurs: "skip" }); } /** diff --git a/umtool/report-to-video/post-say.mjs b/umtool/report-to-video/post-say.mjs @@ -0,0 +1,266 @@ +// 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, `{ "<handle>": +// "<voice>", "*": "<voice>" }`: the stock voice each author's words are read +// in by a thread read (lib/report/postThreadRead.mjs). Handles without "@", +// any case. "*" is everyone the map does not name (default: CONTEXT_VOICE_DEFAULTS +// for the engine). The item's own author reads in the item's narrator voice +// unless the map names them. +// +// 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 = /^[A-Za-z0-9][A-Za-z0-9_.+-]{0,63}$/; +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 `(?<!${W})(?<![\\p{L}\\p{N}]['’])${body}(?!${W})(?!['’][\\p{L}\\p{N}])`; +} + +/** The entries that apply to post item `item` (its own first, then the project's), longest first in each. */ +export function lexiconFor(lexicon, item = null) { + const list = normalizeLexicon(lexicon); + const own = list.filter((x) => 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 {"<handle>": "<voice>", "*": "<voice>"}`]; + 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`); + } + return errors; +} + +/** + * The voice one piece of a read is said in, pure. In order: the run's own `overrides` (`--voice-for`), the + * item's `voice` for its own post (`--voice`), the map's for the author, the narrator's for the item's own author, + * the map's "*", the engine's context default, the narrator's. + * + * @param {{ handle?: string | null, role: string }} piece + * @param {{ map?: Record<string, string>, overrides?: Record<string, string>, self?: string | null, voice?: string | null, + * narrator: string, engine?: string }} o + */ +export function voiceForPiece(piece, { map = {}, 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 overrides[h]; + if (piece?.role === "post" && voice) return voice; + if (h && map[h]) return map[h]; + if (mine) return narrator; + return map[VOICE_MAP_OTHER] ?? CONTEXT_VOICE_DEFAULTS[engine] ?? narrator; +} + +/** `--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 <handle>=<voice> (got ${raw})`); + out[h] = v; + } + return out; +} diff --git a/umtool/report-to-video/post-say.test.mjs b/umtool/report-to-video/post-say.test.mjs @@ -0,0 +1,136 @@ +// post-say.mjs: the pronunciation lexicon (whole words, case, phrases, regex +// characters, an item's own entries, what wins) and its place in what a voice +// SAYS (post-redact.mjs spokenRead: the slur filter and the redaction win over +// it); a read said the old way (staleLexicon); the voice map. The slurs 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 { + applyLexicon, handleKey, lexiconFor, lexiconHits, staleLexicon, takeLexiconErrors, validateLexicon, validateVoiceMap, voiceForPiece, voiceOverridesOf, +} from "./post-say.mjs"; +import { spokenRead } from "./post-redact.mjs"; +import { resolveSlurs } from "./post-slurs.mjs"; +import { validatePostNarration } from "./post-narration.mjs"; + +const LIST = JSON.parse(readFileSync(new URL("./slurs.json", import.meta.url), "utf8")); +const F = LIST.entries.find((e) => e.id === "f-slur").word; +const say = (text, lex, o) => applyLexicon(text, lex, o).text; + +test("a whole word, without case by default: tbh, TBH and Tbh all said T-B-H; never inside a word", () => { + const lex = [{ word: "tbh", say: "T-B-H" }]; + assert.equal(say("tbh it's fine. TBH! (Tbh)", lex), "T-B-H it's fine. T-B-H! (T-B-H)"); + assert.equal(say("tbhx xtbh tbh_ _tbh tbh2", lex), "tbhx xtbh tbh_ _tbh tbh2"); + // An apostrophe and a letter after it are the word going on ("can" is not the "can" of "can't"). + assert.equal(say("I can't, I can.", [{ word: "can", say: "tin can" }]), "I can't, I tin can."); + // With case: only as written. + assert.equal(say("US us Us", [{ word: "US", say: "U.S.", case: true }]), "U.S. us Us"); +}); + +test("a phrase across any spaces; regex characters are literal; @handles and C++", () => { + assert.equal(say("at the\nmoment, at the moments", [{ word: "at the moment", say: "right now" }]), "right now, at the moments"); + assert.equal(say("@grok is this true? grok", [{ word: "@grok", say: "At grok" }]), "At grok is this true? grok"); + assert.equal(say("me@grok", [{ word: "@grok", say: "At grok" }]), "me@grok"); + assert.equal(say("C++ and C+", [{ word: "C++", say: "C plus plus" }]), "C plus plus and C+"); + assert.equal(say("a (sic) b sic", [{ word: "(sic)", say: "sick" }]), "a sick b sic"); + assert.equal(say("1.5x a 1x5x", [{ word: "1.5x", say: "one and a half times" }]), "one and a half times a 1x5x"); + assert.equal(say("$5 or 5", [{ word: "$5", say: "five dollars" }]), "five dollars or 5"); +}); + +test("what wins: an item's own entry over the project's, a longer match over one inside it; a replacement is never matched again", () => { + const lex = [ + { word: "atm", say: "A-T-M" }, + { word: "atm", say: "at the moment", item: "p-2" }, + { word: "not atm", say: "not right now" }, + { word: "A-T-M", say: "loop" }, + ]; + assert.equal(say("atm, not atm", lex, { item: "p-1" }), "A-T-M, not right now"); + assert.equal(say("atm", lex, { item: "p-2" }), "at the moment"); + assert.equal(say("atm", lex), "A-T-M", "no item: the project's only"); + assert.deepEqual(lexiconFor(lex, "p-2").map((x) => x.say), ["at the moment", "not right now", "loop", "A-T-M"]); + assert.deepEqual(applyLexicon("atm atm", lex).applied, [{ word: "atm", say: "A-T-M" }], "applied once each"); + assert.deepEqual(applyLexicon("atm", lex, { item: "p-2" }).applied, [{ word: "atm", say: "at the moment", item: "p-2" }]); +}); + +test("a protected span is never replaced", () => { + const text = "tbh tbh"; + assert.equal(say(text, [{ word: "tbh", say: "T-B-H" }], { protect: [{ start: 0, end: 3 }] }), "tbh T-B-H"); + assert.equal(lexiconHits(text, [{ word: "tbh", say: "x" }], { protect: [{ start: 2, end: 5 }] }).length, 0); +}); + +test("spokenRead: the lexicon applied, recorded -- and the slur filter and the redaction WIN over it", () => { + const e = { id: "p-1", post: "c/1" }; + const slurs = (cfg) => resolveSlurs(cfg, LIST); + // A lexicon entry for a slur's own word never fires: the filter's voice has it. + const lex = [{ word: F, say: "friend" }, { word: "tbh", say: "T-B-H" }]; + const text = `tbh a ${F}`; + assert.deepEqual(spokenRead(text, e, { terms: [], slurs: slurs({ voice: "skip" }), say: lex }), { text: "T-B-H a", slurs: "skip", lexicon: [{ word: "tbh", say: "T-B-H" }] }); + assert.deepEqual(spokenRead(text, e, { terms: [], slurs: slurs({ voice: "placeholder" }), say: lex }), { text: "T-B-H a f-slur", slurs: "placeholder", lexicon: [{ word: "tbh", say: "T-B-H" }] }); + assert.deepEqual(spokenRead(text, e, { terms: [], slurs: slurs({}), say: lex }), { text: `T-B-H a ${F}`, slurs: "said", lexicon: [{ word: "tbh", say: "T-B-H" }] }); + // Even with the filter off: a slur's word is the filter's, never the lexicon's. + assert.equal(spokenRead(text, e, { terms: [], slurs: slurs({ on: false }), say: lex }).text, `T-B-H a ${F}`); + // A spoken form that says a slur: the filter masks it too. + assert.equal(spokenRead("lol", e, { terms: [], slurs: slurs({ voice: "skip" }), say: [{ word: "lol", say: `ha ${F}` }] }).text, "ha"); + // A redacted word is dropped, never replaced -- and a spoken form that says a blanked name is dropped too. + const red = { terms: [{ term: "Quentin" }], slurs: null, say: [{ word: "Quentin", say: "Q" }, { word: "QE", say: "Quentin Example" }] }; + assert.equal(spokenRead("Quentin, hi", e, red).text, "hi"); + assert.equal(spokenRead("QE said", e, red).text, "Example said"); + // No lexicon: no record (the shape the takes had before it). + assert.deepEqual(spokenRead("tbh", e, { terms: [], slurs: null }), { text: "tbh", slurs: null }); + // An item's entry, by the entry's id. + assert.equal(spokenRead("atm", { id: "p-2" }, { terms: [], say: [{ word: "atm", say: "A-T-M", item: "p-2" }] }).text, "A-T-M"); + assert.equal(spokenRead("atm", { id: "p-3" }, { terms: [], say: [{ word: "atm", say: "A-T-M", item: "p-2" }] }).text, "atm"); +}); + +test("staleLexicon: a take that says an entry the old way -- unless it applied it with the same spoken form", () => { + const lex = [{ word: "tbh", say: "T-B-H" }, { word: "Pepe", say: "Pepe the frog" }]; + const e = { id: "p-1" }; + // A take from before the lexicon: its script says tbh. + assert.deepEqual(staleLexicon(e, { file: "a.wav", script: "tbh it is" }, lex), [{ word: "tbh", say: "T-B-H" }]); + // A take that applied it: not stale -- even when the spoken form holds the word. + assert.deepEqual(staleLexicon(e, { file: "a.wav", script: "tbh it is Pepe", lexicon: [{ word: "tbh", say: "T-B-H" }, { word: "Pepe", say: "Pepe the frog" }] }, lex), []); + // A thread read's script is what it said: "T-B-H" is not "tbh". + assert.deepEqual(staleLexicon(e, { file: "a.wav", script: "T-B-H it is" }, lex), []); + // Applied with another spoken form since changed: stale, with what it said. + assert.deepEqual(staleLexicon(e, { file: "a.wav", script: "tbh", lexicon: [{ word: "tbh", say: "tee bee aitch" }] }, lex), [{ word: "tbh", say: "T-B-H", was: "tee bee aitch" }]); + // A recording is a person's read: never stale. A take with no script reads its parts' words. + assert.deepEqual(staleLexicon(e, { file: "a.wav", engine: "recorded", script: "tbh" }, lex), []); + assert.deepEqual(staleLexicon(e, { file: "a.wav", parts: [{ text: "hi" }, { text: "tbh" }] }, lex).map((x) => x.word), ["tbh"]); +}); + +test("validateLexicon: the shape, the limits, a duplicate; a take's record is checked by the build", () => { + assert.deepEqual(validateLexicon([{ word: "tbh", say: "T-B-H" }, { word: "tbh", say: "x", item: "p-1" }, { word: "TBH", say: "y", case: true }]), []); + assert.match(validateLexicon([{ word: "tbh", say: "a" }, { word: "TBH", say: "b" }]).join(), /twice/); + assert.match(validateLexicon([{ word: "!!", say: "a" }]).join(), /letter or a digit/); + assert.match(validateLexicon([{ word: "a", say: "" }]).join(), /what the voice says/); + assert.match(validateLexicon([{ word: "a", say: "<b>x</b>" }]).join(), /Orpheus's tags/); + assert.deepEqual(validateLexicon([{ word: "a", say: "<laugh> a" }]), []); + assert.match(validateLexicon([{ word: "a", say: "b", how: 1 }]).join(), /not a lexicon key/); + assert.match(validateLexicon({}).join(), /must be a list/); + assert.deepEqual(takeLexiconErrors([{ word: "tbh", say: "T-B-H" }], "t"), []); + assert.match(takeLexiconErrors([{ word: "tbh" }], "t").join(), /entries it applied/); + const e = { id: "p-1", type: "post", narration: { takes: [{ file: "narration/posts/1/take-1.orpheus-zac.wav", seconds: 1, lexicon: [{ word: "tbh", say: "T-B-H" }], read: { kind: "thread", parents: "0" } }] } }; + assert.deepEqual(validatePostNarration(e), []); + e.narration.takes[0].read = { kind: "other" }; + assert.match(validatePostNarration(e).join(), /read must be/); +}); + +test("the voice map: a handle keyed without @ and case; who reads in what", () => { + assert.equal(handleKey("@KirscheVerstahl"), "kirscheverstahl"); + assert.deepEqual(validateVoiceMap({ kirscheverstahl: "tara", "*": "leo" }), []); + assert.match(validateVoiceMap({ "@Kirsche": "tara" }).join(), /not a handle/); + assert.match(validateVoiceMap({ a: "no voice!" }).join(), /stock voice/); + const o = { map: { kirscheverstahl: "tara", movail2: "leah" }, self: "ObviousRises", narrator: "zac", engine: "orpheus" }; + assert.equal(voiceForPiece({ handle: "KirscheVerstahl", role: "parent:0" }, o), "tara"); + assert.equal(voiceForPiece({ handle: "someone", role: "parent:0" }, o), "leo", "everyone else: leo on Orpheus"); + assert.equal(voiceForPiece({ handle: "someone", role: "quoted" }, { ...o, map: { ...o.map, "*": "dan" } }), "dan"); + assert.equal(voiceForPiece({ handle: "obviousrises", role: "parent:1" }, o), "zac", "his own words up the thread: the narrator"); + assert.equal(voiceForPiece({ handle: "ObviousRises", role: "post" }, o), "zac"); + assert.equal(voiceForPiece({ handle: "ObviousRises", role: "post" }, { ...o, voice: "leo" }), "leo", "--voice: his post"); + assert.equal(voiceForPiece({ handle: "KirscheVerstahl", role: "post" }, { ...o, self: "KirscheVerstahl" }), "tara", "her own item: the map names her"); + assert.equal(voiceForPiece({ handle: "KirscheVerstahl", role: "parent:0" }, { ...o, overrides: { kirscheverstahl: "mia" } }), "mia", "--voice-for wins"); + assert.equal(voiceForPiece({ handle: "x", role: "parent:0" }, { ...o, engine: "kokoro", narrator: "af_heart" }), "af_heart", "no context default for the engine: the narrator"); + assert.deepEqual(voiceOverridesOf(["@KirscheVerstahl=tara", "a=leo,b=dan"]), { kirscheverstahl: "tara", a: "leo", b: "dan" }); + assert.throws(() => voiceOverridesOf(["tara"]), /<handle>=<voice>/); +});