// `umtool posts narrate` (report-to-video/post-narration.mjs; umtool/docs/ // report-video.md, "Narrated post items"): a post item's narration -- its // script, its takes (synthesized by the EDITOR's tts op, never here), the // one that plays, its approval, and the mix's knobs -- through the writers // (updatePostNarration, updatePostNarrations, updatePostNarrationRender). // // umtool posts narrate

--import [--dry-run] narration/posts/index.json into the cut (one write) // umtool posts narrate

--list every post item's script, takes and pick // umtool posts narrate

one item's // umtool posts narrate

--script "…" set (replace) the script // umtool posts narrate

--take [--note "…"] [--voice v] [--engine e] [--speed s] [--script "…"] // [--reading N] [--temperature t] [--top-p p] [--top-k k] [--min-p m] [--repeat-penalty r] [--chunk-takes n] // a new take, asked of the editor (a job; waits) // umtool posts narrate

--pick | --approve | --unapprove | --off | --on // umtool posts narrate

k=v … this post's mix: lead tail ramp linger clip wet lowpass duck short attach lufs rate // umtool posts narrate

--all --draft-scripts [--force] scripts from the posts' words (verbatim) // umtool posts narrate

--all --take [--limit N] every missing take, one at a time (resumable) // umtool posts narrate

--cut k=v … the cut's mix (render.postNarration) // umtool posts narrate

--words [--worker ] its take's word timings (the editor's transcription, aligned; postFxCli.mjs) // umtool posts narrate

