// `umtool cast` (umtool-report-to-video/cast.mjs; umtool/docs/knobs.md, "The cast"): the CHARACTERS across projects // and their presets, a project's characters (the chain's answer for each author, and the project's OWN characters), // an AUDITION of candidate voices, and the voice a character reads in -- for a project or everywhere (the cast) -- // with the re-reads that asks for. // // umtool cast [ls] [--json] // umtool cast add --name "…" --voice [the preset flags] [--handles a,b] [--speakers Name,…] [--avatar …] [--note "…"] [--narrator] [--json] // umtool cast set [the same flags] [--add-handle h] [--remove-handle h] [--no-convert] [--no-speed] [--no-narrator] [--json] // umtool cast rm [--json] · umtool cast undo [--json] // umtool cast project

[--json] // umtool cast project

add [--name "…"] [--voice ] [the preset flags] [--handles a,b] [--anonymous [--shown "…"]] [--json] // umtool cast project

set [the same flags] [--no-voice] [--no-anonymous] … · rm · undo // umtool cast project

pool its character into the cast ("Add to the pool") // umtool cast project

keep [--anonymous [--shown "…"]] a character of this video only // umtool cast audition --voices a,b,… [--project

] [--text "…" | --item | --line ] // [--no-score | --score-only] [--no-hold] [--json] [--progress ndjson] // umtool cast use

[--everywhere] [--json] // umtool cast reread

[--dry-run] [--json] // umtool cast try

[--text "…" | --item | --line ] [the tuning flags] [--reading N | --another] // [--list | --clear] [--no-hold] [--json] [--progress ndjson] one line read with a tuning (scratch) // umtool cast stale

[] [--json] the reads made with other settings than its tuning now // umtool cast assign

[--model] [--dry-run] [--json] PROPOSED characters for the authors with none // umtool cast assign

--accept | --accept-all | --reject | --reject-all // umtool cast assign

--change [--voice ] [--speed s] [--name "…"] [--anonymous [--shown "…"] | --no-anonymous] // // Plain ESM: the CLI runs under bare node. import path from "node:path"; import { ANON_NAME_PATTERN, CAST_CONVERT_ENGINES, CAST_CONVERT_PITCH, CAST_SEMITONES_MAX, CAST_SPEED, DIRECTION_MAX, TRIM_PAD_MAX_MS, characterOf, characterView, convertPitchErrors, convertPitchLabel, charactersOf, findCharacter, idOfHandle, isQualifiedVoice, isStockVoice, nextAnonName, projectCharactersOf, proposalCharacter, shownNameOf, upgradeCharacter, } from "umtool-report-to-video/cast"; import { handleKey, voiceRefOf, voiceSpecOf } from "umtool-report-to-video/post-say"; import { characterTuning, characterTuningNormal, characterVoice } from "umtool-report-to-video/cast"; import { ORPHEUS_DEFAULT_TAKES, ORPHEUS_TUNING_NAMED, ORPHEUS_TUNING_NAMES, quantizeTtsTuningValue, ttsReadingError, ttsTuningNameOf, ttsTuningValueError } from "yt-dlp-transcript-common/lib/ttsTuning.mjs"; import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs"; import { readManifest } from "../projects/report.mjs"; import { CastError, castFile, castForProject, castWrite, projectCharactersWrite, readCast, readProjectCharacters, undoCast, undoProjectCharacters } from "./castStore.mjs"; const TUNING_USAGE = "[--tuning steady|default|lively] [--temperature |default] [--top-p

|default] [--repeat-penalty |default] [--chunk-takes |default]"; const PRESET_FLAGS = "[--speed ] [--tuning steady|default|lively] [--temperature ] [--top-p

] [--repeat-penalty ] [--chunk-takes ] [--convert-engine openvoice|seed-vc] [--convert-voice ] [--convert-pitch target|source|contour] [--convert-semitones ] [--enhance on|off|default] [--trim on|off|default] [--trim-pad |default] [--direction \"…\"]"; export const CAST_USAGE = [ "usage: umtool cast [ls] [--json]", " umtool cast add --name \"…\" --voice [--handles a,b] [--speakers Name,…]", ` ${PRESET_FLAGS}`, " [--avatar …] [--note \"…\"] [--narrator] [--json]", " umtool cast set [those flags] [--add-handle h] [--remove-handle h] [--no-convert] [--no-speed] [--no-tuning] [--no-narrator] [--json]", " umtool cast rm [--json]", " umtool cast undo [--json]", " umtool cast project [--json]", " umtool cast project add [--name \"…\"] [--voice ] [--handles a,b] [--anonymous [--shown \"…\"]] [the preset flags] [--json]", " umtool cast project set [those flags] [--add-handle h] [--remove-handle h] [--no-voice] [--no-convert] [--no-speed] [--no-tuning] [--no-anonymous] [--json]", " umtool cast project rm | undo | pool | keep [--anonymous [--shown \"…\"]] [--json]", " umtool cast audition --voices kokoro:am_michael,kokoro:am_onyx,orpheus:zac [--project

]", " [--text \"…\" | --item | --line | --stock] [--no-score | --score-only] [--no-hold] [--json] [--progress ndjson]", " umtool cast use [--everywhere] [--json]", " umtool cast reread [--dry-run] [--json]", " umtool cast try [--text \"…\" | --item | --line ]", ` ${TUNING_USAGE}`, " [--reading N | --another] [--scope cast|project] [--list | --clear] [--no-hold] [--json] [--progress ndjson]", " umtool cast stale [] [--json]", " umtool cast assign [--model] [--dry-run] [--json]", " umtool cast assign --accept | --accept-all | --reject | --reject-all [--json]", " umtool cast assign --change [--voice ] [--speed ] [--name \"…\"] [--anonymous [--shown \"…\"] | --no-anonymous] [--json]", "", " THE CAST (/.umtool/cast.json, one writer, an undo point per write): the characters that recur across", " projects -- an id, a name, their handles (X handles / channel slugs) and TWO PRESETS, picked by how a read is made:", " SYNTHETIC: the STOCK voice they read in (--voice engine:voice) and its speed (--speed 0.5-2; Orpheus has none),", " and ORPHEUS's TUNING for their reads (Kokoro and eSpeak NG ignore it): a named starting point (--tuning steady,", " default or lively: temperature, top_p and repeat penalty together) and the numbers, any of them over it", " (--temperature 0.1-1.5, --top-p 0.05-1, --repeat-penalty 1-2, --chunk-takes 1-6: the takes a chunk gets; `default`", " takes one off; --tuning default puts the sampler's three back and keeps its takes; --no-tuning drops all of it,", " and goes with no other tuning flag). A value equal to its default is not kept", " (takes 3 included: a character with no takes of its own reads with the editor's tts.orpheus.takes). It is the", " default of every Orpheus read the character's preset answers for; a read's own tuning flags beat it. --json says", " `tuning` (its own, its name, every value its reads are asked with: `effective`).", " RECORDED (a recording of them made their read): the voice it is converted to (--convert-voice, its engine", " --convert-engine) and the PITCH that read lands on (--convert-pitch: target = the stock voice's own, the read's", " intonation flattened to it; source = the pitch it was read at; contour = the read's rises and falls at the stock", " voice's register; --convert-semitones -12…12 moves a followed one; source and contour are seed-vc's, with its f0", " model), whether it is cleaned first (--enhance on|off; default on), whether its edges are trimmed to speech", " (--trim on|off; default on) and the room kept either side (--trim-pad ), and a DIRECTION (--direction: one", " line for the person reading -- \"higher, brisk, amused\" -- never sent to a model; \"\" removes it). A convert", " target is always a STOCK synthetic voice: a file or a recording is refused. `default` for a convert flag, --enhance,", " --trim or --trim-pad takes that key off (the default again). Also the names their REAL voice goes", " by in a project's speakers.json (--speakers: a reference to compare with, never a target), and one --narrator (a", " recording's default character). A version 1 file (voice, convert at a character's top) reads as these presets;", " the first write after makes it version 2 (undo puts the old file back).", " ONE READ's PRESET, first hit wins: the command's flags (--voice-for, --voice, --speed, --as, --pitch), the item's", " own character (umtool posts character), this video's character for the author (project add; then its voice map,", " umtool posts voices), the cast's, the narrator's, the default.", " project: every character the project's reads use, the voice each reads in now and WHERE IT COMES FROM (item,", " project, cast, narrator, default), its speed, its picked reads in another voice (drift: re-read them), the cast", " voices the project overrides, its reference; this video's own characters; the items that name their own.", " project

add|set|rm|undo: THIS VIDEO's OWN characters (

/narration/characters.json, one writer, an undo", " point per write) -- the same shape, for people who must not enter the pool. --anonymous: it goes by a SHOWN NAME", ` (--shown; default the next of "${ANON_NAME_PATTERN.replace("{n}", "1")}", "${ANON_NAME_PATTERN.replace("{n}", "2")}" …) on the Voices page, in cast project and in a recording's note, and never`, " enters the pool -- and THE CUT's CARDS draw them so too: the shown name, no handle, a neutral avatar. --voice is optional", " here: a character with none leaves the voice to the layers under it. pool : it moves into the cast (an", " anonymous one is refused). keep : a cast character copied here (its presets changed for this", " video only), or an author with no character given one here, in the voice they read in now.", " audition: one line (--text; --item: the character's line from that item; --line n: its n-th line; default its", " first, else a stock line) read by each candidate (2-6) through the editor's tts op (a job; Orpheus is heavy,", " Kokoro fast), kept at one loudness in

