// 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

--take --thread [--parents 0|all|none|] [--skip-parent ]… // [--no-quoted] [--no-linked] [--read-seen] [--voice-for =]… [--voice v] [--engine e] [--speed s] // [--post-take ] [--note "…"] [--force] [--no-hold] [--dry-run] [--json] // // --post-take (characters C3): HIS OWN LINE is an existing take of the item (its number as --list shows it, 1 = // the first) -- a recorded read, or one converted to his character's voice -- not synthesized; the context pieces // are synthesized as ever, in their authors' voices. The take's file is the post's one part (its script the part's // words); the new take's parts record where each came from (a synthesized part its parts-cache file and voice, the // take's its file and `take`: that take's id), and its `read` the take it used. A thread take is refused as the part. // // 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; : parents 0..n; none: no parent // --skip-parent leave one ancestor out (its post id, or its role parent:); 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 CAST (`umtool cast`: the characters across projects), the narrator's for the item's // own author, the map's "*", leo (Orpheus). A voice that names its engine ("kokoro:am_michael") is synthesized by // that engine, the rest by the read's: one read may join parts of two engines (each part records its own). // // 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/.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//take-.-thread.wav, its parts meta beside it // (take-.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, takeIdOf, takesDirOf } from "umtool-report-to-video/post-narration"; import { chosenLineTakes, chronoPieces, lineTakesOf } from "umtool-report-to-video/post-thread"; import { cardText, parentsOf, saysShownDraft, shownDraftOf } from "umtool-report-to-video/post-item"; import { planContext } from "umtool-report-to-video/post-conversation"; import { spokenRead, termsFor } from "umtool-report-to-video/post-redact"; import { readSpeedOf, resolvePieceVoice, tuningAskOf } from "umtool-report-to-video/post-say"; import { SCREEN_LINE_GAP, parseScreenRole, screenWho, screensOf, shapeSpans } from "umtool-report-to-video/post-screens"; import { readManifest } from "../projects/report.mjs"; import { ORPHEUS_DEFAULT_TAKES, TTS_TUNING_FIELDS, normalizeTtsTuning } from "yt-dlp-transcript-common/lib/ttsTuning.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(); const isTuneObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); /** A piece's character's Orpheus tuning (resolvePieceVoice's `tuning`), held for the tuning pass below: `{}` for none. */ const presetTuningOf = (v) => (v?.engine === "orpheus" && isTuneObj(v.tuning) && Object.keys(v.tuning).length ? { presetTuning: v.tuning } : {}); /** 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 --take --thread [--parents 0|all|none|] [--skip-parent ]…", " [--no-quoted] [--no-linked] [--read-seen] [--voice-for =]… [--voice v] [--engine e] [--speed s]", " [--post-take ] [--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) and at its character's SPEED (its synthetic preset's; --speed s:", " every part at that one; Orpheus has no speed), 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-.-thread.wav + take-.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).", " --post-take : his own line is the item's take n (as --list numbers them; a recording, or one converted to his", " character's voice), not synthesized -- the context pieces are, in their authors' voices; each part of the new take", " says where it came from. A thread take, or a take whose file is gone, is refused.", " ITS SCREENS (umtool posts screen): each line a screen reads is read after his words, in the screens' order, in its", " speaker's voice (`who`: the post's author in hers; a handle or a character's name in theirs) -- --no-screens leaves", " them out. --line-take screen::=: that LINE is the item's take n (a recording of that line, or one", " converted to its speaker's character), not synthesized; repeatable.", ].join("\n"); /** * The project's cast as a preset layer (castStore.mjs: the cast the project reads; `{}` with none, or a broken one): * `{ handle: { voice, speed?, character } }` (cast.mjs castPresetMap), voiceSourceOf's `cast`. */ export async function projectCastMap(dir) { const { castForProject } = await import("./castStore.mjs"); const { castPresetMap } = await import("umtool-report-to-video/cast"); return castPresetMap((await castForProject(dir)).cast); } /** * A part's cache key: sha1 of `voice|text` (an engine other than Orpheus: `engine|voice|text`), and of its SPEED when * it is read at one (`…|x1.1`: the same words at another speed are another part; none, or 1: the key as before), and * of its READING and TUNING when it asks one (lane line-rerun: `…|r2`, `…|t{"temperature":0.7}` -- none, reading 0 or * a tuning of the defaults: the key as before, so every part already cached is found). */ /** @type {(engine: string, voice: string, text: string, speed?: number | null, tune?: { reading?: number, tuning?: Record } | null) => string} */ export const partKey = (engine, voice, text, speed = null, tune = null) => createHash("sha1").update(`${engine === "orpheus" ? `${voice}|${text}` : `${engine}|${voice}|${text}`}${typeof speed === "number" && speed !== 1 ? `|x${speed}` : ""}${tuneSig(tune)}`).digest("hex"); /** A part's reading and tuning as its key and its "is it up to date" say them: "" for none (the first reading, the defaults). */ export function tuneSig(tune) { const r = Number.isInteger(tune?.reading) && tune.reading > 0 ? `|r${tune.reading}` : ""; const t = tuningOf(tune?.tuning); return `${r}${t ? `|t${JSON.stringify(t)}` : ""}`; } /** * A tuning with Orpheus's defaults left out, in the fields' order; null when none is left. `takes` equal to the code's * default (3) is left out too (review 1, a nit): `--chunk-takes 3` keys as an untuned part does -- an untuned part's key * never held the settings' takes either. */ export function tuningOf(tuning) { const n = normalizeTtsTuning(tuning, { takes: ORPHEUS_DEFAULT_TAKES }); const out = Object.fromEntries(TTS_TUNING_FIELDS.filter((k) => n[k] !== undefined).map((k) => [k, n[k]])); return Object.keys(out).length ? out : null; } /** * THE NEXT READING of one piece's words (lane line-rerun, "Read again"): one past the highest reading any take's part * of that role recorded for those words (a part with none: 0), or 0 when no take read them. */ export function nextPartReading(e, role, text) { let hi = -1; for (const t of Array.isArray(e?.narration?.takes) ? e.narration.takes : []) { for (const p of Array.isArray(t?.parts) ? t.parts : []) { if (p?.role !== role || norm(p.text) !== norm(text) || p.take) continue; hi = Math.max(hi, Number.isInteger(p.reading) ? p.reading : 0); } } return hi + 1; } /** `--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, engine, from, 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} manifest * @param {Record} e the post item * `map`, `cast` and `item` are voiceSourceOf's layers (cast.mjs projectPresetMap, castPresetMap, itemPresetOf: an entry * a voice as written, or a character's preset `{ voice, speed?, character }`). Each piece's `engine` is its voice's * (a voice that names one), else the read's; `from` where its voice came from (post-say.mjs voiceSourceOf); `speed` * the speed it is asked at (readSpeedOf: the command's `speed`, else the item's own for his words, else its * character's preset's -- none for Orpheus, which has none, or at 1). The read's `engine` is his piece's. * * @param {{ red?: any, map?: Record, cast?: Record, item?: any, overrides?: Record, parents?: string, * skip?: string[], quoted?: boolean, linked?: boolean, readSeen?: boolean, voice?: string | null, engine?: string | null, speed?: number | null }} [o] */ export function threadReadPlan(manifest, e, { red = null, map = {}, cast = {}, item = null, overrides = {}, parents = "0", skip = [], quoted = true, linked = true, readSeen = false, voice = null, engine = null, speed = null, postTake = null, screens = true, names = {}, lineTakes = {}, tuned = {}, inherit = {} } = {}) { 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 = []; // A SCREEN MADE FROM ITS READ (`posts screen … add --from-read`: `source: "read"`) IS that read: its lines are what // the picture says, so his own piece is not read as well (it would say the picture's words twice, and what the card // masks once) -- and no take of his words stands in for it. const fromRead = screensOf(e).find((sc) => sc.source === "read" && screens) ?? null; if (fromRead && postTake) throw new ThreadReadError(`--post-take: ${e.id}'s own words are its screen ${fromRead.id}'s lines (made from its read): no take reads them as well -- leave --post-take out`); for (const p of chronoPieces(e)) { if (p.role === "post" && fromRead) { skipped.push({ role: "post", why: `its read is screen ${fromRead.id}'s lines (made from its read)` }); continue; } 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; } // A SCREEN's line (post-screens.mjs): its speaker's voice -- the post's author's own lines in hers. if (parseScreenRole(p.role)) { if (!screens) { skipped.push({ role: p.role, why: "--no-screens" }); continue; } const sw = screenWho(p.who, e, names); const handle = sw.self ? str(e.handle) : sw.handle; // `written`: the line as SHOWN (its identity: a take is this line's while it said these); what is SAID is its // "said as" (post-screens.mjs saidAs) when it has one. const written = draftScript(p.text).script; const said = spokenRead(p.spoken ? draftScript(p.spoken).script : 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 lt = lineTakes?.[p.role] ?? null; // A RECORDING OF A LINE (`screenLine`: posts screen … record) is that line's as it was recorded: another line's, or // a line whose words or speaker changed since, is refused -- the old audio never plays under new lit text. const sl = lt?.take?.screenLine; if (sl && typeof sl === "object" && (str(sl.said).replace(/\s+/g, " ").trim() !== norm(written) || str(sl.speaker).trim().toLowerCase() !== str(p.who).trim().toLowerCase())) { const sp = /^screen:([a-z0-9-]+):(\d+)$/.exec(p.role); throw new ThreadReadError(`--line-take ${p.role}=${lt.n}: that take does not say line ${sp[2]} of screen ${sp[1]} as it is now (it was recorded for line ${sl.n} as it was: other words or another speaker) -- record the line again (umtool posts screen