--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"; import { mkdir, readFile, readdir, rename, stat } from "node:fs/promises"; import path from "node:path"; import { promisify } from "node:util"; import { NARRATION_INDEX, POST_DERIVE_OPS, POST_NARRATION_LIMITS, POST_DERIVE_ROUTES, derivedFileOf, draftScript, takeIdOf, isNarrated, nextReadingOf, nextTakeNumber, pickedTake, postIdOf, postNarrationKnobs, takeFileOf, takesDirOf, } from "umtool-report-to-video/post-narration"; import { CAST_CONVERT_PITCH, CAST_SEMITONES_MAX, convertPitchLabel } from "umtool-report-to-video/cast"; import { convertAskOf, stepPitchOf } from "./derivePitch.mjs"; import { LEGACY_EDIT_TEXT, excerptSpansOf, legacyReadOf, postItemPlan, postReadText, readEditOf, takeIsEditedRead } from "umtool-report-to-video/post-item"; import { partRoles } from "umtool-report-to-video/post-thread"; import { spokenRead } from "umtool-report-to-video/post-redact"; import { projectRedaction } from "./postRedaction.mjs"; import { readManifest } from "../projects/report.mjs"; import { withEditNotes } from "./edit-guard.mjs"; import { manifestToken, updatePostNarration, updatePostNarrationRender, updatePostNarrations } from "./manifest.mjs"; import { TUNING_FLAGS } from "./readTuning.mjs"; import { TTS_TUNING_FIELDS, normalizeTtsTuning, quantizeTtsTuningValue, ttsReadingError, ttsTuningValueError } from "yt-dlp-transcript-common/lib/ttsTuning.mjs"; const execFileP = promisify(execFile); const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); const FFMPEG = () => process.env.FFMPEG_BIN ?? "ffmpeg"; const FFPROBE = () => process.env.FFPROBE_BIN ?? "ffprobe"; export const NARRATE_USAGE = [ "usage: umtool posts narrate --import [--dry-run] [--json]", " umtool posts narrate --list [--json]", " umtool posts narrate [--script \"…\"] [--take [--note \"…\"] [--voice v] [--engine e] [--speed s]]", " [--reading N|next] [--temperature t] [--top-p p] [--top-k k] [--min-p m] [--repeat-penalty r] [--chunk-takes n] [--no-pick] [--bench-slurs]", " [--pick ] [--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 --recording [--as ] [--no-clean|--clean] [--no-trim|--trim] [--no-convert]", " [--pitch target|source|contour] [--semitones ]", " umtool posts narrate [--recording ] --preview [--as ] [--out ] [--trim-span [=]-]…", " [--no-clean|--clean] [--no-trim|--trim] [--no-convert] [--engine e] [--voice v] [--pitch …] [--semitones ] [--events]", " umtool posts narrate --keep-preview | --discard-preview [--label operator]", " umtool posts narrate --derive --op enhance|convert [--engine e] [--voice v] [--as ]", " [--pitch target|source|contour] [--semitones ]", " umtool posts narrate --take --thread [--parents 0|all|none|] [--skip-parent ]… [--no-quoted]", " [--no-linked] [--read-seen] [--voice-for =]… [--voice v] [--speed s] [--post-take ]", " [--no-screens] [--line-take screen::=]… [--force] [--dry-run] [--no-pick]", " [--reading N|next] [tuning flags] [--for ] [--tuned =reading:N,temperature:t,…]…", " umtool posts narrate … --in-take any of these on a TAKE of the project: the pick, a new", " read (--take, --thread), the script, the mix -- written into the take's patch (umtool posts --help)", " umtool posts narrate --all --draft-scripts [--force] | --all --take [--limit N]", " umtool posts narrate --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=…", " A NARRATED POST ITEM: its script read by a stock synthetic voice, its attachment playing under the read (muffled,", " then clean). Takes are files of the project (narration/posts//take-.-.wav) the EDITOR", " 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}]).", " : the post item's id or its post's id. --pick : 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

--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 ….", " --delete : the take out of the list, its file moved to narration/posts//.trash/ (soft).", " --recording [--as ] [--no-clean] [--no-convert] [--label operator]: a person's RECORDING of the", " item made a character's read -- kept as a recorded take (the original), cleaned (the editor's voice-enhance), then", " converted to the character's STOCK voice (umtool cast: its convert voice) -- each a new take, the last picked, the", " disclosure line said. The character: --as (this video's own, else the cast's), else the item's own (umtool posts", " character), this video's for the post's author, the cast's, the narrator. Its RECORDED PRESET says whether the", " read is cleaned and its edges trimmed to speech (and the room kept): --clean | --no-clean and --trim | --no-trim", " say otherwise for this read.", " --recording --preview: THE SAME CHAIN, NO TAKE MADE (lib/report/recordPreview.mjs; the record page's", " Filter) -- cleaned, its edges cut (--trim-span 0.4-3.1: at these seconds of the recording instead of the auto", " trim's; a parted read: 2=0.2-4), converted -- into the scratch dir narration/.record-preview/.

--words`. // (A caller that hands in its own transcribe op -- a test's stub -- is asked about no lane unless it says.) const held = laneHeld ?? (askOp ? async () => false : transcriptionLaneHeld); if (await held()) { deferred = { words: `umtool posts narrate ${project.id} ${e.id} --words` }; emit("note", { message: `${e.id}: its read says a slur the cut beeps, and the editor's transcription lane is held -- its words are NOT timed now (that would wait for the release). After releasing the lane run: ${deferred.words} (the build refuses this take until then)` }); } } if (!deferred && slurs === "said" && red?.slurs?.on && red.slurs.voice === "beep") { try { timed = await timeTakeWords(project, rel, words, { askOp, emit, deadlineMs: timingDeadlineMs }); } catch (err) { if (err?.name === "OpDeadline") { // Waited its bound: kept as read, timed later -- never an unbounded wait. deferred = { words: `umtool posts narrate ${project.id} ${e.id} --words` }; emit("note", { message: `${e.id}: ${err.message} -- the take is kept as read; time its words later: ${deferred.words} (the build refuses this take until then)` }); } else { emit("note", { message: `${e.id}: its read could not be word-timed for the beep (${err instanceof Error ? err.message : err}) -- synthesized again with the slur left out` }); ({ jobId, result } = await askTts(ttsBody(spokenRead(words, e, red, { voice: "skip" }).text), { ...(editor ? { editor } : {}), emit })); slurs = "skip"; } } } const m = await measureTake(out); const take = { file: rel, engine: result?.engine ?? eng, voice: result?.voice ?? vox, seconds: m.seconds ?? Number(result?.seconds), source: { kind: "tts", engine: result?.engine ?? eng, voice: result?.voice ?? vox, script: words }, script: words, at: new Date().toISOString(), ...(note ? { note } : {}), ...(spd !== null && eng !== "orpheus" ? { speed: spd } : {}), // Where its speed came from (cast.mjs speedAskedOf): the command's --speed (kept as asked), the item's own, the // character's preset (drift when that changes). No speed asked: no key. ...(spd !== null && eng !== "orpheus" ? { speedAsked: speed !== null ? true : e.narration?.speed != null ? "item" : "preset" } : {}), ...(Number.isFinite(m.lufs) ? { lufs: m.lufs } : {}), jobId, // What it was made with, as the editor's result says it (Orpheus: every tuning value and the reading), so it can be // made again exactly; an engine without a sampler reports neither. ...tunedOfResult(result), // Where that tuning came from: its line's own (true) or its character's ("preset": stale when that changes). ...(tuningAsked ? { tuningAsked } : {}), // The line's own values as asked (lane reads-find): what a plain press passes back; none owned, no key. ...(ta.own ? { tuningOwn: ta.own } : {}), // 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

stale` reads them). ...(said.lexicon ? { lexicon: said.lexicon } : {}), // What it SAID, when an anonymous handle made that differ from the script (post-anon.mjs): the lint reads it. ...(said.anonymised ? { said: said.text } : {}), }; const patch = { addTake: take, ...(keepPick ? { keepPick: true } : {}), ...(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) })); return { take, result: wrote, editNotes, ...(deferred ? { deferred } : {}) }; } /** * The tuning and reading a tts result says a take was made with (Orpheus's), as take keys; `{}` for any other engine. * Only the known tuning fields are copied, as numbers: a field a later editor adds never makes the take's write (its * validator) fail after the audio exists. */ export function tunedOfResult(result) { const tuning = {}; if (isObj(result?.tuning)) { for (const k of TTS_TUNING_FIELDS) if (typeof result.tuning[k] === "number" && Number.isFinite(result.tuning[k])) tuning[k] = result.tuning[k]; } return { ...(Object.keys(tuning).length ? { tuning } : {}), ...(Number.isInteger(result?.reading) && result.reading >= 0 ? { reading: result.reading } : {}), }; } // The flags that make a read's tuning (readTuning.mjs, which the cast's re-reads share). export { TUNING_FLAGS } from "./readTuning.mjs"; /** * `--reading N` and the tuning flags as a take asks them: `{ tuning, reading, flags }` (the flags given), or null when * none is. A value the tts op would refuse is refused here, in the flag's name (lib/ttsTuning.mjs: the same ranges). */ export function tuningFlags(str) { const flags = []; const tuning = {}; const num = (flag) => { const raw = str(flag); if (raw === null) return null; flags.push(flag); return String(raw).trim() === "" ? Number.NaN : Number(raw); }; for (const [flag, field] of Object.entries(TUNING_FLAGS)) { const raw = num(flag); if (raw === null) continue; // Quantised as the editor's tts op quantises (3 places, -0 as 0), then checked. const v = quantizeTtsTuningValue(field, raw); const err = ttsTuningValueError(field, v, flag); if (err) throw new NarrateError(err.replace(/ \(got NaN\)$/, ` (got ${str(flag) || "nothing"})`)); tuning[field] = v; } // `--reading next` (lane line-rerun): one past the highest reading of these words -- worked out where the words are. const next = String(str("--reading") ?? "").trim().toLowerCase() === "next"; const reading = next ? (flags.push("--reading"), "next") : num("--reading"); if (reading !== null && !next) { const err = ttsReadingError(reading, "--reading"); if (err) throw new NarrateError(err.replace(/got NaN\)$/, `got ${str("--reading") || "nothing"} -- or next`)); } if (!flags.length) return null; return { tuning: Object.keys(tuning).length ? tuning : null, reading, flags }; } /** A piece of a read, as a part's role names it (post-narration.mjs's part roles; `media:` is never synthesized). */ const TUNED_ROLE_RE = /^(post|quoted|parent:\d|linked:\d|screen:[a-z0-9][a-z0-9-]{0,23}:\d{1,2})$/; /** The fields `--tuned` names: the reading and the tuning's own (llama-server's names). */ const TUNED_FIELDS = new Set(["reading", ...TTS_TUNING_FIELDS]); /** * A THREAD READ's readings and tunings by piece (lane line-rerun): `{ "" | "*": { reading?, tuning? } }` -- * `--reading N|next` and the tuning flags for the whole read ("*"), or for one piece with `--for `; and * `--tuned =reading:N,temperature:t,…` (repeatable: what a read's record asks again exactly). `{}` with none. */ export function threadTunedOf(tuned, { str, multi }) { const out = {}; const forRole = str("--for"); if (forRole !== null && !TUNED_ROLE_RE.test(String(forRole))) { throw new NarrateError(`--for names one piece of the read: post, quoted, parent:, linked: or screen:: (got ${forRole})`); } if (forRole !== null && !tuned) throw new NarrateError("--for goes with --reading and the tuning flags: what that piece is read with"); if (tuned) out[forRole ?? "*"] = { ...(tuned.reading !== null ? { reading: tuned.reading } : {}), ...(tuned.tuning ? { tuning: tuned.tuning } : {}) }; for (const raw of multi("--tuned")) { const m = /^([^=]+)=(.+)$/.exec(String(raw).trim()); if (!m) throw new NarrateError(`--tuned takes =reading:N,temperature:t,… (got ${raw})`); if (m[1] !== "*" && !TUNED_ROLE_RE.test(m[1])) throw new NarrateError(`--tuned ${m[1]}: not a piece of a read (* or post, quoted, parent:, linked:, screen::)`); const t = {}; let reading = null; for (const kv of m[2].split(",")) { const [k, v] = kv.split(":").map((x) => x?.trim()); if (!TUNED_FIELDS.has(k) || v === undefined || v === "") throw new NarrateError(`--tuned ${m[1]}: ${kv} is not one of ${[...TUNED_FIELDS].join(", ")} with a value`); if (k === "reading") { reading = v === "next" ? "next" : Number(v); if (reading !== "next" && ttsReadingError(reading)) throw new NarrateError(`--tuned ${m[1]}: ${ttsReadingError(reading, "reading")}`); } else { const q = quantizeTtsTuningValue(k, Number(v)); const err = ttsTuningValueError(k, q, `--tuned ${m[1]} ${k}`); if (err) throw new NarrateError(err); t[k] = q; } } out[m[1]] = { ...(reading !== null ? { reading } : {}), ...(Object.keys(t).length ? { tuning: t } : {}) }; } return out; } /** * A just-made take's WORD TIMINGS (for a beep over a slur it says): the editor's * transcription of its file, aligned to the script it read (word-zoom.mjs * scriptWordTimes) -- `posts narrate --words`' way, before the take is kept. * Throws when the editor cannot, or hears no words. */ async function timeTakeWords(project, rel, script, { askOp = null, emit = () => {}, deadlineMs = null } = {}) { const { recognizedOf, wordsFileOf } = await import("./postFxCli.mjs"); const { scriptWordTimes } = await import("umtool-report-to-video/word-zoom"); const ask = askOp ?? (await import("umtool-report-to-video/narrate-via-editor")).askEditorOp; const abs = path.join(project.dir, ...rel.split("/")); const outFile = path.join(project.dir, ...wordsFileOf(rel).split("/")); emit("note", { message: `timing ${rel}'s words for the beep (the editor's transcription)…` }); await ask("/api/ops/transcribe", { path: abs, words: true, out: outFile }, { emit, ...(deadlineMs !== null ? { deadlineMs } : {}) }); const heard = recognizedOf(JSON.parse(await readFile(outFile, "utf8")), 0); if (!heard.length) throw new Error("the transcription came back with no word timings"); return scriptWordTimes(script, heard).words; } /** `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, multi = () => [], ask = null, tts = null }) { const manifest = await readManifest(project.dir); if (!manifest) throw new NarrateError(`${project.id} has no manifest`); const render = manifest.render ?? {}; const tl = (manifest.timeline ?? []).filter((e) => e?.type === "post"); const pairs = words.filter((w) => /^[A-Za-z][A-Za-z.]*=/.test(w)); const ref = words.find((w) => !/^[A-Za-z][A-Za-z.]*=/.test(w)) ?? null; const write = async (fn) => withEditNotes(project, async () => fn(await manifestToken(project.dir))); // A read's tuning and reading are one item's new take's -- a single read's, or a thread read's (lane line-rerun: // the whole read's, or one piece's with --for) -- never --all's. const tuned = tuningFlags(str); if (tuned && !(flags.has("--take") && !flags.has("--all") && ref)) { throw new NarrateError(`${tuned.flags.join(", ")} go with one item's --take (umtool posts narrate

--take --reading 1); --all --take does not take them`); } if ((str("--for") !== null || multi("--tuned").length) && !(flags.has("--take") && flags.has("--thread"))) { throw new NarrateError("--for and --tuned are a thread read's (umtool posts narrate

--take --thread --for screen:: --reading next)"); } if (flags.has("--import")) { const idxFile = path.join(project.dir, ...NARRATION_INDEX.split("/")); let rows; try { rows = JSON.parse(await readFile(idxFile, "utf8")); } catch (e) { throw new NarrateError(`no readable ${NARRATION_INDEX} in ${project.id}: ${e instanceof Error ? e.message : e}`); } if (!Array.isArray(rows)) throw new NarrateError(`${NARRATION_INDEX} must be a list of [{id, entry, script, takes, pick}]`); const measure = async (rel) => { const abs = path.join(project.dir, ...String(rel).split("/")); const st = await stat(abs).catch(() => null); if (!st?.isFile()) return null; const parts = await readFile(path.join(project.dir, ...partsFileOf(rel).split("/")), "utf8").then((t) => JSON.parse(t), () => null); return { ...(await measureTake(abs)), at: new Date(st.mtimeMs).toISOString(), parts }; }; const { patches, missing, takes, absent } = await importPatches(manifest, rows, measure); const notYet = absent.length ? `; ${absent.length} take(s) not on disk yet (a later --import brings them): ${absent.slice(0, 5).join(", ")}${absent.length > 5 ? ", …" : ""}` : ""; const items = new Set(patches.map((p) => p.id)).size; if (dryRun || !patches.length) { if (json) out(JSON.stringify({ ok: true, dryRun, items, takes, missing, absent, patches }, null, 2)); else out(`${dryRun ? "would import" : "nothing new to import:"} ${takes} take(s) into ${items} post item(s)${missing.length ? `; ${missing.length} row(s) name no post item of the cut: ${missing.join(", ")}` : ""}${notYet}`); return 0; } const { result, editNotes } = await write((token) => updatePostNarrations(project.dir, patches, { token, op: "post-narration-import" })); if (json) out(JSON.stringify({ ok: true, items, takes, missing, absent, snapshot: result.snapshot, token: result.token, editNotes }, null, 2)); else { out(`imported ${takes} take(s) into ${items} post item(s) from ${NARRATION_INDEX}${missing.length ? `; ${missing.length} row(s) name no post item of the cut: ${missing.join(", ")}` : ""}${notYet}`); if (result.snapshot?.rel && !result.snapshot.skipped) out(` undo point: ${result.snapshot.rel} (umtool timeline ${project.id} undo)`); } return 0; } if (flags.has("--cut")) { const patch = mixPatchOf(pairs, { cut: true }); const { result } = await write((token) => updatePostNarrationRender(project.dir, patch, { token })); out(json ? JSON.stringify({ ok: true, postNarration: result.postNarration, token: result.token }, null, 2) : `the cut's narration mix: ${JSON.stringify(result.postNarration ?? "the defaults")}`); return 0; } if (flags.has("--list") || (!ref && !flags.has("--all"))) { if (json) out(JSON.stringify({ ok: true, items: tl.map((e) => ({ id: e.id, narrated: isNarrated(e), narration: e.narration ?? null, seconds: postItemPlan(e, render).total, ...(legacyReadOf(e) ? { readEdit: "legacy" } : readEditOf(e) === "reading" ? { readEdit: "reading" } : {}) })) }, null, 2)); else { const narrated = tl.filter(isNarrated).length; out(`${project.id}: ${tl.length} post item(s), ${narrated} narrated, ${tl.filter((e) => e.narration?.approved).length} approved`); for (const e of tl) out(narrationLines(e, render).join("\n")); } return 0; } if (flags.has("--all")) { if (flags.has("--draft-scripts")) { const force = flags.has("--force"); const patches = []; for (const e of tl) { if (!force && typeof e.narration?.script === "string" && e.narration.script) continue; // What is read: its excerpt's spans (post-item.mjs postReadText), else the whole post. const d = draftScript(postReadText(e)); if (!d.script) continue; patches.push({ id: e.id, patch: { script: d.script, excerpt: excerptSpansOf(e) ? true : null } }); } if (dryRun || !patches.length) { out(json ? JSON.stringify({ ok: true, dryRun, patches }, null, 2) : `${dryRun ? "would draft" : "nothing to draft:"} ${patches.length} script(s)${patches.length ? "" : " (every post item has one; --force redrafts them)"}`); return 0; } const { result } = await write((token) => updatePostNarrations(project.dir, patches, { token, op: "post-narration-scripts" })); out(json ? JSON.stringify({ ok: true, drafted: patches.length, snapshot: result.snapshot }, null, 2) : `drafted ${patches.length} script(s) from the posts' words (verbatim); undo point: ${result.snapshot?.rel ?? "-"}`); return 0; } if (flags.has("--take")) { if (flags.has("--thread")) throw new NarrateError("--take --thread reads one item: name it (umtool posts narrate

--take --thread)"); const limitRaw = str("--limit"); const limit = limitRaw === null ? Infinity : Number(limitRaw); const todo = tl.filter((e) => e.narration?.script && !(e.narration.takes ?? []).length); out(`${todo.length} post item(s) have a script and no take${Number.isFinite(limit) ? ` (doing ${Math.min(limit, todo.length)})` : ""}`); let made = 0; for (const e0 of todo.slice(0, Number.isFinite(limit) ? limit : undefined)) { // Read again: a take made since (an earlier run, another hand) is not made twice. const now = findPostItem(await readManifest(project.dir), e0.id); if (!now || (now.narration?.takes ?? []).length) continue; out(`${now.id}: asking the editor…`); const { take } = await makeTake(project, now, { render, emit: (_ev, f) => f?.message && out(f.message) }); out(` ${take.file} ${take.seconds} s`); made += 1; } out(`made ${made} take(s)`); return 0; } throw new NarrateError("--all goes with --draft-scripts or --take"); } const e = findPostItem(manifest, ref); if (!e) throw new NarrateError(`no post item ${ref} in ${project.id} (its id, or the post's id)`); if (str("--delete") !== null) { const k = Number(str("--delete")); if (!Number.isInteger(k) || k < 1) throw new NarrateError("--delete takes a take's number as --list shows it (1 = the first)"); const r = await deleteTake(project, e, k - 1); out(json ? JSON.stringify({ ok: true, id: e.id, narration: r.narration, token: r.token }, null, 2) : `${e.id}: take ${k} moved to the post's .trash/ (out of the list)\n${narrationLines(r.entry, render).join("\n")}`); return 0; } if (flags.has("--preview") || flags.has("--keep-preview") || flags.has("--discard-preview")) { // RECORD -> FILTER -> PREVIEW (recordPreview.mjs): the chain run into the scratch dir, no take made; then kept, or dropped. const { discardPreview, keepPreview, previewDirOf, runPreview } = await import("./recordPreview.mjs"); const label = str("--label") ?? "operator"; if (flags.has("--discard-preview")) { await discardPreview(project.dir, e, label); out(json ? JSON.stringify({ ok: true, id: e.id, discarded: previewDirOf(project.dir, e, label) }, null, 2) : `${e.id}: its preview is gone (${previewDirOf(project.dir, e, label)})`); return 0; } if (flags.has("--keep-preview")) { // A preview of the record page's session is kept only while the session is still the recording it was made from. const { readPreview } = await import("./recordPreview.mjs"); const made = await readPreview(project.dir, e, label); const parts = made?.session ? await (await import("./recordSession.mjs")).sessionParts(project.dir, e, label).catch(() => null) : null; if (made?.session && !parts) throw new NarrateError(`${e.id}'s preview is of the record page's session, and that session is gone or not whole any more: --discard-preview, and Filter again`); const r = await keepPreview(project, e, { label, note: str("--note"), script: str("--script"), parts }); // A preview of the record page's session: its parts are takes now, the session is over. if (r.session) await (await import("./recordSession.mjs")).clearSession(project.dir, e, label); if (json) out(JSON.stringify({ ok: true, id: e.id, takes: r.takes, picked: r.picked, notes: r.notes, disclosure: r.disclosure, character: r.character, token: r.token }, null, 2)); else { out(`${e.id}: ${r.takes.map((t) => `${t.step} -> ${t.file}`).join(", ")}; picked ${r.picked} (from its preview: nothing converted again)`); if (r.disclosure) out(` disclosure: ${r.disclosure}`); } return 0; } // The recording: the file named, else the record page's session of this post (every part of it in). const file = str("--recording"); let parts; const fromSession = file === null; if (file !== null) { const abs = path.resolve(file); if (!(await stat(abs).catch(() => null))?.isFile()) throw new NarrateError(`--recording takes a sound file (no ${file})`); parts = [{ file: abs, text: String(e.narration?.script ?? "") }]; } else { const { sessionParts } = await import("./recordSession.mjs"); try { parts = await sessionParts(project.dir, e, label); } catch (err) { throw new NarrateError(`--preview takes --recording , or the record page's session of ${e.id}: ${err.message}`); } } const events = flags.has("--events"); const r = await runPreview(project, e, parts, { label, session: fromSession, as: str("--as"), clean: flags.has("--no-clean") ? false : flags.has("--clean") ? true : undefined, ...(flags.has("--no-trim") ? { trim: { on: false, padMs: null } } : flags.has("--trim") ? { trim: { on: true, padMs: null } } : {}), spans: trimSpans(multi("--trim-span"), parts.length), convert: !flags.has("--no-convert"), engine: str("--engine"), voice: str("--voice"), ...pitchFlags(str), out: str("--out"), ask, // --events: one JSON object a line (the record page's job reads them); else the sentences. emit: (ev, f) => (events ? out(JSON.stringify({ ev, ...f })) : !json && f?.message && out(ev === "note" ? f.message : ` ${f.message}`)), }); if (events) out(JSON.stringify({ ev: "result", ok: true, id: e.id, ...r })); else if (json) out(JSON.stringify({ ok: true, id: e.id, ...r }, null, 2)); else { out(`${e.id}: previewed${r.character ? ` as ${r.character.name}` : ""} -- NO TAKE MADE`); out(` raw ${r.raw}`); if (r.clean) out(` cleaned ${r.clean}`); if (r.filtered) out(` filtered ${r.filtered}${r.convert ? ` (${r.convert.engine ?? "the editor's engine"} -> ${r.convert.voice}${convertPitchLabel(r.convert) ? `, pitch: ${convertPitchLabel(r.convert)}` : ""})` : ""}`); if (r.out) out(` copied to ${r.out}`); for (const n of r.notes) out(` ${n}`); out(` keep it: umtool posts narrate ${project.id} ${e.id} --keep-preview${label !== "operator" ? ` --label ${label}` : ""} (drop it: --discard-preview)`); } return 0; } if (str("--recording") !== null) { // A RECORDING made a character's read: kept as a take (the original), cleaned, converted to its stock voice. const r = await importRecording(project, e, str("--recording"), { // --no-clean / --clean and --no-trim / --trim win over the character's recorded preset; neither: the preset's. as: str("--as"), label: str("--label") ?? "operator", clean: flags.has("--no-clean") ? false : flags.has("--clean") ? true : undefined, ...(flags.has("--no-trim") ? { trim: { on: false, padMs: null } } : flags.has("--trim") ? { trim: { on: true, padMs: null } } : {}), convert: !flags.has("--no-convert"), note: str("--note"), ...pitchFlags(str), emit: (_ev, f) => !json && f?.message && out(f.message), }); if (json) out(JSON.stringify({ ok: true, id: e.id, ...r }, null, 2)); else { out(`${e.id}: ${r.takes.map((t) => `${t.step} -> ${t.file}`).join(", ")}; picked ${r.picked}`); for (const n of r.notes) out(` ${n}`); if (r.disclosure) out(` disclosure: ${r.disclosure}`); } return 0; } if (str("--derive") !== null) { const k = Number(str("--derive")); if (!Number.isInteger(k) || k < 1) throw new NarrateError("--derive takes a take's number as --list shows it (1 = the first)"); const op = str("--op") ?? ""; try { const pitched = pitchFlags(str); if (op !== "convert" && (pitched.pitch !== undefined || pitched.semitones !== undefined)) throw new NarrateError("--pitch and --semitones are a convert's (--op convert): an enhance keeps the read's own pitch"); let asked = { engine: str("--engine"), voice: str("--voice"), ...pitched }; if (op === "convert") { // A convert is the CHARACTER's (cast.mjs characterForRead: --as, the item's own, this video's for the author, // the cast's, the narrator): its recorded preset's engine, stock voice, pitch and semitones, each unless a flag // says otherwise -- and with no character and no --voice it is refused, never the editor's default voice. const { readLayers } = await import("./characterLayers.mjs"); const { recordedPresetOf } = await import("umtool-report-to-video/cast"); const who = (await readLayers(project.dir)).characterForRead(e, str("--as")); if (str("--as") && !who?.character) throw new NarrateError(`--as ${str("--as")}: no such character in this video's characters or the cast (umtool cast project ${project.id}, umtool cast ls)`); const d = convertAskOf(asked, who?.character ? recordedPresetOf(who.character).convert : null, who?.character?.id ?? null); if (!d.ok) throw new NarrateError(`${d.error} (${d.fix})`); asked = d.value; if (!json && d.from === "character") out(` as ${who.character.id}: ${asked.engine ?? "the editor's engine"} -> ${asked.voice}${convertPitchLabel(asked) ? ` (pitch: ${convertPitchLabel(asked)})` : ""}`); } const r = await deriveTake(project, e, { from: k - 1, op, ...asked, ask, emit: (_ev, f) => !json && f?.message && out(f.message) }); if (json) out(JSON.stringify({ ok: true, id: e.id, take: r.take, token: r.result.token }, null, 2)); else out(`${e.id}: take ${r.take.file} (${r.take.seconds} s), from take ${k} by ${op}, picked`); return 0; } catch (err) { if (err?.name === "OpNotInstalled") throw new NarrateError(err.message); throw err; } } if (flags.has("--words")) { const { takeWords, fxLines } = await import("./postFxCli.mjs"); const r = await takeWords(project, e, { worker: str("--worker"), emit: (_ev, f) => !json && f?.message && out(f.message) }); if (json) out(JSON.stringify({ ok: true, id: e.id, take: r.take.file, heard: r.heard, of: r.of, recognized: r.recognized, words: r.result.entry.narration.takes[r.take.index].words, token: r.result.token }, null, 2)); else { out(`${e.id}: take ${r.take.file} timed: ${r.heard} of its script's ${r.of} words heard (${r.recognized} recognized${r.sources > 1 ? `, over ${r.sources} parts` : ""}); the rest placed between them`); if (Array.isArray(r.result.entry.fx) && r.result.entry.fx.length) out(fxLines(r.result.entry, render).join("\n")); } 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"), speed: speedFlag(str), note: str("--note"), force: flags.has("--force"), hold: !flags.has("--no-hold"), dryRun, // His own line from an existing take (its number as --list shows it), the context synthesized around it. postTake: str("--post-take"), // ITS SCREENS (post-screens.mjs): read after his words unless --no-screens; a line from a take (--line-take). screens: !flags.has("--no-screens"), lineTakes: lineTakesOf(multi("--line-take")), // Its readings and tunings (lane line-rerun): the whole read's, one piece's (--for), each piece's (--tuned). tuned: threadTunedOf(tuned, { str, multi }), keepPick: flags.has("--no-pick"), events: flags.has("--events"), // The editor's tts op as the caller hands it (postsCommand's `tts`: a test's stub) -- the lanes then never held. ...(tts ? { ask: tts, lanes: null } : {}), }); } if (str("--post-take") !== null) throw new NarrateError("--post-take is a thread read's (umtool posts narrate

--take --thread --post-take )"); if (multi("--line-take").length) throw new NarrateError("--line-take is a thread read's (umtool posts narrate