/narration/auditions/ (a re-audition is a cache hit), and with --project", " scored for closeness to the character's real voice (TitaNet-small, local; speakers.json). --no-score: synthesize", " only; --score-only: score what is kept.", " use: the voice for this project (its own character's when it has one for them, else its voice map) or", " --everywhere (the cast; the project's own override of it is removed); then the items whose picked reads say the", " character in another voice -- reread makes them (a new take each, picked, awaiting approval).", " try: ONE LINE read in the character's own voice with a tuning (its own, or the flags laid over it) and a reading", " (--reading N; --another: the next after the highest kept for that line and tuning) -- the editor's tts op, a", " job -- levelled to -20 LUFS in

/narration/auditions/ and kept in a short list (tries.json, the newest 12 per", " character; --list shows it and the line the page prefills, --clear empties it). SCRATCH: no take on any post,", " nothing written to the draft. The line: --text, else --item / --line (as audition), else the character's first", " own line in the project, else a stock line. --scope cast|project: the character of that layer (the same id may be", " the cast's and this video's own; none: this video's own first). Keep a tuning with cast set / cast project

set.", " stale: every picked Orpheus read of a character (or of all) made with OTHER SETTINGS than its tuning now -- a", " read whose tuning its own line asked is never stale; a recorded read never; takes compared only when the", " character names its takes. Listed, never re-made.", " assign: every post item's author gets a character BY RULE (no model): the item's own, this video's, its voice map's", " or the cast's; an author with none, a PROPOSED character of this video -- an id from the handle, their name, a", " STOCK Kokoro voice, the next in one fixed rotation that this project does not use yet (a gender hint only from", " the profile's own stated pronouns, when the capture has them). Proposals are kept apart in", "

/narration/characters.json (one writer, an undo point: cast project

undo) and applied to NOTHING until a", " person accepts: --accept / --accept-all makes it this video's character and names it on that author's items", " (those that name none; a picked read is never touched -- one in another voice is drift: cast reread);", " --reject / --reject-all drops it; --change sets its voice (a stock one), speed, name or anonymity first", " -- a changed row is a PERSON's (by: person): never re-sent to a model, never overwritten. An author an anonymous", " character covers (its handles, or an item naming it) is never proposed for and never sent to a model.", " --dry-run writes nothing. --model (optional, on request only): the generation task cast-assign (routed by", " settings.generation) is asked per author -- name, bio, post text -- for {character, voice, speed, direction}, each", " field checked (a stock voice, a speed 0.5-2, one plain line) and laid over the rule's row; the rule's row stays", " when the answer fails.", " Exit 0 done · 1 refused or failed · 2 usage.", ].join("\n"); const VALUED = new Set(["--scope", "--tuning", "--temperature", "--top-p", "--repeat-penalty", "--chunk-takes", "--reading", "--name", "--voice", "--handles", "--speakers", "--convert-engine", "--convert-voice", "--convert-pitch", "--convert-semitones", "--avatar", "--note", "--add-handle", "--remove-handle", "--voices", "--project", "--text", "--item", "--line", "--progress", "--speed", "--enhance", "--trim", "--trim-pad", "--direction", "--shown", "--accept", "--reject", "--change"]); const splitList = (v) => String(v ?? "").split(",").map((x) => x.trim()).filter(Boolean); function parse(args) { const words = []; /** @type {Map} */ const flags = new Map(); for (let i = 0; i < args.length; i += 1) { const a = args[i]; if (VALUED.has(a)) { if (i + 1 >= args.length) throw new CastError(`${a} needs a value`); flags.set(a, [...(flags.get(a) ?? []), args[++i]]); } else if (a.startsWith("--")) flags.set(a, [...(flags.get(a) ?? []), ""]); else words.push(a); } return { words, flags, str: (k) => flags.get(k)?.at(-1) ?? null, has: (k) => flags.has(k), all: (k) => flags.get(k) ?? [] }; } /** `on` / `off` / `default` as true / false / null (null: the key removed -- the default again). */ function onOff(flag, v) { const x = String(v).trim().toLowerCase(); if (x === "on" || x === "true" || x === "yes") return true; if (x === "off" || x === "false" || x === "no") return false; if (x === "default") return null; throw new CastError(`${flag} is on, off or default (got ${v || "nothing"})`); } const numberOf = (flag, v, lo, hi, what) => { const n = Number(v); if (String(v).trim() === "" || !Number.isFinite(n) || n < lo || n > hi) throw new CastError(`${flag} is ${what} from ${lo} to ${hi} (got ${v || "nothing"})`); return n; }; /** The fields `add`/`set` take from the flags (only those given). */ function fieldsOf(p) { const f = {}; if (p.str("--name") !== null) f.name = p.str("--name").trim(); if (p.str("--voice") !== null) { const v = p.str("--voice").trim(); if (!isQualifiedVoice(v)) throw new CastError(`--voice is a STOCK voice with its engine: kokoro:am_michael, orpheus:zac (got ${v})`); f.voice = v; } if (p.str("--speed") !== null) f.speed = numberOf("--speed", p.str("--speed"), CAST_SPEED[0], CAST_SPEED[1], "a number"); if (p.str("--handles") !== null) f.handles = splitList(p.str("--handles")).map(handleKey); if (p.str("--speakers") !== null) f.speakers = splitList(p.str("--speakers")); if (p.str("--avatar") !== null) f.avatar = p.str("--avatar"); if (p.str("--note") !== null) f.note = p.str("--note"); if (["--convert-engine", "--convert-voice", "--convert-pitch", "--convert-semitones"].some((k) => p.str(k) !== null)) { // `default` for one of them takes that key off the entry (the editor's engine, the character's own voice, no pitch said). const given = (k) => (p.str(k) !== null && p.str(k).trim().toLowerCase() !== "default" ? p.str(k).trim() : null); const dropped = (k) => p.str(k) !== null && p.str(k).trim().toLowerCase() === "default"; const ce = given("--convert-engine"); if (ce !== null && !CAST_CONVERT_ENGINES.includes(ce)) throw new CastError(`--convert-engine is ${CAST_CONVERT_ENGINES.join(" or ")} (or default)`); const cp = given("--convert-pitch"); if (cp !== null && !CAST_CONVERT_PITCH.includes(cp)) throw new CastError(`--convert-pitch is one of ${CAST_CONVERT_PITCH.join(", ")} (or default)`); const cs = p.str("--convert-semitones") === null ? null : Number(p.str("--convert-semitones")); if (cs !== null && !(p.str("--convert-semitones").trim() !== "" && Number.isFinite(cs) && Math.abs(cs) <= CAST_SEMITONES_MAX)) throw new CastError(`--convert-semitones is a number from -${CAST_SEMITONES_MAX} to ${CAST_SEMITONES_MAX}`); const cvv = given("--convert-voice"); if (cvv && !isQualifiedVoice(cvv)) throw new CastError(`--convert-voice is a STOCK voice with its engine, kokoro:am_michael -- never a file or a recording (got ${cvv})`); // Only the keys given: `set` lays them over the character's entry (convertOver), `add` takes them as they are. f.convert = { ...(ce ? { engine: ce } : dropped("--convert-engine") ? { engine: null } : {}), ...(cvv ? { voice: cvv } : dropped("--convert-voice") ? { voice: null } : {}), ...(cp ? { pitch: cp } : dropped("--convert-pitch") ? { pitch: null } : {}), ...(cs !== null ? { semitones: cs } : {}), }; } if (p.str("--enhance") !== null) f.enhance = onOff("--enhance", p.str("--enhance")); if (p.str("--trim") !== null) f.trimOn = onOff("--trim", p.str("--trim")); if (p.str("--trim-pad") !== null) f.trimPad = p.str("--trim-pad").trim().toLowerCase() === "default" ? null : numberOf("--trim-pad", p.str("--trim-pad"), 0, TRIM_PAD_MAX_MS, "a number of milliseconds"); if (p.str("--direction") !== null) { const d = p.str("--direction").replace(/\s+/g, " ").trim(); if (d.length > DIRECTION_MAX) throw new CastError(`--direction is one line for the person reading (at most ${DIRECTION_MAX} characters)`); f.direction = d; } if (p.str("--shown") !== null) f.shown = p.str("--shown").trim(); const tuning = tuningFlagsOf(p); if (tuning) f.tuning = tuning; return f; } /** The flags that set a character's tuning field, and the field each sets (S1's words: readTuning.mjs). */ export const CHARACTER_TUNING_FLAGS = Object.freeze({ "--temperature": "temperature", "--top-p": "top_p", "--repeat-penalty": "repeat_penalty", "--chunk-takes": "takes" }); /** * The tuning flags given: `{ named, set }` -- `named` a named starting point (--tuning) or null, `set` each field a * flag gave (quantised and in range; null: `default`, the field off) -- or null when none is given. */ export function tuningFlagsOf(p) { const named0 = p.str("--tuning"); const set = {}; let any = named0 !== null; for (const [flag, field] of Object.entries(CHARACTER_TUNING_FLAGS)) { const raw = p.str(flag); if (raw === null) continue; any = true; if (raw.trim().toLowerCase() === "default") { set[field] = null; continue; } const v = quantizeTtsTuningValue(field, raw.trim() === "" ? Number.NaN : Number(raw)); const e = ttsTuningValueError(field, v, flag); if (e) throw new CastError(e.replace(/\(got NaN\)$/, `(got ${raw || "nothing"})`)); set[field] = v; } if (!any) return null; let named = null; if (named0 !== null) { named = named0.trim().toLowerCase(); if (!ORPHEUS_TUNING_NAMES.includes(named)) throw new CastError(`--tuning is ${ORPHEUS_TUNING_NAMES.join(", ")} (got ${named0 || "nothing"})`); } return { named, set }; } /** * A tuning with the flags laid over `before` (pure): a named starting point replaces the sampler's three values (the * takes kept), then each field flag; normalised as a character keeps it (cast.mjs characterTuningNormal). */ export function tuningOver(before, f) { let t = { ...characterTuningNormal(before) }; if (f?.named) t = { ...(t.takes !== undefined ? { takes: t.takes } : {}), ...ORPHEUS_TUNING_NAMED[f.named] }; for (const [k, v] of Object.entries(f?.set ?? {})) { if (v === null) delete t[k]; else t[k] = v; } return characterTuningNormal(t); } /** What a tuning write says beside it: takes 3 is not kept (the setting's are used), and a voice that ignores a tuning. */ function tuningNotes(c, f, settingTakes) { const notes = []; if (f?.tuning?.set?.takes === ORPHEUS_DEFAULT_TAKES && settingTakes !== ORPHEUS_DEFAULT_TAKES) notes.push(`takes ${ORPHEUS_DEFAULT_TAKES} is Orpheus's default and is not kept: its reads take the editor's setting (${settingTakes})`); const voice = characterVoice(c); if (Object.keys(characterTuning(c)).length && voice && !String(voice).startsWith("orpheus:")) notes.push(`${voice} has no sampler: its reads ignore the tuning (Orpheus's) until its voice is an Orpheus one`); return notes; } /** * A convert entry with the flags' keys laid over it, and what makes no sense together refused in a sentence: the * target's own pitch drops the semitones (nothing is followed to move), 0 semitones is no entry. */ function convertOver(before, given) { const cv = { ...(before ?? {}), ...given }; for (const k of Object.keys(cv)) if (cv[k] === null) delete cv[k]; if ((given.pitch === "target" || given.pitch === null) && given.semitones === undefined) delete cv.semitones; if (cv.semitones === 0) delete cv.semitones; const wrong = convertPitchErrors(cv); if (wrong.length) throw new CastError(`convert: ${wrong[0]} (--convert-engine seed-vc --convert-pitch source|contour)`); return cv; } /** * THE CHARACTER the flags make, pure: `before` (version 2's shape; null: a new one, `id`) with the fields given laid * over its presets -- `layer` "cast" (it may be the narrator: the caller clears the others') or "project" (it may be * anonymous, shown under `anon()`'s name when none is given; its voice may be removed). Refused in a sentence. */ export function characterFrom(before, id, f, p, { layer = "cast", anon = () => ANON_NAME_PATTERN.replace("{n}", "1") } = {}) { const c = before ? JSON.parse(JSON.stringify(upgradeCharacter(before))) : { id, name: "", handles: [] }; if (f.name !== undefined) c.name = f.name; if (f.handles) c.handles = f.handles; if (!Array.isArray(c.handles)) c.handles = []; for (const h of p.all("--add-handle").map(handleKey)) if (h && !c.handles.includes(h)) c.handles = [...c.handles, h]; for (const h of p.all("--remove-handle").map(handleKey)) c.handles = c.handles.filter((x) => x !== h); // The synthetic preset. const syn = { ...(c.synthetic ?? {}) }; if (f.voice) syn.voice = f.voice; if (f.speed !== undefined) syn.speed = f.speed; if (p.has("--no-speed") || syn.speed === 1) delete syn.speed; // Its Orpheus tuning: the flags laid over the one it has; a tuning equal to the defaults is none. if (f.tuning) { const t = tuningOver(syn.tuning, f.tuning); if (Object.keys(t).length) syn.tuning = t; else delete syn.tuning; } if (p.has("--no-tuning")) { if (f.tuning) throw new CastError("--no-tuning drops the whole tuning: not with --tuning, --temperature, --top-p, --repeat-penalty or --chunk-takes"); delete syn.tuning; } if (p.has("--no-voice")) { if (layer !== "project") throw new CastError("--no-voice is for a character of one video (umtool cast project

set …): a cast character has a stock voice"); delete syn.voice; delete syn.speed; delete syn.tuning; } if (syn.speed !== undefined && !syn.voice) throw new CastError("--speed is its voice's: give the character a voice too (--voice )"); if (syn.tuning !== undefined && !syn.voice) throw new CastError("a tuning is its voice's: give the character a voice too (--voice orpheus:)"); if (Object.keys(syn).length) c.synthetic = syn; else delete c.synthetic; // The recorded preset. const rec = { ...(c.recorded ?? {}) }; if (f.convert) rec.convert = convertOver(rec.convert, f.convert); if (p.has("--no-convert")) delete rec.convert; if (rec.convert && !Object.keys(rec.convert).length) delete rec.convert; if (f.enhance !== undefined) { if (f.enhance === null) delete rec.enhance; else rec.enhance = f.enhance; } if (f.trimOn !== undefined || f.trimPad !== undefined) { const t = { ...(rec.trim ?? {}) }; if (f.trimOn === null) delete t.on; else if (f.trimOn !== undefined) t.on = f.trimOn; if (f.trimPad === null) delete t.padMs; else if (f.trimPad !== undefined) t.padMs = f.trimPad; if (f.trimOn === null && f.trimPad === undefined) delete t.padMs; if (Object.keys(t).length) rec.trim = t; else delete rec.trim; } if (f.direction !== undefined) { if (f.direction) rec.direction = f.direction; else delete rec.direction; } if (Object.keys(rec).length) c.recorded = rec; else delete c.recorded; if (f.speakers) c.speakers = f.speakers; for (const k of ["avatar", "note"]) { if (f[k] !== undefined) c[k] = f[k]; if (c[k] === "") delete c[k]; } if (c.speakers && !c.speakers.length) delete c.speakers; if (layer === "cast") { if (p.has("--anonymous") || f.shown !== undefined) throw new CastError("an anonymous character is one video's, never the pool's: umtool cast project