${e.id} record ${sp[1]} ${sp[2]} --recording ), or unchoose it (set ${sp[1]} take.${sp[2]}=off)`); } if (lt) { // THE LINE FROM A TAKE (--line-take): that take's file is the line's piece, and its words are what the TAKE says // (`said`, else its script -- as --post-take's are), so every check that reads a read's words reads the audio's. // A take that does not say the line is REFUSED, never played as it. const words = norm(lt.take.said) || norm(lt.take.script); const anonHandles = red?.anon instanceof Map ? [...red.anon.keys()] : Object.keys(red?.anon ?? {}).filter((x) => x !== "postIds"); // The project's terms AND the post's own (its markup): what the card blanks, a take never says. const why = lineTakeProblem(words, said.text, { handles: anonHandles, terms: termsFor(e, red).map((x) => x.term) }); if (why) { const sp = /^screen:([a-z0-9-]+):(\d+)$/.exec(p.role); throw new ThreadReadError(`--line-take ${p.role}=${lt.n}: its take does not say line ${sp[2]} of screen ${sp[1]} (it says ${why === "other words" ? "other words than the line: another line's, more words, or the line changed" : why}) -- record that line, or name the take that reads it`); } pieces.push({ role: p.role, handle, who: p.who, speaker: str(p.who), date: null, voice: takeVoiceOf(lt.take), from: "take", written, line: written, text: words, lexicon: [], slurs: lt.take.slurs ?? null, take: { n: lt.n, id: takeIdOf(lt.take), file: lt.take.file, ...(lt.take.engine ? { engine: lt.take.engine } : {}) } }); continue; } const v = resolvePieceVoice({ handle, role: sw.self ? "post" : p.role }, { map, cast, item, overrides, self: str(e.handle), voice: null, narrator, engine: eng }); const spd = readSpeedOf({ flag: speed, preset: v.speed ?? null, own: sw.self ? e.narration?.speed ?? null : null, engine: v.engine }); pieces.push({ role: p.role, handle, who: p.who, speaker: str(p.who), date: null, line: written, voice: v.voice, engine: v.engine, from: v.from, ...(spd !== null ? { speed: spd } : {}), ...(v.character ? { character: v.character } : {}), ...presetTuningOf(v), written, text: said.text.trim(), lexicon: said.lexicon ?? [], slurs: said.slurs, ...(said.anonymised ? { anonymised: said.anonymised } : {}) }); 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 = resolvePieceVoice({ handle: p.handle, role: p.role }, { map, cast, item, overrides, self: str(e.handle), voice, narrator, engine: eng }); const spd = readSpeedOf({ flag: speed, preset: v.speed ?? null, own: p.role === "post" ? e.narration?.speed ?? null : null, engine: v.engine }); pieces.push({ role: p.role, handle: p.handle, date: p.date, voice: v.voice, engine: v.engine, from: v.from, ...(spd !== null ? { speed: spd } : {}), ...(v.character ? { character: v.character } : {}), ...presetTuningOf(v), written, text: said.text.trim(), lexicon: said.lexicon ?? [], slurs: said.slurs, ...(said.anonymised ? { anonymised: said.anonymised } : {}) }); } if (!fromRead && !pieces.some((p) => p.role === "post")) throw new ThreadReadError(`${e.id} has no words of his own to read (--script "…" first)`); if (!pieces.length) throw new ThreadReadError(`${e.id} has nothing to read (its screen ${fromRead?.id ?? ""} reads no line)`); // HIS LINE FROM A TAKE (--post-take): the take's file is the post's piece, its script its words; nothing synthesized. if (postTake) { const at = pieces.findIndex((p) => p.role === "post"); const t = postTake.take; // Its words as the take SAID them (`said`: a synthesized take that said an anonymous handle as the shown name), else its script. const words = norm(t.said) || norm(t.script) || pieces[at].text; pieces[at] = { role: "post", handle: pieces[at].handle, date: pieces[at].date, voice: takeVoiceOf(t), from: "take", written: words, text: words, lexicon: [], slurs: t.slurs ?? null, take: { n: postTake.n, id: takeIdOf(t), file: t.file, ...(t.engine ? { engine: t.engine } : {}) }, }; } // EACH SYNTHESIZED PIECE's READING AND TUNING (lane line-rerun): the one asked for its role (`tuned[role]`), else // the whole read's (`tuned["*"]`), else the one the playing read gave it while it says the same words (`inherit`, // posts screen read's) -- a reading "next" one past the highest its words were read at. // ITS CHARACTER's TUNING (lane character-tuning): a piece whose read asks no tuning of its own is asked its // character's (the synthetic preset's that answered for its voice: `presetTuning`), and says so (`tuningAsked`: // "preset"; its own: true). A character with no tuning: the piece as it always was. for (const pc of pieces) { const preset = pc.presetTuning ?? null; delete pc.presetTuning; if (pc.take) continue; const kept = isTuneObj(inherit?.[pc.role]) && norm(inherit[pc.role].said) === norm(pc.text) ? inherit[pc.role] : null; const ask = tuned?.[pc.role] ?? tuned?.["*"] ?? kept; // Field by field: the read's own values AS ASKED over the character's (post-say.mjs tuningAskOf: makeTake's rule // -- an explicit default is the read's own); the tuning asked and keyed is then normalised (S3's key rule). const ta = tuningAskOf({ own: isTuneObj(ask) && isTuneObj(ask.tuning) ? ask.tuning : null, preset, engine: pc.engine ?? "orpheus" }); const t = ta.tuning ? tuningOf(ta.tuning) : null; if (t) pc.tuning = t; // (An explicit default over a character's tuning is the read's own even when nothing is left to key: said so.) if (ta.asked && (t || (ta.asked === true && preset))) pc.tuningAsked = ta.asked; // The read's own values as asked (its takes too) over a character's: what `read.tuned` keeps, so a later read asks // them again. With no character tuning, S3's record as it was (the tuning asked). if (ta.own && preset) pc.ownTuning = ta.own; if (!isTuneObj(ask)) continue; const reading = ask.reading === "next" ? nextPartReading(e, pc.role, pc.text) : Number.isInteger(ask.reading) ? ask.reading : 0; if (reading > 0) pc.reading = reading; } 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 { // The read's engine: his piece's -- a take's line has none of a synthesizer's, so the first synthesized piece's. engine: pieces.find((p) => p.role === "post" && !p.take)?.engine ?? pieces.find((p) => !p.take)?.engine ?? eng, narrator, pieces, skipped, script: postTake ? null : 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 anonymous handles its pieces say as their shown names (post-anon.mjs). anonymised: [...new Set(pieces.flatMap((p) => p.anonymised ?? []))], }; } /** * The characters' NAMES -> their first handle (the project's own over the cast's), lower case: a screen line's `who` * may be a name (post-screens.mjs screenWho). `{}` with no layers. */ export function characterNames(L) { const out = {}; const add = (c) => { const n = str(c?.name).trim().toLowerCase(); const h = Array.isArray(c?.handles) ? str(c.handles[0]) : ""; if (n && h && !out[n] && c?.anonymous !== true) out[n] = h; }; for (const c of Array.isArray(L?.cast?.characters) ? L.cast.characters : []) add(c); const own = Array.isArray(L?.project?.characters) ? L.project.characters : []; for (const c of own) { const n = str(c?.name).trim().toLowerCase(); if (n) delete out[n]; } for (const c of own) add(c); return out; } /** A NEGATION: a line that has one, a take must say it (it is never the word left out). */ const NEGATION_RE = /^(?:not|no|nope|never|nor|none|nothing|nobody|nowhere|neither|cannot|.+n't|(?:do|does|did|ca|wo|is|are|was|were|could|should|would|have|has|had|ai|must|need|might)nt)$/u; /** * WHAT A LINE TAKE SAYS AMISS, pure: null when its words SAY the line -- the line's said words IN ORDER, normalized * (case, edge punctuation), NO word more, at most one word fewer and never a negation (not, no, never, -n't…) -- else * why not: "a shape" (an e-mail, a number: shapeSpans), "a handle" (an @handle, an anonymous author's `handles`), "a * redacted term" (`terms`: the project's and the post's own, post-redact.mjs termsFor), "other words". */ export function lineTakeProblem(takeWords, lineWords, { handles = [], terms = [] } = {}) { if (shapeSpans(str(takeWords)).length) return "a shape"; const keys = (t) => str(t).toLowerCase().replace(/[’‘]/g, "'").split(/\s+/).map((w) => w.replace(/^[^\p{L}\p{N}@]+|[^\p{L}\p{N}]+$/gu, "")).filter(Boolean); const a = keys(takeWords); const b = keys(lineWords); const banned = new Set(handles.map((h) => String(h).replace(/^@+/, "").toLowerCase())); if (a.some((w) => w.startsWith("@") || banned.has(w))) return "a handle"; const termRes = terms.map((t) => new RegExp(`(? re.test(str(takeWords)))) return "a redacted term"; if (!a.length || !b.length || a.length > b.length || b.length - a.length > 1) return "other words"; // In order, every word the line's; one word of the line may be left out -- never a negation. let i = 0; let skipped = null; for (const w of a) { while (i < b.length && b[i] !== w) { if (skipped !== null) return "other words"; skipped = b[i]; i += 1; } if (i >= b.length) return "other words"; i += 1; } if (i < b.length) { if (skipped !== null || i + 1 < b.length) return "other words"; skipped = b[i]; } return skipped !== null && NEGATION_RE.test(skipped) ? "other words" : null; } /** Whether a take's words SAY a line (lineTakeProblem's null). */ export const saysLine = (takeWords, lineWords, o = {}) => lineTakeProblem(takeWords, lineWords, o) === null; /** A take's voice as a thread read's label says it: its voice (or recorded label) without an engine ("am_michael", "operator"). */ export function takeVoiceOf(t) { const v = str(t?.voice) || str(t?.label) || (t?.engine === "recorded" ? "recorded" : "take"); return v.includes(":") ? v.slice(v.indexOf(":") + 1) : v; } /** * THE TAKE A THREAD READ's own line may be (--post-take n, as --list numbers them), checked: `{ n, take }`. Refused: no * such take, a THREAD take (its own context in it), one with no file. */ export function postTakeOf(e, n, { line = null } = {}) { const takes = Array.isArray(e?.narration?.takes) ? e.narration.takes : []; const k = Number(n); if (!Number.isInteger(k) || k < 1) throw new ThreadReadError(`--post-take takes a take's number as --list shows it (1 = the first), not ${n}`); if (k > takes.length) throw new ThreadReadError(`--post-take ${k}: ${e?.id} has ${takes.length} take(s)`); const t = takes[k - 1]; if (!t || typeof t.file !== "string" || !t.file) throw new ThreadReadError(`--post-take ${k}: that take has no file`); if (/-thread\.wav$/.test(t.file) || t.read?.kind === "thread") throw new ThreadReadError(`--post-take ${k} is a thread read itself (${t.file}): name a take of his line alone`); // A RECORDING OF A SCREEN LINE (`screenLine`) is that line's alone: never his words, never another line. const sl = t.screenLine && typeof t.screenLine === "object" ? t.screenLine : null; if (sl && line === null) throw new ThreadReadError(`--post-take ${k} is a recording of line ${sl.n} of screen ${sl.screen}: it is read in that line's place (--line-take screen:${sl.screen}:${sl.n}=${k}), never as his words`); // Owned by its CONTENT (its screen, words and speaker -- threadReadPlan holds it to the line as it is), not its index. if (sl && line !== null && parseScreenRole(line)?.id !== sl.screen) throw new ThreadReadError(`--post-take ${k} is a recording of a line of screen ${sl.screen}, not of ${line}`); return { n: k, take: t }; } /** The read's PARTS, pure: each piece's parts (scriptParts) with its voice, engine, role and cache key, in order -- a take's line one part, its file. */ export function readParts(plan) { return plan.pieces.flatMap((pc, piece) => { // A screen line's parts carry the line they were made from (`line`): the guard holds the read to the line as it is. const line = typeof pc.line === "string" ? { line: pc.line, speaker: str(pc.speaker) } : {}; if (pc.take) return [{ piece, para: 0, role: pc.role, voice: pc.voice, text: pc.text, file: pc.take.file, take: pc.take.id, key: null, ...line }]; const eng = pc.engine ?? plan.engine; const tune = { ...(pc.reading ? { reading: pc.reading } : {}), ...(pc.tuning ? { tuning: pc.tuning } : {}) }; // Where its tuning came from (not in its key: the same tuning is the same audio, whoever asked it). const from = pc.tuningAsked ? { tuningAsked: pc.tuningAsked } : {}; return scriptParts(pc.text).map((q) => ({ piece, para: q.para, role: pc.role, voice: pc.voice, engine: eng, ...(pc.speed !== undefined ? { speed: pc.speed } : {}), ...tune, ...from, text: q.text, key: partKey(eng, pc.voice, q.text, pc.speed ?? null, tune), ...line })); }); } /** Each piece's `engine:voice` (and its speed, when it has one), in order, once each -- what a read sounds like, for "is it up to date". */ const voiceSig = (rows, fallback) => [...new Set(rows.map((p) => (p.take ? `take:${typeof p.take === "object" ? p.take.id : p.take}` : `${p.engine ?? fallback}:${p.voice}${typeof p.speed === "number" && p.speed !== 1 ? `x${p.speed}` : ""}${tuneSig(p)}`)))].join("+"); /** * 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-.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) => (p.take ? p.file : `${PARTS_CACHE}/${p.key}.wav`) } = {}) { let t = 0; const meta = parts.map((p, i) => { const prev = i > 0 ? parts[i - 1] : null; // Two lines of one SCREEN (post-screens.mjs): a short pause, an exchange's. const sameScreen = !!prev && p.piece !== prev.piece && parseScreenRole(p.role) !== null && parseScreenRole(p.role)?.id === parseScreenRole(prev.role)?.id; const gap = !prev ? 0 : sameScreen ? SCREEN_LINE_GAP : 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]); // A part from a take (--post-take) says which (`take`: its id); a synthesized one its parts-cache file and voice. const row = { n: i + 1, para: p.piece * 100 + p.para, text: p.text, ...(typeof p.line === "string" ? { line: p.line, speaker: str(p.speaker) } : {}), voice: p.voice, ...(p.engine ? { engine: p.engine } : {}), ...(typeof p.speed === "number" ? { speed: p.speed } : {}), ...(p.reading ? { reading: p.reading } : {}), ...(p.tuning ? { tuning: p.tuning } : {}), ...(p.tuningAsked ? { tuningAsked: p.tuningAsked } : {}), role: p.role, piece: p.piece, file: fileOf(p), ...(p.take ? { take: p.take } : {}), 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, speed = null, postTake = null, screens = true, lineTakes = {}, pieces = [] }) { // Each piece's reading and tuning, as made (lane line-rerun), with the words it said: a later read of the same words // keeps it (posts screen read), and `--tuned` asks it again exactly (castProject.mjs threadArgvOf). // Only the READ's OWN values (as asked, its takes too) are kept: a tuning that came from the piece's character is not // the read's, so a later read asks the character's as it is then (lane character-tuning; review 2 #9). A piece with // no character tuning: its own as S3 kept it (the tuning asked). const ownTuning = (pc) => (pc.ownTuning ? pc.ownTuning : pc.tuning && pc.tuningAsked !== "preset" ? pc.tuning : null); const tuned = Object.fromEntries((pieces ?? []).filter((pc) => !pc.take && (pc.reading || ownTuning(pc))).map((pc) => [pc.role, { ...(pc.reading ? { reading: pc.reading } : {}), ...(ownTuning(pc) ? { tuning: ownTuning(pc) } : {}), said: pc.text }])); 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 } : {}), // The speed the command asked for the whole read (`--speed`); a character's own is its preset's, not the read's. ...(typeof speed === "number" && Number.isFinite(speed) ? { speed } : {}), // His line from a take (--post-take): its number then, and its file. ...(postTake ? { postTake: { n: postTake.n, file: postTake.take.file } } : {}), // Its screens (post-screens.mjs): left out; lines from takes (--line-take). ...(screens ? {} : { screens: false }), // Each with the line it said then (`line`): it is re-attached only while the line says the same (defaultLineTakes). ...(Object.keys(lineTakes ?? {}).length ? { lineTakes: Object.fromEntries(Object.entries(lineTakes).map(([r, lt]) => [r, { n: lt.n, file: lt.take.file, ...(typeof lt.line === "string" ? { line: lt.line } : {}) }])) } : {}), ...(Object.keys(tuned).length ? { tuned } : {}), }; } /** Is the picked take this read already (the same words, voices and engines)? */ export function upToDate(e, plan) { const t = pickedTake(e); if (!t || norm(t.script) !== norm(plan.want) || str(t.voice) !== plan.voice || (t.engine ?? "orpheus") !== plan.engine) return false; // His line from a take: the same take's file, or not up to date. if (str(t.read?.postTake?.file) !== str(plan.pieces.find((p) => p.take && p.role === "post")?.take?.file)) return false; // A screen line from a take: the same takes' files, or not up to date. const lines = Object.fromEntries(plan.pieces.filter((p) => p.take && p.role !== "post").map((p) => [p.role, p.take.file])); const had = Object.fromEntries(Object.entries(t.read?.lineTakes ?? {}).map(([r, x]) => [r, str(x?.file)])); if (JSON.stringify(Object.entries(lines).sort()) !== JSON.stringify(Object.entries(had).sort())) return false; // A take whose parts say their voices: each piece in the same engine and voice, at the same speed. const parts = Array.isArray(t.parts) ? t.parts.filter((p) => typeof p?.voice === "string") : []; if (!parts.length) return !plan.pieces.some((p) => typeof p.speed === "number" || p.reading || p.tuning); if (voiceSig(parts, t.engine ?? "orpheus") !== voiceSig(plan.pieces, plan.engine)) return false; // EACH PIECE's READING AND TUNING (review 1, finding 2): per piece, never through the voices' set -- two lines of one // voice at readings 1 and 0 are not the same read as 0 and 1. for (const pc of plan.pieces) { if (pc.take) continue; const mine = parts.filter((p) => p.role === pc.role && !p.take); if (mine.length && mine.some((p) => tuneSig(p) !== tuneSig(pc))) return false; if (!mine.length && (pc.reading || pc.tuning)) return false; } return true; } const fileThere = async (f) => !!(await stat(f).catch(() => null))?.isFile(); /** A file's length, seconds (ffprobe). */ async function durationOf(file) { const { stdout } = await execFileP(process.env.FFPROBE_BIN ?? "ffprobe", ["-v", "error", "-show_entries", "format=duration", "-of", "default=noprint_wrappers=1:nokey=1", file]).catch(() => ({ stdout: "" })); const s = Number(String(stdout).trim()); if (!(s > 0)) throw new ThreadReadError(`${file} has no length (not a sound file?) -- delete it from ${PARTS_CACHE}/ and run it again`); return s; } /** * 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, cast: cast0 = undefined, item: item0 = undefined, overrides = {}, parents = "0", skip = [], quoted = true, linked = true, readSeen = false, voice = null, engine = null, speed = null, note = null, force = false, hold = true, dryRun = false, ask = null, lanes: lanes0 = undefined, emit = () => {}, editor = null, signals = false, postTake: postTakeN = null, screens = true, lineTakes: lineTakesN = {}, names: names0 = undefined, tuned = {}, inherit = {}, keepPick = 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); // The layers (characterLayers.mjs): the project's characters over its voice map (a broken map refuses the read), the // cast, the item's own character -- each the caller's when it hands one in. const L = map0 !== undefined && cast0 !== undefined && item0 !== undefined ? null : await (await import("./characterLayers.mjs")).readLayers(project.dir, { strictMap: map0 === undefined }); const map = map0 !== undefined ? map0 : L.map; const cast = cast0 !== undefined ? cast0 : L.castMap; const item = item0 !== undefined ? item0 : L?.itemOf(e) ?? null; const postTake = postTakeN === null || postTakeN === undefined ? null : postTakeOf(e, postTakeN); // A screen line from a take (--line-take): checked as --post-take's is. // The takes the screens CHOSE for their lines (`lineTakes`, the operator's: the bench's select, `set take.=`), // under the ones the command names -- never one nobody chose. const lineTakes = Object.fromEntries(Object.entries({ ...chosenLineTakes(e), ...(lineTakesN ?? {}) }).map(([role, n]) => { if (!parseScreenRole(role)) throw new ThreadReadError(`--line-take names a screen's line as screen:: (got ${role})`); try { return [role, postTakeOf(e, n, { line: role })]; } catch (err) { throw new ThreadReadError(String(err instanceof Error ? err.message : err).replace(/--post-take/g, `--line-take ${role}=`)); } })); // The characters' names (a screen's `who` may be one), to their handles. const names = names0 !== undefined ? names0 : characterNames(L); const plan = threadReadPlan(manifest, e, { red, map, cast, item, overrides, parents, skip, quoted, linked, readSeen, voice, engine, speed, postTake, screens, names, lineTakes, tuned, inherit }); for (const [r, lt] of Object.entries(lineTakes)) lt.line = plan.pieces.find((pc) => pc.role === r)?.line; // A READING OR TUNING ASKED FOR A PIECE (review 1, finding 2): of a piece the read has, synthesized -- a piece read // from a take (a recording, his line from --post-take, a line's chosen or re-attached take) is never "read again". for (const role of Object.keys(tuned ?? {})) { if (role === "*") { if (!plan.pieces.some((pc) => !pc.take)) throw new ThreadReadError(`${e.id}: every piece of this read is a take (a recording): there is nothing synthesized to read again -- record it again`); continue; } const pc = plan.pieces.find((x) => x.role === role); if (!pc) throw new ThreadReadError(`${e.id}: this read has no piece ${role} (its pieces: ${plan.pieces.map((x) => x.role).join(", ")})`); if (pc.take) throw new ThreadReadError(`${e.id}: ${role} is read from take ${pc.take.n} (${pc.take.file}), not synthesized -- to read it again, record it again, or choose "synthesized" for it`); } const parts = readParts(plan); const cacheDir = path.join(project.dir, ...PARTS_CACHE.split("/")); const wavOf = (p) => (p.take ? path.join(project.dir, ...p.file.split("/")) : path.join(cacheDir, `${p.key}.wav`)); const have = await Promise.all(parts.map((p) => fileThere(wavOf(p)))); const lost = parts.find((p, i) => p.take && !have[i]); if (lost) throw new ThreadReadError(`${lost.role === "post" ? `--post-take ${postTake?.n}` : `--line-take ${lost.role}`}: its file ${lost.file} is not there`); 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.engine === plan.engine ? p.voice : `${p.engine}:${p.voice}`}): asking the editor…` }); await writeFile(path.join(cacheDir, `${p.key}.txt`), p.text); try { const { jobId } = await askTts({ text: p.text, engine: p.engine ?? plan.engine, voice: p.voice, out: wavOf(p), ...(typeof p.speed === "number" ? { speed: p.speed } : {}), ...(p.tuning ? { tuning: p.tuning } : {}), ...(p.reading ? { reading: p.reading } : {}) }, { ...(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.take ? `take ${p.take.n}: ` : p.engine && p.engine !== plan.engine ? `${p.engine}:` : ""}${p.voice})`).join(" + ")}`, ...(Number.isFinite(mt.lufs) ? { lufs: mt.lufs } : {}), parts: meta, ...(plan.slurs ? { slurs: plan.slurs } : {}), ...(plan.lexicon.length ? { lexicon: plan.lexicon } : {}), // Where its parts' speeds came from: --speed (kept as asked), else their characters' presets / the item's own. ...(plan.pieces.some((p) => typeof p.speed === "number") ? { speedAsked: typeof speed === "number" ? true : "preset" } : {}), read: readRecordOf({ parents, skip, quoted, linked, readSeen, overrides, voice, speed, postTake, screens, lineTakes, pieces: plan.pieces }), // STAMPED FOR READING when his post piece was WRITTEN as other words than the post's as drafted (review 2, // finding 1: never judged from its parts, which hold the words as spoken -- a lexicon word is not an edit). ...(postWrittenEdited(e, plan) ? { forReading: true } : {}), }; // A re-read (--no-pick, the bench's Read again) joins the list unpicked: Pick makes it the one. const patch = { addTake: take, ...(keepPick ? { keepPick: true } : {}), ...(plan.script ? { script: plan.script } : {}) }; // THE ITEM CHANGED WHILE ITS READ WAS MADE (a bench edit during minutes of synthesis): what was read is not what it // holds now -- refused, never kept as a stale read (the parts made are cached: running it again is quick). const nowE = ((await readManifest(project.dir))?.timeline ?? []).find((x) => x?.id === e.id); const sig = (x) => JSON.stringify([x?.screens ?? null, x?.text ?? null, x?.narration?.script ?? null]); if ((Array.isArray(e.screens) || Array.isArray(nowE?.screens)) && (!nowE || sig(nowE) !== sig(e))) throw new ThreadReadError(`${e.id} changed while its read was made (its screens or its words): run it again -- the parts made are cached`); 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 }; } /** Whether a thread read's post piece was written as other words than the post's as drafted (its stamp). */ export function postWrittenEdited(e, plan) { const pc = plan.pieces.find((x) => x.role === "post"); if (!pc) return false; return !!String(shownDraftOf(e) ?? "").trim() && !saysShownDraft(e, pc.written); } /** 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

