Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit 5a36e5f87389c122636f1d0b95450856c1a30435
parent 846a8c3a11210578156e027aa38fb956d6cdbc63
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Wed, 11 Nov 2026 18:48:56 -0500

umtool: a project's own characters (narration/characters.json, the cast's writer: a token, an undo point, atomic) and a post item's own (posts character); cast set takes the preset fields, cast project add|set|rm|undo|pool|keep; a thread read's parts are asked at their character's speed and --speed reaches them; a recording made a read takes its character's clean, trim and convert

Co-Authored-By: Claude <noreply@anthropic.com>

Diffstat:
Mumtool/lib/report/cast.test.mjs | 5+++--
Mumtool/lib/report/castCli.mjs | 427++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------------
Mumtool/lib/report/castProject.mjs | 76++++++++++++++++++++++++++++++++++++++++++++++++++++++----------------------
Mumtool/lib/report/castStore.mjs | 126++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------------------
Aumtool/lib/report/characterLayers.mjs | 40++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/characters.test.mjs | 392+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/manifest.mjs | 2+-
Mumtool/lib/report/postNarrationCli.mjs | 128++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------------
Mumtool/lib/report/postRecord.mjs | 9++++++---
Mumtool/lib/report/postThreadRead.mjs | 82+++++++++++++++++++++++++++++++++++++++++++++++--------------------------------
Mumtool/lib/report/postsCli.mjs | 12++++++++++++
Mumtool/lib/report/readVoice.mjs | 24++++++++++++++----------
12 files changed, 1128 insertions(+), 195 deletions(-)

