// `umtool narration` -- A CARD's NARRATION from the CLI (report-to-video/narration.mjs; lane line-rerun, S3 of the // Orpheus re-tune plan): its words, its reading and its tuning, and its READINGS -- every voice kept for it beside the // build (out/narration/.{wav,json}, narration-store.mjs) -- read again, compared and picked, with no agent. A // card's narration is SPOKEN ONLY: no card draws its words (narration.mjs), so an edit changes what is said and the // card's length, never what is shown. // // umtool narration [--list] [--json] every narrated card: its words, reading, tuning, readings // umtool narration [--json] one card's // umtool narration --read [--text "…"] [--reading N|next] [--temperature t] [--top-p p] [--top-k k] // [--min-p m] [--repeat-penalty r] [--chunk-takes n] [--json] // ONE READING asked of the editor (its tts op, a job; waits) // and kept beside the build -- the card NOT changed // umtool narration --pick [--json] the card made that reading: its words, reading, tuning // umtool narration [--text "…"] [--reading N] [tuning flags | --tuning-off] [--json] set them // // Plain ESM: the CLI runs it under bare node. import { readFile, readdir, stat } from "node:fs/promises"; import path from "node:path"; import { narrationKey, narrationTuningOf, narrationsOf, resolveNarration } from "umtool-report-to-video/narration"; import { narrationDir, narrationWavPath } from "umtool-report-to-video/narration-store"; import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs"; import { readManifest } from "../projects/report.mjs"; import { withEditNotes } from "./edit-guard.mjs"; import { StaleToken, StructureRefused, manifestToken, updateCardNarration } from "./manifest.mjs"; import { NarrateError, tuningFlags } from "./postNarrationCli.mjs"; export const CARD_NARRATION_USAGE = [ "usage: umtool narration [--list] [--json]", " umtool narration [--json]", " umtool narration --read [--text \"…\"] [--reading N|next] [--temperature t] [--top-p p] [--top-k k]", " [--min-p m] [--repeat-penalty r] [--chunk-takes n] [--json]", " umtool narration --pick [--json]", " umtool narration [--text \"…\"] [--reading N] [tuning flags | --tuning-off] [--json]", " A CARD's NARRATION: the words a stock synthetic voice says over a card (spoken only -- no card draws them), its", " READING (0 the first; 1, 2, … the same words read anew) and Orpheus's TUNING (umtool posts narrate --help). Its", " READINGS are the voices kept for it beside the build (out/narration/.wav): each its words, reading, tuning.", " --read: one reading asked of the editor (its tts op, a job; it waits while render mode holds the machine) and", " kept -- the card is NOT changed; --text reads other words, --reading next one past the highest these words were", " read at. --pick : the card made that reading (its words, reading and tuning; nothing synthesized). Without", " --read or --pick: the card's words (--text), reading and tuning set (--tuning-off: none). A verdict on the card's", " words (the narration review) is kept by a pick of another reading of the same words.", ].join("\n"); const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); const spacing = (t) => String(t ?? "").replace(/\s+/g, " ").trim(); /** Every reading kept beside the build (its record and its sound there), by card id, each oldest first -- read once. */ export async function allCardReadings(projectDir) { const dir = narrationDir(path.join(projectDir, "out")); const names = await readdir(dir).catch(() => []); const out = new Map(); for (const f of names) { if (!/^[0-9a-f]{64}\.json$/.test(f)) continue; const rec = await readFile(path.join(dir, f), "utf8").then(JSON.parse, () => null); if (!isObj(rec) || typeof rec.id !== "string" || `${rec.key}.json` !== f) continue; if (!(await stat(narrationWavPath(dir, rec.key)).catch(() => null))?.isFile()) continue; out.set(rec.id, [...(out.get(rec.id) ?? []), rec]); } for (const list of out.values()) list.sort((a, b) => String(a.createdAt ?? "").localeCompare(String(b.createdAt ?? ""))); return out; } /** Every reading kept for `cardId` beside the build, oldest first. */ export async function cardReadings(projectDir, cardId) { return (await allCardReadings(projectDir)).get(cardId) ?? []; } /** The reading a record was asked at (`askedReading`; an engine with no seed reports none), else the one reported. */ export const readingOfRecord = (r) => (Number.isInteger(r?.askedReading) ? r.askedReading : Number.isInteger(r?.reading) ? r.reading : 0); /** One past the highest reading `text` was kept at (a record with none: 0), or 0 when it never was. */ export function nextCardReading(readings, text) { let hi = -1; for (const r of readings) if (spacing(r.text) === spacing(text)) hi = Math.max(hi, readingOfRecord(r)); return hi + 1; } /** A reading as a line: its key, words, reading, tuning, length -- and whether the card plays it. */ const readingLine = (r, current) => ` ${r.key === current ? "▶" : " "} ${r.key.slice(0, 12)} ${Number(r.seconds).toFixed(2)} s reading ${readingOfRecord(r)}${r.askedTuning ? ` ${Object.entries(r.askedTuning).map(([k, v]) => `${k} ${v}`).join(", ")}` : ""} "${spacing(r.text).slice(0, 70)}"`; /** * A VERDICT ON THESE WORDS IS KEPT (lane line-rerun ruling; `narration --pick` and `reads pick`, one rule): the review * keys a verdict by the narration's key, which a reading moves -- a verdict given on the card as it played (`nowKey`, * its key before the pick), on the same words, moves to the reading picked (`rec`). Returns `{ kept, row }`. */ export async function keepCardVerdict(projectDir, cardId, { nowKey, rec }) { const { readNarrationReview, setNarrationReview } = await import("umtool-report-to-video/narration-review"); const row = (await readNarrationReview(projectDir)).rows?.[cardId]; const kept = !!row?.verdict && row.key === nowKey && spacing(row.text) === spacing(rec.text); if (kept) await setNarrationReview(projectDir, cardId, { verdict: row.verdict, key: rec.key, text: rec.text }); return { kept, row }; } /** `umtool narration …` */ export async function cardNarrationCommand(args, { root = REPORTS_ROOT, out = (s) => console.log(s), err = (s) => console.error(s), narrate = null } = {}) { const flags = new Map(); const words = []; const VALUED = new Set(["--text", "--reading", "--pick", "--temperature", "--top-p", "--top-k", "--min-p", "--repeat-penalty", "--chunk-takes"]); for (let i = 0; i < args.length; i += 1) { const a = args[i]; if (VALUED.has(a)) { flags.set(a, args[i + 1] ?? ""); i += 1; } else if (a.startsWith("--")) flags.set(a, true); else words.push(a); } const str = (k) => (flags.has(k) && typeof flags.get(k) === "string" ? flags.get(k) : null); const json = flags.has("--json"); const [projectArg, cardId] = words; if (!projectArg || flags.has("--help")) { out(CARD_NARRATION_USAGE); return projectArg ? 0 : 2; } try { const r = await resolveProject(projectArg, root); if (r.ambiguous) throw new NarrateError(`"${projectArg}" is the name of ${r.ambiguous.length} projects — pass its id`); if (!r.project) throw new NarrateError(`no project matches "${projectArg}"`); const project = r.project; const manifest = await readManifest(project.dir); if (!manifest) throw new NarrateError(`${project.id} has no manifest`); const all = narrationsOf(manifest); if (!cardId || flags.has("--list")) { const rows = []; for (const n of all) rows.push({ ...n, readings: await cardReadings(project.dir, n.id) }); if (json) out(JSON.stringify({ ok: true, cards: rows }, null, 2)); else { out(`${project.id}: ${rows.length} narrated card(s)`); for (const n of rows) out([`${n.id} ${n.engine} · ${n.voice} reading ${n.reading ?? 0}${n.tuning ? ` ${JSON.stringify(n.tuning)}` : ""} "${spacing(n.text).slice(0, 70)}"`, ...n.readings.map((x) => readingLine(x, n.key))].join("\n")); } return 0; } const e = (manifest.timeline ?? []).find((x) => x?.id === cardId); const now = all.find((x) => x.id === cardId); if (!e || !now) throw new NarrateError(`${cardId} is not a card with a narration (umtool narration ${project.id} --list)`); const readings = await cardReadings(project.dir, cardId); const tuned = tuningFlags(str); const write = async (patch) => withEditNotes(project, async () => updateCardNarration(project.dir, cardId, patch, { token: await manifestToken(project.dir) })); if (flags.has("--read")) { // ONE READING, the card not changed: its words (--text, else its own), the reading and tuning asked (else its own). const text = str("--text") !== null ? String(str("--text")).trim() : now.text; if (!text) throw new NarrateError("--text needs words"); const reading = tuned?.reading === "next" ? nextCardReading(readings, text) : tuned?.reading ?? (now.reading ?? 0); const tuning = tuned?.tuning ? narrationTuningOf({ ...(now.tuning ?? {}), ...tuned.tuning }) : now.tuning ?? null; const ask = resolveNarration({ ...e, narration: { ...e.narration, text, ...(reading > 0 ? { reading } : { reading: undefined }), ...(tuning ? { tuning } : { tuning: undefined }) } }, manifest.render); const n = { id: cardId, ...ask, key: narrationKey(ask) }; const run = narrate ?? (await import("umtool-report-to-video/narrate-via-editor")).narrateCut; const recs = await run({ narrations: [n], dir: narrationDir(path.join(project.dir, "out")), emit: (_ev, f) => !json && f?.message && out(f.message) }); const rec = recs.get(cardId); if (json) out(JSON.stringify({ ok: true, id: cardId, key: n.key, reading: n.reading ?? 0, tuning: n.tuning ?? null, text: n.text, seconds: rec?.seconds ?? null, plays: n.key === now.key }, null, 2)); else out(`${cardId}: reading ${n.reading ?? 0} kept (${n.key.slice(0, 12)}, ${rec?.seconds ?? "?"} s)${n.key === now.key ? " -- the one the card plays" : ` -- the card plays another; pick it: umtool narration ${project.id} ${cardId} --pick ${n.key}`}`); return 0; } if (str("--pick") !== null) { const key = String(str("--pick")).trim(); const rec = readings.find((x) => x.key === key || (key.length >= 8 && x.key.startsWith(key))); if (!rec) throw new NarrateError(`${cardId} has no reading ${key} kept (umtool narration ${project.id} ${cardId})`); const patch = { text: rec.text, reading: readingOfRecord(rec) > 0 ? readingOfRecord(rec) : null, tuning: rec.askedTuning ?? null }; const want = resolveNarration({ ...e, narration: { ...e.narration, text: patch.text, reading: patch.reading ?? undefined, tuning: patch.tuning ?? undefined } }, manifest.render); if (narrationKey(want) !== rec.key) throw new NarrateError(`${cardId}: reading ${rec.key.slice(0, 12)} was made with another voice or speed than the card's now -- read it again (--read)`); const { result } = await write(patch); const { kept, row } = await keepCardVerdict(project.dir, cardId, { nowKey: now.key, rec }); if (json) out(JSON.stringify({ ok: true, id: cardId, key: rec.key, narration: result.entry.narration, verdictKept: kept, token: result.token ?? null }, null, 2)); else out(`${cardId}: plays reading ${readingOfRecord(rec)} (${rec.key.slice(0, 12)})${kept ? ` -- still ${row.verdict} (the same words)` : ""}`); return 0; } const patch = {}; if (str("--text") !== null) patch.text = String(str("--text")); if (tuned?.reading === "next") throw new NarrateError("--reading next goes with --read (a reading is made, then picked)"); if (tuned?.reading !== undefined && tuned?.reading !== null) patch.reading = tuned.reading; if (tuned?.tuning) patch.tuning = narrationTuningOf({ ...(e.narration.tuning ?? {}), ...tuned.tuning }); if (flags.has("--tuning-off")) patch.tuning = null; if (!Object.keys(patch).length) { if (json) out(JSON.stringify({ ok: true, id: cardId, narration: e.narration, key: now.key, readings }, null, 2)); else out([`${cardId} ${now.engine} · ${now.voice} reading ${now.reading ?? 0}${now.tuning ? ` ${JSON.stringify(now.tuning)}` : ""}`, ` "${now.text}"`, ...readings.map((x) => readingLine(x, now.key))].join("\n")); return 0; } const { result } = await write(patch); if (json) out(JSON.stringify({ ok: true, id: cardId, narration: result.entry.narration, token: result.token ?? null }, null, 2)); else out(`${cardId}: ${JSON.stringify(result.entry.narration)}`); return 0; } catch (e) { if (e instanceof NarrateError || e instanceof StructureRefused || e instanceof StaleToken) { const msg = e instanceof StructureRefused ? e.errors.join("; ") : e.message; if (json) out(JSON.stringify({ ok: false, error: msg }, null, 2)); else err(`umtool narration: ${msg}`); return 1; } throw e; } }