--take --thread --line-take screen::=)"); if (flags.has("--thread")) throw new NarrateError("--thread goes with --take (umtool posts narrate

--take --thread)"); if (flags.has("--take")) { // `--reading next` (lane line-rerun): one past the highest reading of the words this take reads. const words = String(str("--script") ?? e.narration?.script ?? "").trim(); const asked = tuned?.reading === "next" ? { ...tuned, reading: nextReadingOf(e.narration?.takes, words) } : tuned; const keepPick = flags.has("--no-pick"); const r = await makeTake(project, e, { script: str("--script"), note: str("--note"), engine: str("--engine"), voice: str("--voice"), speed: speedFlag(str), ...(asked ? { tuning: asked.tuning, reading: asked.reading } : {}), keepPick, render, emit: (_ev, f) => !json && f?.message && out(f.message), // --bench-slurs (the re-read queue's): the bench's slur rule -- a beep left out, as a bench press leaves it. benchSlurs: flags.has("--bench-slurs"), // The editor's tts op as the caller hands it (postsCommand's `tts`: a test's stub). ...(tts ? { ask: tts, laneHeld: async () => false } : {}), }); if (json) out(JSON.stringify({ ok: true, id: e.id, take: r.take, picked: !keepPick, narration: r.result.narration, token: r.result.token }, null, 2)); else out(`${e.id}: take ${r.take.file} (${r.take.seconds} s), ${keepPick ? "not picked (--pick to play it)" : "picked"}${r.take.note ? ` — note: ${r.take.note}` : ""}${tunedLabel(asked)}`); return 0; } const patch = pairs.length ? mixPatchOf(pairs) : {}; const script = str("--script"); if (script !== null) patch.script = script; const pickRaw = str("--pick"); if (pickRaw !== null) { const n = Number(pickRaw); if (!Number.isInteger(n) || n < 1) throw new NarrateError("--pick takes a take's number as --list shows it (1 = the first)"); patch.pick = n - 1; } if (flags.has("--approve")) patch.approved = true; if (flags.has("--unapprove")) patch.approved = null; if (flags.has("--off")) patch.off = true; if (flags.has("--on")) patch.off = null; if (!Object.keys(patch).length) { out(json ? JSON.stringify({ ok: true, id: e.id, narration: e.narration ?? null, plan: postItemPlan(e, render) }, null, 2) : narrationLines(e, render).join("\n")); return 0; } const { result } = await write((token) => updatePostNarration(project.dir, e.id, patch, { token })); if (json) out(JSON.stringify({ ok: true, id: e.id, narration: result.narration, token: result.token }, null, 2)); else out(narrationLines(result.entry, render).join("\n")); return 0; } /** `--line-take screen::=` words as `{ : }`; throws naming a bad one. */ export function lineTakesOf(list) { const out = {}; for (const raw of (Array.isArray(list) ? list : []).flatMap((x) => String(x).split(",")).map((x) => x.trim()).filter(Boolean)) { const m = /^(screen:[a-z0-9][a-z0-9-]{0,23}:\d{1,2})=(\d{1,3})$/.exec(raw); if (!m) throw new NarrateError(`--line-take takes screen::= (got ${raw})`); out[m[1]] = Number(m[2]); } return out; } export const CHARACTER_USAGE = [ "usage: umtool posts character [ | --clear] [--json]", " THE CHARACTER ONE POST ITEM's OWN READ IS MADE WITH (its `narration.character`): the id of one of this video's", " own characters (umtool cast project

), else of the cast's (umtool cast ls) -- its presets answer for this", " item's read before its author's handle does: the synthetic one for a new take or a thread read (voice, speed),", " the recorded one for a recording made its read (--recording). No character: the one it names, and what its read", " resolves to now. --clear: by its author's handle again. One undoable write; no take is made or changed (a picked", " read in another voice is DRIFT: umtool cast project

).", ].join("\n"); /** `umtool posts character