diff --git a/umtool/lib/report/cast.test.mjs b/umtool/lib/report/cast.test.mjs @@ -108,7 +108,8 @@ test("the store: one writer, a stale token refused, undo points, a broken file n test("umtool cast ls/add/set/rm/undo: the characters across projects", async () => { let r = await cast(["add", "hostman", "--name", "Host Man", "--voice", "orpheus:zac", "--handles", "@HostMan", "--speakers", "Host", "--json"]); assert.equal(r.code, 0, r.text()); - assert.deepEqual(r.json().character, { id: "hostman", name: "Host Man", handles: ["hostman"], voice: "orpheus:zac", speakers: ["Host"] }); + // A character as the CLI says it: version 2's presets, and the `voice` (and `convert`) they answer to. + assert.deepEqual(r.json().character, { id: "hostman", name: "Host Man", handles: ["hostman"], synthetic: { voice: "orpheus:zac" }, speakers: ["Host"], voice: "orpheus:zac" }); r = await cast(["add", "hostman", "--name", "Again", "--voice", "orpheus:zac"]); assert.equal(r.code, 1); assert.match(r.text(), /in the cast already/); @@ -226,7 +227,7 @@ test("cast project: each character's voice now and where it comes from, its drif // --everywhere for an author the cast does not know: a new character from the handle. r = await cast(["use", "voices", "@guest", "kokoro:af_heart", "--everywhere", "--json"]); assert.equal(r.code, 0, r.text()); - assert.deepEqual((await readCast(ROOT)).cast.characters.find((c) => c.id === "guest"), { id: "guest", name: "The Guest", handles: ["guest"], voice: "kokoro:af_heart" }); + assert.deepEqual((await readCast(ROOT)).cast.characters.find((c) => c.id === "guest"), { id: "guest", name: "The Guest", handles: ["guest"], synthetic: { voice: "kokoro:af_heart" }, voice: "kokoro:af_heart" }); // reread --dry-run lists; reread makes them (the stub editor is not here: the plan alone). r = await cast(["reread", "voices", "hostman", "--dry-run", "--json"]); assert.deepEqual(r.json().items.map((x) => x.argv.join(" ")), ["posts narrate voices p-1 --take"]); diff --git a/umtool/lib/report/castCli.mjs b/umtool/lib/report/castCli.mjs @@ -1,13 +1,17 @@ // `umtool cast` (umtool-report-to-video/cast.mjs; umtool/docs/knobs.md, "The cast"): the CHARACTERS across projects -// and their voices, a project's characters, an AUDITION of candidate voices, and the voice a character reads in -- -// for a project (its voice map) or everywhere (the cast) -- with the re-reads that asks for. +// 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 <id> --name "…" --voice <engine:voice> [--handles a,b] [--speakers Name,…] [--convert-engine e] -// [--convert-voice <engine:voice>] [--convert-pitch target|source|contour] [--convert-semitones n] [--avatar …] [--note "…"] [--narrator] [--json] -// umtool cast set <id> [the same flags] [--add-handle h] [--remove-handle h] [--no-convert] [--no-narrator] [--json] +// umtool cast add <id> --name "…" --voice <engine:voice> [the preset flags] [--handles a,b] [--speakers Name,…] [--avatar …] [--note "…"] [--narrator] [--json] +// umtool cast set <id> [the same flags] [--add-handle h] [--remove-handle h] [--no-convert] [--no-speed] [--no-narrator] [--json] // umtool cast rm <id> [--json] · umtool cast undo [--json] // umtool cast project <p> [--json] +// umtool cast project <p> add <id> [--name "…"] [--voice <engine:voice>] [the preset flags] [--handles a,b] [--anonymous [--shown "…"]] [--json] +// umtool cast project <p> set <id> [the same flags] [--no-voice] [--no-anonymous] … · rm <id> · undo +// umtool cast project <p> pool <id> its character into the cast ("Add to the pool") +// umtool cast project <p> keep <character|@handle> [--anonymous [--shown "…"]] a character of this video only // umtool cast audition <character|@handle> --voices a,b,… [--project <p>] [--text "…" | --item <id> | --line <n>] // [--no-score | --score-only] [--no-hold] [--json] [--progress ndjson] // umtool cast use <p> <character|@handle> <voice> [--everywhere] [--json] @@ -15,49 +19,73 @@ // // Plain ESM: the CLI runs under bare node. import path from "node:path"; -import { CAST_CONVERT_ENGINES, CAST_CONVERT_PITCH, CAST_SEMITONES_MAX, characterOf, convertPitchErrors, convertPitchLabel, charactersOf, findCharacter, isQualifiedVoice } from "umtool-report-to-video/cast"; -import { handleKey, voiceRefOf } from "umtool-report-to-video/post-say"; +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, isQualifiedVoice, nextAnonName, projectCharactersOf, shownNameOf, upgradeCharacter, +} from "umtool-report-to-video/cast"; +import { handleKey, voiceRefOf, voiceSpecOf } from "umtool-report-to-video/post-say"; import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs"; import { readManifest } from "../projects/report.mjs"; -import { CastError, castFile, castForProject, castWrite, readCast, undoCast } from "./castStore.mjs"; +import { CastError, castFile, castForProject, castWrite, projectCharactersWrite, readCast, readProjectCharacters, undoCast, undoProjectCharacters } from "./castStore.mjs"; + +const PRESET_FLAGS = "[--speed <s>] [--convert-engine openvoice|seed-vc] [--convert-voice <engine:voice>] [--convert-pitch target|source|contour] [--convert-semitones <n>] [--enhance on|off|default] [--trim on|off|default] [--trim-pad <ms>|default] [--direction \"…\"]"; export const CAST_USAGE = [ "usage: umtool cast [ls] [--json]", - " umtool cast add <id> --name \"…\" --voice <engine:voice> [--handles a,b] [--speakers Name,…] [--convert-engine openvoice|seed-vc]", - " [--convert-voice <engine:voice>] [--convert-pitch target|source|contour] [--convert-semitones <n>]", + " umtool cast add <id> --name \"…\" --voice <engine:voice> [--handles a,b] [--speakers Name,…]", + ` ${PRESET_FLAGS}`, " [--avatar …] [--note \"…\"] [--narrator] [--json]", - " umtool cast set <id> [those flags] [--add-handle h] [--remove-handle h] [--no-convert] [--no-narrator] [--json]", + " umtool cast set <id> [those flags] [--add-handle h] [--remove-handle h] [--no-convert] [--no-speed] [--no-narrator] [--json]", " umtool cast rm <id> [--json]", " umtool cast undo [--json]", " umtool cast project <project> [--json]", + " umtool cast project <project> add <id> [--name \"…\"] [--voice <engine:voice>] [--handles a,b] [--anonymous [--shown \"…\"]] [the preset flags] [--json]", + " umtool cast project <project> set <id> [those flags] [--add-handle h] [--remove-handle h] [--no-voice] [--no-convert] [--no-speed] [--no-anonymous] [--json]", + " umtool cast project <project> rm <id> | undo | pool <id> | keep <character|@handle> [--anonymous [--shown \"…\"]] [--json]", " umtool cast audition <character|@handle> --voices kokoro:am_michael,kokoro:am_onyx,orpheus:zac [--project <p>]", " [--text \"…\" | --item <id> | --line <n> | --stock] [--no-score | --score-only] [--no-hold] [--json] [--progress ndjson]", " umtool cast use <project> <character|@handle> <engine:voice> [--everywhere] [--json]", " umtool cast reread <project> <character|@handle> [--dry-run] [--json]", "", " THE CAST (<reports>/.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), the STOCK voice they read in (engine:voice),", - " optionally the voice a recording of them 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), 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 project's narration/voices.json overrides it", - " (umtool posts voices); every read asks the same function: the read's own voice, the project's map, the cast, the", - " narrator's, the default.", - " project: every character the project's reads use, the voice each reads in now and where it comes from, its", - " picked reads in another voice (drift: re-read them), the cast voices the project overrides, its reference.", + " 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).", + " 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 <ms>), 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 <p> add|set|rm|undo: THIS VIDEO's OWN characters (<p>/narration/characters.json, one writer, an undo", + " point per write) -- the same shape, for people who must not enter the pool. --anonymous: shown on screen and", + ` said under a shown name, never its own (--shown; default the next of "${ANON_NAME_PATTERN.replace("{n}", "1")}", "${ANON_NAME_PATTERN.replace("{n}", "2")}" …). --voice is optional`, + " here: a character with none leaves the voice to the layers under it. pool <id>: it moves into the cast (an", + " anonymous one is refused). keep <character|@handle>: 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 <p>/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 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). Exit 0 done · 1 refused or failed · 2 usage.", + " 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).", + " Exit 0 done · 1 refused or failed · 2 usage.", ].join("\n"); -const VALUED = new Set(["--name", "--voice", "--handles", "--speakers", "--convert-engine", "--convert-voice", "--convert-pitch", "--convert-semitones", "--avatar", "--note", "--add-handle", "--remove-handle", "--voices", "--project", "--text", "--item", "--line", "--progress"]); +const VALUED = new Set(["--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"]); const splitList = (v) => String(v ?? "").split(",").map((x) => x.trim()).filter(Boolean); function parse(args) { @@ -75,6 +103,20 @@ function parse(args) { 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 = {}; @@ -84,20 +126,38 @@ function fieldsOf(p) { 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)) { - const ce = p.str("--convert-engine"); - if (ce !== null && !CAST_CONVERT_ENGINES.includes(ce)) throw new CastError(`--convert-engine is ${CAST_CONVERT_ENGINES.join(" or ")}`); - const cp = p.str("--convert-pitch"); - if (cp !== null && !CAST_CONVERT_PITCH.includes(cp)) throw new CastError(`--convert-pitch is one of ${CAST_CONVERT_PITCH.join(", ")}`); + // `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 } : {}), ...(p.str("--convert-voice") ? { voice: p.str("--convert-voice") } : {}), ...(cp ? { pitch: cp } : {}), ...(cs !== null ? { semitones: cs } : {}) }; + 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(); return f; } @@ -107,14 +167,116 @@ function fieldsOf(p) { */ function convertOver(before, given) { const cv = { ...(before ?? {}), ...given }; - if (given.pitch === "target" && given.semitones === undefined) delete cv.semitones; + 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; } -const line = (c) => `${c.id.padEnd(16)} ${c.voice.padEnd(20)} ${c.name}${c.handles?.length ? ` ${c.handles.map((h) => `@${h}`).join(" ")}` : ""}${c.convert ? ` convert: ${c.convert.engine ?? "default"} -> ${c.convert.voice ?? c.voice}${convertPitchLabel(c.convert) ? `, pitch ${convertPitchLabel(c.convert)}` : ""}` : ""}${c.speakers?.length ? ` real voice: ${c.speakers.join(", ")}` : ""}${c.narrator ? " (the narrator)" : ""}${c.note ? ` -- ${c.note}` : ""}`; +/** + * 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; + if (p.has("--no-voice")) { + if (layer !== "project") throw new CastError("--no-voice is for a character of one video (umtool cast project <p> set …): a cast character has a stock voice"); + delete syn.voice; + delete syn.speed; + } + if (syn.speed !== undefined && !syn.voice) throw new CastError("--speed is its voice's: give the character a voice too (--voice <engine:voice>)"); + 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 <p> add <id> --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 <id> --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); +} + +/** 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}` : ""}`; + return `${c.id.padEnd(16)} ${voice.padEnd(20)} ${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}` : ""}`; +}; + +/** An id for a handle's new character ("kirsche.verstahl" -> "kirsche-verstahl"). */ +const idOfHandle = (h) => h.replace(/[^a-z0-9_-]/g, "-").replace(/^[^a-z0-9]+/, "").slice(0, 48) || "character"; async function projectOf(ref, reportsRoot) { const r = await resolveProject(ref, reportsRoot); @@ -131,19 +293,127 @@ export async function projectView(project, { reportsRoot = REPORTS_ROOT } = {}) 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 view = projectCharacters(manifest, { map, cast: castRead.cast, speakers }); - return { manifest, map, castRead, speakers, view }; + const view = projectCharacters(manifest, { map, cast: castRead.cast, project: ownRead.doc, speakers }); + return { manifest, map, castRead, ownRead, speakers, view }; } -/** The handles `ref` names in a project: a character's (the cast's), or one @handle. */ -function handlesOf(ref, castRead, view) { - const c = findCharacter(castRead.cast, String(ref).replace(/^@+/, "")); - if (c && !String(ref).startsWith("@")) return { character: c, handles: [...(c.handles ?? [])] }; +/** 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; - return { character: characterOf(castRead.cast, h), handles: [h], row }; + 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 <p> 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, sub, rest, p, { reportsRoot, out, file }) { + const what = (w) => `${w} (${project.id})`; + if (sub === "add" || sub === "set") { + const [id] = rest; + if (!id) throw new CastError(`cast project ${sub} 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 (sub === "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(`${sub} ${id}`) }); + out({ ok: true, scope: "project", changed: r.changed, character: characterView(r.character), token: r.token }, `${r.changed} in ${project.id}: ${line(r.character)}`); + return 0; + } + if (sub === "rm" || sub === "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 (sub === "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 (sub === "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 <engine: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 (sub === "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 <p>: nothing (the view), add, set, rm, undo, pool or keep (not ${sub})`); } /** @@ -186,27 +456,20 @@ export async function castCommand(args, { reportsRoot = REPORTS_ROOT, log = cons 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 <engine:voice>'); - const c = { id, name: f.name, handles: f.handles ?? [], voice: f.voice, ...(f.convert ? { convert: convertOver(null, f.convert) } : {}), ...(f.speakers ? { speakers: f.speakers } : {}), ...(f.avatar ? { avatar: f.avatar } : {}), ...(f.note ? { note: f.note } : {}), ...(p.has("--narrator") ? { narrator: true } : {}) }; + 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 convert flags are laid over the entry: --convert-pitch alone keeps its engine and voice. - const c = { ...chars[at], ...f, ...(f.convert ? { convert: convertOver(chars[at].convert, f.convert) } : {}) }; - 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); - if (p.has("--no-convert")) delete c.convert; - if (p.has("--narrator")) { - for (const x of chars) delete x.narrator; - c.narrator = true; - } - if (p.has("--no-narrator")) delete c.narrator; - for (const k of ["note", "avatar"]) if (c[k] === "") delete c[k]; + // 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}` }); - out({ ok: true, changed: r.changed, character: r.character, token: r.token }, `${r.changed} ${line(r.character)}`); + out({ ok: true, changed: r.changed, character: characterView(r.character), token: r.token }, `${r.changed} ${line(r.character)}`); return 0; } if (sub === "rm" || sub === "remove") { @@ -218,7 +481,7 @@ export async function castCommand(args, { reportsRoot = REPORTS_ROOT, log = cons const [gone] = chars.splice(at, 1); return { removed: gone }; }, { what: `rm ${id}` }); - out({ ok: true, removed: r.removed, token: r.token }, `removed ${id} from the cast (umtool cast undo puts it back)`); + 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") { @@ -227,20 +490,32 @@ export async function castCommand(args, { reportsRoot = REPORTS_ROOT, log = cons return 0; } if (sub === "project") { - const [ref] = rest; + const [ref, psub, ...prest] = rest; if (!ref) throw new CastError("cast project takes the project"); const project = await projectOf(ref, reportsRoot); - const { view, map, castRead } = await projectView(project, { 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 } : {}), map, ...view }, null, 2)); + 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; } - 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}` : ""}`); + 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.padEnd(20)} (${c.voice.from}) ${c.items} item(s), ${c.context} context${c.speaker ? ` real voice: ${c.speaker}` : ""}`); + 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.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)}`); + } + 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") { @@ -248,27 +523,31 @@ export async function castCommand(args, { reportsRoot = REPORTS_ROOT, log = cons 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 }); - const t = handlesOf(who, before.castRead, before.view); + 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 <h>)`); 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; if (p.has("--everywhere")) { 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 = t.character ? chars.find((x) => x.id === t.character.id) : null; - if (c) c.voice = voice; + 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 = h.replace(/[^a-z0-9_-]/g, "-").replace(/^[^a-z0-9]+/, "").slice(0, 48) || "character"; + 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], voice }); + chars.push({ id, name: (t.row?.name || h).slice(0, 80), handles: [h], synthetic: { voice } }); } return {}; - }, { what: `${t.character?.id ?? `@${t.handles[0]}`} reads in ${voice} (from ${project.id})` }); + }, { 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) { @@ -276,8 +555,20 @@ export async function castCommand(args, { reportsRoot = REPORTS_ROOT, log = cons removed.push(h); } } + // (A character of this video's own for the handle still answers first: said, never removed unasked.) } else { - for (const h of t.handles) await updateVoiceMap(project.dir, { set: { handle: h, voice } }); + // 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"); @@ -285,7 +576,7 @@ export async function castCommand(args, { reportsRoot = REPORTS_ROOT, log = cons out( { ok: true, scope, handles: t.handles, voice, removed, 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} (its voice map)`}${removed.length ? `; ${project.id}'s own override removed (${removed.join(", ")})` : ""}`, + `${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(", ")})` : ""}`, 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"), @@ -297,7 +588,7 @@ export async function castCommand(args, { reportsRoot = REPORTS_ROOT, log = cons 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); + 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) { diff --git a/umtool/lib/report/castProject.mjs b/umtool/lib/report/castProject.mjs @@ -1,39 +1,52 @@ // A PROJECT's CAST (the Voices panel; `umtool cast project <p>`): every character the project's reads use -- the // post items' authors, the authors of the posts they answer, quote and link, and the narrator -- with the voice each -// reads in NOW and where it comes from (the project's map, the cast, the narrator's, the default), how many items it +// reads in NOW and where it comes from (the item's own character, the project's own characters and its map, the +// cast, the narrator's, the default: post-say.mjs voiceSourceOf, the chain every read asks), how many items it // reads, what its picked reads are actually in (stale ones: DRIFT), its real-voice reference (speakers.json) and its // lines to audition; and THE RE-READS a voice change asks for, as the commands that make them. // // Plain ESM. import { postNarrationKnobs } from "umtool-report-to-video/post-narration"; import { handleKey, resolvePieceVoice, voiceRefOf, voiceSpecOf } from "umtool-report-to-video/post-say"; -import { castDrift, castVoiceMap, characterOf, charactersOf, convertTargetOf, narratorOf, speakerFor, takeReads, voiceDrift, ENGINE_WEIGHT } from "umtool-report-to-video/cast"; +import { + castDrift, castPresetMap, characterForRead, characterOf, charactersOf, convertTargetOf, itemCharacterOf, itemPresetOf, narratorOf, projectCharactersOf, projectPresetMap, recordedPresetOf, + shownNameOf, speakerFor, takeReads, voiceDrift, ENGINE_WEIGHT, +} from "umtool-report-to-video/cast"; import { characterLines } from "./castAudition.mjs"; const str = (v) => (typeof v === "string" ? v : ""); /** * The voice a piece of a picked read would be said in NOW, as the read that made it would ask (its own --voice-for - * and --voice kept: an override made on purpose): `(e, role, handle, take, read) => { engine, voice, from }`. A read - * converted from a recording is compared with its character's convert target (the cast's), else not at all. + * and --voice kept: an override made on purpose): `(e, role, handle, take, read) => { engine, voice, from, speed?, + * character? }`. A read converted from a recording is compared with its character's convert target (the chain's: + * cast.mjs characterForRead), else not at all. `project` is the project's own characters (characters.json's document). */ -export function resolverFor({ map = {}, cast = null, render = {} }) { - const castMap = castVoiceMap(cast); +export function resolverFor({ map = {}, cast = null, project = null, render = {} }) { + const castMap = castPresetMap(cast); + const layer = projectPresetMap(project, map); return (e, role, handle, take, read = null) => { if (read?.kind === "converted") { - const c = characterOf(cast, handle); - const ref = c ? voiceRefOf(convertTargetOf(c).voice) : null; - return ref ? { ...ref, from: "cast" } : null; + const who = characterForRead(e, { project, cast }); + const ref = who?.character && who.layer !== "narrator" ? voiceRefOf(convertTargetOf(who.character).voice) : null; + return ref ? { ...ref, from: who.layer } : null; } const k = postNarrationKnobs(e, render); const tr = take?.read?.kind === "thread" ? take.read : null; return resolvePieceVoice({ handle, role }, { - map, cast: castMap, overrides: tr?.voiceFor ?? {}, voice: tr?.voice ?? null, self: e.handle ?? null, + map: layer, cast: castMap, item: itemPresetOf(e, { project, cast }), overrides: tr?.voiceFor ?? {}, voice: tr?.voice ?? null, self: e.handle ?? null, narrator: e.narration?.voice ?? k.voice, engine: e.narration?.engine ?? k.engine, }); }; } +/** A character as a row carries it: its id, name, presets (and the `voice` / `convert` they answer to), what it is. */ +const rowCharacter = (c, layer) => ({ + id: c.id, name: c.name, layer, ...(c.voice ? { voice: c.voice } : {}), ...(c.convert ? { convert: c.convert } : {}), + ...(c.synthetic ? { synthetic: c.synthetic } : {}), ...(c.recorded ? { recorded: c.recorded } : {}), + ...(c.note ? { note: c.note } : {}), ...(c.narrator ? { narrator: true } : {}), ...(c.anonymous ? { anonymous: true, shown: shownNameOf(c) } : {}), +}); + /** The post items' authors and context authors: `Map<handle, { handle, name, items: id[], context: id[] }>`. */ export function authorsOf(manifest) { const out = new Map(); @@ -57,21 +70,28 @@ export function authorsOf(manifest) { } /** - * THE PROJECT's CHARACTERS, pure: `{ narrator, characters: [...], drift, overrides }` -- each character - * `{ key, character, name, handles, items, context, itemIds, contextIds, voice: {engine, voice, spec, from}, - * contextVoice?, reads: [{ id, role, spec, kind }], drift: [...], speaker, lines, weight }`, the most-read first. + * THE PROJECT's CHARACTERS, pure: `{ narrator, characters: [...], drift, overrides, own, itemCharacters }` -- each + * character `{ key, character, name, handles, items, context, itemIds, contextIds, voice: {engine, voice, spec, from, + * speed?, character?}, contextVoice?, recorded?, reads: [{ id, role, spec, kind }], drift: [...], speaker, lines, + * weight }`, the most-read first. A handle's character is the project's own (characters.json) before the cast's; + * `character.layer` says which. `own` is every character the project holds, in the cut or not; `itemCharacters` the + * post items that name their own (`narration.character`), each with the character it names (`found: false`: no such + * one -- the read falls to the layers under it). */ -export function projectCharacters(manifest, { map = {}, cast = null, speakers = [] } = {}) { +export function projectCharacters(manifest, { map = {}, cast = null, project = null, speakers = [] } = {}) { const render = manifest?.render ?? {}; const k = postNarrationKnobs({}, render); - const resolve = resolverFor({ map, cast, render }); - const castMap = castVoiceMap(cast); + const resolve = resolverFor({ map, cast, project, render }); + const castMap = castPresetMap(cast); + const layer = projectPresetMap(project, map); + const pchars = projectCharactersOf(project); const drift = voiceDrift(manifest, resolve); const groups = new Map(); for (const a of authorsOf(manifest).values()) { - const c = characterOf(cast, a.handle); + const own = pchars.find((c) => (c.handles ?? []).includes(a.handle)) ?? null; + const c = own ?? characterOf(cast, a.handle); const key = c ? c.id : `@${a.handle}`; - const g = groups.get(key) ?? { key, character: c, name: c?.name ?? a.name ?? a.handle, handles: [], itemIds: [], contextIds: [] }; + const g = groups.get(key) ?? { key, character: c, layer: c ? (own ? "project" : "cast") : null, name: c ? shownNameOf(c) : a.name ?? a.handle, handles: [], itemIds: [], contextIds: [] }; g.handles.push(a.handle); for (const id of a.items) if (!g.itemIds.includes(id)) g.itemIds.push(id); for (const id of a.context) if (!g.contextIds.includes(id)) g.contextIds.push(id); @@ -82,19 +102,23 @@ export function projectCharacters(manifest, { map = {}, cast = null, speakers = for (const e of tl) if (e?.type === "post") for (const r of takeReads(e)) reads.push({ id: e.id, ...r }); const rows = [...groups.values()].map((g) => { const h = g.handles[0]; - const first = tl.find((e) => e?.type === "post" && g.itemIds.includes(e.id)) ?? null; - const ctxItem = tl.find((e) => e?.type === "post" && g.contextIds.includes(e.id)) ?? null; + // The handle's own voice: an item that names its own character answers for itself (itemCharacters), not for the handle. + const plain = (e) => !e?.narration?.character; + const first = tl.find((e) => e?.type === "post" && g.itemIds.includes(e.id) && plain(e)) ?? null; + const ctxItem = tl.find((e) => e?.type === "post" && g.contextIds.includes(e.id) && plain(e)) ?? null; const own = first ? resolve(first, "post", h, null) : null; - const ctx = ctxItem ? resolve(ctxItem, "parent:0", h, null) : resolvePieceVoice({ handle: h, role: "parent:0" }, { map, cast: castMap, narrator: k.voice, engine: k.engine }); + const ctx = ctxItem ? resolve(ctxItem, "parent:0", h, null) : resolvePieceVoice({ handle: h, role: "parent:0" }, { map: layer, cast: castMap, narrator: k.voice, engine: k.engine }); const now = own ?? ctx; const mine = new Set(g.handles); const sp = speakerFor(g.character ?? { name: g.name, handles: g.handles, id: h }, speakers); return { key: g.key, name: g.name, handles: g.handles, - character: g.character ? { id: g.character.id, name: g.character.name, voice: g.character.voice, ...(g.character.convert ? { convert: g.character.convert } : {}), ...(g.character.note ? { note: g.character.note } : {}), ...(g.character.narrator ? { narrator: true } : {}) } : null, + character: g.character ? rowCharacter(g.character, g.layer) : null, items: g.itemIds.length, context: g.contextIds.length, itemIds: g.itemIds, contextIds: g.contextIds, voice: { ...now, spec: voiceSpecOf(now) }, ...(own && ctx && voiceSpecOf(own) !== voiceSpecOf(ctx) ? { contextVoice: { ...ctx, spec: voiceSpecOf(ctx) } } : {}), + // What a recording of them is made into (the recorded preset, its defaults filled) -- a character's only. + ...(g.character ? { recorded: recordedPresetOf(g.character) } : {}), weight: ENGINE_WEIGHT[now.engine] ?? "fast", reads: reads.filter((r) => r.handle && mine.has(handleKey(r.handle))).map((r) => ({ id: r.id, role: r.role, spec: voiceSpecOf({ engine: r.engine, voice: r.voice }), kind: r.kind })), drift: drift.filter((d) => mine.has(d.handle)), @@ -105,11 +129,18 @@ export function projectCharacters(manifest, { map = {}, cast = null, speakers = rows.sort((a, b) => b.items + b.context - (a.items + a.context) || a.name.localeCompare(b.name)); const nar = narratorOf(cast); const recorded = reads.filter((r) => r.kind === "recorded" || r.kind === "converted"); + const itemCharacters = tl.filter((e) => e?.type === "post" && e.narration?.character).map((e) => { + const it = itemCharacterOf(e, { project, cast }); + const v = resolve(e, "post", e.handle ?? null, null); + return { id: e.id, handle: handleKey(e.handle) || null, character: it.id, found: !!it.character, layer: it.layer, ...(it.character ? { name: shownNameOf(it.character) } : {}), voice: { ...v, spec: voiceSpecOf(v) } }; + }); return { narrator: { engine: k.engine, voice: k.voice, spec: `${k.engine}:${k.voice}`, from: render?.postNarration?.voice ? "project" : "default", character: nar ? { id: nar.id, name: nar.name, voice: nar.voice } : null, recorded: recorded.map((r) => ({ id: r.id, kind: r.kind, voice: r.voice })) }, characters: rows, ...castDrift(manifest, { cast, map, resolve }), cast: charactersOf(cast).length, + own: pchars.map((c) => rowCharacter(c, "project")).map((c, i) => ({ ...c, handles: pchars[i].handles ?? [] })), + itemCharacters, }; } @@ -125,6 +156,7 @@ export function threadArgvOf(read, { handles = [], author = null } = {}) { if (read.seen === true) a.push("--read-seen"); for (const [h, v] of Object.entries(read.voiceFor ?? {})) if (!drop.has(handleKey(h))) a.push("--voice-for", `${h}=${v}`); if (read.voice && !(author && drop.has(handleKey(author)))) a.push("--voice", String(read.voice)); + if (typeof read.speed === "number") a.push("--speed", String(read.speed)); return a; } diff --git a/umtool/lib/report/castStore.mjs b/umtool/lib/report/castStore.mjs @@ -2,6 +2,12 @@ // // <REPORTS_ROOT>/.umtool/cast.json the characters, for every project // <REPORTS_ROOT>/.umtool/cast.undo.json the undo points: the file as it was before each write (the last 50) +// <project>/narration/characters.json THE PROJECT's OWN characters (cast.mjs PROJECT_CHARACTERS_FILE): the +// <project>/narration/characters.undo.json same writer, the same rules, its own undo points +// +// A version 1 cast (`voice` / `convert` at a character's top) is READ as version 2 (cast.mjs upgradeCast) and +// written as version 2 by the first write after -- whose undo point is the version 1 text, so `undo` puts the old +// file back as it was, and it reads the same. // // Every write is serialised in-process, re-reads the file inside the lock, checks the caller's token (the sha1 of // the file it read: a write over a newer file is refused), refuses a cast cast.mjs refuses (whole), keeps an undo @@ -15,7 +21,10 @@ import { createHash } from "node:crypto"; import { mkdir, readFile, rename, stat, writeFile } from "node:fs/promises"; import path from "node:path"; -import { CAST_FORMAT, CAST_VERSION, emptyCast, validateCast } from "umtool-report-to-video/cast"; +import { + CAST_FORMAT, CAST_VERSION, PROJECT_CHARACTERS_FILE, PROJECT_CHARACTERS_FORMAT, PROJECT_CHARACTERS_VERSION, characterView, emptyCast, emptyProjectCharacters, upgradeCharacter, + validateCast, validateProjectCharacters, +} from "umtool-report-to-video/cast"; import { REPORTS_ROOT } from "../paths.mjs"; import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; @@ -52,27 +61,53 @@ export async function castFileFor(dir, reportsRoot = REPORTS_ROOT) { const sha = (text) => createHash("sha1").update(text).digest("hex").slice(0, 16); -/** - * The cast as its file holds it: `{ cast, token, file, exists, error? }` -- `token` the sha1 of the text (null with - * no file). A file that does not parse or is refused reads as the empty cast with `error`. - */ -export async function readCastFile(file) { +/** The two files this store writes: what each is called, how it is refused, read and written. */ +const CAST_KIND = Object.freeze({ + what: "the cast", validate: validateCast, empty: emptyCast, + doc: (characters) => ({ format: CAST_FORMAT, version: CAST_VERSION, characters }), +}); +const PROJECT_KIND = Object.freeze({ + what: "the project's characters", validate: validateProjectCharacters, empty: emptyProjectCharacters, + doc: (characters) => ({ format: PROJECT_CHARACTERS_FORMAT, version: PROJECT_CHARACTERS_VERSION, characters }), +}); + +async function readKind(kind, file) { let text; try { text = await readFile(file, "utf8"); } catch (e) { - if (e?.code === "ENOENT") return { cast: emptyCast(), token: null, file, exists: false, text: null }; - return { cast: emptyCast(), token: null, file, exists: false, text: null, error: `${file} cannot be read: ${e?.message ?? e}` }; + if (e?.code === "ENOENT") return { cast: kind.empty(), token: null, file, exists: false, text: null }; + return { cast: kind.empty(), token: null, file, exists: false, text: null, error: `${file} cannot be read: ${e?.message ?? e}` }; } let doc; try { doc = JSON.parse(text); } catch (e) { - return { cast: emptyCast(), token: sha(text), file, exists: true, text, error: `${file} is not JSON: ${e instanceof Error ? e.message : e}` }; + return { cast: kind.empty(), token: sha(text), file, exists: true, text, error: `${file} is not JSON: ${e instanceof Error ? e.message : e}` }; } - const errors = validateCast(doc, path.basename(file)); - if (errors.length) return { cast: emptyCast(), token: sha(text), file, exists: true, text, error: `${path.basename(file)} is refused: ${errors.join("; ")}` }; - return { cast: doc, token: sha(text), file, exists: true, text }; + const errors = kind.validate(doc, path.basename(file)); + if (errors.length) return { cast: kind.empty(), token: sha(text), file, exists: true, text, error: `${path.basename(file)} is refused: ${errors.join("; ")}` }; + // As a reader is handed it: each character version 2's shape, with the `voice` / `convert` its presets answer to. + return { cast: { ...kind.doc(doc.characters.map(characterView)) }, token: sha(text), file, exists: true, text }; +} + +/** + * The cast as its file holds it: `{ cast, token, file, exists, error? }` -- `token` the sha1 of the text (null with + * no file), `cast` as VERSION 2 whatever the file's, each character a VIEW (cast.mjs characterView). A file that does not parse or is refused + * reads as the empty cast with `error`. + */ +export const readCastFile = (file) => readKind(CAST_KIND, file); + +/** A project's own characters file. */ +export const projectCharactersFile = (dir) => path.join(/* turbopackIgnore: true */ dir, ...PROJECT_CHARACTERS_FILE.split("/")); + +/** + * A project's OWN characters as its file holds them: `{ doc, token, file, exists, error? }` (readCastFile's shape, + * the document under `doc`). No file: none. A file that does not parse or is refused reads as none, with `error`. + */ +export async function readProjectCharacters(dir) { + const { cast, ...rest } = await readKind(PROJECT_KIND, projectCharactersFile(dir)); + return { doc: cast, ...rest }; } /** The cast under a reports root. */ @@ -110,23 +145,17 @@ function withCastLock(fn) { return run; } -/** - * ONE WRITE of the cast: `mutate(characters)` (a copy; it throws CastError to refuse) returns what the caller - * wants back. Refused when the file changed since the caller's `token` (409), when it does not parse, or when the - * result is refused (cast.mjs validateCast). Returns `{ ...result, cast, token, undo: <points left> }`. - * @param {string} file - * @param {(chars: any[]) => any} mutate - * @param {{ token?: string | null, what?: string }} [o] - */ -export function castWrite(file, mutate, { token = null, what = "an edit" } = {}) { +function writeKind(kind, file, mutate, { token = null, what = "an edit" } = {}) { return withCastLock(async () => { - const read = await readCastFile(file); + const read = await readKind(kind, file); if (read.error && read.exists) throw new CastError(`${read.error} -- fix the file first; nothing written`, 409); - if (token !== null && token !== undefined && token !== read.token) throw new CastError(`the cast changed since it was read (${token} -> ${read.token}): read it again`, 409); - const chars = JSON.parse(JSON.stringify(read.cast.characters ?? [])); + if (token !== null && token !== undefined && token !== read.token) throw new CastError(`${kind.what} changed since it was read (${token} -> ${read.token}): read it again`, 409); + // The mutation is handed version 2's characters (no `voice` / `convert` beside the presets: one it sets is the + // newer word, upgradeCharacter), and what is written is version 2's shape. + const chars = JSON.parse(JSON.stringify((read.cast.characters ?? []).map(upgradeCharacter))); const result = mutate(chars) ?? {}; - const doc = { format: CAST_FORMAT, version: CAST_VERSION, characters: chars }; - const errors = validateCast(doc); + const doc = kind.doc(chars.map(upgradeCharacter)); + const errors = kind.validate(doc, path.basename(file)); if (errors.length) throw new CastError(`refused: ${errors.join("; ")}`); const points = [...(await readCastUndo(file)), { at: new Date().toISOString(), what, text: read.exists ? read.text : null }].slice(-CAST_UNDO_KEEP); await writeAtomic(undoFileOf(file), `${JSON.stringify({ file: path.basename(file), points }, null, 1)}\n`); @@ -136,18 +165,49 @@ export function castWrite(file, mutate, { token = null, what = "an edit" } = {}) }); } -/** Put the cast back as it was before its last write (that write's undo point, taken off the list). */ -export function undoCast(file, { token = null } = {}) { +function undoKind(kind, file, { token = null } = {}) { return withCastLock(async () => { - const read = await readCastFile(file); - if (token !== null && token !== undefined && token !== read.token) throw new CastError(`the cast changed since it was read: read it again`, 409); + const read = await readKind(kind, file); + if (token !== null && token !== undefined && token !== read.token) throw new CastError(`${kind.what} changed since it was read: read it again`, 409); const points = await readCastUndo(file); const last = points.pop(); - if (!last) throw new CastError("nothing to undo on the cast"); - if (last.text === null) await writeAtomic(file, `${JSON.stringify(emptyCast(), null, 1)}\n`); + if (!last) throw new CastError(`nothing to undo on ${kind.what}`); + if (last.text === null) await writeAtomic(file, `${JSON.stringify(kind.empty(), null, 1)}\n`); else await writeAtomic(file, last.text); await writeAtomic(undoFileOf(file), `${JSON.stringify({ file: path.basename(file), points }, null, 1)}\n`); - const now = await readCastFile(file); + const now = await readKind(kind, file); return { undone: last.what, at: last.at, left: points.length, cast: now.cast, token: now.token }; }); } + +/** + * ONE WRITE of the cast: `mutate(characters)` (a copy, as version 2 holds them; it throws CastError to refuse) + * returns what the caller wants back. Refused when the file changed since the caller's `token` (409), when it does + * not parse, or when the result is refused (cast.mjs validateCast). Written as VERSION 2. Returns `{ ...result, + * cast, token, undo: <points left> }`. + * @param {string} file + * @param {(chars: any[]) => any} mutate + * @param {{ token?: string | null, what?: string }} [o] + */ +export const castWrite = (file, mutate, o) => writeKind(CAST_KIND, file, mutate, o); + +/** Put the cast back as it was before its last write (that write's undo point, taken off the list). */ +export const undoCast = (file, o) => undoKind(CAST_KIND, file, o); + +/** + * ONE WRITE of a project's own characters (`<dir>/narration/characters.json`): castWrite's rules -- a token, an undo + * point, atomic, refused whole (cast.mjs validateProjectCharacters). Returns `{ ...result, doc, token, undo }`. + * @param {string} dir the project's folder + * @param {(chars: any[]) => any} mutate + * @param {{ token?: string | null, what?: string }} [o] + */ +export async function projectCharactersWrite(dir, mutate, o) { + const { cast, ...rest } = await writeKind(PROJECT_KIND, projectCharactersFile(dir), mutate, o); + return { ...rest, doc: cast }; +} + +/** A project's own characters as they were before their last write. */ +export async function undoProjectCharacters(dir, o) { + const { cast, ...rest } = await undoKind(PROJECT_KIND, projectCharactersFile(dir), o); + return { ...rest, doc: cast }; +} diff --git a/umtool/lib/report/characterLayers.mjs b/umtool/lib/report/characterLayers.mjs @@ -0,0 +1,40 @@ +// THE LAYERS ONE READ ASKS, read from a project's folder (cast.mjs, post-say.mjs voiceSourceOf; knobs.md, "A +// character is a preset"): the project's own characters (`narration/characters.json`) over its voice map +// (`narration/voices.json`), the CAST it reads (castStore.mjs castForProject), and the character a post item names +// for itself (`narration.character`). Every reader -- a single post's take (readVoice.mjs), a thread read +// (postThreadRead.mjs), a recording made a read (postNarrationCli.mjs importRecording), the bench's routes, `umtool +// cast project` -- loads them here, so they ask the same files. +// +// A broken characters.json or cast.json reads as none (its `error` kept: `umtool cast project` says it); a broken +// voice map reads as none too unless `strictMap` (a thread read refuses one, as before). +// +// Plain ESM. +import { castPresetMap, characterForRead, itemCharacterOf, itemPresetOf, projectPresetMap } from "umtool-report-to-video/cast"; +import { castForProject, readProjectCharacters } from "./castStore.mjs"; + +/** + * @param {string} dir the project's folder + * @param {{ reportsRoot?: string, strictMap?: boolean }} [o] + * @returns {Promise<{ castRead: any, projectRead: any, voiceMap: Record<string, string>, cast: any, project: any, + * map: Record<string, any>, castMap: Record<string, any>, itemOf: (e: any) => any, itemCharacterOf: (e: any) => any, + * characterForRead: (e: any, as?: string | null) => any }>} + */ +export async function readLayers(dir, { reportsRoot = undefined, strictMap = false } = {}) { + const { readVoiceMap } = await import("./postSay.mjs"); + const castRead = await castForProject(dir, ...(reportsRoot ? [reportsRoot] : [])); + const projectRead = await readProjectCharacters(dir); + const voiceMap = strictMap ? await readVoiceMap(dir) : await readVoiceMap(dir).catch(() => ({})); + const layers = { project: projectRead.doc, cast: castRead.cast }; + return { + castRead, projectRead, voiceMap, ...layers, + /** voiceSourceOf's `map`: the project's characters over its voice map. */ + map: projectPresetMap(projectRead.doc, voiceMap), + /** voiceSourceOf's `cast`. */ + castMap: castPresetMap(castRead.cast), + /** voiceSourceOf's `item` for post item `e`. */ + itemOf: (e) => itemPresetOf(e, layers), + itemCharacterOf: (e) => itemCharacterOf(e, layers), + /** The character a recording of `e` is made into (cast.mjs characterForRead). */ + characterForRead: (e, as = null) => characterForRead(e, { ...layers, as }), + }; +} diff --git a/umtool/lib/report/characters.test.mjs b/umtool/lib/report/characters.test.mjs @@ -0,0 +1,392 @@ +// A character is a preset, on disk (castStore.mjs, castCli.mjs, characterLayers.mjs, postThreadRead.mjs, +// postNarrationCli.mjs): a version 1 cast read as version 2 and written as it (undo puts the old file back), the +// preset flags of `umtool cast set`, a project's OWN characters (one writer, an undo point a write, anonymous ones +// "Anon 1", "Anon 2"), "Add to the pool" / "Keep in this video only", a post item's own character, the chain's answer +// and its source in `umtool cast project`, a preset's SPEED on a single take and on a thread read's parts (and the +// flag over it), and a recording made a read with its character's recorded preset. No editor: the tts and voice ops +// are stubs; every project is a temp dir. +import assert from "node:assert/strict"; +import { existsSync } from "node:fs"; +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { after, test } from "node:test"; +import { encodeWav16 } from "yt-dlp-transcript-common/lib/montage/voiceMatch.mjs"; +import { VOICE_A, VOICE_B, syntheticVoice, withSilence } from "yt-dlp-transcript-common/testing/audio/syntheticVoice.mjs"; +import { CastError, castFile, castWrite, projectCharactersFile, projectCharactersWrite, readCast, readCastFile, readProjectCharacters, undoCast, undoProjectCharacters } from "./castStore.mjs"; +import { castCommand } from "./castCli.mjs"; +import { readLayers } from "./characterLayers.mjs"; +import { importRecording, makeTake } from "./postNarrationCli.mjs"; +import { postsCommand } from "./postsCli.mjs"; +import { partKey, readParts, threadReadPlan, threadTake, upToDate } from "./postThreadRead.mjs"; +import { itemReadVoice } from "./readVoice.mjs"; +import { threadArgvOf } from "./castProject.mjs"; + +const ROOT = await mkdtemp(path.join(tmpdir(), "umtool-characters-")); +after(() => rm(ROOT, { recursive: true, force: true })); +const wavOf = async (file, voice, seconds = 1.5, silence = 0.3) => { + await mkdir(path.dirname(file), { recursive: true }); + await writeFile(file, encodeWav16(withSilence(syntheticVoice({ ...voice, seconds }), { before: silence, after: silence }))); +}; +const run = (command, key) => async (args, extra = {}) => { + const lines = []; + const code = await command(args, { [key]: ROOT, log: (s) => lines.push(s), out: (s) => lines.push(s), err: (s) => lines.push(s), ...extra }); + return { code, lines, text: () => lines.join("\n"), json: () => JSON.parse(lines.join("\n")) }; +}; +const cast = run(castCommand, "reportsRoot"); +const posts = run(postsCommand, "root"); +const stubAsk = (asked) => async (body) => { + asked.push(body); + await wavOf(body.out, body.voice === "am_michael" ? VOICE_A : VOICE_B, 1.2); + return { jobId: `job-${asked.length}`, result: { wav: body.out, engine: body.engine, voice: body.voice } }; +}; + +// THE PROJECT: @hostman's post (p-1), his answer to @guest (p-2: a thread), @guest's own post (p-3), a stranger's (p-4). +const DIR = path.join(ROOT, "chars"); +{ + const post = (id, handle, author, o = {}) => ({ type: "post", id: `p-${id}`, post: `hostx/${id}`, platform: "x", author, handle, date: `2026-10-30T1${id}:00:00.000Z`, text: `words of ${id} from ${handle}.`, ...o }); + await mkdir(DIR, { recursive: true }); + await writeFile(path.join(DIR, "video.manifest.json"), JSON.stringify({ + schemaVersion: 1, slug: "chars", title: "Characters", provenance: { channelsDir: "../channels", channelSlug: "chan" }, + render: { width: 1920, height: 1080, fps: 30, palette: { bg: "#000000", fg: "#ffffff", muted: "#888888", accent: "#c8752a" }, postNarration: { engine: "kokoro", voice: "af_heart" } }, + timeline: [ + post("1", "hostman", "Host Man", { narration: { script: "Host's first line, read aloud." } }), + post("2", "hostman", "Host Man", { parents: [{ id: "20", handle: "guest", author: "The Guest", date: "2026-10-30T09:00:00.000Z", text: "the guest asks a question" }], narration: { script: "Host answers the guest." } }), + post("3", "guest", "The Guest", { narration: { script: "The guest's own line." } }), + post("4", "stranger", "A Stranger", { narration: { script: "A stranger says a thing." } }), + ], + }, null, 2)); +} +const project = { id: "chars", dir: DIR }; +const manifest = async () => JSON.parse(await readFile(path.join(DIR, "video.manifest.json"), "utf8")); +const item = async (id) => (await manifest()).timeline.find((e) => e.id === id); + +test("the store: a version 1 cast reads as version 2, the first write makes it version 2, undo puts the old file back", async () => { + const file = castFile(ROOT); + const v1 = `${JSON.stringify({ format: "umtool-cast", version: 1, characters: [ + { id: "hostman", name: "Host Man", handles: ["hostman"], voice: "kokoro:am_michael", speakers: ["Host"] }, + { id: "me", name: "Me", handles: ["operator"], voice: "kokoro:bm_george", convert: { engine: "seed-vc", pitch: "contour", semitones: 2 }, narrator: true }, + ] }, null, 1)}\n`; + await mkdir(path.dirname(file), { recursive: true }); + await writeFile(file, v1); + const r = await readCastFile(file); + assert.equal(r.error, undefined); + assert.equal(r.cast.version, 2, "in memory: version 2"); + assert.deepEqual(r.cast.characters[1], { + id: "me", name: "Me", handles: ["operator"], synthetic: { voice: "kokoro:bm_george" }, recorded: { convert: { engine: "seed-vc", pitch: "contour", semitones: 2 } }, narrator: true, + voice: "kokoro:bm_george", convert: { engine: "seed-vc", pitch: "contour", semitones: 2 }, + }, "its presets, and the voice / convert they answer to"); + assert.equal(await readFile(file, "utf8"), v1, "reading writes nothing"); + // A write: version 2 on disk, the presets alone (no voice / convert beside them). + const w = await castWrite(file, (chars) => { + assert.equal(chars[0].voice, undefined, "the mutation is handed version 2's characters"); + chars[0].synthetic.speed = 1.1; + }, { token: r.token, what: "hostman at 1.1" }); + const disk = JSON.parse(await readFile(file, "utf8")); + assert.equal(disk.version, 2); + assert.deepEqual(disk.characters[0], { id: "hostman", name: "Host Man", handles: ["hostman"], synthetic: { voice: "kokoro:am_michael", speed: 1.1 }, speakers: ["Host"] }); + assert.deepEqual(disk.characters[1], { id: "me", name: "Me", handles: ["operator"], synthetic: { voice: "kokoro:bm_george" }, recorded: { convert: { engine: "seed-vc", pitch: "contour", semitones: 2 } }, narrator: true }); + assert.equal(w.undo, 1); + // A refusal writes nothing: a convert target that is a file. + await assert.rejects(castWrite(file, (chars) => { chars[0].recorded = { convert: { voice: "narration/me.wav" } }; }), /never a file or a recording/); + assert.deepEqual(JSON.parse(await readFile(file, "utf8")), disk); + // Undo: the version 1 text, byte for byte -- and it reads the same. + const u = await undoCast(file); + assert.equal(u.undone, "hostman at 1.1"); + assert.equal(await readFile(file, "utf8"), v1); + assert.equal((await readCast(ROOT)).cast.characters[0].voice, "kokoro:am_michael"); +}); + +test("umtool cast set: the preset fields -- speed, clean, trim and its pad, the direction; default takes one off", async () => { + let r = await cast(["set", "hostman", "--speed", "1.15", "--enhance", "off", "--trim", "on", "--trim-pad", "120", "--direction", "higher, brisk, amused", "--convert-engine", "seed-vc", "--convert-pitch", "source", "--json"]); + assert.equal(r.code, 0, r.text()); + assert.deepEqual(r.json().character.synthetic, { voice: "kokoro:am_michael", speed: 1.15 }); + assert.deepEqual(r.json().character.recorded, { convert: { engine: "seed-vc", pitch: "source" }, enhance: false, trim: { on: true, padMs: 120 }, direction: "higher, brisk, amused" }); + assert.equal(r.json().character.voice, "kokoro:am_michael", "the view still says its voice"); + assert.equal(JSON.parse(await readFile(castFile(ROOT), "utf8")).version, 2, "the write made the file version 2"); + r = await cast(["ls"]); + assert.match(r.text(), /hostman\s+kokoro:am_michael ×1\.15\s+Host Man @hostman convert: seed-vc -> kokoro:am_michael, pitch source; not cleaned; trim pad 120 ms; direction: "higher, brisk, amused"/); + // `default` takes a key off; --no-speed the speed; "" the direction. + r = await cast(["set", "hostman", "--enhance", "default", "--trim", "default", "--convert-pitch", "default", "--no-speed", "--direction", "", "--json"]); + assert.equal(r.code, 0, r.text()); + assert.deepEqual(r.json().character.synthetic, { voice: "kokoro:am_michael" }); + assert.deepEqual(r.json().character.recorded, { convert: { engine: "seed-vc" } }); + for (const [args, re] of [ + [["--speed", "3"], /--speed is a number from 0\.5 to 2/], + [["--enhance", "maybe"], /--enhance is on, off or default/], + [["--trim-pad", "9000"], /--trim-pad is a number of milliseconds from 0 to 2000/], + [["--direction", "x".repeat(201)], /--direction is one line for the person reading \(at most 200/], + [["--convert-voice", "me.wav"], /--convert-voice is a STOCK voice with its engine.*never a file or a recording/], + [["--anonymous"], /an anonymous character is one video's, never the pool's/], + [["--no-voice"], /a cast character has a stock voice/], + ]) { + r = await cast(["set", "hostman", ...args]); + assert.equal(r.code, 1, args.join(" ")); + assert.match(r.text(), re); + } + assert.deepEqual((await readCast(ROOT)).cast.characters[0].recorded, { convert: { engine: "seed-vc" } }, "a refusal writes nothing"); + r = await cast(["set", "hostman", "--speed", "1.15"]); + assert.equal(r.code, 0, r.text()); +}); + +test("a project's own characters: one writer, an undo point a write, anonymous ones Anon 1, Anon 2; voices.json left alone", async () => { + await mkdir(path.join(DIR, "narration"), { recursive: true }); + const voices = path.join(DIR, "narration", "voices.json"); + const mapText = `${JSON.stringify({ stranger: "kokoro:am_onyx" }, null, 1)}\n`; + await writeFile(voices, mapText); + assert.equal((await readProjectCharacters(DIR)).exists, false); + let r = await cast(["project", "chars", "add", "anon-a", "--anonymous", "--handles", "@Guest", "--voice", "kokoro:am_puck", "--speed", "0.9", "--direction", "flat, tired", "--enhance", "off", "--json"]); + assert.equal(r.code, 0, r.text()); + assert.deepEqual(r.json().character, { + id: "anon-a", name: "Anon 1", anonymous: true, shown: "Anon 1", handles: ["guest"], synthetic: { voice: "kokoro:am_puck", speed: 0.9 }, recorded: { enhance: false, direction: "flat, tired" }, voice: "kokoro:am_puck", + }); + r = await cast(["project", "chars", "add", "anon-b", "--anonymous", "--name", "the second one", "--json"]); + assert.deepEqual([r.json().character.shown, r.json().character.name, r.json().character.synthetic], ["Anon 2", "the second one", undefined], "the next shown name; no voice of its own"); + const file = projectCharactersFile(DIR); + assert.equal(file, path.join(DIR, "narration", "characters.json")); + const disk = JSON.parse(await readFile(file, "utf8")); + assert.deepEqual([disk.format, disk.version, disk.characters.length], ["umtool-project-characters", 1, 2]); + assert.equal(disk.characters[0].voice, undefined, "the presets alone on disk"); + assert.ok(existsSync(file.replace(/\.json$/, ".undo.json"))); + // Refusals, in the layer's words -- nothing written. + for (const [args, re] of [ + [["add", "anon-a", "--name", "Again"], /is one of chars's characters already/], + [["add", "plain"], /takes --name "…" \(or --anonymous/], + [["add", "plain", "--name", "Plain", "--shown", "X"], /--shown is an anonymous character's shown name/], + [["add", "plain", "--name", "Plain", "--narrator"], /the narrator is a cast character/], + [["add", "plain", "--name", "Plain", "--voice", "/tmp/me.wav"], /--voice is a STOCK voice with its engine/], + [["add", "plain", "--name", "Plain", "--convert-voice", "seedvc:/home/me.wav"], /never a file or a recording/], + [["add", "plain", "--name", "Plain", "--handles", "guest"], /@guest is anon-a's already/], + [["set", "nobody", "--speed", "1"], /no nobody among chars's characters/], + [["pool", "anon-a"], /anon-a is anonymous: it stays in this video/], + [["pool", "anon-b"], /anonymous/], + [["frobnicate"], /nothing \(the view\), add, set, rm, undo, pool or keep/], + ]) { + r = await cast(["project", "chars", ...args]); + assert.equal(r.code, 1, args.join(" ")); + assert.match(r.text(), re); + } + assert.deepEqual(JSON.parse(await readFile(file, "utf8")), disk); + // The store itself: a stale token refused, a broken file never overwritten. + const read = await readProjectCharacters(DIR); + await assert.rejects(projectCharactersWrite(DIR, () => {}, { token: "stale" }), (e) => e instanceof CastError && e.status === 409); + await projectCharactersWrite(DIR, (chars) => { chars[1].shown = "The Second"; }, { token: read.token, what: "rename" }); + assert.equal((await readProjectCharacters(DIR)).doc.characters[1].shown, "The Second"); + const u = await undoProjectCharacters(DIR); + assert.equal(u.undone, "rename"); + assert.equal((await readProjectCharacters(DIR)).doc.characters[1].shown, "Anon 2"); + // set, rm, undo through the CLI. + r = await cast(["project", "chars", "set", "anon-b", "--shown", "Witness", "--voice", "kokoro:af_bella", "--json"]); + assert.deepEqual([r.json().character.shown, r.json().character.voice], ["Witness", "kokoro:af_bella"]); + r = await cast(["project", "chars", "set", "anon-b", "--no-voice", "--json"]); + assert.equal(r.json().character.synthetic, undefined); + r = await cast(["project", "chars", "rm", "anon-b"]); + assert.equal(r.code, 0, r.text()); + assert.equal((await readProjectCharacters(DIR)).doc.characters.length, 1); + r = await cast(["project", "chars", "undo"]); + assert.match(r.text(), /undone: rm anon-b \(chars\)/); + assert.equal((await readProjectCharacters(DIR)).doc.characters.length, 2); + await cast(["project", "chars", "rm", "anon-b"]); + assert.equal(await readFile(voices, "utf8"), mapText, "voices.json is not rewritten"); + // A broken file: read as none, said, never overwritten. + const good = await readFile(file, "utf8"); + await writeFile(file, "{ nope"); + assert.match((await readProjectCharacters(DIR)).error, /not JSON/); + r = await cast(["project", "chars", "add", "x", "--name", "X"]); + assert.equal(r.code, 1); + assert.match(r.text(), /fix the file first/); + assert.equal(await readFile(file, "utf8"), "{ nope"); + r = await cast(["project", "chars"]); + assert.match(r.text(), /this video's characters are NOT read/); + await writeFile(file, good); +}); + +test("cast project: the chain's answer and its source for each author; a post item's own character", async () => { + let r = await cast(["project", "chars", "--json"]); + assert.equal(r.code, 0, r.text()); + let v = r.json(); + const row = (key) => v.characters.find((c) => c.key === key); + // hostman: the cast's character, its speed with it. guest: this video's anonymous character, over nothing. + assert.deepEqual([row("hostman").voice.spec, row("hostman").voice.from, row("hostman").voice.speed, row("hostman").character.layer], ["kokoro:am_michael", "cast", 1.15, "cast"]); + assert.deepEqual([row("anon-a").voice.spec, row("anon-a").voice.from, row("anon-a").voice.speed, row("anon-a").voice.character], ["kokoro:am_puck", "project", 0.9, "anon-a"]); + assert.deepEqual([row("anon-a").name, row("anon-a").character.anonymous, row("anon-a").character.shown, row("anon-a").character.layer], ["Anon 1", true, "Anon 1", "project"], "shown under its shown name"); + assert.deepEqual(row("anon-a").recorded, { convert: { engine: null, voice: "kokoro:am_puck" }, enhance: false, trim: { on: true, padMs: null }, direction: "flat, tired" }); + // stranger: the voice map -- a project character with only a synthetic voice. + assert.deepEqual([row("@stranger").voice.spec, row("@stranger").voice.from, row("@stranger").character], ["kokoro:am_onyx", "project", null]); + assert.deepEqual(v.own.map((c) => [c.id, c.handles]), [["anon-a", ["guest"]]]); + assert.deepEqual(v.itemCharacters, []); + assert.equal(v.charactersFile, projectCharactersFile(DIR)); + r = await cast(["project", "chars"]); + assert.match(r.text(), /hostman\s+kokoro:am_michael ×1\.15\s+\(cast: hostman\)/); + assert.match(r.text(), /anon-a\s+kokoro:am_puck ×0\.9\s+\(project: anon-a\).*shown as "Anon 1"/); + assert.match(r.text(), /a recording of them: converted to kokoro:am_puck; not cleaned; edges trimmed; direction: "flat, tired"/); + assert.match(r.text(), /@stranger\s+kokoro:am_onyx\s+\(project\)/); + + // A POST ITEM's OWN CHARACTER: p-4 (the stranger's) read as the cast's `me`. + r = await posts(["character", "chars", "p-4", "ghost"]); + assert.equal(r.code, 2); + assert.match(r.text(), /no character ghost among chars's own or in the cast/); + r = await posts(["character", "chars", "p-4", "me", "--json"]); + assert.equal(r.code, 0, r.text()); + assert.deepEqual([r.json().character, r.json().layer, r.json().changed, r.json().voice.spec, r.json().voice.from], ["me", "cast", "set", "kokoro:bm_george", "item"]); + assert.equal((await item("p-4")).narration.character, "me"); + r = await posts(["character", "chars", "p-4"]); + assert.match(r.text(), /p-4: read as me \(Me; the cast's\): kokoro:bm_george \(item: me\)/); + r = await cast(["project", "chars", "--json"]); + v = r.json(); + assert.deepEqual(v.itemCharacters.map((x) => [x.id, x.character, x.found, x.layer, x.voice.spec, x.voice.from]), [["p-4", "me", true, "cast", "kokoro:bm_george", "item"]]); + assert.deepEqual([row("@stranger").voice.spec, row("@stranger").voice.from], ["kokoro:am_onyx", "project"], "the handle's own answer is still the map's"); + // The single take asks the same chain (readVoice.mjs), and a thread read's plan. + assert.deepEqual(await itemReadVoice(project, await item("p-4"), { render: (await manifest()).render }), { engine: "kokoro", voice: "bm_george", from: "item", character: "me" }); + // The project's own first: an id both layers have. + await projectCharactersWrite(DIR, (chars) => { chars.push({ id: "me", name: "Me, here", handles: [], synthetic: { voice: "kokoro:am_echo", speed: 1.3 } }); }); + assert.deepEqual(await itemReadVoice(project, await item("p-4"), { render: (await manifest()).render }), { engine: "kokoro", voice: "am_echo", from: "item", speed: 1.3, character: "me" }); + await undoProjectCharacters(DIR); + // --clear: by its author's handle again. + r = await posts(["character", "chars", "p-4", "--clear", "--json"]); + assert.deepEqual([r.json().character, r.json().changed, r.json().voice.from], [null, "cleared", "project"]); + assert.equal((await item("p-4")).narration.character, undefined); + r = await posts(["character", "chars", "p-4", "me", "--clear"]); + assert.equal(r.code, 2); +}); + +test("a preset's speed on a single take: the flag, then the character's, then the item's own", async () => { + const m = await manifest(); + const asked = []; + // hostman (the cast: kokoro am_michael ×1.15): his take is asked at 1.15, and says so. + let t = await makeTake(project, await item("p-1"), { render: m.render, ask: stubAsk(asked), redaction: null }); + assert.deepEqual([asked.at(-1).engine, asked.at(-1).voice, asked.at(-1).speed], ["kokoro", "am_michael", 1.15]); + assert.equal(t.take.speed, 1.15); + // The flag over it. + t = await makeTake(project, await item("p-1"), { render: m.render, speed: 0.8, ask: stubAsk(asked), redaction: null }); + assert.equal(asked.at(-1).speed, 0.8); + // The stranger (the voice map: no preset): no speed asked. + t = await makeTake(project, await item("p-4"), { render: m.render, ask: stubAsk(asked), redaction: null }); + assert.deepEqual([asked.at(-1).voice, "speed" in asked.at(-1)], ["am_onyx", false]); + assert.equal(t.take.speed, undefined); +}); + +test("a thread read: each part at its character's speed, the flag over them all, Orpheus none -- and another speed is another part", async () => { + const m = await manifest(); + const e2 = await item("p-2"); + const L = await readLayers(DIR); + const plan = threadReadPlan(m, e2, { map: L.map, cast: L.castMap, item: L.itemOf(e2) }); + assert.deepEqual(plan.pieces.map((p) => [p.role, p.voice, p.from, p.speed ?? null, p.character ?? null]), [["parent:0", "am_puck", "project", 0.9, "anon-a"], ["post", "am_michael", "cast", 1.15, "hostman"]]); + const parts = readParts(plan); + assert.deepEqual(parts.map((p) => p.speed), [0.9, 1.15]); + assert.equal(parts[1].key, partKey("kokoro", "am_michael", parts[1].text, 1.15)); + assert.notEqual(parts[1].key, partKey("kokoro", "am_michael", parts[1].text), "the same words at another speed are another part"); + assert.equal(partKey("kokoro", "am_michael", "hi", 1), partKey("kokoro", "am_michael", "hi"), "at 1: the key as before"); + // --speed: every part at that one. + assert.deepEqual(threadReadPlan(m, e2, { map: L.map, cast: L.castMap, speed: 1.4 }).pieces.map((p) => p.speed), [1.4, 1.4]); + // Orpheus has no speed: a piece in it is asked none, whatever the flag says. + assert.deepEqual(threadReadPlan(m, e2, { map: { guest: "orpheus:tara" }, cast: L.castMap, speed: 1.4 }).pieces.map((p) => [p.engine, p.speed ?? null]), [["orpheus", null], ["kokoro", 1.4]]); + // His own words with no preset: the item's own speed (narration.speed), as a single take. + assert.deepEqual(threadReadPlan(m, { ...e2, narration: { ...e2.narration, speed: 0.75 } }, { map: {}, cast: {} }).pieces.map((p) => [p.role, p.speed ?? null]), [["parent:0", null], ["post", 0.75]]); + + // Made: the editor is asked each part at its speed, the take's parts keep it, and the same read again is up to date. + const asked = []; + const r = await threadTake(project, e2, { manifest: m, red: null, ask: stubAsk(asked), lanes: null }); + assert.deepEqual(asked.map((b) => [b.voice, b.speed]), [["am_puck", 0.9], ["am_michael", 1.15]]); + assert.deepEqual(r.take.parts.map((p) => [p.role, p.voice, p.speed]), [["parent:0", "am_puck", 0.9], ["post", "am_michael", 1.15]]); + assert.equal(r.take.read.speed, undefined, "a preset's speed is the character's, not the read's"); + const after = await item("p-2"); + const again = await threadTake(project, after, { red: null, ask: stubAsk(asked), lanes: null }); + assert.equal(again.upToDate, true); + assert.equal(asked.length, 2); + // The flag: not up to date; the parts asked again at it (new cache keys), the read records it, and a re-read keeps it. + assert.equal(upToDate(after, threadReadPlan(await manifest(), after, { map: L.map, cast: L.castMap, speed: 1.4 })), false); + const fast = await threadTake(project, after, { red: null, speed: 1.4, ask: stubAsk(asked), lanes: null }); + assert.deepEqual(asked.slice(2).map((b) => b.speed), [1.4, 1.4]); + assert.equal(fast.take.read.speed, 1.4); + assert.deepEqual(threadArgvOf(fast.take.read), ["--speed", "1.4"]); + // Through the CLI: --speed reaches a thread read (it was ignored), and a bad one is refused in the flag's name. + let c = await posts(["narrate", "chars", "p-2", "--take", "--thread", "--speed", "1.4", "--dry-run", "--json"]); + assert.equal(c.code, 0, c.text()); + assert.deepEqual(c.json().pieces.map((p) => p.speed), [1.4, 1.4]); + assert.equal(c.json().upToDate, true); + c = await posts(["narrate", "chars", "p-2", "--take", "--thread", "--speed", "9", "--dry-run"]); + assert.equal(c.code, 2); + assert.match(c.text(), /--speed is a number from 0\.5 to 2/); +}); + +test("\"Add to the pool\" and \"Keep in this video only\"", async () => { + // Keep an author with no character here: a character of this video, in the voice they read in now. + let r = await cast(["project", "chars", "keep", "@stranger", "--json"]); + assert.equal(r.code, 0, r.text()); + assert.deepEqual(r.json().character, { id: "stranger", name: "A Stranger", handles: ["stranger"], synthetic: { voice: "kokoro:am_onyx" }, voice: "kokoro:am_onyx" }); + // Keep a cast character here: a copy, without its narrator mark; changing it leaves the pool's as it is. + r = await cast(["project", "chars", "keep", "me", "--json"]); + assert.equal(r.code, 0, r.text()); + assert.equal(r.json().character.narrator, undefined); + assert.deepEqual(r.json().character.recorded, { convert: { engine: "seed-vc", pitch: "contour", semitones: 2 } }); + r = await cast(["project", "chars", "set", "me", "--convert-semitones", "-3", "--json"]); + assert.equal(r.json().character.recorded.convert.semitones, -3); + assert.equal((await readCast(ROOT)).cast.characters.find((c) => c.id === "me").recorded.convert.semitones, 2, "the pool's is untouched"); + r = await cast(["project", "chars", "keep", "me"]); + assert.equal(r.code, 1); + assert.match(r.text(), /me is one of chars's characters already/); + // `use` for this project: this video's own character takes it (its preset answers before the voice map). + r = await cast(["use", "chars", "@stranger", "kokoro:am_fenrir", "--json"]); + assert.equal(r.code, 0, r.text()); + assert.equal((await readProjectCharacters(DIR)).doc.characters.find((c) => c.id === "stranger").voice, "kokoro:am_fenrir"); + assert.deepEqual(JSON.parse(await readFile(path.join(DIR, "narration", "voices.json"), "utf8")), { stranger: "kokoro:am_onyx" }, "the map is left as it was"); + // Add to the pool: into the cast, out of the project; one the cast has already is refused. + r = await cast(["project", "chars", "pool", "me"]); + assert.equal(r.code, 1); + assert.match(r.text(), /me is in the cast already/); + r = await cast(["project", "chars", "pool", "stranger", "--json"]); + assert.equal(r.code, 0, r.text()); + assert.deepEqual([r.json().scope, r.json().changed], ["cast", "pooled"]); + assert.deepEqual((await readCast(ROOT)).cast.characters.find((c) => c.id === "stranger").synthetic, { voice: "kokoro:am_fenrir" }); + assert.equal((await readProjectCharacters(DIR)).doc.characters.some((c) => c.id === "stranger"), false); + r = await cast(["undo"]); + assert.match(r.text(), /undone: stranger into the pool \(from chars\)/); + await cast(["project", "chars", "rm", "me"]); +}); + +test("a recording made a read with its character's recorded preset: clean off, trim off, the direction; the flags over them", async () => { + const rec = path.join(ROOT, "my-read.wav"); + await wavOf(rec, VOICE_B, 2, 0.6); + const ops = []; + const askOp = async (route, body) => { + ops.push(route.split("/").at(-1)); + await wavOf(body.out, VOICE_A, 2); + return { jobId: `op-${ops.length}`, result: { engine: body.engine ?? "openvoice", voice: body.voice } }; + }; + // p-3 is @guest's: this video's anonymous character (enhance off, direction) -- not cleaned, converted to its voice. + let r = await importRecording(project, await item("p-3"), rec, { ask: askOp }); + assert.deepEqual(r.character, { id: "anon-a", name: "Anon 1", voice: "kokoro:am_puck", layer: "project" }, "named as it is shown"); + assert.equal(r.direction, "flat, tired"); + assert.deepEqual(ops, ["voice-convert"]); + assert.deepEqual(r.takes.map((t) => t.step), ["recorded", "converted to kokoro:am_puck"]); + assert.match(r.notes[0], /not cleaned: anon-a's recorded preset says so/); + assert.equal(r.disclosure, "Narration: voice converted to a synthetic voice (openvoice · kokoro:am_puck)", "the disclosure line is what it was"); + const kept = (await item("p-3")).narration.takes[0]; + assert.match(kept.note, /recorded for Anon 1/); + const trimmed = kept.seconds; + assert.ok(trimmed < 2.6, `its edges trimmed (${trimmed} s of 3.2)`); + // The command over the preset: clean it this once. + ops.length = 0; + r = await importRecording(project, await item("p-3"), rec, { clean: true, ask: askOp }); + assert.deepEqual(ops, ["voice-enhance", "voice-convert"]); + // The preset says trim off: kept as recorded, edges and all; a pad is the room kept. + await cast(["project", "chars", "set", "anon-a", "--trim", "off"]); + r = await importRecording(project, await item("p-3"), rec, { convert: false, ask: askOp }); + const whole = (await item("p-3")).narration.takes.find((t) => t.file === r.takes[0].file).seconds; + assert.ok(whole > 3, `not trimmed (${whole} s)`); + await cast(["project", "chars", "set", "anon-a", "--trim", "on", "--trim-pad", "400"]); + r = await importRecording(project, await item("p-3"), rec, { convert: false, ask: askOp }); + const padded = (await item("p-3")).narration.takes.find((t) => t.file === r.takes[0].file).seconds; + assert.ok(padded > trimmed + 0.3 && padded < whole, `the pad kept (${padded} s between ${trimmed} and ${whole})`); + // --as: a character of this video's by id, the cast's by id; the item's own character before its author's. + r = await importRecording(project, await item("p-1"), rec, { as: "anon-a", convert: false, ask: askOp }); + assert.equal(r.character.layer, "flag"); + await assert.rejects(importRecording(project, await item("p-1"), rec, { as: "ghost", ask: askOp }), /--as ghost: no such character in this video's characters or the cast/); + await posts(["character", "chars", "p-3", "me"]); + ops.length = 0; + r = await importRecording(project, await item("p-3"), rec, { ask: askOp }); + assert.deepEqual([r.character.id, r.character.layer], ["me", "item"]); + assert.deepEqual(r.takes.map((t) => t.step), ["recorded", "cleaned", "converted to kokoro:bm_george (pitch: contour +2 st)"]); + await posts(["character", "chars", "p-3", "--clear"]); +}); diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs @@ -3307,7 +3307,7 @@ export function handlesWithoutAvatar(m, handles) { // ---- a post item's narration (report-to-video/post-narration.mjs) ---------- /** The narration keys a write may set on one post item (post-narration.mjs; knobs.md, "A narrated post item"). */ -export const POST_NARRATION_KNOBS = Object.freeze(["script", "excerpt", "engine", "voice", "speed", "pick", "approved", "off", "lead", "tail", "ramp", "linger", "clip", "wet", "lowpassHz", "duck", "short", "attach", "lufs", "rate", "pace", "window"]); +export const POST_NARRATION_KNOBS = Object.freeze(["script", "excerpt", "engine", "voice", "speed", "character", "pick", "approved", "off", "lead", "tail", "ramp", "linger", "clip", "wet", "lowpassHz", "duck", "short", "attach", "lufs", "rate", "pace", "window"]); /** * One post item's narration, changed in place (`m` the manifest inside a diff --git a/umtool/lib/report/postNarrationCli.mjs b/umtool/lib/report/postNarrationCli.mjs @@ -24,7 +24,7 @@ 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_DERIVE_ROUTES, derivedFileOf, draftScript, takeIdOf, isNarrated, nextTakeNumber, pickedTake, postIdOf, postNarrationKnobs, takeFileOf, takesDirOf, + NARRATION_INDEX, POST_DERIVE_OPS, POST_NARRATION_LIMITS, POST_DERIVE_ROUTES, derivedFileOf, draftScript, takeIdOf, isNarrated, nextTakeNumber, pickedTake, postIdOf, postNarrationKnobs, takeFileOf, takesDirOf, } from "umtool-report-to-video/post-narration"; import { CAST_CONVERT_PITCH, CAST_SEMITONES_MAX } from "umtool-report-to-video/cast"; import { stepPitchOf } from "./derivePitch.mjs"; @@ -330,12 +330,15 @@ export async function makeTake(project, e, { script = null, note = null, engine const k = postNarrationKnobs(e, render); 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)`); - // The voice his own read is said in: the one asked for, the project's voice map, the CAST, the narrator's (readVoice.mjs). + // 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 (readVoice.mjs). const { itemReadVoice } = await import("./readVoice.mjs"); const said0 = await itemReadVoice(project, e, { render, engine, voice }); const eng = said0.engine; const vox = said0.voice; - const spd = speed ?? e.narration?.speed ?? null; + // Its speed: the one asked for (--speed), else its character's (the synthetic preset's that answered for the + // voice), else the item's own (`narration.speed`). + const spd = speed ?? said0.speed ?? e.narration?.speed ?? null; const pid = postIdOf(e); const dir = path.join(project.dir, ...takesDirOf(pid).split("/")); await mkdir(dir, { recursive: true }); @@ -532,7 +535,10 @@ export async function narrateCommand(project, words, flags, { json = false, dryR 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"), { - as: str("--as"), label: str("--label") ?? "operator", clean: !flags.has("--no-clean"), convert: !flags.has("--no-convert"), note: str("--note"), + // --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), }); @@ -585,15 +591,14 @@ export async function narrateCommand(project, words, flags, { json = false, dryR 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"), note: str("--note"), force: flags.has("--force"), hold: !flags.has("--no-hold"), dryRun, + voice: str("--voice"), engine: str("--engine"), speed: speedFlag(str), note: str("--note"), force: flags.has("--force"), hold: !flags.has("--no-hold"), dryRun, }); } if (flags.has("--thread")) throw new NarrateError("--thread goes with --take (umtool posts narrate <p> <item> --take --thread)"); if (flags.has("--take")) { - const speedRaw = str("--speed"); const r = await makeTake(project, e, { script: str("--script"), note: str("--note"), engine: str("--engine"), voice: str("--voice"), - speed: speedRaw === null ? null : Number(speedRaw), render, emit: (_ev, f) => !json && f?.message && out(f.message), + speed: speedFlag(str), render, emit: (_ev, f) => !json && f?.message && out(f.message), }); if (json) out(JSON.stringify({ ok: true, id: e.id, take: r.take, narration: r.result.narration, token: r.result.token }, null, 2)); else out(`${e.id}: take ${r.take.file} (${r.take.seconds} s), picked${r.take.note ? ` — note: ${r.take.note}` : ""}`); @@ -622,6 +627,58 @@ export async function narrateCommand(project, words, flags, { json = false, dryR return 0; } +export const CHARACTER_USAGE = [ + "usage: umtool posts character <project> <item> [<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 <p>), 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 <p>).", +].join("\n"); + +/** `umtool posts character <p> <item> [<id> | --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 <project> [--all | <item> …] [--linger <s>] [--dry-run] [--json]", " NARRATED POSTS, NO LINGERING: each post read in full, then over `linger` (1.8 s) after the words; a video", @@ -673,6 +730,16 @@ export async function fitCommand(project, refs, { all = false, linger = null, js return 0; } +/** `--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; +} + /** `--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 = {}; @@ -751,30 +818,40 @@ export async function deriveTake(project, e, { from, op, engine = null, voice = * 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 `as` names (an id, a handle), else the post's author's in the cast, else - * the cast's narrator; none: kept as recorded (and cleaned). 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 }`. + * 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 = true, convert = true, pitch = undefined, semitones = undefined, note = null, emit = () => {}, editor = null, ask = null } = {}) { +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 } = {}) { 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 { castForProject } = await import("./castStore.mjs"); - const { characterOf, convertPitchLabel, convertTargetOf, findCharacter, narratorOf } = await import("umtool-report-to-video/cast"); + 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 castRead = await castForProject(project.dir); - const character = as ? findCharacter(castRead.cast, String(as).replace(/^@+/, "")) : characterOf(castRead.cast, e0.handle) ?? narratorOf(castRead.cast); - if (as && !character) throw new NarrateError(`--as ${as}: no such character in the cast (umtool cast ls)`); + const layers = await readLayers(project.dir); + const who = layers.characterForRead(e0, as); + const character = who?.character ?? null; + if (as && !character) 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 = await keepRecording(project, e0, [{ file: abs, text: String(e0.narration?.script ?? "") }], { label, manifest: await readManifest(project.dir), note: note ?? `recorded${character ? ` for ${character.name}` : ""}` }); + const kept = 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)` }); + 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 (clean) { + if (doClean) { try { const r = await deriveTake(project, e, { from, op: "enhance", emit, editor, ask }); takes.push({ step: "cleaned", file: r.take.file }); @@ -784,11 +861,12 @@ export async function importRecording(project, e0, file, { as = null, label = "o 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) { - if (!character) notes.push("not converted: no character to convert to (--as <character>, or the post's author or a narrator in the cast: umtool cast add …)"); + const target = character ? preset.convert : null; + if (!character) notes.push("not converted: no character to convert to (--as <character>, 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 <engine:voice>)`); else { - const target = convertTargetOf(character); // 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) }; @@ -803,7 +881,11 @@ export async function importRecording(project, e0, file, { as = null, label = "o } } } - return { takes, picked: takes.at(-1).file, notes, disclosure: e ? postNarrationDisclosure(e) : null, character: character ? { id: character.id, name: character.name, voice: character.voice } : null }; + return { + takes, picked: takes.at(-1).file, notes, disclosure: 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 } : {}), + }; } /** diff --git a/umtool/lib/report/postRecord.mjs b/umtool/lib/report/postRecord.mjs @@ -61,9 +61,12 @@ export function targetLufsOf(manifest) { * @param {{ id: string, dir: string }} project * @param {Record<string, any>} entry * @param {Array<{ file: string, text?: string, para?: number }>} parts - * @param {{ label?: string, manifest?: Record<string, any>, note?: string | null, script?: string | null }} [o] + * @param {{ label?: string, manifest?: Record<string, any>, note?: string | null, script?: string | null, trim?: { on?: boolean, padMs?: number | null } | null }} [o] */ -export async function keepRecording(project, entry, parts, { label = "operator", manifest = null, note = null, script = null } = {}) { +export async function keepRecording(project, entry, parts, { label = "operator", manifest = null, note = null, script = null, trim = null } = {}) { + // A character's recorded preset (cast.mjs recordedPresetOf): its edges left as recorded (`trim.on` false), or the + // room kept either side of the words (`trim.padMs`); none: trimmed, RECORD_ROOM. + const room = trim && Number.isFinite(trim.padMs) ? { head: trim.padMs / 1000, tail: trim.padMs / 1000 } : RECORD_ROOM; if (!RECORD_LABEL_RE.test(label)) throw new Error(`"${label}" is not a voice label (a-z, 0-9, - and _)`); if (!parts.length) throw new Error("nothing was recorded"); const pid = postIdOf(entry); @@ -83,7 +86,7 @@ export async function keepRecording(project, entry, parts, { label = "operator", await execFileP(ff, ["-nostdin", "-v", "error", "-y", "-i", p.file, "-vn", "-ac", "1", "-ar", "48000", "-c:a", "pcm_s16le", raw]); const { seconds } = await measureTake(raw); const sil = await detectSilence(raw, { silenceMinDur: 0.15 }).catch(() => []); - const span = trimSpan(sil, seconds ?? 0); + const span = trim?.on === false ? { from: 0, to: r3(seconds ?? 0) } : trimSpan(sil, seconds ?? 0, room); const out = path.join(partsDir, `p${String(k + 1).padStart(2, "0")}.wav`); await execFileP(ff, ["-nostdin", "-v", "error", "-y", "-i", raw, "-af", `atrim=${span.from}:${span.to},asetpts=PTS-STARTPTS`, "-ar", "48000", "-ac", "1", "-c:a", "pcm_s16le", out]); await rm(raw, { force: true }); diff --git a/umtool/lib/report/postThreadRead.mjs b/umtool/lib/report/postThreadRead.mjs @@ -56,7 +56,7 @@ import { chronoPieces } from "umtool-report-to-video/post-thread"; import { cardText, parentsOf } from "umtool-report-to-video/post-item"; import { planContext } from "umtool-report-to-video/post-conversation"; import { spokenRead } from "umtool-report-to-video/post-redact"; -import { resolvePieceVoice } from "umtool-report-to-video/post-say"; +import { readSpeedOf, resolvePieceVoice } from "umtool-report-to-video/post-say"; import { readManifest } from "../projects/report.mjs"; import { withEditNotes } from "./edit-guard.mjs"; import { manifestToken, updatePostNarration } from "./manifest.mjs"; @@ -81,11 +81,12 @@ export class ThreadReadError extends Error { export const THREAD_READ_USAGE = [ " umtool posts narrate <project> <item> --take --thread [--parents 0|all|none|<n>] [--skip-parent <id|parent:i>]…", - " [--no-quoted] [--no-linked] [--read-seen] [--voice-for <handle>=<voice>]… [--voice v] [--engine e]", + " [--no-quoted] [--no-linked] [--read-seen] [--voice-for <handle>=<voice>]… [--voice v] [--engine e] [--speed s]", " [--note \"…\"] [--force] [--no-hold] [--dry-run] [--json]", " A THREAD READ: the post it answers (--parents all: every ancestor; none: no parent), the post it quotes, the posts", " its words link to and his words, in DATE order, each in its author's voice (the project's voice map, umtool posts", - " voices; --voice-for handle=voice for this read), the redaction, the slur filter and the pronunciation lexicon", + " voices; --voice-for handle=voice for this read) and at its character's SPEED (its synthetic preset's; --speed s:", + " every part at that one; Orpheus has no speed), the redaction, the slur filter and the pronunciation lexicon", " (umtool posts say) applied. A parent or quoted post the item before already shows is not read again (--read-seen:", " it is). Each part is synthesized once by the editor (its tts op, a job) into narration/parts-cache/ and reused by", " every read after; the take (take-<n>.<engine>-thread.wav + take-<n>.parts.json) is saved with its parts' roles and", @@ -94,15 +95,21 @@ export const THREAD_READ_USAGE = [ " could not be synthesized (the parts already made stay cached: run it again).", ].join("\n"); -/** The project's cast as a voice map (castStore.mjs: the cast the project reads; `{}` with none, or a broken one). */ +/** + * The project's cast as a preset layer (castStore.mjs: the cast the project reads; `{}` with none, or a broken one): + * `{ handle: { voice, speed?, character } }` (cast.mjs castPresetMap), voiceSourceOf's `cast`. + */ export async function projectCastMap(dir) { const { castForProject } = await import("./castStore.mjs"); - const { castVoiceMap } = await import("umtool-report-to-video/cast"); - return castVoiceMap((await castForProject(dir)).cast); + const { castPresetMap } = await import("umtool-report-to-video/cast"); + return castPresetMap((await castForProject(dir)).cast); } -/** A part's cache key: sha1 of `voice|text` (an engine other than Orpheus: `engine|voice|text`). */ -export const partKey = (engine, voice, text) => createHash("sha1").update(engine === "orpheus" ? `${voice}|${text}` : `${engine}|${voice}|${text}`).digest("hex"); +/** + * A part's cache key: sha1 of `voice|text` (an engine other than Orpheus: `engine|voice|text`), and of its SPEED when + * it is read at one (`…|x1.1`: the same words at another speed are another part; none, or 1: the key as before). + */ +export const partKey = (engine, voice, text, speed = null) => createHash("sha1").update(`${engine === "orpheus" ? `${voice}|${text}` : `${engine}|${voice}|${text}`}${typeof speed === "number" && speed !== 1 ? `|x${speed}` : ""}`).digest("hex"); /** `--parents` as a selector: "0" (default), "all", "none", or a whole number n (parents 0..n). */ export function parentsSelector(v) { @@ -135,14 +142,16 @@ export function seenIds(manifest, e) { * * @param {Record<string, any>} manifest * @param {Record<string, any>} e the post item - * `cast` is the cast as a voice map (cast.mjs castVoiceMap: `{ handle: "engine:voice" }`). Each piece's `engine` is - * its voice's (a voice that names one), else the read's; `from` where its voice came from (post-say.mjs voiceSourceOf). - * The read's `engine` is his piece's. + * `map`, `cast` and `item` are voiceSourceOf's layers (cast.mjs projectPresetMap, castPresetMap, itemPresetOf: an entry + * a voice as written, or a character's preset `{ voice, speed?, character }`). Each piece's `engine` is its voice's + * (a voice that names one), else the read's; `from` where its voice came from (post-say.mjs voiceSourceOf); `speed` + * the speed it is asked at (readSpeedOf: the command's `speed`, else its character's preset's, else the item's own + * for his words -- none for Orpheus, which has none, or at 1). The read's `engine` is his piece's. * - * @param {{ red?: any, map?: Record<string, string>, cast?: Record<string, string>, overrides?: Record<string, string>, parents?: string, - * skip?: string[], quoted?: boolean, linked?: boolean, readSeen?: boolean, voice?: string | null, engine?: string | null }} [o] + * @param {{ red?: any, map?: Record<string, any>, cast?: Record<string, any>, item?: any, overrides?: Record<string, string>, parents?: string, + * skip?: string[], quoted?: boolean, linked?: boolean, readSeen?: boolean, voice?: string | null, engine?: string | null, speed?: number | null }} [o] */ -export function threadReadPlan(manifest, e, { red = null, map = {}, cast = {}, overrides = {}, parents = "0", skip = [], quoted = true, linked = true, readSeen = false, voice = null, engine = null } = {}) { +export function threadReadPlan(manifest, e, { red = null, map = {}, cast = {}, item = null, overrides = {}, parents = "0", skip = [], quoted = true, linked = true, readSeen = false, voice = null, engine = null, speed = null } = {}) { const render = manifest?.render ?? {}; const k = postNarrationKnobs(e, render); const eng = engine ?? e.narration?.engine ?? k.engine; @@ -200,8 +209,9 @@ export function threadReadPlan(manifest, e, { red = null, map = {}, cast = {}, o skipped.push({ role: p.role, why: "nothing left to say (all of it redacted)" }); continue; } - const v = resolvePieceVoice({ handle: p.handle, role: p.role }, { map, cast, overrides, self: str(e.handle), voice, narrator, engine: eng }); - pieces.push({ role: p.role, handle: p.handle, date: p.date, voice: v.voice, engine: v.engine, from: v.from, written, text: said.text.trim(), lexicon: said.lexicon ?? [], slurs: said.slurs }); + const v = resolvePieceVoice({ handle: p.handle, role: p.role }, { map, cast, item, overrides, self: str(e.handle), voice, narrator, engine: eng }); + const spd = readSpeedOf({ flag: speed, preset: v.speed ?? null, own: p.role === "post" ? e.narration?.speed ?? null : null, engine: v.engine }); + pieces.push({ role: p.role, handle: p.handle, date: p.date, voice: v.voice, engine: v.engine, from: v.from, ...(spd !== null ? { speed: spd } : {}), ...(v.character ? { character: v.character } : {}), written, text: said.text.trim(), lexicon: said.lexicon ?? [], slurs: said.slurs }); } if (!pieces.some((p) => p.role === "post")) throw new ThreadReadError(`${e.id} has no words of his own to read (--script "…" first)`); const lexicon = [...new Map(pieces.flatMap((p) => p.lexicon).map((x) => [`${x.word.toLowerCase()}|${x.item ?? ""}`, x])).values()]; @@ -218,12 +228,12 @@ export function threadReadPlan(manifest, e, { red = null, map = {}, cast = {}, o export function readParts(plan) { return plan.pieces.flatMap((pc, piece) => { const eng = pc.engine ?? plan.engine; - return scriptParts(pc.text).map((q) => ({ piece, para: q.para, role: pc.role, voice: pc.voice, engine: eng, text: q.text, key: partKey(eng, pc.voice, q.text) })); + return scriptParts(pc.text).map((q) => ({ piece, para: q.para, role: pc.role, voice: pc.voice, engine: eng, ...(pc.speed !== undefined ? { speed: pc.speed } : {}), text: q.text, key: partKey(eng, pc.voice, q.text, pc.speed ?? null) })); }); } -/** Each piece's `engine:voice`, in order, once each -- what a read sounds like, for "is it up to date". */ -const voiceSig = (rows, fallback) => [...new Set(rows.map((p) => `${p.engine ?? fallback}:${p.voice}`))].join("+"); +/** Each piece's `engine:voice` (and its speed, when it has one), in order, once each -- what a read sounds like, for "is it up to date". */ +const voiceSig = (rows, fallback) => [...new Set(rows.map((p) => `${p.engine ?? fallback}:${p.voice}${typeof p.speed === "number" && p.speed !== 1 ? `x${p.speed}` : ""}`))].join("+"); /** * THE JOIN's TIMES, pure: each part's start in the take, its length, the gap before it (POST_PART_GAP: a new piece, @@ -237,7 +247,7 @@ export function joinTimes(parts, seconds, { fileOf = (p) => `${PARTS_CACHE}/${p. const gap = !prev ? 0 : p.piece !== prev.piece ? POST_PART_GAP.piece : p.para !== prev.para ? POST_PART_GAP.para : POST_PART_GAP.inside; t += gap; const s = Number(seconds[i]); - const row = { n: i + 1, para: p.piece * 100 + p.para, text: p.text, voice: p.voice, ...(p.engine ? { engine: p.engine } : {}), role: p.role, piece: p.piece, file: fileOf(p), start: r3(t), seconds: r3(s), gapBefore: gap }; + const row = { n: i + 1, para: p.piece * 100 + p.para, text: p.text, voice: p.voice, ...(p.engine ? { engine: p.engine } : {}), ...(typeof p.speed === "number" ? { speed: p.speed } : {}), role: p.role, piece: p.piece, file: fileOf(p), start: r3(t), seconds: r3(s), gapBefore: gap }; t += s; return row; }); @@ -245,11 +255,13 @@ export function joinTimes(parts, seconds, { fileOf = (p) => `${PARTS_CACHE}/${p. } /** The `read` record of a take: how it was asked for (only what differs from the defaults). */ -export function readRecordOf({ parents = "0", skip = [], quoted = true, linked = true, readSeen = false, overrides = {}, voice = null }) { +export function readRecordOf({ parents = "0", skip = [], quoted = true, linked = true, readSeen = false, overrides = {}, voice = null, speed = null }) { return { kind: "thread", parents: parentsSelector(parents), ...(skip?.length ? { skip: [...skip] } : {}), ...(quoted ? {} : { quoted: false }), ...(linked ? {} : { linked: false }), ...(readSeen ? { seen: true } : {}), ...(Object.keys(overrides ?? {}).length ? { voiceFor: { ...overrides } } : {}), ...(voice ? { voice } : {}), + // The speed the command asked for the whole read (`--speed`); a character's own is its preset's, not the read's. + ...(typeof speed === "number" && Number.isFinite(speed) ? { speed } : {}), }; } @@ -257,9 +269,9 @@ export function readRecordOf({ parents = "0", skip = [], quoted = true, linked = export function upToDate(e, plan) { const t = pickedTake(e); if (!t || norm(t.script) !== norm(plan.want) || str(t.voice) !== plan.voice || (t.engine ?? "orpheus") !== plan.engine) return false; - // A take whose parts say their voices: each piece in the same engine and voice. + // A take whose parts say their voices: each piece in the same engine and voice, at the same speed. const parts = Array.isArray(t.parts) ? t.parts.filter((p) => typeof p?.voice === "string") : []; - if (!parts.length) return true; + if (!parts.length) return !plan.pieces.some((p) => typeof p.speed === "number"); return voiceSig(parts, t.engine ?? "orpheus") === voiceSig(plan.pieces, plan.engine); } @@ -281,16 +293,20 @@ async function durationOf(file) { */ export async function threadTake(project, e, opts = {}) { const { - manifest: m0 = null, red: red0 = undefined, map: map0 = undefined, cast: cast0 = undefined, overrides = {}, parents = "0", skip = [], quoted = true, linked = true, - readSeen = false, voice = null, engine = null, note = null, force = false, hold = true, dryRun = false, + manifest: m0 = null, red: red0 = undefined, map: map0 = undefined, cast: cast0 = undefined, item: item0 = undefined, overrides = {}, parents = "0", skip = [], quoted = true, linked = true, + readSeen = false, voice = null, engine = null, speed = null, note = null, force = false, hold = true, dryRun = false, ask = null, lanes: lanes0 = undefined, emit = () => {}, editor = null, signals = false, } = opts; const manifest = m0 ?? (await readManifest(project.dir)); if (!manifest) throw new ThreadReadError(`${project.id} has no manifest`); const red = red0 !== undefined ? red0 : await (await import("./postRedaction.mjs")).projectRedaction(project.dir, manifest); - const map = map0 !== undefined ? map0 : await (await import("./postSay.mjs")).readVoiceMap(project.dir); - const cast = cast0 !== undefined ? cast0 : await projectCastMap(project.dir); - const plan = threadReadPlan(manifest, e, { red, map, cast, overrides, parents, skip, quoted, linked, readSeen, voice, engine }); + // The layers (characterLayers.mjs): the project's characters over its voice map (a broken map refuses the read), the + // cast, the item's own character -- each the caller's when it hands one in. + const L = map0 !== undefined && cast0 !== undefined && item0 !== undefined ? null : await (await import("./characterLayers.mjs")).readLayers(project.dir, { strictMap: map0 === undefined }); + const map = map0 !== undefined ? map0 : L.map; + const cast = cast0 !== undefined ? cast0 : L.castMap; + const item = item0 !== undefined ? item0 : L?.itemOf(e) ?? null; + const plan = threadReadPlan(manifest, e, { red, map, cast, item, overrides, parents, skip, quoted, linked, readSeen, voice, engine, speed }); const parts = readParts(plan); const cacheDir = path.join(project.dir, ...PARTS_CACHE.split("/")); const wavOf = (p) => path.join(cacheDir, `${p.key}.wav`); @@ -353,7 +369,7 @@ export async function threadTake(project, e, opts = {}) { emit("note", { message: `part ${n + 1}/${todo.length} (${p.role}, ${p.engine === plan.engine ? p.voice : `${p.engine}:${p.voice}`}): asking the editor…` }); await writeFile(path.join(cacheDir, `${p.key}.txt`), p.text); try { - const { jobId } = await askTts({ text: p.text, engine: p.engine ?? plan.engine, voice: p.voice, out: wavOf(p) }, { ...(editor ? { editor } : {}), emit }); + const { jobId } = await askTts({ text: p.text, engine: p.engine ?? plan.engine, voice: p.voice, out: wavOf(p), ...(typeof p.speed === "number" ? { speed: p.speed } : {}) }, { ...(editor ? { editor } : {}), emit }); if (jobId) jobs.push(jobId); } catch (err) { throw new ThreadReadError(`part ${p.role} "${p.text.slice(0, 60)}${p.text.length > 60 ? "…" : ""}" (${p.voice}) was not synthesized: ${err instanceof Error ? err.message : err} -- the ${fresh + base.cached} part(s) made are cached; run it again`); @@ -397,7 +413,7 @@ export async function threadTake(project, e, opts = {}) { parts: meta, ...(plan.slurs ? { slurs: plan.slurs } : {}), ...(plan.lexicon.length ? { lexicon: plan.lexicon } : {}), - read: readRecordOf({ parents, skip, quoted, linked, readSeen, overrides, voice }), + read: readRecordOf({ parents, skip, quoted, linked, readSeen, overrides, voice, speed }), }; const patch = { addTake: take, ...(plan.script ? { script: plan.script } : {}) }; const { result, editNotes } = await withEditNotes(project, async () => updatePostNarration(project.dir, e.id, patch, { token: await manifestToken(project.dir) })); @@ -429,19 +445,19 @@ export async function threadCommand(project, e, o) { } throw err; } - const pieces = r.plan.pieces.map((p) => ({ role: p.role, handle: p.handle, date: p.date, voice: p.voice, engine: p.engine, from: p.from, words: p.text.split(/\s+/).filter(Boolean).length, ...(p.lexicon.length ? { lexicon: p.lexicon } : {}) })); + const pieces = r.plan.pieces.map((p) => ({ role: p.role, handle: p.handle, date: p.date, voice: p.voice, engine: p.engine, from: p.from, ...(p.speed !== undefined ? { speed: p.speed } : {}), ...(p.character ? { character: p.character } : {}), words: p.text.split(/\s+/).filter(Boolean).length, ...(p.lexicon.length ? { lexicon: p.lexicon } : {}) })); const guard = r.take ? await guardOf(project, e.id) : null; if (json) { out(JSON.stringify({ ok: true, id: e.id, upToDate: r.upToDate, dryRun: r.dryRun, engine: r.plan.engine, voice: r.plan.voice, pieces, skipped: r.plan.skipped, - parts: r.parts.map((p) => ({ role: p.role, voice: p.voice, engine: p.engine, key: p.key, cached: p.cached, text: p.text })), + parts: r.parts.map((p) => ({ role: p.role, voice: p.voice, engine: p.engine, ...(p.speed !== undefined ? { speed: p.speed } : {}), key: p.key, cached: p.cached, text: p.text })), fresh: r.fresh, cached: r.cached, jobs: r.jobs, lane: r.lane, ...(r.take ? { take: r.take, pick: r.result.narration?.pick ?? null, token: r.result.token, snapshot: r.result.snapshot ?? null, guard } : {}), }, null, 2)); return 0; } out(`${e.id}: a thread read of ${pieces.length} piece(s), ${r.parts.length} part(s) (${r.cached} cached${r.dryRun ? `, ${r.parts.length - r.cached} to synthesize` : ""})`); - for (const p of pieces) out(` ${p.role.padEnd(9)} ${(p.engine !== r.plan.engine ? `${p.engine}:${p.voice}` : p.voice).padEnd(6)} ${p.from === "cast" ? "(cast) " : ""}${p.handle ? `@${p.handle}` : ""}${p.date ? ` ${p.date.slice(0, 16)}` : ""} ${p.words} words${p.lexicon ? ` (said: ${p.lexicon.map((x) => `${x.word} -> ${x.say}`).join(", ")})` : ""}`); + for (const p of pieces) out(` ${p.role.padEnd(9)} ${(p.engine !== r.plan.engine ? `${p.engine}:${p.voice}` : p.voice).padEnd(6)} ${p.from === "cast" ? "(cast) " : p.from === "item" ? `(the item's character: ${p.character}) ` : p.from === "project" && p.character ? `(this video's character: ${p.character}) ` : ""}${p.speed !== undefined ? `×${p.speed} ` : ""}${p.handle ? `@${p.handle}` : ""}${p.date ? ` ${p.date.slice(0, 16)}` : ""} ${p.words} words${p.lexicon ? ` (said: ${p.lexicon.map((x) => `${x.word} -> ${x.say}`).join(", ")})` : ""}`); for (const s of r.plan.skipped) out(` (not read: ${s.role}${s.id ? ` ${s.id}` : ""} -- ${s.why})`); if (r.upToDate) { out(` up to date: the picked take already reads this, in these voices (--force makes it again)`); diff --git a/umtool/lib/report/postsCli.mjs b/umtool/lib/report/postsCli.mjs @@ -80,6 +80,9 @@ const SAY_LINES = [ " masked slur and a redacted word are never replaced. stale: the picked reads that still say one the old way.", " umtool posts voices <project> [ls] | set <handle|*> <voice> | remove <handle|*> [--json]", " THE VOICE MAP (narration/voices.json): the voice a thread read gives each author (* everyone else; default leo).", + " umtool posts character <project> <item> [<character> | --clear] [--json]", + " THE CHARACTER ONE ITEM's OWN READ IS MADE WITH: one of this video's own (umtool cast project <p>) or the cast's;", + " its presets answer before its author's handle does. --clear: by its handle again (posts character --help).", ]; export const POSTS_USAGE = [ @@ -523,6 +526,15 @@ export async function postsCommand(args, { root = REPORTS_ROOT, out = (s) => con throw e?.name === "RereadError" || e?.name === "YellError" ? new CliError(e.message) : e; }); } + if (verb === "character") { + // A post item's own character (postNarrationCli.mjs characterCommand; cast.mjs). + const { CHARACTER_USAGE, characterCommand } = await import("./postNarrationCli.mjs"); + if (!projectArg || flags.has("--help") || words.length < 3) { + err(CHARACTER_USAGE); + return 2; + } + return await characterCommand(await projectOf(projectArg, root), words.slice(2), { flags, json, out }); + } if (verb === "narrate") { const { NARRATE_USAGE, narrateCommand } = await import("./postNarrationCli.mjs"); if (!projectArg || flags.has("--help")) { diff --git a/umtool/lib/report/readVoice.mjs b/umtool/lib/report/readVoice.mjs @@ -1,22 +1,24 @@ // THE VOICE A POST ITEM's OWN READ IS SAID IN (a single post's take: `umtool posts narrate <p> <item> --take`, the // bench's Re-take), through the SAME function a thread read asks for his piece (post-say.mjs resolvePieceVoice): the -// read's own voice (--voice, the bench's voice field), the project's voice map, the CAST, the narrator's (the item's -// own `narration.voice`, else the cut's). So a post read alone and the same post read with its thread agree. +// read's own voice (--voice, the bench's voice field), the item's own character (`narration.character`), the +// project's characters and voice map, the CAST, the narrator's (the item's own `narration.voice`, else the cut's). So +// a post read alone and the same post read with its thread agree. // // Plain ESM. import { postNarrationKnobs } from "umtool-report-to-video/post-narration"; import { resolvePieceVoice, voiceRefOf } from "umtool-report-to-video/post-say"; /** - * `{ engine, voice, from }` for post item `e`'s own read -- `from` "override", "project", "cast", "narrator". - * `map` and `cast` are read from the project when not given (a broken voice map reads as none here: the read is not - * refused for it; `umtool posts voices` says what is wrong with it). + * `{ engine, voice, from, speed?, character? }` for post item `e`'s own read -- `from` "override", "item", "project", + * "cast", "narrator"; `speed` and `character` the preset's that answered (a character's `synthetic.speed`, its id). + * `map`, `cast` and `item` (voiceSourceOf's layers) are read from the project when not given (characterLayers.mjs; a + * broken voice map reads as none here: the read is not refused for it; `umtool posts voices` says what is wrong). * * @param {{ dir: string }} project * @param {Record<string, any>} e - * @param {{ render?: Record<string, any>, engine?: string | null, voice?: string | null, map?: Record<string, string>, cast?: Record<string, string> }} [o] + * @param {{ render?: Record<string, any>, engine?: string | null, voice?: string | null, map?: Record<string, any>, cast?: Record<string, any>, item?: any }} [o] */ -export async function itemReadVoice(project, e, { render = {}, engine = null, voice = null, map = undefined, cast = undefined } = {}) { +export async function itemReadVoice(project, e, { render = {}, engine = null, voice = null, map = undefined, cast = undefined, item = undefined } = {}) { const k = postNarrationKnobs(e, render); const eng = engine ?? e.narration?.engine ?? k.engine; const narrator = e.narration?.voice ?? k.voice; @@ -24,9 +26,11 @@ export async function itemReadVoice(project, e, { render = {}, engine = null, vo const ref = voiceRefOf(voice, eng) ?? { engine: eng, voice: String(voice) }; return { engine: engine ?? ref.engine ?? eng, voice: ref.voice, from: "override" }; } - const m = map !== undefined ? map : await (await import("./postSay.mjs")).readVoiceMap(project.dir).catch(() => ({})); - const c = cast !== undefined ? cast : await (await import("./postThreadRead.mjs")).projectCastMap(project.dir).catch(() => ({})); - const r = resolvePieceVoice({ handle: e.handle ?? null, role: "post" }, { map: m, cast: c, self: e.handle ?? null, narrator, engine: eng }); + const L = map !== undefined && cast !== undefined && item !== undefined ? null : await (await import("./characterLayers.mjs")).readLayers(project.dir).catch(() => null); + const m = map !== undefined ? map : L?.map ?? {}; + const c = cast !== undefined ? cast : L?.castMap ?? {}; + const it = item !== undefined ? item : L?.itemOf(e) ?? null; + const r = resolvePieceVoice({ handle: e.handle ?? null, role: "post" }, { map: m, cast: c, item: it, self: e.handle ?? null, narrator, engine: eng }); // An engine asked for outright that the resolved voice is not of: the narrator's voice in it. if (engine && r.engine !== engine) return { engine, voice: narrator, from: "narrator" }; return r;