// `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/./,",
" its paths printed; --out copies the filtered read there. Without --recording: the record page's session",
" of the item. A step whose inputs did not change is not run again (another --pitch asks for the convert alone).",
" --keep-preview makes its takes (recorded, cleaned, converted; the last picked) from those files, converting",
" nothing again; --discard-preview removes it. --events: its progress as one JSON object a line.",
" --speed (--take, --take --thread): the speed the read is asked at (0.5-2; Orpheus has none) -- default the",
" item's own, else its character's (the synthetic preset's: umtool cast set --speed). A thread read: every part.",
" --reading N (--take): ANOTHER READING of the same words -- 0 the first (the default), 1, 2, … each read anew by",
" Orpheus (its seeds move; a new cached file), the same N again the same file. --temperature (0.1-1.5) --top-p",
" (0.05-1) --top-k (0-200) --min-p (0-0.5) --repeat-penalty (1-2) --chunk-takes (1-6, the tries a sentence gets):",
" Orpheus's TUNING for this read, any of them, the rest its defaults. The take records the tuning (every value) and",
" the reading it was made with. Kokoro and eSpeak NG ignore both (the editor says so). One item's --take only, not",
" --all. --reading next: one past the highest reading these words were read at (0 for new words). --no-pick: the",
" new take joins the list unpicked (--pick makes it the one; the bench's Read again does this). --bench-slurs:",
" the bench's slur rule (a cut that beeps has the slur left out, not word-timed): what `umtool reads … reread` asks.",
" With --thread: the whole read's, every synthesized piece read anew (next: each one past its own highest); --for",
" (post, quoted, parent:, linked:, screen::) one piece's only, the others from the cache;",
" --tuned =reading:N,temperature:t,… (repeatable) each piece's exactly (what a read's `read.tuned` says).",
" --post-take (--take --thread): 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 around it is; each part records where it came from.",
" --derive --op enhance|convert [--engine e] [--voice v]: a NEW take made from take n by the editor's op",
" (enhance: denoise, level; convert: the performance kept, the timbre a STOCK synthetic voice) -- the original kept.",
" A convert is the CHARACTER's (--as, else 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 its flag says otherwise. With no",
" character and no --voice it is refused: the editor's default voice is never asked for.",
" --pitch target|source|contour [--semitones ] (a convert, by --derive or --recording): the PITCH the converted",
" read lands on -- target: the stock voice's own (the read's intonation is flattened to it); source: the pitch it",
" was read at (raise your voice and it rises); contour: the read's rises and falls, moved as a whole to the stock",
" voice's register; --semitones (-12 to 12) then moves a followed pitch. Default: the character's own (umtool cast",
" set --convert-pitch …), else the editor's (settings.voice.convert). source and contour are seed-vc's, with",
" its f0 model (archilyzer voice setup --engine seed-vc --with f0); the editor refuses what it cannot do.",
" A narrated post lasts lead + its read + tail + linger (1.8 s); a longer video is cut to that -- its best part,",
" pace=fast plays a post (or, with --cut, every post) back to back: lead 0.1, tail 0.15, ramp 0.3, linger 0.45 --",
" unless it sets one itself; pace=normal the cut's gaps.",
" once `umtool posts fit` has scanned it (else from its in point). clip=full plays the attachments whole.",
" rate=0.8–1.5 (default 1): the READ sped up (its pitch kept), the attachment untouched; the post's length, its",
" muffle and its parts follow the faster read (a 10 s take at rate=1.25 reads in 8 s).",
" --words [--worker ]: the picked take's WORD TIMINGS -- the editor's transcribe op (a job; parakeet keeps word times)",
" on the take (or each of its parts), the words heard aligned to its script, kept on the take: a word zoom's time",
" (umtool posts fx) is its word's start there.",
].join("\n");
export class NarrateError extends Error {}
const ON = new Set(["on", "true", "yes", "1"]);
const OFF = new Set(["off", "false", "no", "0", "none"]);
/** A take's length (ffprobe) and loudness (ffmpeg ebur128), measured when it comes in. */
export async function measureTake(file) {
const { stdout } = await execFileP(FFPROBE(), ["-v", "error", "-show_entries", "format=duration", "-of", "default=noprint_wrappers=1:nokey=1", file]);
const seconds = Number(String(stdout).trim());
let lufs = null;
try {
const { stderr } = await execFileP(FFMPEG(), ["-nostdin", "-hide_banner", "-nostats", "-i", file, "-af", "ebur128=framelog=quiet", "-f", "null", "-"], { maxBuffer: 1 << 24 });
const all = [...String(stderr).matchAll(/\bI:\s+(-?[\d.]+|-inf)\s+LUFS/g)];
const v = all.length ? Number(all.at(-1)[1]) : NaN;
lufs = Number.isFinite(v) && v > -70 ? Math.round(v * 10) / 10 : null;
} catch {
lufs = null;
}
return { seconds: Number.isFinite(seconds) ? Math.round(seconds * 1000) / 1000 : null, lufs };
}
/** The post item `ref` names: its id, its post's id, or `p-`. */
export function findPostItem(manifest, ref) {
const tl = Array.isArray(manifest?.timeline) ? manifest.timeline : [];
const r = String(ref ?? "");
return tl.find((e) => e?.type === "post" && (e.id === r || postIdOf(e) === r || e.id === `p-${r}`)) ?? null;
}
/**
* `--import`'s patches from the index's rows (pure but for `measure`): each
* row's takes merged into the item's by file (a take already there kept as
* it is), the script set when the item has none, the pick set when the item
* had no takes. Rows naming no post item of the cut come back in `missing`.
*
* @param {Record} manifest
* @param {Array>} rows
* @param {(rel: string) => Promise<{ seconds: number|null, lufs: number|null, at?: string|null }>} measure
*/
export async function importPatches(manifest, rows, measure) {
const patches = [];
const missing = [];
const absent = [];
let takes = 0;
for (const row of rows) {
const e = findPostItem(manifest, row?.entry) ?? findPostItem(manifest, row?.id);
if (!e) {
missing.push(String(row?.entry ?? row?.id ?? "?"));
continue;
}
const had = Array.isArray(e.narration?.takes) ? e.narration.takes : [];
const files = new Set(had.map((t) => t?.file));
const add = [];
for (const t of Array.isArray(row.takes) ? row.takes : []) {
if (typeof t?.file !== "string" || files.has(t.file)) continue;
const m = await measure(t.file);
// A take still being made (not on disk yet) comes in with a later run.
if (!m) {
absent.push(t.file);
continue;
}
add.push({
file: t.file,
engine: t.engine ?? "orpheus",
voice: t.voice ?? "zac",
source: { kind: "tts", engine: t.engine ?? "orpheus", voice: t.voice ?? "zac", script: typeof t.script === "string" ? t.script : String(row.script ?? "") },
seconds: Number.isFinite(m.seconds) ? m.seconds : Number(t.seconds),
script: typeof t.script === "string" ? t.script : String(row.script ?? ""),
at: typeof t.at === "string" ? t.at : m.at ?? new Date().toISOString(),
...(Number.isFinite(m.lufs) ? { lufs: m.lufs } : {}),
...(typeof t.note === "string" ? { note: t.note } : {}),
// A take composed of parts (a long post, paragraph by paragraph): the row's, else take-.parts.json beside it.
// Each part's ROLE stored as it comes in (post-thread.mjs): the text it reads, its own or inferred.
// Its STAMP decided FIRST (review 2, finding 6): an imported read of words edited for reading is his post's,
// part by part (Rule B, as a made take's) -- never a role inferred from the edited words.
...(() => {
const parts = normalizeParts(Array.isArray(t.parts) ? t.parts : m.parts);
const script = typeof t.script === "string" ? t.script : String(row.script ?? "");
const edited = takeIsEditedRead(e, { script, ...(parts ? { parts } : {}) });
return { ...(edited ? { forReading: true } : {}), ...(parts ? { parts: edited ? parts : withPartRoles(e, parts) } : {}) };
})(),
});
files.add(t.file);
}
const patch = {};
if (typeof row.script === "string" && !(typeof e.narration?.script === "string" && e.narration.script)) patch.script = row.script;
// Each new take goes in; the row's pick holds only for an item that had none.
if (!add.length && !Object.keys(patch).length) continue;
const list = [];
if (patch.script !== undefined) list.push({ script: patch.script });
for (const t of add) list.push({ addTake: t, keepPick: true });
const total = had.length + add.length;
if (!had.length && total) list.push({ pick: Number.isInteger(row.pick) && row.pick >= 0 && row.pick < total ? row.pick : 0 });
for (const p of list) patches.push({ id: e.id, patch: p });
takes += add.length;
}
return { patches, missing, takes, absent };
}
const fmtKnob = (k, v) => `${k}=${typeof v === "boolean" ? (v ? "on" : "off") : v}`;
/**
* @returns {Array<{ n: number, para?: number, text?: string, file?: string, start: number, seconds: number, gapBefore?: number }> | null}
* A take's PARTS as the batch writes them (`take-.parts.json`: a list, or
* `{ parts: [...] }`), each `{ n, para, text, file, start, seconds, gapBefore }`
* -- only those keys, numbers rounded; null when there are none.
*/
export function normalizeParts(raw) {
const list = Array.isArray(raw) ? raw : Array.isArray(raw?.parts) ? raw.parts : null;
if (!list?.length) return null;
const r3 = (v) => Math.round(Number(v) * 1000) / 1000;
return list
.filter((p) => p && typeof p === "object" && Number.isFinite(Number(p.start)) && Number(p.seconds) > 0)
.map((p, k) => ({
n: Number.isInteger(p.n) ? p.n : k + 1,
...(Number.isInteger(p.para) ? { para: p.para } : {}),
...(typeof p.text === "string" ? { text: p.text } : {}),
...(typeof p.file === "string" ? { file: p.file } : {}),
start: r3(p.start),
seconds: r3(p.seconds),
...(Number.isFinite(Number(p.gapBefore)) ? { gapBefore: r3(p.gapBefore) } : {}),
// The text it reads (post-thread.mjs), the voice and the piece the batch read it in.
...(typeof p.role === "string" && /^(post|quoted|parent:\d|media:\d|linked:\d|screen:[a-z0-9][a-z0-9-]{0,23}:\d{1,2})$/.test(p.role) ? { role: p.role } : {}),
...(typeof p.voice === "string" && /^[A-Za-z0-9][A-Za-z0-9_.+-]{0,63}$/.test(p.voice) ? { voice: p.voice } : {}),
...(typeof p.engine === "string" && /^(orpheus|kokoro|espeak-ng)$/.test(p.engine) ? { engine: p.engine } : {}),
...(Number.isInteger(p.piece) && p.piece >= 0 ? { piece: p.piece } : {}),
// A screen line's part (post-screens.mjs): the line and the speaker it was made from (the stale-read guard's).
...(typeof p.line === "string" ? { line: p.line } : {}),
...(typeof p.speaker === "string" ? { speaker: p.speaker } : {}),
}));
}
/**
* A take's parts with each one's ROLE (post-thread.mjs partRoles): the text
* it reads -- its own role kept, else the one inferred from its words and its
* piece (`para` div 100); a part no text on the card holds is left without.
*/
export function withPartRoles(entry, parts) {
const roles = partRoles(entry, { parts });
return parts.map((p, k) => (p.role || !roles[k]?.role ? p : { ...p, role: roles[k].role }));
}
/** `take-.parts.json` for a take file `narration/posts//take-.-.wav`. */
export const partsFileOf = (rel) => String(rel).replace(/(take-\d+)(?:-[a-z]+)?\.[^/]*\.wav$/, "$1.parts.json");
/** One item's narration as lines. */
export function narrationLines(e, render) {
const n = e.narration ?? {};
const t = pickedTake(e);
const plan = postItemPlan(e, render);
const lines = [
`${e.id} ${isNarrated(e) ? "NARRATED" : n.off ? "narration off" : "not narrated"}${n.approved ? " · approved" : ""} ${plan.total.toFixed(2)} s`,
` script: ${n.script ? JSON.stringify(n.script) : "(none)"}`,
];
// ITS PLAYING TAKE PREDATES THE RULE (post-item.mjs legacyReadOf): its card follows what that take says.
if (legacyReadOf(e)) lines.push(` ${LEGACY_EDIT}`);
(n.takes ?? []).forEach((tk, i) => {
const tuned = [...(Number.isInteger(tk.reading) && tk.reading > 0 ? [`reading ${tk.reading}`] : []), ...Object.entries(normalizeTtsTuning(tk.tuning)).map(([k, v]) => `${k} ${v}`)];
lines.push(` ${t?.index === i ? "▶" : " "} #${i + 1} ${tk.file} ${Number(tk.seconds).toFixed(2)} s ${tk.engine ?? "?"} · ${tk.voice ?? "?"}${tuned.length ? ` ${tuned.join(", ")}` : ""}${tk.parts?.length ? ` ${tk.parts.length} parts` : ""}${tk.note ? ` note: ${tk.note}` : ""}${tk.script && tk.script !== n.script ? " (an older script)" : ""}`);
});
if (plan.narration) {
const k = postNarrationKnobs(e, render);
lines.push(` mix: ${["lead", "tail", "ramp", "linger", "clip", "wet", "lowpassHz", "duck", "short", "attach", "lufs", "rate", "pace"].map((x) => fmtKnob(x, k[x])).join(" ")}`);
if (n.window) lines.push(` window: attachment ${n.window.media + 1} ${n.window.start}–${n.window.end} s (score ${n.window.score}): ${n.window.reason}`);
lines.push(` plays: voice ${plan.narration.at}–${(plan.narration.at + plan.narration.seconds).toFixed(2)} s, muffled to ${plan.narration.voiceEnd} s, clean from ${plan.narration.rampEnd} s; attachments ${plan.steps.map((s) => `${s.kind} ${s.at}+${s.seconds}`).join(", ") || "none"}${plan.held ? `, held ${plan.held} s` : ""}`);
}
return lines;
}
/** What a legacy edited script is told (`--list`, the bench): the fact, and what moves it to the new rule. */
export const LEGACY_EDIT = LEGACY_EDIT_TEXT;
/** `k=v` words as a narration patch (the post's mix, or with `cut` the cut's). */
export function mixPatchOf(pairs, { cut = false } = {}) {
const out = {};
for (const pair of pairs) {
const eq = pair.indexOf("=");
if (eq < 1) throw new NarrateError(`${pair}: a knob is key=value`);
const k = pair.slice(0, eq);
const raw = pair.slice(eq + 1);
const v = raw.toLowerCase();
const clear = v === "" || v === "default";
const num = () => {
const x = Number(raw);
if (!Number.isFinite(x)) throw new NarrateError(`${k}= takes a number`);
return x;
};
if (["lead", "tail", "ramp", "linger", "wet", "lufs", "rate"].includes(k)) out[k] = clear ? null : num();
else if (k === "clip") out.clip = clear ? null : v;
else if (k === "lowpass" || k === "lowpassHz") out.lowpassHz = clear ? null : num();
// The pace (post-narration.mjs POST_PACES): fast plays it back to back; normal (or default) the cut's gaps.
else if (k === "pace") out.pace = clear ? null : v;
else if (k === "duck") out.duck = clear ? null : ON.has(v) ? true : OFF.has(v) ? false : (() => { throw new NarrateError("duck= takes on or off"); })();
else if (k === "short") out.short = clear ? null : v;
else if (k === "attach" && !cut) out.attach = clear ? null : v;
else if ((k === "engine" || k === "voice") && cut) out[k] = clear ? null : raw;
// The cut's read-follow (read-follow.mjs): follow=on|off, follow.dim=<0.2-1>, follow.ease=.
else if (k === "follow" && cut) out.follow = { ...(out.follow ?? {}), on: clear ? null : ON.has(v) ? true : OFF.has(v) ? false : (() => { throw new NarrateError("follow= takes on or off"); })() };
else if ((k === "follow.dim" || k === "follow.ease") && cut) out.follow = { ...(out.follow ?? {}), [k.slice(7)]: clear ? null : num() };
// The cut's thread reads (post-thread.mjs): thread.parent|quoted=, thread.carry=auto|on|off, thread.reveal=on|off,
// thread.shrink|dim|seconds|pan=.
else if (/^thread\.(parent|quoted|carry|reveal|shrink|dim|seconds|pan)$/.test(k) && cut) {
const knob = k.slice(7);
let val;
if (clear) val = null;
else if (knob === "parent" || knob === "quoted") val = v;
else if (knob === "carry") val = v === "auto" ? "auto" : ON.has(v) ? true : OFF.has(v) ? false : (() => { throw new NarrateError("thread.carry= takes auto, on or off"); })();
else if (knob === "reveal") val = ON.has(v) ? true : OFF.has(v) ? false : (() => { throw new NarrateError("thread.reveal= takes on or off"); })();
else val = num();
out.thread = { ...(out.thread ?? {}), [knob]: val };
}
else if (k === "fit" && !cut) {
// fit=read[:linger]: the item ends `linger` after the words (posts fit picks the clip's best part for it).
const m = /^read(?::([\d.]+))?$/.exec(v);
if (!m) throw new NarrateError("fit= takes read or read:");
out.linger = m[1] !== undefined ? Number(m[1]) : null;
out.clip = null;
} else throw new NarrateError(`${pair}: not a narration knob (lead, tail, ramp, end, wet, lowpass, duck, short, ${cut ? "linger, clip, lufs, rate, pace, engine, voice, follow, follow.dim, follow.ease, thread.parent|quoted|carry|reveal|shrink|dim|seconds|pan" : "linger, clip, attach, lufs, rate, pace, fit"})`);
}
if (!Object.keys(out).length) throw new NarrateError("nothing to set");
return out;
}
/**
* Ask the editor for one take of `e` and keep it: the next take- file in
* the project, measured, appended (and picked) through the writer. Returns
* the take and the write's result.
*/
/** The longest a take waits for its beep's word timing (the editor's transcription) before it defers it. */
export const BEEP_TIMING_DEADLINE_MS = 5 * 60 * 1000;
/**
* Is the editor's transcription lane HELD (render mode, a TTS session)? Its
* transcribe job would wait for a worker until it is released. Unknown (no
* token, the editor not answering): false -- the timing's own deadline bounds it.
*/
export async function transcriptionLaneHeld() {
try {
const { editorLanes } = await import("./renderMode.mjs");
const { editorConfig } = await import("./fetchWindows.mjs");
const lanes = editorLanes(editorConfig());
return lanes ? await lanes.isHeld("transcription") : false;
} catch {
return false;
}
}
export async function makeTake(project, e, { script = null, note = null, engine = null, voice = null, speed = null, tuning = null, reading = null, keepPick = false, render = {}, emit = () => {}, editor = null, ask = null, askOp = null, redaction = undefined, laneHeld = null, timingDeadlineMs = BEEP_TIMING_DEADLINE_MS, benchSlurs = false } = {}) {
const words = String(script ?? e.narration?.script ?? "").trim();
if (!words) throw new NarrateError(`${e.id} has no script to read (--script "…", or --all --draft-scripts)`);
// What the voice SAYS: the script with every redacted term left out (post-redact.mjs), each slur as the cut's
// filter has it (post-slurs.mjs: skipped, its stand-in, or said for a beep), and each word of the project's
// pronunciation lexicon said its way (post-say.mjs) -- the script itself is kept as written.
const red = redaction !== undefined ? redaction : await projectRedaction(project.dir, (await readManifest(project.dir)) ?? {});
// THE ASK (postTakeAsk.mjs, the one the bench's take op builds too; lane reads-find): the voice his own read is said
// in (the one asked for, the item's own character, the project's characters and voice map, the CAST, the
// narrator's), its speed (the one asked for, else the item's own, else its character's), its tuning (the line's own
// values over its character's, field by field; a character with no tuning: the ask as it always was) and what is
// said. `benchSlurs` (the re-read queue): the bench's slur rule -- a beep left out, as a bench press leaves it.
const { askBody, benchSlurVoice, postTakeAskOf } = await import("./postTakeAsk.mjs");
const A = await postTakeAskOf(project, e, { render, script: words, engine, voice, speed, tuning, reading, red, slurVoice: benchSlurs ? benchSlurVoice(red) : undefined });
const eng = A.engine;
const vox = A.voice;
const spd = A.speed;
const pid = postIdOf(e);
const dir = path.join(project.dir, ...takesDirOf(pid).split("/"));
await mkdir(dir, { recursive: true });
const onDisk = await readdir(dir).catch(() => []);
const n = nextTakeNumber(e, onDisk);
const rel = takeFileOf(pid, n, eng, vox);
const out = path.join(project.dir, ...rel.split("/"));
const askTts = ask ?? (await import("umtool-report-to-video/narrate-via-editor")).askEditorTts;
const said = A.said;
const tuningAsked = A.tuningAsked;
const ta = { own: A.tuningOwn };
const ttsBody = (text) => askBody(A, out, text);
let { jobId, result } = await askTts(ttsBody(said.text), { ...(editor ? { editor } : {}), emit });
if (result?.note) emit("note", { message: `${e.id}: ${result.note}` });
if (!(await stat(out).catch(() => null))?.isFile()) throw new NarrateError(`the editor's job ${jobId} finished but ${rel} is not there (its result names ${result?.wav ?? "no file"})`);
// A BEEP needs the slur's time: the take is word-timed now (the editor's transcription). When that cannot be
// done, the read is synthesized again with the slur left out -- a published take never says one it cannot cover.
let slurs = said.slurs;
let timed = null;
let deferred = null;
if (slurs === "said" && red?.slurs?.on && red.slurs.voice === "beep") {
// NEVER BLOCK ON THE LANE (rev 9, 6 Nov): with the transcription lane held -- as it is while Orpheus runs --
// the editor's transcribe job would wait for a worker until it is released, and this take with it. The take is
// kept as read (it says the slur; the build refuses to play it until its words are timed) and the timing is
// left for after the release: `posts narrate - --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;
}
}