--take --thread …` (postNarrationCli.mjs routes it here). */ export async function threadCommand(project, e, o) { const { json = false, events = false, out = (s) => console.log(s) } = o; const say = (s) => !json && !events && 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 || events) && err instanceof ThreadReadError) { out(events ? JSON.stringify({ ev: "result", ok: false, id: e.id, error: err.message }) : JSON.stringify({ ok: false, id: e.id, error: err.message }, null, 2)); return 1; } throw err; } // --events (the bench's Read again, review 1 finding 2): ONE line, the take MADE (its file and number) or none, and // why -- the bench plays and names only the take this job made, never the list's last. if (events) { const n = r.take ? (r.result?.narration?.takes ?? []).findIndex((t) => t?.file === r.take.file) + 1 : null; out(JSON.stringify({ ev: "result", ok: true, id: e.id, upToDate: !!r.upToDate, dryRun: !!r.dryRun, take: r.take ? { file: r.take.file, n, parts: (r.take.parts ?? []).map((p) => ({ role: p.role ?? null, file: p.file ?? null, reading: p.reading ?? 0 })) } : null, picked: r.take ? r.result?.narration?.pick === n - 1 : false, ...(r.upToDate ? { why: "the playing take already reads this, in these voices, at these readings" } : {}) })); return 0; } const pieces = r.plan.pieces.map((p) => ({ role: p.role, handle: p.handle, date: p.date, voice: p.voice, engine: p.engine, from: p.from, ...(p.take ? { take: p.take } : {}), ...(p.speed !== undefined ? { speed: p.speed } : {}), ...(p.character ? { character: p.character } : {}), words: p.text.split(/\s+/).filter(Boolean).length, ...(p.lexicon.length ? { lexicon: p.lexicon } : {}) })); const guard = r.take ? await guardOf(project, e.id) : null; // RECORDINGS OF ITS LINES NOBODY CHOSE (screenLine takes): said, never read in -- the operator chooses. const used = new Set(r.plan.pieces.filter((p) => p.take && p.role !== "post").map((p) => p.role)); const notChosen = lineTakesOf(e).filter((L) => !used.has(L.role) && r.plan.pieces.some((p) => p.role === L.role)).map((L) => ({ role: L.role, takes: L.takes.filter((x) => x.current).map((x) => x.n) })).filter((L) => L.takes.length); 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, ...(notChosen.length ? { lineTakesNotChosen: notChosen } : {}), parts: r.parts.map((p) => ({ role: p.role, voice: p.voice, engine: p.engine, ...(p.speed !== undefined ? { speed: p.speed } : {}), ...(p.take ? { take: p.take, file: p.file } : { 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.take ? p.voice : p.engine !== r.plan.engine ? `${p.engine}:${p.voice}` : p.voice).padEnd(6)} ${p.take ? `(take ${p.take.n}: ${p.take.file}) ` : ""}${p.from === "cast" ? "(cast) " : p.from === "item" ? `(the item's character: ${p.character}) ` : p.from === "project" && p.character ? `(this video's character: ${p.character}) ` : ""}${p.speed !== undefined ? `×${p.speed} ` : ""}${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})`); for (const L of notChosen) { const m = /^screen:([a-z0-9-]+):(\d+)$/.exec(L.role); out(` (${L.role} is synthesized: its recording${L.takes.length > 1 ? "s" : ""} take ${L.takes.join(", take ")} not chosen -- --line-take ${L.role}=${L.takes.at(-1)}, or umtool posts screen ${project.id} ${e.id} set ${m[1]} take.${m[2]}=${L.takes.at(-1)})`); } 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(", ")})` : ""}, ${o.keepPick ? "not picked (--pick to play it)" : "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; }