add --anonymous"); if (p.has("--narrator")) c.narrator = true; if (p.has("--no-narrator")) delete c.narrator; } else { if (p.has("--narrator")) throw new CastError("the narrator is a cast character (umtool cast set --narrator)"); if (p.has("--anonymous")) c.anonymous = true; if (p.has("--no-anonymous")) { delete c.anonymous; delete c.shown; } if (f.shown !== undefined) { if (!c.anonymous) throw new CastError("--shown is an anonymous character's shown name (--anonymous)"); if (f.shown) c.shown = f.shown; else delete c.shown; } if (c.anonymous && !c.shown) c.shown = anon(); if (c.anonymous && !c.name) c.name = c.shown; } return upgradeCharacter(c); } /** * What a write says of the character's tuning: `json` `{ tuning: { tuning, name, effective, takesFrom }, notes? }` * (characterTuning.mjs tuningView: every value its reads are asked with -- the editor's takes when it names none) and * the `text` lines. */ async function tuningOut(c, f = {}) { const T = await import("./characterTuning.mjs"); const settingTakes = await T.orpheusTakesSetting(); const view = T.tuningView(characterTuning(c), settingTakes); const notes = tuningNotes(c, f, settingTakes); return { json: { tuning: view, ...(notes.length ? { notes } : {}) }, text: `${view.tuning ? `\n Orpheus tuning: ${T.tuningWords(view)}` : ""}${notes.map((n) => `\n note: ${n}`).join("")}`, }; } /** A character's recorded preset as words: "convert: seed-vc -> kokoro:am_michael, pitch contour +2 st; not cleaned; …". */ function recordedWords(c) { const rec = c.recorded; if (!rec) return ""; const cv = rec.convert; const bits = []; if (cv) bits.push(`convert: ${cv.engine ?? "default"} -> ${cv.voice ?? c.voice ?? "?"}${convertPitchLabel(cv) ? `, pitch ${convertPitchLabel(cv)}` : ""}`); if (rec.enhance === false) bits.push("not cleaned"); if (rec.trim?.on === false) bits.push("edges not trimmed"); else if (typeof rec.trim?.padMs === "number") bits.push(`trim pad ${rec.trim.padMs} ms`); if (rec.direction) bits.push(`direction: "${rec.direction}"`); return bits.join("; "); } /** A character as a line (a view: cast.mjs characterView). */ const line = (c0) => { const c = characterView(c0); const speed = c.synthetic?.speed; const voice = `${c.voice ?? "(no voice of its own)"}${typeof speed === "number" ? ` ×${speed}` : ""}`; const t = characterTuning(c); const tuned = Object.keys(t).length ? ` tuning ${ttsTuningNameOf(t)} (${Object.entries(t).map(([k, v]) => `${k} ${v}`).join(", ")})` : ""; return `${c.id.padEnd(16)} ${voice.padEnd(20)}${tuned} ${c.anonymous ? `${shownNameOf(c)} (anonymous; ${c.name})` : c.name}${c.handles?.length ? ` ${c.handles.map((h) => `@${h}`).join(" ")}` : ""}${recordedWords(c) ? ` ${recordedWords(c)}` : ""}${c.speakers?.length ? ` real voice: ${c.speakers.join(", ")}` : ""}${c.narrator ? " (the narrator)" : ""}${c.note ? ` -- ${c.note}` : ""}`; }; async function projectOf(ref, reportsRoot) { const r = await resolveProject(ref, reportsRoot); if (r.ambiguous) throw new CastError(`"${ref}" is the name of ${r.ambiguous.length} projects — pass its id`); if (!r.project) throw new CastError(`no project matches "${ref}"`); return r.project; } /** A project's characters view (castProject.mjs projectCharacters) with the files it read. */ export async function projectView(project, { reportsRoot = REPORTS_ROOT } = {}) { const manifest = await readManifest(project.dir); if (!manifest) throw new CastError(`${project.id} has no manifest`); const { readVoiceMap } = await import("./postSay.mjs"); const { readSpeakers } = await import("./speakerCheck.mjs"); const { projectCharacters } = await import("./castProject.mjs"); const castRead = await castForProject(project.dir, reportsRoot); const ownRead = await readProjectCharacters(project.dir); const map = await readVoiceMap(project.dir).catch(() => ({})); const speakers = await readSpeakers(project.dir).catch(() => []); const settingTakes = await (await import("./characterTuning.mjs")).orpheusTakesSetting(); const view = projectCharacters(manifest, { map, cast: castRead.cast, project: ownRead.doc, speakers, settingTakes }); return { manifest, map, castRead, ownRead, speakers, view }; } /** The handles `ref` names in a project: a character's (the project's own, else the cast's), or one @handle. */ function handlesOf(ref, castRead, view, ownRead = null) { const bare = String(ref).replace(/^@+/, ""); const at = String(ref).startsWith("@"); const own = projectCharactersOf(ownRead?.doc); const mine = at ? null : own.find((c) => c.id === bare.toLowerCase()) ?? null; if (mine) return { character: mine, layer: "project", handles: [...(mine.handles ?? [])] }; const c = findCharacter(castRead.cast, bare); if (c && !at) return { character: c, layer: "cast", handles: [...(c.handles ?? [])] }; const h = handleKey(ref); const row = view?.characters?.find((r) => r.handles.includes(h)) ?? null; const ownByHandle = own.find((x) => (x.handles ?? []).includes(h)) ?? null; return { character: ownByHandle ?? characterOf(castRead.cast, h), layer: ownByHandle ? "project" : characterOf(castRead.cast, h) ? "cast" : null, handles: [h], row }; } /** * `umtool cast project

add|set|rm|undo|pool|keep …`: THIS VIDEO's OWN characters (castStore.mjs * projectCharactersWrite: one writer, an undo point a write), and the two ways between them and the pool. */ async function projectCharactersCommand(project, op, rest, p, { reportsRoot, out, file }) { const what = (w) => `${w} (${project.id})`; if (op === "add" || op === "set") { const [id] = rest; if (!id) throw new CastError(`cast project ${op} takes the character's id`); const f = fieldsOf(p); const r = await projectCharactersWrite(project.dir, (chars) => { const at = chars.findIndex((c) => c.id === id); if (op === "add") { if (at >= 0) throw new CastError(`${id} is one of ${project.id}'s characters already (umtool cast project ${project.id} set ${id} …)`); if (!f.name && !p.has("--anonymous")) throw new CastError('cast project add takes --name "…" (or --anonymous: its shown name)'); const c = characterFrom(null, id, f, p, { layer: "project", anon: () => nextAnonName(chars) }); chars.push(c); return { changed: "added", character: c }; } if (at < 0) throw new CastError(`no ${id} among ${project.id}'s characters (umtool cast project ${project.id})`); const c = characterFrom(chars[at], id, f, p, { layer: "project", anon: () => nextAnonName(chars.filter((_, i) => i !== at)) }); chars[at] = c; return { changed: "updated", character: c }; }, { what: what(`${op} ${id}`) }); const tv = await tuningOut(r.character, f); out({ ok: true, scope: "project", changed: r.changed, character: characterView(r.character), ...tv.json, token: r.token }, `${r.changed} in ${project.id}: ${line(r.character)}${tv.text}`); return 0; } if (op === "rm" || op === "remove") { const [id] = rest; if (!id) throw new CastError("cast project rm takes the character's id"); const r = await projectCharactersWrite(project.dir, (chars) => { const at = chars.findIndex((c) => c.id === id); if (at < 0) throw new CastError(`no ${id} among ${project.id}'s characters`); const [gone] = chars.splice(at, 1); return { removed: gone }; }, { what: what(`rm ${id}`) }); out({ ok: true, scope: "project", removed: characterView(r.removed), token: r.token }, `removed ${id} from ${project.id}'s characters (umtool cast project ${project.id} undo puts it back)`); return 0; } if (op === "undo") { const r = await undoProjectCharacters(project.dir); out({ ok: true, scope: "project", undone: r.undone, at: r.at, left: r.left, token: r.token }, `undone: ${r.undone} (${r.left} undo point(s) left)`); return 0; } if (op === "pool") { // "Add to the pool": the project's character into the cast, then out of the project (the cast's answers here too). const [id] = rest; if (!id) throw new CastError("cast project pool takes the character's id"); const own = await readProjectCharacters(project.dir); if (own.error) throw new CastError(own.error); const c = (own.doc.characters ?? []).map(upgradeCharacter).find((x) => x.id === id); if (!c) throw new CastError(`no ${id} among ${project.id}'s characters`); if (c.anonymous) throw new CastError(`${id} is anonymous: it stays in this video (umtool cast project ${project.id} set ${id} --no-anonymous first, if that is meant)`); if (!c.synthetic?.voice) throw new CastError(`${id} has no stock voice: a cast character has one (umtool cast project ${project.id} set ${id} --voice )`); const castPath = (await castForProject(project.dir, reportsRoot)).file ?? file; const w = await castWrite(castPath, (chars) => { if (chars.some((x) => x.id === id)) throw new CastError(`${id} is in the cast already (umtool cast set ${id} …; or umtool cast project ${project.id} rm ${id})`); chars.push(c); return { character: c }; }, { what: `${id} into the pool (from ${project.id})` }); await projectCharactersWrite(project.dir, (chars) => { const at = chars.findIndex((x) => x.id === id); if (at >= 0) chars.splice(at, 1); return {}; }, { what: what(`${id} into the pool`) }); out({ ok: true, scope: "cast", changed: "pooled", character: characterView(w.character), token: w.token }, `${id} is in the pool now, for every project: ${line(w.character)}`); return 0; } if (op === "keep") { // "Keep in this video only": a cast character copied here, or an author with none given one here. const [who] = rest; if (!who) throw new CastError("cast project keep takes a cast character (its id) or an author (@handle)"); const v = await projectView(project, { reportsRoot }); if (v.ownRead.error) throw new CastError(v.ownRead.error); const t = handlesOf(who, v.castRead, v.view, v.ownRead); if (t.layer === "project") throw new CastError(`${t.character.id} is one of ${project.id}'s characters already (umtool cast project ${project.id} set ${t.character.id} …)`); const f = fieldsOf(p); const r = await projectCharactersWrite(project.dir, (chars) => { let base; if (t.character) { // The cast's, as it is now -- never its narrator mark (the narrator is the cast's). const { narrator: _n, ...copy } = upgradeCharacter((v.castRead.cast.characters ?? []).find((x) => x.id === t.character.id)); base = copy; } else { const h = t.handles[0]; if (!h || h === "*") throw new CastError(`${who}: no such character, and not a handle`); const now = t.row?.voice ?? null; const spec = now && now.engine ? voiceSpecOf({ engine: now.engine, voice: now.voice }) : null; base = { id: idOfHandle(h), name: (t.row?.name || h).slice(0, 80), handles: [h], ...(isQualifiedVoice(spec) ? { synthetic: { voice: spec } } : {}) }; } if (chars.some((x) => x.id === base.id)) throw new CastError(`${base.id} is one of ${project.id}'s characters already`); const c = characterFrom(base, base.id, f, p, { layer: "project", anon: () => nextAnonName(chars) }); chars.push(c); return { character: c }; }, { what: what(`keep ${who}`) }); out({ ok: true, scope: "project", changed: "kept", character: characterView(r.character), token: r.token }, `kept in ${project.id} only: ${line(r.character)}`); return 0; } throw new CastError(`cast project

: nothing (the view), add, set, rm, undo, pool or keep (not ${op})`); } /** * `umtool cast …` * @param {string[]} args * `model` (the tests' to stub): `cast assign --model`'s ask -- `(project, authors) => { answers, model }` (castAssignModel.mjs). * @param {{ reportsRoot?: string, log?: (s: string) => void, err?: (s: string) => void, ask?: any, lanes?: any, model?: any }} [o] */ export async function castCommand(args, { reportsRoot = REPORTS_ROOT, log = console.log, err = console.error, ask = undefined, lanes = undefined, model = undefined } = {}) { let p; try { p = parse(args); } catch (e) { err(`umtool cast: ${e instanceof Error ? e.message : e}`); return 2; } const json = p.has("--json"); const out = (o, text) => log(json ? JSON.stringify(o, null, 2) : text); const [sub = "ls", ...rest] = p.words; if (p.has("--help") || sub === "help") { log(CAST_USAGE); return 0; } const file = castFile(reportsRoot); try { if (sub === "ls") { const r = await readCast(reportsRoot); const chars = charactersOf(r.cast); out({ ok: true, file, token: r.token, characters: chars, ...(r.error ? { error: r.error } : {}) }, [ `the cast: ${chars.length} character(s) (${file})${r.error ? `\n NOT READ: ${r.error}` : ""}${chars.length ? "" : " -- umtool cast add --name \"…\" --voice kokoro:am_michael --handles "}`, ...chars.map((c) => ` ${line(c)}`), ].join("\n")); return 0; } if (sub === "add" || sub === "set") { const [id] = rest; if (!id) throw new CastError(`cast ${sub} takes the character's id`); const f = fieldsOf(p); const r = await castWrite(file, (chars) => { const at = chars.findIndex((c) => c.id === id); if (sub === "add") { if (at >= 0) throw new CastError(`${id} is in the cast already (umtool cast set ${id} …)`); if (!f.name || !f.voice) throw new CastError('cast add takes --name "…" and --voice '); const c = characterFrom(null, id, f, p, { layer: "cast" }); if (c.narrator) for (const x of chars) delete x.narrator; chars.push(c); return { changed: "added", character: c }; } if (at < 0) throw new CastError(`no ${id} in the cast (umtool cast ls)`); // The flags are laid over the character's presets: --convert-pitch alone keeps its engine and voice. const c = characterFrom(chars[at], id, f, p, { layer: "cast" }); if (p.has("--narrator")) for (const x of chars) delete x.narrator; if (p.has("--narrator")) c.narrator = true; chars[at] = c; return { changed: "updated", character: c }; }, { what: `${sub} ${id}` }); const tv = await tuningOut(r.character, f); out({ ok: true, changed: r.changed, character: characterView(r.character), ...tv.json, token: r.token }, `${r.changed} ${line(r.character)}${tv.text}`); return 0; } if (sub === "rm" || sub === "remove") { const [id] = rest; if (!id) throw new CastError("cast rm takes the character's id"); const r = await castWrite(file, (chars) => { const at = chars.findIndex((c) => c.id === id); if (at < 0) throw new CastError(`no ${id} in the cast`); const [gone] = chars.splice(at, 1); return { removed: gone }; }, { what: `rm ${id}` }); out({ ok: true, removed: characterView(r.removed), token: r.token }, `removed ${id} from the cast (umtool cast undo puts it back)`); return 0; } if (sub === "undo") { const r = await undoCast(file); out({ ok: true, undone: r.undone, at: r.at, left: r.left, token: r.token }, `undone: ${r.undone} (${r.left} undo point(s) left)`); return 0; } if (sub === "project") { const [ref, psub, ...prest] = rest; if (!ref) throw new CastError("cast project takes the project"); const project = await projectOf(ref, reportsRoot); if (psub && psub !== "ls") return await projectCharactersCommand(project, psub, prest, p, { reportsRoot, out, file }); const { view, map, castRead, ownRead } = await projectView(project, { reportsRoot }); if (json) { log(JSON.stringify({ ok: true, project: project.id, castFile: castRead.file, ...(castRead.error ? { castError: castRead.error } : {}), charactersFile: ownRead.file, charactersToken: ownRead.token, ...(ownRead.error ? { charactersError: ownRead.error } : {}), map, ...view, }, null, 2)); return 0; } const fromWords = (v) => `${v.from}${v.character && v.from !== "narrator" && v.from !== "default" ? `: ${v.character}` : ""}`; const speedWords = (v) => (typeof v.speed === "number" ? ` ×${v.speed}` : ""); log(`${project.id}: ${view.characters.length} character(s); the narrator ${view.narrator.spec} (${view.narrator.from})${castRead.error ? `\n the cast is NOT read: ${castRead.error}` : ""}${ownRead.error ? `\n this video's characters are NOT read: ${ownRead.error}` : ""}`); for (const c of view.characters) { log(` ${(c.character ? c.character.id : c.key).padEnd(18)} ${`${c.voice.spec}${speedWords(c.voice)}`.padEnd(20)} (${fromWords(c.voice)}) ${c.items} item(s), ${c.context} context${c.speaker ? ` real voice: ${c.speaker}` : ""}${c.character?.anonymous ? ` shown as "${c.character.shown}"` : ""}`); if (c.recorded && (c.character?.recorded || c.recorded.convert.voice)) log(` a recording of them: ${c.recorded.convert.voice ? `converted to ${c.recorded.convert.voice}${c.recorded.convert.engine ? ` (${c.recorded.convert.engine})` : ""}${convertPitchLabel(c.recorded.convert) ? `, pitch ${convertPitchLabel(c.recorded.convert)}` : ""}` : "not converted (no stock voice)"}; ${c.recorded.enhance ? "cleaned" : "not cleaned"}; ${c.recorded.trim.on ? `edges trimmed${c.recorded.trim.padMs !== null ? ` (pad ${c.recorded.trim.padMs} ms)` : ""}` : "edges not trimmed"}${c.recorded.direction ? `; direction: "${c.recorded.direction}"` : ""}`); if (c.stale?.length) log(` ${c.stale.length} read(s) made with other settings than its tuning now: ${[...new Set(c.stale.map((d) => d.id))].join(", ")} -- umtool cast stale ${project.id} ${c.character?.id ?? c.key}`); if (c.drift.length) log(` ${c.drift.length} read(s) in another voice: ${c.drift.map((d) => `${d.id} ${d.reads} (now ${d.want})`).join(", ")} -- umtool cast reread ${project.id} ${c.character?.id ?? `@${c.handles[0]}`}`); } for (const o of view.overrides) log(` note: @${o.handle} (${o.character}) reads in ${o.project} here -- the cast says ${o.cast} (an override on purpose)`); if (view.own.length) { log(` this video's own characters (${ownRead.file}):`); for (const c of view.own) log(` ${line(c)}`); } if (view.proposed?.length) { log(` PROPOSED, applied to nothing until accepted (umtool cast assign ${project.id} --accept | --change … | --reject ):`); for (const x of view.proposed) log(` ${proposalLine(x)}`); } for (const it of view.itemCharacters) log(` item ${it.id} is read as ${it.character}${it.found ? ` (${it.layer === "project" ? "this video's" : "the cast's"}): ${it.voice.spec}${speedWords(it.voice)} (${fromWords(it.voice)})` : ` -- NO SUCH CHARACTER: it reads as its author does, ${it.voice.spec} (${fromWords(it.voice)}); umtool posts character ${project.id} ${it.id} --clear`}`); return 0; } if (sub === "use") { const [ref, who, voice] = rest; if (!ref || !who || !voice) throw new CastError("cast use takes the project, the character (or @handle) and the voice: cast use quartering-diet thequartering kokoro:am_michael"); const project = await projectOf(ref, reportsRoot); const before = await projectView(project, { reportsRoot }); if (before.ownRead.error) throw new CastError(before.ownRead.error); const t = handlesOf(who, before.castRead, before.view, before.ownRead); if (!t.handles.length) throw new CastError(`${who} has no handles to give a voice (umtool cast set ${who} --add-handle )`); if (!voiceRefOf(voice)) throw new CastError(`${voice} is not a stock voice (tara, kokoro:am_michael): a file or a recording is never a voice`); const { updateVoiceMap } = await import("./postSay.mjs"); const removed = []; let scope = "project"; const cast = before.castRead.cast; // This video's own characters that answer for these handles (their presets come before the cast's). const ownFor = projectCharactersOf(before.ownRead.doc).filter((c) => (c.handles ?? []).some((h) => t.handles.includes(h))); if (p.has("--everywhere")) { const anon = ownFor.find((c) => c.anonymous); if (anon) throw new CastError(`${anon.id} is anonymous: it stays in this video, never the pool (umtool cast use ${project.id} ${anon.id} ${voice} sets its voice here)`); if (!isQualifiedVoice(voice)) throw new CastError(`--everywhere takes a voice with its engine (kokoro:am_michael), so every project reads it the same`); scope = "cast"; const castPath = before.castRead.file ?? file; // The cast's character: the one named, else the one a handle belongs to (a project's own character is not it). const target = t.layer === "cast" ? t.character : t.handles.map((h) => characterOf(cast, h)).find(Boolean) ?? null; await castWrite(castPath, (chars) => { const c = target ? chars.find((x) => x.id === target.id) : null; if (c) c.synthetic = { ...(c.synthetic ?? {}), voice }; else { const h = t.handles[0]; const id = idOfHandle(h); if (chars.some((x) => x.id === id)) throw new CastError(`${id} is in the cast already, without @${h}: umtool cast set ${id} --add-handle ${h}`); chars.push({ id, name: (t.row?.name || h).slice(0, 80), handles: [h], synthetic: { voice } }); } return {}; }, { what: `${target?.id ?? `@${t.handles[0]}`} reads in ${voice} (from ${project.id})` }); // Its voice everywhere -- here too: the project's own override of it goes. for (const h of t.handles) { if (h in before.map) { await updateVoiceMap(project.dir, { remove: h }); removed.push(h); } } // (A character of this video's own for the handle still answers first: said below, never removed unasked.) } else { // This video's own character for a handle takes it (its preset answers before the voice map); else the map. const own = projectCharactersOf(before.ownRead.doc); const mineOf = (h) => own.find((c) => (c.handles ?? []).includes(h) && c.voice) ?? null; const ids = [...new Set(t.handles.map((h) => mineOf(h)?.id).filter(Boolean))]; if (ids.length) { if (!isQualifiedVoice(voice)) throw new CastError(`${ids.join(", ")} is this video's own character: its voice names its engine (kokoro:am_michael)`); await projectCharactersWrite(project.dir, (chars) => { for (const c of chars) if (ids.includes(c.id)) c.synthetic = { ...(c.synthetic ?? {}), voice }; return {}; }, { what: `${ids.join(", ")} read${ids.length === 1 ? "s" : ""} in ${voice} (${project.id})` }); } for (const h of t.handles) if (!mineOf(h)) await updateVoiceMap(project.dir, { set: { handle: h, voice } }); } const after = await projectView(project, { reportsRoot }); const { rereadPlan } = await import("./castProject.mjs"); const plan = rereadPlan(project.id, after.manifest, after.view.characters.flatMap((c) => c.drift), t.handles); out( { ok: true, scope, handles: t.handles, voice, removed, ...(scope === "cast" && ownFor.some((c) => c.voice) ? { shadowedBy: ownFor.filter((c) => c.voice).map((c) => c.id) } : {}), reread: plan.items.map((x) => ({ id: x.id, take: x.take, thread: x.thread, reads: x.reads, argv: x.argv })), skipped: plan.skipped }, [ `${t.handles.map((h) => `@${h}`).join(", ")} read${t.handles.length === 1 ? "s" : ""} in ${voice} ${scope === "cast" ? "everywhere (the cast)" : `in ${project.id}`}${removed.length ? `; ${project.id}'s own override removed (${removed.join(", ")})` : ""}`, ...(scope === "cast" ? ownFor.filter((c) => c.voice).map((c) => ` here, this video's own character ${c.id} still answers first (${c.voice}): umtool cast project ${project.id} rm ${c.id} follows the cast`) : []), plan.items.length ? ` ${plan.items.length} item(s) read them in another voice -- umtool cast reread ${project.id} ${who}:` : " no picked read says them in another voice", ...plan.items.map((x) => ` ${x.id} ${x.reads.map((r) => `${r.role} ${r.reads} -> ${r.want}`).join(", ")}`), ].join("\n"), ); return 0; } if (sub === "reread") { const [ref, who] = rest; if (!ref || !who) throw new CastError("cast reread takes the project and the character (or @handle)"); const project = await projectOf(ref, reportsRoot); const v = await projectView(project, { reportsRoot }); const t = handlesOf(who, v.castRead, v.view, v.ownRead); const { rereadPlan } = await import("./castProject.mjs"); const plan = rereadPlan(project.id, v.manifest, v.view.characters.flatMap((c) => c.drift), t.handles); if (p.has("--dry-run") || !plan.items.length) { out({ ok: true, dryRun: p.has("--dry-run"), items: plan.items, skipped: plan.skipped }, [ plan.items.length ? `${plan.items.length} item(s) to re-read:` : `no picked read says ${who} in another voice`, ...plan.items.map((x) => ` umtool ${x.argv.join(" ")}`), ...plan.skipped.map((s) => ` (not re-read: ${s.id} -- ${s.why})`), ].join("\n")); return 0; } const { postsCommand } = await import("./postsCli.mjs"); const done = []; for (const x of plan.items) { const said = []; const code = await postsCommand([...x.argv.slice(1), "--json"], { root: reportsRoot, out: (s) => said.push(s), err: (s) => said.push(s) }); done.push({ id: x.id, code }); if (!json) log(`${x.id}: ${code === 0 ? "re-read, picked (awaiting approval)" : `FAILED -- ${said.join(" ").slice(0, 300)}`}`); } const failed = done.filter((d) => d.code !== 0).length; if (json) log(JSON.stringify({ ok: failed === 0, done, skipped: plan.skipped }, null, 2)); return failed ? 1 : 0; } if (sub === "audition") return await auditionCommand(rest, p, { reportsRoot, log, err, ask, lanes }); if (sub === "try") return await tryCommand(rest, p, { reportsRoot, log, err, ask, lanes }); if (sub === "stale") return await staleCommand(rest, p, { reportsRoot, out }); if (sub === "assign") return await assignCommand(rest, p, { reportsRoot, out, json, model, log }); throw new CastError(`cast: ls, add, set, rm, undo, project, audition, try, stale, use, reread or assign (not ${sub})`); } catch (e) { if (e instanceof CastError || e?.name === "AuditionError" || e?.name === "SayError") { if (json) log(JSON.stringify({ ok: false, error: e.message }, null, 2)); err(`umtool cast: ${e.message}`); return 1; } err(`umtool cast: ${e instanceof Error ? e.stack ?? e.message : String(e)}`); return 1; } } /** The layer a character an audition found is of: this video's own ("project"), the cast's, or null (an author). */ function layerOf(character, castRead, ownRead) { if (projectCharactersOf(ownRead?.doc).some((c) => c.id === character.id)) return "project"; return charactersOf(castRead?.cast).some((c) => c.id === character.id) ? "cast" : null; } /** * `umtool cast try

…`: ONE LINE read in the character's own voice with a tuning and a reading * (characterTuning.mjs: scratch, kept in a short list), or the list (--list), or the list emptied (--clear). */ async function tryCommand(rest, p, { reportsRoot, log, err, ask, lanes }) { const [ref, who] = rest; if (!ref || !who) throw new CastError("cast try takes the project and the character (its id, or @handle)"); const A = await import("./castAudition.mjs"); const T = await import("./characterTuning.mjs"); const json = p.has("--json"); const ndjson = p.str("--progress") === "ndjson"; const say = (s) => (ndjson ? err(s) : !json && log(s)); const emit = (ev, f = {}) => { if (ev === "note") say(f.message); else if (ndjson) log(JSON.stringify({ ev: "cast-try", ...f })); }; const project = await projectOf(ref, reportsRoot); const manifest = await readManifest(project.dir); if (!manifest) throw new CastError(`${project.id} has no manifest`); const castRead = await castForProject(project.dir, reportsRoot); const ownRead = await readProjectCharacters(project.dir); if (p.has("--no-tuning")) throw new CastError("cast try reads with a tuning: --tuning default for the defaults (--no-tuning is cast set's)"); if (p.str("--reading") !== null && p.has("--another")) throw new CastError("--reading N or --another, not both"); // --scope: the layer the character is looked up in -- the cast's, or this video's own (the same id may be both); // none: this video's own first, then the cast's, then an author. const scope = p.str("--scope"); if (scope !== null && scope !== "cast" && scope !== "project") throw new CastError(`--scope is cast or project (got ${scope || "nothing"})`); let character; if (scope === "cast") { character = findCharacter(castRead.cast, String(who).replace(/^@+/, "")); if (!character) throw new CastError(`${who} is not in the cast (umtool cast ls)`); } else if (scope === "project") { const h = handleKey(who); const c = projectCharactersOf(ownRead.doc).find((x) => x.id === String(who).toLowerCase()) ?? projectCharactersOf(ownRead.doc).find((x) => (x.handles ?? []).includes(h)); if (!c) throw new CastError(`${who} is not one of ${project.id}'s own characters (umtool cast project ${project.id})`); character = { ...c, name: shownNameOf(c) }; } else character = await A.auditionCharacter(castRead.cast, who, { project, manifest }); const layer = scope ?? layerOf(character, castRead, ownRead); const spec = characterVoice(character); const settingTakes = await T.orpheusTakesSetting(); const kept = characterTuning(character); const who0 = { id: character.id, name: character.name, layer, voice: spec ?? null, tuning: T.tuningView(kept, settingTakes) }; if (p.has("--clear")) { const r = await T.clearTries(project.dir, character.id, layer); if (json) log(JSON.stringify({ ok: true, project: project.id, character: who0, ...r }, null, 2)); else log(`${character.name}: ${r.cleared} tr${r.cleared === 1 ? "y" : "ies"} cleared in ${project.id}`); return 0; } const said = await A.auditionLine(project, manifest, character, { text: p.str("--text"), item: p.str("--item"), line: p.str("--line") }); if (p.has("--list")) { const rows = (await T.readTries(project.dir)).filter((r) => T.rowOf(r, character.id, layer)); if (json) log(JSON.stringify({ ok: true, project: project.id, character: who0, line: said, settingTakes, tries: rows }, null, 2)); else { log(`${character.name} (${spec ?? "no voice of its own"}${kept && Object.keys(kept).length ? `; ${T.tuningWords(who0.tuning)}` : ""}): ${rows.length} tr${rows.length === 1 ? "y" : "ies"} in ${project.id}; the line: "${said.text}" (${said.from})`); for (const r of rows) log(` reading ${r.reading} ${T.tuningWords(T.tuningView(r.tuning, settingTakes))} ${r.rel} "${String(r.text).slice(0, 60)}"`); } return 0; } if (!spec || !voiceRefOf(spec)?.engine) throw new CastError(`${character.name} has no stock voice of its own to try (umtool cast set ${character.id} --voice orpheus:)`); const cand = A.candidatesOf([spec])[0]; const f = tuningFlagsOf(p); const readingRaw = p.str("--reading"); let tuning = f ? tuningOver(kept, f) : kept; if (cand.engine !== "orpheus") { if (f || readingRaw !== null || p.has("--another")) throw new CastError(`a tuning and a reading are Orpheus's: ${spec} reads the same every time (umtool cast audition compares voices)`); tuning = {}; } let reading = 0; if (readingRaw !== null) { const n = readingRaw.trim() === "" ? Number.NaN : Number(readingRaw); const e = ttsReadingError(n, "--reading"); if (e) throw new CastError(e.replace(/got NaN\)$/, `got ${readingRaw || "nothing"})`)); reading = n; } else if (p.has("--another")) reading = T.nextReading(await T.readTries(project.dir), character.id, { voice: spec, text: said.text, tuning }, layer); const dir = A.auditionDirOf(project); const plan = await A.auditionPlan(dir, [{ ...cand, tuning, reading }], said.text); emit("try", { phase: "start", voice: spec, reading, tuning }); const r = await A.synthesizeAuditions(dir, plan, said.text, { ask, emit, hold: !p.has("--no-hold"), lanes }); const c = plan[0]; const row = { key: c.key, character: character.id, layer, voice: spec, text: said.text, from: said.from, tuning, ...(c.meta?.tuning ? { made: c.meta.tuning } : {}), reading, rel: c.rel, seconds: c.meta?.seconds ?? null, lufs: c.meta?.lufs ?? null, at: new Date().toISOString(), ...(c.meta?.jobId ? { jobId: c.meta.jobId } : {}), }; const k = await T.addTry(project.dir, row); const view = T.tuningView(tuning, settingTakes); if (json) log(JSON.stringify({ ok: true, project: project.id, character: who0, try: row, tuning: view, fresh: r.fresh, jobs: r.jobs, swept: k.removed }, null, 2)); else if (ndjson) log(JSON.stringify({ ev: "cast-try", phase: "done", key: row.key, reading, fresh: r.fresh })); else log(`${character.name}: ${spec}, ${cand.engine === "orpheus" ? `${T.tuningWords(view)}, reading ${reading}` : "its voice"}${r.fresh ? "" : " (kept already)"} -- ${row.rel}`); return 0; } /** `umtool cast stale

[]`: the reads made with other settings than a character's tuning now. */ async function staleCommand(rest, p, { reportsRoot, out }) { const [ref, who] = rest; if (!ref) throw new CastError("cast stale takes the project (and a character, or @handle)"); const project = await projectOf(ref, reportsRoot); const v = await projectView(project, { reportsRoot }); let rows = v.view.tuningStale ?? []; let id = null; if (who) { const t = handlesOf(who, v.castRead, v.view, v.ownRead); if (!t.character) throw new CastError(`${who} is no character in ${project.id} (umtool cast project ${project.id})`); id = t.character.id; rows = rows.filter((r) => r.character === id); } const items = [...new Set(rows.map((r) => r.id))]; const said = (t) => `temperature ${t.temperature}, top_p ${t.top_p}, repeat penalty ${t.repeat_penalty}, takes ${t.takes}`; out({ ok: true, project: project.id, character: id, count: rows.length, items, reads: rows }, [ rows.length ? `${rows.length} read${rows.length === 1 ? "" : "s"} ${id ? `by ${id} ` : ""}made with other settings than ${id ? "its" : "their character's"} tuning now (listed, never re-made):` : `no read ${id ? `by ${id} ` : ""}was made with other settings than ${id ? "its" : "its character's"} tuning now`, ...rows.map((r) => ` ${r.id} ${r.role} (${r.character}): made with ${said(r.made)}${r.reading ? `, reading ${r.reading}` : ""} -- now ${said(r.want)}`), ].join("\n")); return 0; } /** `umtool cast audition …` */ async function auditionCommand(rest, p, { reportsRoot, log, err, ask, lanes }) { const A = await import("./castAudition.mjs"); const [who] = rest; if (!who) throw new CastError("cast audition takes the character (its id, or @handle)"); const json = p.has("--json"); const ndjson = p.str("--progress") === "ndjson"; const say = (s) => (ndjson ? err(s) : !json && log(s)); const emit = (ev, f = {}) => { if (ev === "note") say(f.message); else if (ndjson) log(JSON.stringify({ ev: "cast-audition", ...f })); }; const project = p.str("--project") ? await projectOf(p.str("--project"), reportsRoot) : null; const castRead = project ? await castForProject(project.dir, reportsRoot) : await readCast(reportsRoot); const manifest = project ? await readManifest(project.dir) : null; const character = await A.auditionCharacter(castRead.cast, who, { project, manifest }); const { text, from } = await A.auditionLine(project, manifest, character, { text: p.has("--stock") ? A.STOCK_ASK : p.str("--text"), item: p.str("--item"), line: p.str("--line") }); const candidates = A.candidatesOf(p.all("--voices")); const dir = A.auditionDirOf(project, reportsRoot); const relBase = project ? A.AUDITION_DIR : path.relative(reportsRoot, dir); const plan = await A.auditionPlan(dir, candidates, text, { relBase }); let fresh = 0; let jobs = []; if (!p.has("--score-only")) { const r = await A.synthesizeAuditions(dir, plan, text, { ask, emit, hold: !p.has("--no-hold"), lanes }); fresh = r.fresh; jobs = r.jobs; } let score = null; if (project && !p.has("--no-score")) score = await A.scoreAuditions(project, character, plan, { emit }); const prior = project ? await A.readAuditionScores(project.dir) : { rows: {} }; // Not scored this time: the scores kept for these candidates against the same real voice. const speaker = score?.speaker ?? (project ? (await A.referenceFor(project, character))?.name ?? null : null); const scoreOf = (k) => score?.rows?.[k]?.score ?? (speaker ? prior.rows[`${k}|${speaker}`]?.score : null) ?? null; const rows = plan.map((c) => ({ spec: c.spec, engine: c.engine, voice: c.voice, weight: c.weight, key: c.key, rel: c.rel, cached: c.cached, fresh: !!c.fresh, seconds: c.meta?.seconds ?? null, lufs: c.meta?.lufs ?? null, score: scoreOf(c.key), ...(c.meta?.disclosure ? { disclosure: c.meta.disclosure } : {}), })); if (json) { log(JSON.stringify({ ok: true, character: { id: character.id, name: character.name, handles: character.handles ?? [], voice: character.voice ?? null }, project: project?.id ?? null, text, from, candidates: rows, fresh, jobs, speaker, reference: score?.reference ?? (speaker ? A.referenceRelOf(speaker) : null), ...(score?.why ? { why: score.why } : {}) }, null, 2)); return 0; } if (ndjson) { log(JSON.stringify({ ev: "cast-audition", phase: "done", fresh, candidates: rows.length })); return 0; } log(`${character.name}: "${text}" (${from})`); for (const r of rows) log(` ${r.spec.padEnd(22)} ${r.weight === "heavy" ? "heavy" : "fast "} ${r.seconds ? `${r.seconds.toFixed(1)} s` : "-"} ${r.score !== null ? `closeness ${r.score.toFixed(3)}${speaker ? ` to ${speaker}` : ""}` : ""} ${r.rel}${r.fresh ? "" : " (kept)"}`); const unscored = Object.values(score?.rows ?? {}).find((r) => r?.score === null && r?.why); if (score?.why || unscored) log(` not scored: ${score?.why ?? unscored.why}${score?.why ? "" : " (the reference's windows: umtool prep, or fetch them)"}`); if (score?.reference) log(` the real voice (a reference, never a target): ${score.reference}`); return 0; } /** A proposal as a line: its id, voice, name, handles, who proposed it and why. */ const proposalLine = (x) => `${x.id.padEnd(16)} ${`${x.synthetic?.voice ?? "?"}${typeof x.synthetic?.speed === "number" ? ` ×${x.synthetic.speed}` : ""}`.padEnd(20)} ${x.anonymous ? `${shownNameOf(x)} (anonymous; ${x.name})` : x.name} ${(x.handles ?? []).map((h) => `@${h}`).join(" ")} [${x.by}${x.model ? `: ${x.model}` : ""}]${x.recorded?.direction ? ` direction: "${x.recorded.direction}"` : ""}${x.why ? ` -- ${x.why}` : ""}`; const ASSIGN_STATE = { anonymous: "an anonymous character's (never proposed for, never sent to a model)", item: "every item names its own character", project: "this video's character", map: "this video's voice map", cast: "the cast's character", proposed: "PROPOSED already", propose: "PROPOSED now" }; /** * `umtool cast assign

…` (umtool-report-to-video/cast-assign.mjs): the rule's plan and its PROPOSED characters * (kept in the project's characters file, applied to nothing), and the three a person does with one -- accept, * change, reject. */ async function assignCommand(rest, p, { reportsRoot, out, json, model = undefined, log = console.log }) { const [ref] = rest; if (!ref) throw new CastError("cast assign takes the project"); const project = await projectOf(ref, reportsRoot); const asks = [["--accept", p.str("--accept")], ["--accept-all", p.has("--accept-all")], ["--reject", p.str("--reject")], ["--reject-all", p.has("--reject-all")], ["--change", p.str("--change")]].filter(([, v]) => v !== null && v !== false); if (asks.length > 1) throw new CastError(`cast assign: one of ${asks.map(([k]) => k).join(", ")} at a time`); const what = (w) => `assign: ${w} (${project.id})`; const [ask] = asks[0] ?? []; if (ask && p.has("--model")) throw new CastError(`cast assign: --model makes proposals; ${ask} acts on one`); if (ask === "--accept" || ask === "--accept-all") { const id = p.str("--accept"); const r = await projectCharactersWrite(project.dir, (chars, extra) => { const pick = ask === "--accept-all" ? [...extra.proposed] : extra.proposed.filter((x) => x.id === id); if (!pick.length) throw new CastError(ask === "--accept-all" ? `nothing is proposed in ${project.id} (umtool cast assign ${project.id})` : `no proposal ${id} in ${project.id} (umtool cast assign ${project.id} --dry-run lists them)`); const made = []; for (const x of pick) { if (chars.some((c) => c.id === x.id)) throw new CastError(`${x.id} is one of ${project.id}'s characters already: --reject ${x.id}, or --change it first`); for (const h of x.handles ?? []) { const o = chars.find((c) => (c.handles ?? []).includes(h)); if (o) throw new CastError(`@${h} is ${o.id}'s already (this video's): --reject ${x.id}`); } const c = proposalCharacter(x); chars.push(c); made.push(c); } extra.proposed = extra.proposed.filter((x) => !pick.includes(x)); return { accepted: made }; }, { what: what(ask === "--accept-all" ? "accept all" : `accept ${id}`) }); // That author's items name it -- those that name none (a person's choice stays); no take is made or changed. const manifest = await readManifest(project.dir); const patches = []; for (const c of r.accepted) { for (const e of manifest?.timeline ?? []) { if (e?.type === "post" && (c.handles ?? []).includes(handleKey(e.handle)) && !String(e.narration?.character ?? "").trim()) patches.push({ id: e.id, patch: { character: c.id } }); } } let items = []; let itemsError = null; if (patches.length) { const { withEditNotes } = await import("./edit-guard.mjs"); const { manifestToken, updatePostNarrations } = await import("./manifest.mjs"); try { await withEditNotes(project, async () => updatePostNarrations(project.dir, patches, { token: await manifestToken(project.dir), op: "post-character" })); items = patches.map((x) => ({ id: x.id, character: x.patch.character })); } catch (e) { itemsError = `the character${r.accepted.length === 1 ? " is" : "s are"} made, but the items were not named: ${e instanceof Error ? e.message : e} (umtool posts character ${project.id} )`; } } out( { ok: !itemsError, scope: "project", accepted: r.accepted.map(characterView), items, ...(itemsError ? { error: itemsError } : {}), token: r.token }, [ ...r.accepted.map((c) => `accepted in ${project.id}: ${line(c)}`), items.length ? ` ${items.length} item(s) name it now: ${items.map((x) => x.id).join(", ")} (no take made or changed; a picked read in another voice is drift -- umtool cast project ${project.id})` : " no item to name (each names its own already)", ...(itemsError ? [` ${itemsError}`] : []), ].join("\n"), ); return itemsError ? 1 : 0; } if (ask === "--reject" || ask === "--reject-all") { const id = p.str("--reject"); const r = await projectCharactersWrite(project.dir, (_chars, extra) => { const gone = ask === "--reject-all" ? [...extra.proposed] : extra.proposed.filter((x) => x.id === id); if (!gone.length) throw new CastError(ask === "--reject-all" ? `nothing is proposed in ${project.id}` : `no proposal ${id} in ${project.id}`); extra.proposed = extra.proposed.filter((x) => !gone.includes(x)); return { rejected: gone }; }, { what: what(ask === "--reject-all" ? "reject all" : `reject ${id}`) }); out({ ok: true, scope: "project", rejected: r.rejected.map((x) => x.id), token: r.token }, `rejected in ${project.id}: ${r.rejected.map((x) => x.id).join(", ")} (umtool cast project ${project.id} undo puts ${r.rejected.length === 1 ? "it" : "them"} back)`); return 0; } if (ask === "--change") { const id = p.str("--change"); const f = fieldsOf(p); const extraFlags = ["--convert-engine", "--convert-voice", "--convert-pitch", "--convert-semitones", "--enhance", "--trim", "--trim-pad", "--handles", "--speakers", "--avatar", "--note"].filter((k) => p.has(k)); if (extraFlags.length) throw new CastError(`cast assign --change sets a proposal's voice, speed, name, direction or anonymity (${extraFlags.join(", ")}: accept it first, then umtool cast project ${project.id} set ${id} …)`); if (f.voice !== undefined && !isStockVoice(f.voice)) throw new CastError(`--voice: a proposal's voice is one of the stock voices (kokoro:am_michael, orpheus:zac), not ${f.voice}`); const r = await projectCharactersWrite(project.dir, (_chars, extra) => { const at = extra.proposed.findIndex((x) => x.id === id); if (at < 0) throw new CastError(`no proposal ${id} in ${project.id}`); const { by, why, model: m, ...base } = extra.proposed[at]; const c = characterFrom(base, id, f, p, { layer: "project", anon: () => nextAnonName([..._chars, ...extra.proposed.filter((_, i) => i !== at)]) }); if (c.recorded && Object.keys(c.recorded).some((k) => k !== "direction")) throw new CastError("a proposal carries a direction line at most"); // A PERSON's row now: never re-sent to a model (cast assign --model) and never overwritten by one. const next = { ...c, by: "person", why: `changed by hand${by && by !== "person" ? ` (proposed by ${by === "model" && m ? `the model, ${m}` : by})` : ""}`, ...(m ? { model: m } : {}) }; extra.proposed[at] = next; return { proposal: next }; }, { what: what(`change ${id}`) }); out({ ok: true, scope: "project", proposal: r.proposal, token: r.token }, `changed: ${proposalLine(r.proposal)}`); return 0; } // THE PLAN (cast-assign.mjs assignPlan): the rule's answer for every author; the new proposals kept (--dry-run: not). const { assignPlan } = await import("umtool-report-to-video/cast-assign"); const v = await projectView(project, { reportsRoot }); if (v.ownRead.error) throw new CastError(v.ownRead.error); const used = [v.view.narrator?.spec, ...v.view.characters.map((c) => c.voice?.spec)].filter(Boolean); const plan = assignPlan(v.manifest, { project: v.ownRead.doc, cast: v.castRead.cast, map: v.map, used }); let proposals = plan.proposals; let replaced = []; let modelRun = null; if (p.has("--model")) { // OPTIONAL, on request only: the generation task cast-assign's answers laid over the rule's rows (castAssignModel.mjs). const { modelProposals } = await import("./castAssignModel.mjs"); // A dry run asks nothing (the editor's job would write its answers file): it says what would be asked. const dryAsk = async (_p, handles) => { throw Object.assign(new Error(`a dry run: the model would be asked about ${handles.length} author(s) (${handles.map((h) => `@${h}`).join(", ")})`), { dry: true }); }; modelRun = await modelProposals(project, v.manifest, plan, { ask: p.has("--dry-run") ? dryAsk : model, emit: (s) => !json && log(` ${s}`) }); if (p.has("--dry-run") && modelRun.report.error) modelRun = { ...modelRun, report: { asked: modelRun.report.asked, kept: 0, model: null, summary: modelRun.report.error } }; proposals = modelRun.proposals; replaced = modelRun.replaced; } const dryRun = p.has("--dry-run"); let token = v.ownRead.token; if (!dryRun && (proposals.length || plan.moot.length || replaced.length)) { const w = await projectCharactersWrite(project.dir, (chars, extra) => { extra.proposed = extra.proposed.filter((x) => !plan.moot.includes(x.id)); for (const x of replaced) { const at = extra.proposed.findIndex((y) => y.id === x.id); if (at >= 0) extra.proposed[at] = x; } for (const x of proposals) { if (chars.some((c) => c.id === x.id) || extra.proposed.some((y) => y.id === x.id)) throw new CastError(`${x.id} is taken since the plan was made: run cast assign again`); extra.proposed.push(x); } return {}; }, { token: v.ownRead.token, what: what(`${proposals.length} proposed${replaced.length ? `, ${replaced.length} given the model's answer` : ""}${plan.moot.length ? `, ${plan.moot.length} moot dropped` : ""}`) }); token = w.token; } const authors = plan.authors.map((a) => { const fresh = proposals.find((x) => x.id === a.character && a.state === "propose"); return { handle: a.handle, name: a.name, items: a.items, state: a.state, ...(a.character ? { character: a.character } : {}), ...(fresh?.synthetic?.voice ?? a.voice ? { voice: fresh?.synthetic?.voice ?? a.voice } : {}), ...(fresh ? { proposal: fresh } : a.proposal ? { proposal: a.proposal } : {}) }; }); const held = authors.filter((a) => a.state === "proposed").map((a) => replaced.find((x) => x.id === a.proposal.id) ?? a.proposal); out( { ok: true, project: project.id, dryRun, authors, proposed: proposals, held, moot: plan.moot, ...(modelRun ? { model: modelRun.report } : {}), token }, [ `${project.id}: ${authors.length} author(s); ${proposals.length} proposed now${held.length ? `, ${held.length} proposed before` : ""}${plan.moot.length ? `; ${plan.moot.length} proposal(s) moot (${plan.moot.join(", ")})${dryRun ? "" : ", dropped"}` : ""}${dryRun ? " -- a dry run, nothing written" : " -- applied to nothing until accepted"}`, ...authors.map((a) => ` @${a.handle.padEnd(18)} ${String(a.voice ?? "").padEnd(20)} ${ASSIGN_STATE[a.state]}${a.character ? `: ${a.character}` : ""} (${a.items.length} item(s))`), ...(modelRun ? [` the model: ${modelRun.report.summary}`, ...(modelRun.report.refused ?? []).slice(0, 12).map((x) => ` (${x})`)] : []), ...[...proposals, ...held].map((x) => ` ${proposalLine(x)}`), ...([...proposals, ...held].length ? [` umtool cast assign ${project.id} --accept | --accept-all | --change --voice … | --reject `] : []), ].join("\n"), ); // The rule's rows are kept either way; a model that was not heard is a failure of what was asked. return modelRun?.report.error ? 1 : 0; }