[ | --clear]` -- a post item's own character (cast.mjs itemCharacterOf). */ export async function characterCommand(project, rest, { flags = new Map(), json = false, out = (s) => console.log(s) } = {}) { const [ref, id] = rest; const manifest = await readManifest(project.dir); if (!manifest) throw new NarrateError(`${project.id} has no manifest`); const e0 = findPostItem(manifest, ref); if (!e0) throw new NarrateError(`no post item ${ref} in ${project.id} (its id, or the post's id)`); const clear = flags.has("--clear"); if (clear && id) throw new NarrateError("posts character: a character's id, or --clear -- not both"); const { readLayers } = await import("./characterLayers.mjs"); const { characterById, shownNameOf } = await import("umtool-report-to-video/cast"); const { itemReadVoice } = await import("./readVoice.mjs"); const { voiceSpecOf } = await import("umtool-report-to-video/post-say"); const layers = await readLayers(project.dir); let e = e0; let changed = null; if (clear || id) { let want = null; if (id) { const hit = characterById(id, layers); if (!hit) throw new NarrateError(`no character ${id} among ${project.id}'s own or in the cast (umtool cast project ${project.id}; umtool cast ls)${layers.projectRead.error ? ` -- and this video's characters are not read: ${layers.projectRead.error}` : ""}`); want = hit.character.id; } if ((e0.narration?.character ?? null) !== want) { const { result } = await withEditNotes(project, async () => updatePostNarration(project.dir, e0.id, { character: want }, { token: await manifestToken(project.dir) })); e = result.entry; changed = want ? "set" : "cleared"; } } const it = layers.itemCharacterOf(e); const v = await itemReadVoice(project, e, { render: manifest.render ?? {}, map: layers.map, cast: layers.castMap, item: layers.itemOf(e) }); const voice = { ...v, spec: voiceSpecOf(v) }; if (json) out(JSON.stringify({ ok: true, id: e.id, character: it?.id ?? null, found: it ? !!it.character : null, layer: it?.layer ?? null, changed, voice }, null, 2)); else { const how = `${voice.spec}${typeof voice.speed === "number" ? ` ×${voice.speed}` : ""} (${voice.from}${voice.character && voice.from !== "narrator" ? `: ${voice.character}` : ""})`; if (!it) out(`${e.id}: no character of its own${changed ? " now" : ""} -- read by its author's handle: ${how}`); else if (!it.character) out(`${e.id}: names ${it.id}, which is NOT a character of this video's or the cast's -- it reads as its author does: ${how} (umtool posts character ${project.id} ${e.id} --clear)`); else out(`${e.id}: read as ${it.id} (${shownNameOf(it.character)}; ${it.layer === "project" ? "this video's own" : "the cast's"}): ${how}`); } return 0; } export const FIT_USAGE = [ "usage: umtool posts fit [--all | …] [--linger ] [--dry-run] [--json]", " NARRATED POSTS, NO LINGERING: each post read in full, then over `linger` (1.8 s) after the words; a video", " attachment longer than that is cut to its BEST PART of that length -- a scored scan of its sound (loudness,", " its peaks), its speech (when transcribed) and its scene cuts, the start snapped to a pause or a cut -- recorded", " with why (narration.window). One undoable write; each post's old and new length and the window printed.", " --linger sets those posts' own linger too. A video no longer than the read is left as it is.", ].join("\n"); /** `umtool posts fit` (lib/report/postFit.mjs). */ export async function fitCommand(project, refs, { all = false, linger = null, json = false, dryRun = false, out = (s) => console.log(s), scan = undefined } = {}) { const { fitPostItem } = await import("./postFit.mjs"); const { fitPostItems } = await import("./manifest.mjs"); const manifest = await readManifest(project.dir); if (!manifest) throw new NarrateError(`${project.id} has no manifest`); const render = manifest.render ?? {}; const items = all ? (manifest.timeline ?? []).filter((e) => e?.type === "post" && isNarrated(e)) : refs.map((r) => { const e = findPostItem(manifest, r); if (!e) throw new NarrateError(`no post item ${r} in ${project.id}`); return e; }); if (!items.length) throw new NarrateError(all ? `${project.id} has no narrated post item` : "name the post items to fit, or --all"); const fits = []; const rows = []; for (const e of items) { const before = postItemPlan(e, render).total; const f = await fitPostItem(e, render, project.dir, { linger, ...(scan ? { scan } : {}) }); if (!f || f.untouched || !f.window) { rows.push({ id: e.id, before, after: before, note: !f ? "not narrated, clip=full, or no video" : `its video (${f.duration} s) is no longer than the read (${f.L} s): as it is` }); if (linger !== null && isNarrated(e)) fits.push({ id: e.id, media: {}, window: e.narration?.window ?? null, linger }); continue; } const next = JSON.parse(JSON.stringify(e)); for (const [k, mp] of Object.entries(f.media)) for (const [kk, v] of Object.entries(mp)) if (v === null) delete next.media[k][kk]; else next.media[k][kk] = v; next.narration = { ...next.narration, window: f.window, ...(linger !== null ? { linger } : {}) }; rows.push({ id: e.id, before, after: postItemPlan(next, render).total, window: f.window }); fits.push({ id: e.id, media: f.media, window: f.window, ...(linger !== null ? { linger } : {}) }); } let result = null; if (!dryRun && fits.length) ({ result } = await withEditNotes(project, async () => fitPostItems(project.dir, fits, { token: await manifestToken(project.dir) }))); if (json) out(JSON.stringify({ ok: true, dryRun, rows, snapshot: result?.snapshot ?? null, token: result?.token ?? null }, null, 2)); else { for (const r of rows) { out(`${r.id} ${r.before.toFixed(1)} s -> ${r.after.toFixed(1)} s${r.window ? ` window ${r.window.start}–${r.window.end} s: ${r.window.reason}` : ` (${r.note})`}`); } const saved = rows.reduce((n, r) => n + (r.before - r.after), 0); out(`${dryRun ? "would fit" : "fitted"} ${fits.length} post item(s); the cut ${saved >= 0 ? "shorter" : "longer"} by ${Math.abs(saved).toFixed(1)} s${result?.snapshot?.rel && !result.snapshot.skipped ? `; undo point: ${result.snapshot.rel}` : ""}`); } return 0; } /** " — reading 2, temperature 0.7": what the flags asked of this read (the take records every value); "" for none. */ function tunedLabel(tuned) { if (!tuned) return ""; const said = [...(tuned.reading !== null ? [`reading ${tuned.reading}`] : []), ...Object.entries(tuned.tuning ?? {}).map(([k, v]) => `${k} ${v}`)]; return said.length ? ` — ${said.join(", ")}` : ""; } /** `--speed` as a read takes it (null: not given); a value the tts op would refuse is refused here, in the flag's name. */ function speedFlag(str) { const raw = str("--speed"); if (raw === null) return null; const n = Number(raw); const [lo, hi] = POST_NARRATION_LIMITS.speed; if (String(raw).trim() === "" || !Number.isFinite(n) || n < lo || n > hi) throw new NarrateError(`--speed is a number from ${lo} to ${hi} (got ${raw || "nothing"})`); return n; } /** * `--trim-span` as the cut marks of a preview: `-` (the first part) or `=-` (part n), seconds * in the part as recorded, once a part. Returns `[{ from, to } | null]` per part, or null when none was given. */ export function trimSpans(specs, count) { if (!specs.length) return null; const out = new Array(count).fill(null); for (const spec of specs) { const m = /^(?:(\d+)=)?(\d+(?:\.\d+)?)-(\d+(?:\.\d+)?)$/.exec(String(spec).trim()); const n = m ? Number(m[1] ?? 1) : 0; if (!m || n < 1 || n > count || !(Number(m[3]) - Number(m[2]) >= 0.2)) throw new NarrateError(`--trim-span is - or =- in seconds, at least 0.2 s, for a part 1-${count} (got ${spec || "nothing"})`); if (out[n - 1]) throw new NarrateError(`--trim-span names part ${n} twice`); out[n - 1] = { from: Number(m[2]), to: Number(m[3]) }; } return out; } /** `--pitch` / `--semitones` as a convert takes them (only those given); a value the editor would refuse anyway is refused here, in the flag's name. */ export function pitchFlags(str) { const out = {}; const p = str("--pitch"); if (p !== null) { if (!CAST_CONVERT_PITCH.includes(p)) throw new NarrateError(`--pitch is one of ${CAST_CONVERT_PITCH.join(", ")} (got ${p || "nothing"})`); out.pitch = p; } const s = str("--semitones"); if (s !== null) { const n = Number(s); if (s.trim() === "" || !Number.isFinite(n) || Math.abs(n) > CAST_SEMITONES_MAX) throw new NarrateError(`--semitones is a number from -${CAST_SEMITONES_MAX} to ${CAST_SEMITONES_MAX} (got ${s || "nothing"})`); out.semitones = n; } return out; } /** * A DERIVED TAKE (post-narration.mjs: "run AI on recorded voice"): take * `from` (an index) run through the editor's `op` (`enhance`, `convert`) into * a NEW take -- source `{kind: "take", from: }`, its step recorded -- * the original untouched; a parted take part by part (its parts kept). The * editor's op is a job (`POST /api/ops/voice-enhance|voice-convert` with * `{file, out, engine?, voice?, pitch?, semitones?, params?, parts?}`); one it has no engine for * throws OpNotInstalled. A convert's `pitch` / `semitones` (the pitch the read lands on: the editor's voice-convert) * go as asked and are kept on the take's step as the editor says it ran them. */ export async function deriveTake(project, e, { from, op, engine = null, voice = null, pitch = null, semitones = null, params = null, emit = () => {}, editor = null, ask = null } = {}) { const takes = e.narration?.takes ?? []; const t = takes[from]; if (!t) throw new NarrateError(`${e.id} has no take ${from + 1}`); if (!POST_DERIVE_OPS.includes(op)) throw new NarrateError(`--op is one of ${POST_DERIVE_OPS.join(", ")}`); 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 = derivedFileOf(pid, n, op, engine ?? voice ?? "default"); const abs = (r) => path.join(project.dir, ...r.split("/")); const partsRel = rel.replace(/\.wav$/, ".parts"); const parts = Array.isArray(t.parts) && t.parts.every((p) => typeof p.file === "string") ? t.parts.map((p) => ({ ...p, file: `${partsRel}/p${String(p.n).padStart(2, "0")}.wav` })) : null; // `voice` is the convert op's stock target; enhance keeps the take's voice and takes none. const target = op === "convert" ? voice : null; const body = { file: abs(t.file), out: abs(rel), ...(engine ? { engine } : {}), ...(target ? { voice: target } : {}), ...(params ? { params } : {}), ...(op === "convert" && pitch ? { pitch } : {}), ...(op === "convert" && typeof semitones === "number" ? { semitones } : {}), ...(parts ? { parts: t.parts.map((p, k) => ({ file: abs(p.file), out: abs(parts[k].file) })) } : {}), }; const askOp = ask ?? (await import("umtool-report-to-video/narrate-via-editor")).askEditorOp; const { jobId, result: said } = await askOp(POST_DERIVE_ROUTES[op], body, { ...(editor ? { editor } : {}), emit }); if (!(await stat(abs(rel)).catch(() => null))?.isFile()) throw new NarrateError(`the editor's job ${jobId} finished but ${rel} is not there`); const m = await measureTake(abs(rel)); // The editor's defaults, when the ask named none: the engine it ran, the stock voice it landed on. const ran = engine ?? (typeof said?.engine === "string" ? said.engine : null); const landed = op === "convert" ? (target ?? (typeof said?.voice === "string" ? said.voice : null)) : null; // The pitch it landed on, as the editor ran it (its default when none was asked); the target's own is not a step's news. const pitched = op === "convert" ? stepPitchOf({ pitch, semitones }, said) : {}; const take = { // A take's voice is the bare stock voice ("am_michael"); its step keeps the target as asked ("kokoro:am_michael"). file: rel, engine: "derived", voice: (landed ? String(landed).split(":").pop() : null) ?? t.voice ?? "?", seconds: m.seconds ?? t.seconds, source: { kind: "take", from: takeIdOf(t) }, steps: [{ op, ...(ran ? { engine: ran } : {}), ...(landed ? { voice: landed } : {}), ...pitched, ...(params ? { params } : {}), ranAt: new Date().toISOString(), job: jobId }], script: t.script ?? e.narration?.script ?? "", at: new Date().toISOString(), jobId, ...(Number.isFinite(m.lufs) ? { lufs: m.lufs } : {}), ...(parts ? { parts } : {}), // Its audio is its source's words at its source's speed: what it said and where that speed came from, copied. ...(typeof t.speed === "number" ? { speed: t.speed } : {}), ...(t.speedAsked !== undefined ? { speedAsked: t.speedAsked } : {}), ...(typeof t.said === "string" ? { said: t.said } : {}), // And the reading it was: the tuning and reading its source was synthesized with. ...tunedOfResult(t), // A recording of a screen line stays that line's (and, as it, never picked). ...(isObj(t.screenLine) ? { screenLine: { ...t.screenLine } } : {}), }; const { result } = await withEditNotes(project, async () => updatePostNarration(project.dir, e.id, { addTake: take, ...(isObj(t.screenLine) ? { keepPick: true } : {}) }, { token: await manifestToken(project.dir) })); return { take, result }; } /** * A RECORDING MADE A CHARACTER's READ (operator, 6 Nov: "running AI voice changing on a recording of me so I can * provide the wording and such while you clean up any audio issues"): `file` (any sound or video ffmpeg reads) kept * as a RECORDED take (postRecord.mjs keepRecording: trimmed, levelled -- the original, never overwritten), then a * derived take CLEANED by the editor's voice-enhance (skipped, and said, when it has no engine for it), then a * derived take CONVERTED by its voice-convert to the character's STOCK voice (cast.mjs convertTargetOf: its convert * voice, else its voice) at the PITCH asked (`pitch`, `semitones`), else the character's own (its convert entry's), * else the editor's. * * THE CHARACTER, and its RECORDED PRESET (cast.mjs characterForRead, recordedPresetOf): the one `as` names (an id, a * handle, a name -- the project's own characters first), else the item's own (`narration.character`), else the * project's for the post's author, else the cast's, else the cast's narrator; none: kept as recorded (and cleaned). * What the command says wins over the preset: `clean` (undefined: the preset's `enhance`, on unless it says off), * `trim` (undefined: the preset's -- its edges trimmed to speech unless `trim.on` is false, `trim.padMs` the room * kept either side), `pitch` / `semitones`. Each step a new take, the last one picked, with the disclosure line the * cut will carry. Returns `{ takes: [{ step, file }], picked, notes, disclosure, character, direction }`. */ export async function importRecording(project, e0, file, { as = null, label = "operator", clean = undefined, convert = true, trim = undefined, pitch = undefined, semitones = undefined, note = null, emit = () => {}, editor = null, ask = null, screenLine = null, script = null, character: given = undefined } = {}) { const abs = path.resolve(String(file ?? "")); if (!(await stat(abs).catch(() => null))?.isFile()) throw new NarrateError(`--recording takes a sound file (no ${file})`); const { keepRecording } = await import("./postRecord.mjs"); const { readLayers } = await import("./characterLayers.mjs"); const { convertPitchLabel, recordedPresetOf, shownNameOf } = await import("umtool-report-to-video/cast"); const { postNarrationDisclosure } = await import("umtool-report-to-video/post-narration"); const layers = await readLayers(project.dir); // A SCREEN LINE's recording (screenLineRecord.mjs) is made into its SPEAKER's character, which the caller found // (`character`: null -- none, kept as recorded); a read of the item into the item's (characterForRead). const who = given !== undefined ? (given ? { character: given, layer: "line" } : null) : layers.characterForRead(e0, as); const character = who?.character ?? null; if (as && !character && given === undefined) throw new NarrateError(`--as ${as}: no such character in this video's characters or the cast (umtool cast project ${project.id}, umtool cast ls)`); const preset = character ? recordedPresetOf(character) : null; const doClean = clean ?? preset?.enhance ?? true; const doTrim = trim ?? (preset ? preset.trim : undefined); const notes = []; const takes = []; const fresh = async () => findPostItem(await readManifest(project.dir), e0.id); const kept = screenLine ? await keepRecording(project, e0, [{ file: abs, text: String(script ?? "") }], { label, manifest: await readManifest(project.dir), note: note ?? `line ${screenLine.n} of screen ${screenLine.screen} recorded${character ? ` for ${shownNameOf(character)}` : ""}`, script: String(script ?? ""), screenLine, ...(doTrim ? { trim: doTrim } : {}) }) : await keepRecording(project, e0, [{ file: abs, text: String(e0.narration?.script ?? "") }], { label, manifest: await readManifest(project.dir), note: note ?? `recorded${character ? ` for ${shownNameOf(character)}` : ""}`, ...(doTrim ? { trim: doTrim } : {}) }); takes.push({ step: "recorded", file: kept.take.file }); emit("note", { message: `kept as recorded: ${kept.take.file} (levelled ${kept.gain >= 0 ? "+" : ""}${kept.gain} dB${doTrim?.on === false ? ", its edges not trimmed" : ""})` }); let e = await fresh(); const indexOf = (rel) => (e?.narration?.takes ?? []).findIndex((t) => t.file === rel); let from = indexOf(kept.take.file); if (doClean) { try { const r = await deriveTake(project, e, { from, op: "enhance", emit, editor, ask }); takes.push({ step: "cleaned", file: r.take.file }); e = await fresh(); from = indexOf(r.take.file); } catch (err) { if (err?.name !== "OpNotInstalled" && !/not installed/i.test(String(err?.message))) throw err; notes.push(`not cleaned: ${err.message} (archilyzer voice setup --engine deepfilternet)`); } } else if (clean === undefined) notes.push(`not cleaned: ${character.id}'s recorded preset says so (enhance off)`); if (convert) { const target = character ? preset.convert : null; if (!character && screenLine) notes.push(`not converted: line ${screenLine.n}'s speaker has no character to convert to -- kept as recorded (umtool cast add … --handle , or --as )`); else if (!character) notes.push("not converted: no character to convert to (--as , the item's own, or the post's author or a narrator in the cast: umtool cast add …)"); else if (!target.voice) notes.push(`not converted: ${character.id} has no stock voice to convert to (umtool cast ${who.layer === "cast" || who.layer === "narrator" ? "" : `project ${project.id} `}set ${character.id} --convert-voice )`); else { // The pitch asked for this read, else the character's; semitones asked of the target's own pitch are dropped // with it (a character kept at "contour +2" read once with --pitch target). const pitched = { pitch: pitch ?? target.pitch ?? null, semitones: semitones ?? (pitch === "target" ? null : target.semitones ?? null) }; try { const r = await deriveTake(project, e, { from, op: "convert", engine: target.engine, voice: target.voice, ...pitched, emit, editor, ask }); const how = convertPitchLabel(r.take.steps?.[0]); takes.push({ step: `converted to ${target.voice}${how ? ` (pitch: ${how})` : ""}`, file: r.take.file }); e = await fresh(); } catch (err) { if (err?.name !== "OpNotInstalled" && !/not installed/i.test(String(err?.message))) throw err; notes.push(`not converted: ${err.message} (archilyzer voice setup --engine ${target.engine ?? "openvoice"})`); } } } // A line's: none picked; its disclosure the one its line will carry in the read (a recorded reading, converted or not). const conv = screenLine ? (e?.narration?.takes ?? []).find((t) => t.file === takes.at(-1).file)?.steps?.find((st) => st?.op === "convert") : null; return { takes, picked: screenLine ? null : takes.at(-1).file, notes, disclosure: screenLine ? (conv ? `a recorded reading converted to a stock voice (${conv.engine ?? "?"} · ${conv.voice ?? "?"})` : "a recorded reading") : e ? postNarrationDisclosure(e) : null, character: character ? { id: character.id, name: shownNameOf(character), voice: character.voice ?? null, layer: who.layer } : null, ...(preset?.direction ? { direction: preset.direction } : {}), }; } /** * DELETE A TAKE, SOFTLY: its file (and its parts) moved into the post's * `narration/posts//.trash/`, the take out of the list (the pick * follows). Returns the write's result. */ export async function deleteTake(project, e, index) { const takes = e.narration?.takes ?? []; const t = takes[index]; if (!t) throw new NarrateError(`${e.id} has no take ${index + 1}`); // Refused BEFORE anything is moved: a take another take is made of -- a thread read's part (`parts[].take`, its // --post-take) or a derived take's source -- would leave that one pointing at a file that is gone. const id = takeIdOf(t); const users = takes.map((x, i) => ({ x, n: i + 1 })).filter(({ x }) => x !== t && ((Array.isArray(x?.parts) && x.parts.some((p) => p?.take === id || (p?.take && p?.file === t.file))) || (x?.source?.kind === "take" && x.source.from === id))); if (users.length) throw new NarrateError(`take ${index + 1} (${t.file}) is a part of ${users.map(({ x, n }) => `take ${n} (${x.file})`).join(", ")}: delete ${users.length === 1 ? "that take" : "those takes"} first -- nothing moved`); // A take a screen CHOSE for one of its lines (`lineTakes`): unchosen first. const chooser = (Array.isArray(e.screens) ? e.screens : []).flatMap((sc) => Object.entries(isObj(sc?.lineTakes) ? sc.lineTakes : {}).filter(([, v]) => v === id).map(([k]) => ({ sc: sc.id, k })))[0]; if (chooser) throw new NarrateError(`take ${index + 1} (${t.file}) is chosen for line ${chooser.k} of screen ${chooser.sc}: unchoose it first (umtool posts screen

${e.id} set ${chooser.sc} take.${chooser.k}=off) -- nothing moved`); const trash = path.join(project.dir, ...takesDirOf(postIdOf(e)).split("/"), ".trash"); await mkdir(trash, { recursive: true }); const stamp = new Date().toISOString().replace(/[:.]/g, "-"); const moved = []; try { for (const rel of [t.file, String(t.file).replace(/\.wav$/, ".parts")]) { const from = path.join(project.dir, ...String(rel).split("/")); const to = path.join(trash, `${stamp}-${path.basename(from)}`); if (await stat(from).catch(() => null)) { await rename(from, to); moved.push([from, to]); } } const { result } = await withEditNotes(project, async () => updatePostNarration(project.dir, e.id, { dropTake: index }, { token: await manifestToken(project.dir) })); return result; } catch (err) { // A move or the write failed: what moved goes back where it was -- and what cannot is said, file by file. const stuck = []; for (const [from, to] of moved) { try { await rename(to, from); } catch (re) { stuck.push(`${path.relative(project.dir, to)} (belongs at ${path.relative(project.dir, from)}: ${re instanceof Error ? re.message : re})`); } } if (stuck.length) throw new NarrateError(`${err instanceof Error ? err.message : err} -- and ${stuck.length} file(s) could NOT be put back, still in the trash: ${stuck.join("; ")}`); throw err; } }