Archilyzer · Source

archilyzer

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

commit 065ed70ea3a9b050a08fba4abfffa177e533396a
parent 6e2572c1b95c80db6c73064023ed282acf53edc6
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Fri,  6 Nov 2026 21:53:14 -0500

umtool cast: the CLI -- a project's characters and their drift, auditions scored against the real voice, use/reread, a recording made a character's read, the lint's guard

umtool cast ls|add|set|rm|undo the characters; project <p> each character's voice now and where
it comes from, its picked reads in another voice (drift), its real-voice reference; audition
<character> --voices a,b,c: one line read by each candidate through the editor's tts op (a
re-audition is a cache hit), levelled to -20 LUFS in <p>/narration/auditions/, scored for
closeness to the character's real voice (speakers.json, speaker-check's TitaNet arithmetic);
use <p> <character> <voice> [--everywhere] the project's map or the cast (the project's own
override then removed) with the re-reads it asks for; reread runs them.

posts narrate <p> <item> --recording <file> [--as <character>]: kept as recorded (the original),
cleaned by voice-enhance when the editor can, converted by voice-convert to the character's STOCK
voice -- each a new take, the last picked, the disclosure said.

umtool lint: a cast character read in another voice than now is a warning; a cast voice the
project overrides on purpose a note.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
Mumtool/bin/umtool.mjs | 7+++++++
Aumtool/lib/report/cast.test.mjs | 281+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/castAudition.mjs | 294+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/castCli.mjs | 403+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/castProject.mjs | 160+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/lintCli.mjs | 31+++++++++++++++++++++++++++++--
Mumtool/lib/report/postNarrationCli.mjs | 87++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Mumtool/lib/report/postsCli.mjs | 2+-
8 files changed, 1259 insertions(+), 6 deletions(-)

diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs @@ -15,6 +15,7 @@ // umtool show <project> [--json] // umtool check [<project> | --all] [--json] exit 1 on anything blocking // umtool links <project> [--json] [--fix] do the clip QRs open on their sites (out/links.json) +// umtool cast [ls|add|set|rm|undo|project|audition|use|reread] … the characters' voices across projects (castCli.mjs) // umtool speaker-check <project> [--clip <id> …] [--set 'Name=…'] [--list] which named voice each clip is (speaker-check.json) // umtool check-joins <project> --take <id> [--json] [--all] do the post joins of a rendered take carry on, or jump // umtool link-policy <project> [--via <site>] [--direct a,b] [--clear] [--fix] cite via site X; these channels direct @@ -864,6 +865,10 @@ function usage() { " umtool check [<project>] [--json] exit 1 on anything blocking", " umtool links <project> [--json] [--fix] do the clip QRs open on their sites? (corpus.json -> slugToPage", " -> the shard's record; polite, cached; out/links.json, which check reads); exit 1 when one is dead", + " umtool cast [ls] | add <id> --name … --voice <engine:voice> [--handles a,b] | set <id> … | rm <id> | undo", + " | project <p> | audition <character> --voices a,b,c [--project <p>] [--text …] | use <p> <character> <voice>", + " [--everywhere] | reread <p> <character> the CAST: characters' stock voices across projects (cast.json), a", + " project's characters and their drift, an audition of candidate voices (scored against the real voice)", " umtool speaker-check <project> [--clip <id> …] [--json] which of the project's named voices (speakers.json) each", " clip is: TitaNet-small, local -> speaker-check.json; --set 'Name=<clip>,<channel>/<id>,channel:<slug>' / --remove / --list", " umtool check-joins <project> --take <id> [--json] [--all] [--limit <n>] every boundary of the take's master where the", @@ -1175,6 +1180,8 @@ const COMMANDS = { vertical: async () => process.exit(await (await import("../lib/report/verticalCli.mjs")).verticalCommand(argv.slice(argv.indexOf("vertical") + 1))), // Do the QR links open on their sites (UI notes #8): lib/report/linksCli.mjs. links: async () => process.exit(await (await import("../lib/report/linksCli.mjs")).linksCommand(argv.slice(argv.indexOf("links") + 1))), + // The cast: characters' voices across projects, auditions, a project's voices (operator, 6 Nov): lib/report/castCli.mjs. + cast: async () => process.exit(await (await import("../lib/report/castCli.mjs")).castCommand(argv.slice(argv.indexOf("cast") + 1))), // Which named voice each clip is (UI notes #15): lib/report/speakerCheck.mjs. "speaker-check": async () => process.exit(await (await import("../lib/report/speakerCheck.mjs")).speakerCheckCommand(argv.slice(argv.indexOf("speaker-check") + 1))), // Do a rendered take's post joins carry on (operator, 4 Nov, mid-7): lib/report/checkJoinsCli.mjs. diff --git a/umtool/lib/report/cast.test.mjs b/umtool/lib/report/cast.test.mjs @@ -0,0 +1,281 @@ +// The cast across projects (castStore.mjs, castCli.mjs, castProject.mjs, castAudition.mjs): its one writer (a token, +// undo points, a broken file never overwritten), the CLI, a project's characters and their drift, `use` (the +// project's map or the cast) and the re-reads it asks for, every read agreeing (a single take and a thread read +// through the cast, a cast voice of another engine synthesized by it), an audition (cached, levelled, scored for +// closeness to the real voice with the test kit's fake embedder), a recording made a character's read, and the +// lint's guard. No editor: the tts and voice ops are stubs; every project is a temp dir. +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises"; +import { existsSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +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, readCast, readCastFile, undoCast } from "./castStore.mjs"; +import { castCommand } from "./castCli.mjs"; +import { rereadPlan, threadArgvOf } from "./castProject.mjs"; +import { auditionKey, candidatesOf, characterLines, STOCK_LINE } from "./castAudition.mjs"; +import { makeTake, importRecording } from "./postNarrationCli.mjs"; +import { threadReadPlan, threadTake } from "./postThreadRead.mjs"; +import { castProblems } from "./lintCli.mjs"; +import { castVoiceMap } from "umtool-report-to-video/cast"; + +const ROOT = await mkdtemp(path.join(tmpdir(), "umtool-cast-")); +after(() => rm(ROOT, { recursive: true, force: true })); +const FAKE_EMBED = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "..", "..", "common", "testing", "audio", "fakeSpeakerEmbed.mjs"); +process.env.VOICE_MATCH_PYTHON = process.execPath; +process.env.VOICE_MATCH_SCRIPT = FAKE_EMBED; +process.env.VOICE_MATCH_MODEL = "fake.onnx"; +const ff = (args) => execFileSync("ffmpeg", ["-v", "error", "-y", ...args]); +const wavOf = async (file, voice, seconds = 2.5) => { + await mkdir(path.dirname(file), { recursive: true }); + await writeFile(file, encodeWav16(withSilence(syntheticVoice({ ...voice, seconds }), { before: 0.3, after: 0.3 }))); +}; +const io = () => { + const lines = []; + return { lines, opts: { reportsRoot: ROOT, log: (s) => lines.push(s), err: (s) => lines.push(s) }, text: () => lines.join("\n"), json: () => JSON.parse(lines.join("\n")) }; +}; +const cast = async (args, extra = {}) => { + const o = io(); + const code = await castCommand(args, { ...o.opts, ...extra }); + return { code, ...o }; +}; + +/** A tts stub: `out` written as VOICE_A for am_michael and zac, VOICE_B for any other. */ +const stubAsk = (asked) => async (body) => { + asked.push(body); + await wavOf(body.out, ["am_michael", "zac"].includes(body.voice) ? VOICE_A : VOICE_B, 1.5); + return { jobId: `job-${asked.length}`, result: { wav: body.out, engine: body.engine, voice: body.voice, disclosure: `Narration: synthetic voice (${body.engine} · ${body.voice})` } }; +}; + +// THE PROJECT: two clips of "Host" (VOICE_A, the real voice), post items by @hostman (two, one a thread answering +// @guest), and the guest's own item. +const DIR = path.join(ROOT, "voices"); +const CH = path.join(ROOT, "channels"); +{ + const timeline = []; + for (const id of ["k01", "k02"]) { + const d = path.join(CH, "chan", "data", `v${id}`); + await mkdir(path.join(d, "clips"), { recursive: true }); + await writeFile(path.join(d, "transcript.cues.json"), JSON.stringify({ id: `v${id}`, cues: [{ start: 102.5, end: 104, text: "slow news day" }] })); + await wavOf(path.join(d, "clips", "x.wav"), VOICE_A, 2.5); + ff(["-i", path.join(d, "clips", "x.wav"), "-af", "adelay=2000:all=1,apad=pad_dur=3.5", "-c:a", "aac", path.join(d, "clips", "100.00-108.00.mp4")]); + await rm(path.join(d, "clips", "x.wav")); + timeline.push({ type: "clip", id, channel: "chan", video: `v${id}`, start: 100, end: 108, cutStart: 102.5, cutEnd: 104, cite: 102.5, quote: "slow news day" }); + } + const post = (id, handle, o = {}) => ({ type: "post", id: `p-${id}`, post: `hostx/${id}`, platform: "x", author: handle === "hostman" ? "Host Man" : "The Guest", handle, date: `2026-10-30T1${id}:00:00.000Z`, text: `words of ${id} from ${handle}.`, ...o }); + timeline.push( + post("1", "hostman", { narration: { script: "Host's first line, read aloud.", takes: [{ file: "narration/posts/1/take-1.orpheus-zac.wav", engine: "orpheus", voice: "zac", seconds: 1.5, script: "Host's first line, read aloud." }], pick: 0 } }), + post("2", "hostman", { 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", { narration: { script: "The guest's own line." } }), + ); + await mkdir(DIR, { recursive: true }); + await writeFile(path.join(DIR, "video.manifest.json"), JSON.stringify({ + schemaVersion: 1, slug: "voices", title: "Voices", kind: "report-video", provenance: { channelsDir: "../channels", channelSlug: "chan" }, + render: { width: 1920, height: 1080, fps: 30, palette: { bg: "#000000", fg: "#ffffff", muted: "#888888", accent: "#c8752a" } }, timeline, + }, null, 2)); + await wavOf(path.join(DIR, "narration", "posts", "1", "take-1.orpheus-zac.wav"), VOICE_A, 1.5); + await writeFile(path.join(DIR, "speakers.json"), JSON.stringify({ speakers: [{ name: "Host", clips: ["k01", "k02"] }] })); +} +const project = { id: "voices", dir: DIR }; +const manifest = async () => JSON.parse(await readFile(path.join(DIR, "video.manifest.json"), "utf8")); + +test("the store: one writer, a stale token refused, undo points, a broken file never overwritten", async () => { + const file = path.join(ROOT, "store", ".umtool", "cast.json"); + const r0 = await readCastFile(file); + assert.equal(r0.exists, false); + const a = await castWrite(file, (chars) => chars.push({ id: "a", name: "A", handles: ["a"], voice: "kokoro:am_adam" }), { what: "add a" }); + await assert.rejects(castWrite(file, (chars) => chars.push({ id: "b", name: "B", handles: [], voice: "kokoro:am_echo" }), { token: "stale" }), (e) => e instanceof CastError && e.status === 409); + await castWrite(file, (chars) => { chars[0].voice = "orpheus:zac"; }, { token: a.token, what: "a reads zac" }); + await assert.rejects(castWrite(file, (chars) => { chars[0].voice = "/tmp/me.wav"; }), /STOCK voice/); + assert.equal((await readCastFile(file)).cast.characters[0].voice, "orpheus:zac"); + const u = await undoCast(file); + assert.equal(u.undone, "a reads zac"); + assert.equal((await readCastFile(file)).cast.characters[0].voice, "kokoro:am_adam"); + await undoCast(file); + assert.deepEqual((await readCastFile(file)).cast.characters, []); + await assert.rejects(undoCast(file), /nothing to undo/); + await writeFile(file, "{ not json"); + const broken = await readCastFile(file); + assert.match(broken.error, /not JSON/); + await assert.rejects(castWrite(file, () => {}), /fix the file first/); + assert.equal(await readFile(file, "utf8"), "{ not json"); +}); + +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"] }); + r = await cast(["add", "hostman", "--name", "Again", "--voice", "orpheus:zac"]); + assert.equal(r.code, 1); + assert.match(r.text(), /in the cast already/); + r = await cast(["add", "me", "--name", "Me", "--voice", "seedvc:/home/me.wav"]); + assert.equal(r.code, 1); + assert.match(r.text(), /STOCK voice/); + r = await cast(["add", "me", "--name", "Me", "--voice", "kokoro:bm_george", "--narrator", "--convert-engine", "seed-vc"]); + assert.equal(r.code, 0, r.text()); + r = await cast(["set", "me", "--note", "the operator", "--add-handle", "operator"]); + assert.equal(r.code, 0, r.text()); + r = await cast(["ls", "--json"]); + assert.deepEqual(r.json().characters.map((c) => [c.id, c.voice, c.handles.join(",")]), [["hostman", "orpheus:zac", "hostman"], ["me", "kokoro:bm_george", "operator"]]); + assert.equal(r.json().characters[1].narrator, true); + r = await cast(["rm", "me"]); + assert.equal(r.code, 0); + r = await cast(["undo"]); + assert.match(r.text(), /undone: rm me/); + assert.equal((await readCast(ROOT)).cast.characters.length, 2); + assert.equal(castFile(ROOT), path.join(ROOT, ".umtool", "cast.json")); +}); + +test("every read agrees: a single take and a thread read ask the same layers -- a cast voice of another engine is that engine's", async () => { + const m = await manifest(); + const asked = []; + // The cast says hostman reads zac (orpheus); the project's map nothing: his single take is zac. + const e1 = m.timeline.find((e) => e.id === "p-1"); + const t1 = await makeTake(project, e1, { render: m.render, ask: stubAsk(asked), redaction: null }); + assert.deepEqual([t1.take.engine, t1.take.voice], ["orpheus", "zac"]); + // The cast moves him to Kokoro: the next single take, and his piece of a thread read, are Kokoro's. + await castWrite(castFile(ROOT), (chars) => { chars.find((c) => c.id === "hostman").voice = "kokoro:am_michael"; }); + const e1b = (await manifest()).timeline.find((e) => e.id === "p-1"); + const t2 = await makeTake(project, e1b, { render: m.render, ask: stubAsk(asked), redaction: null }); + assert.deepEqual([t2.take.engine, t2.take.voice], ["kokoro", "am_michael"]); + assert.match(t2.take.file, /take-\d+\.kokoro-am_michael\.wav$/); + const e2 = m.timeline.find((e) => e.id === "p-2"); + const castMap = castVoiceMap((await readCast(ROOT)).cast); + const plan = threadReadPlan(m, e2, { cast: castMap, map: { guest: "tara" } }); + assert.deepEqual(plan.pieces.map((p) => [p.role, p.engine, p.voice, p.from]), [["parent:0", "orpheus", "tara", "project"], ["post", "kokoro", "am_michael", "cast"]]); + assert.equal(plan.engine, "kokoro", "the read's engine is his piece's"); + asked.length = 0; + const r = await threadTake(project, e2, { manifest: m, red: null, map: { guest: "tara" }, ask: stubAsk(asked), lanes: null }); + assert.deepEqual(asked.map((b) => [b.engine, b.voice]), [["orpheus", "tara"], ["kokoro", "am_michael"]], "each part asked of its own engine"); + assert.deepEqual(r.take.parts.map((p) => [p.role, p.engine, p.voice]), [["parent:0", "orpheus", "tara"], ["post", "kokoro", "am_michael"]]); + const { postNarrationDisclosure } = await import("umtool-report-to-video/post-narration"); + const after = (await manifest()).timeline.find((e) => e.id === "p-2"); + assert.equal(postNarrationDisclosure(after), "Narration: synthetic voices (Orpheus · tara; Kokoro-82M · am_michael)"); + // Up to date: the same read again asks nothing. + const again = await threadTake(project, after, { red: null, map: { guest: "tara" }, ask: stubAsk(asked), lanes: null }); + assert.equal(again.upToDate, true); +}); + +test("cast project: each character's voice now and where it comes from, its drift, its reference; use and reread", async () => { + // p-1's picked take is the latest (kokoro am_michael); pick the first (orpheus zac) again: drift. + const { updatePostNarration, manifestToken } = await import("./manifest.mjs"); + await updatePostNarration(DIR, "p-1", { pick: 0 }, { token: await manifestToken(DIR) }); + let r = await cast(["project", "voices", "--json"]); + assert.equal(r.code, 0, r.text()); + const v = r.json(); + const host = v.characters.find((c) => c.key === "hostman"); + assert.equal(host.voice.spec, "kokoro:am_michael"); + assert.equal(host.voice.from, "cast"); + assert.equal(host.speaker, "Host"); + assert.deepEqual([host.items, host.context], [2, 0]); + assert.deepEqual(host.drift.map((d) => [d.id, d.reads, d.want]), [["p-1", "orpheus:zac", "kokoro:am_michael"]]); + assert.ok(host.lines.some((l) => l.text === "Host's first line, read aloud.")); + const guest = v.characters.find((c) => c.key === "@guest"); + assert.deepEqual([guest.items, guest.context, guest.voice.from], [1, 1, "narrator"]); + assert.equal(guest.contextVoice.spec, "orpheus:leo"); + // The lint's guard: the drift a warning, nothing overridden yet. + let g = await castProblems(await manifest(), project, ROOT); + assert.equal(g.warnings.length, 1); + assert.match(g.warnings[0], /@hostman \(hostman\) reads in orpheus:zac -- now kokoro:am_michael \(the cast\): umtool cast reread voices hostman/); + // use, for this project: the map; the re-reads it asks for. + r = await cast(["use", "voices", "@guest", "orpheus:leah", "--json"]); + assert.equal(r.code, 0, r.text()); + assert.equal(r.json().scope, "project"); + assert.deepEqual(JSON.parse(await readFile(path.join(DIR, "narration", "voices.json"), "utf8")), { guest: "orpheus:leah" }); + assert.deepEqual(r.json().reread.map((x) => x.id), ["p-2"], "the thread read says the guest in tara"); + assert.deepEqual(r.json().reread[0].argv, ["posts", "narrate", "voices", "p-2", "--take", "--thread"]); + // A project override of a cast voice is a note, not a warning. + r = await cast(["use", "voices", "hostman", "kokoro:am_onyx", "--json"]); + g = await castProblems(await manifest(), project, ROOT); + assert.equal(g.notes.length, 1); + assert.match(g.notes[0], /@hostman \(hostman\) reads in kokoro:am_onyx in this project -- the cast says kokoro:am_michael \(an override on purpose/); + // --everywhere: the cast, and the project's own override goes. + r = await cast(["use", "voices", "hostman", "kokoro:am_michael", "--everywhere", "--json"]); + assert.equal(r.code, 0, r.text()); + assert.deepEqual(r.json().removed, ["hostman"]); + assert.deepEqual(JSON.parse(await readFile(path.join(DIR, "narration", "voices.json"), "utf8")), { guest: "orpheus:leah" }); + assert.deepEqual(r.json().reread.map((x) => x.id), ["p-1"]); + // --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" }); + // 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"]); +}); + +test("rereadPlan: a thread read's own options kept, the changed author's overrides dropped; a conversion is skipped", () => { + assert.deepEqual(threadArgvOf({ kind: "thread", parents: "all", skip: ["5"], quoted: false, voiceFor: { guest: "dan", other: "leo" }, voice: "zac" }, { handles: ["guest"], author: "hostman" }), + ["--parents", "all", "--skip-parent", "5", "--no-quoted", "--voice-for", "other=leo", "--voice", "zac"]); + assert.deepEqual(threadArgvOf({ kind: "thread", voice: "zac" }, { handles: ["hostman"], author: "HostMan" }), []); + const m = { timeline: [{ type: "post", id: "p-9", handle: "x", narration: { takes: [{ file: "a.wav", read: { kind: "thread", parents: "1" } }], pick: 0 } }] }; + const plan = rereadPlan("p", m, [{ id: "p-9", handle: "x", role: "post", reads: "orpheus:zac", want: "kokoro:am_michael", kind: "tts", thread: true }, { id: "p-8", handle: "x", role: "post", kind: "converted", thread: false }], ["x"]); + assert.deepEqual(plan.items[0].argv, ["posts", "narrate", "p", "p-9", "--take", "--thread", "--parents", "1"]); + assert.equal(plan.skipped[0].id, "p-8"); +}); + +test("an audition: candidates checked, synthesized once, levelled, scored for closeness to the real voice", async () => { + assert.throws(() => candidatesOf(["/home/me/voice.wav"]), /never a candidate/); + assert.throws(() => candidatesOf(["a", "b", "c", "d", "e", "f", "g"].map((v) => `kokoro:${v}`)), /at most 6/); + assert.deepEqual(candidatesOf(["kokoro:am_michael,orpheus:zac", "am_onyx"]).map((c) => [c.spec, c.weight]), [["kokoro:am_michael", "fast"], ["orpheus:zac", "heavy"], ["kokoro:am_onyx", "fast"]]); + assert.deepEqual(characterLines(await manifest(), ["hostman"]).map((l) => l.item), ["p-1", "p-2"]); + const asked = []; + let r = await cast(["audition", "hostman", "--project", "voices", "--voices", "kokoro:am_michael,kokoro:bm_george", "--json"], { ask: stubAsk(asked), lanes: null }); + assert.equal(r.code, 0, r.text()); + const a = r.json(); + assert.equal(a.text, "Host's first line, read aloud."); + assert.equal(a.from, "item:p-1"); + assert.equal(a.speaker, "Host"); + assert.equal(a.reference, "narration/auditions/ref-host.wav"); + assert.ok(existsSync(path.join(DIR, "narration", "auditions", "ref-host.wav"))); + const [mich, geo] = a.candidates; + assert.equal(mich.key, auditionKey("kokoro", "am_michael", a.text)); + assert.ok(mich.score > geo.score, `the candidate in the host's voice is closer (${mich.score} vs ${geo.score})`); + for (const c of a.candidates) { + assert.ok(existsSync(path.join(DIR, c.rel))); + assert.ok(Math.abs(c.lufs - -20) < 2.5, `levelled to -20 LUFS (${c.lufs})`); + } + assert.equal(asked.length, 2); + // Again: nothing asked, the scores kept. + r = await cast(["audition", "hostman", "--project", "voices", "--voices", "kokoro:am_michael,kokoro:bm_george", "--no-score", "--json"], { ask: stubAsk(asked), lanes: null }); + assert.equal(asked.length, 2, "a re-audition is a cache hit"); + assert.equal(r.json().candidates[0].score, mich.score); + // A stock line for a character with no line; an author not in the cast by @handle; nothing to score against. + r = await cast(["audition", "@guest", "--project", "voices", "--voices", "kokoro:af_heart", "--text", "Hello there.", "--json"], { ask: stubAsk(asked), lanes: null }); + assert.equal(r.code, 0, r.text()); + assert.match(r.json().why, /no reference voice/); + assert.equal(STOCK_LINE.length > 20, true); + const files = await readdir(path.join(DIR, "narration", "auditions")); + assert.ok(!files.some((f) => f.endsWith(".raw.wav")), "no raw file left behind"); +}); + +test("a recording made a character's read: kept, cleaned (when the editor can), converted to its stock voice", async () => { + const rec = path.join(ROOT, "my-read.wav"); + await wavOf(rec, VOICE_B, 2); + const askOp = async (route, body) => { + if (route.endsWith("voice-enhance")) { + const e = new Error("the editor has no engine for /api/ops/voice-enhance yet (not installed: DeepFilterNet)"); + e.name = "OpNotInstalled"; + throw e; + } + await wavOf(body.out, VOICE_A, 2); + return { jobId: "conv-1", result: { engine: body.engine ?? "openvoice", voice: body.voice } }; + }; + const e = (await manifest()).timeline.find((x) => x.id === "p-3"); + const r = await importRecording(project, e, rec, { ask: askOp }); + assert.equal(r.character.id, "guest", "the post's author in the cast"); + assert.deepEqual(r.takes.map((t) => t.step), ["recorded", "converted to kokoro:af_heart"]); + assert.match(r.notes[0], /not cleaned: .*not installed/); + const after = (await manifest()).timeline.find((x) => x.id === "p-3"); + const picked = after.narration.takes[after.narration.pick]; + assert.equal(picked.file, r.picked); + assert.equal(picked.voice, "af_heart"); + assert.deepEqual(picked.steps[0], { ...picked.steps[0], op: "convert", voice: "kokoro:af_heart" }); + assert.equal(after.narration.takes[0].engine, "recorded", "the original kept"); + assert.equal(r.disclosure, "Narration: voice converted to a synthetic voice (openvoice · kokoro:af_heart)"); + await assert.rejects(importRecording(project, e, rec, { as: "nobody", ask: askOp }), /no such character/); +}); diff --git a/umtool/lib/report/castAudition.mjs b/umtool/lib/report/castAudition.mjs @@ -0,0 +1,294 @@ +// AN AUDITION (operator, 6 Nov 2026: "in UI alone be able to try rendering different ones to compare"): ONE LINE +// read by 2-6 candidate stock voices, each synthesized by the EDITOR (its tts op, a job on its queue: the GPU and the +// heavy slot are its to arbitrate -- Orpheus pins ~8.5 GB, Kokoro is fast), kept beside the project and brought to +// ONE LOUDNESS so they compare by ear, not by level; and each scored for its CLOSENESS TO THE CHARACTER'S REAL VOICE +// when the project names one (speakers.json, as `umtool speaker-check` reads it: TitaNet-small, local) -- a +// reference to compare with, NEVER a target. +// +// <project>/narration/auditions/<key>.wav the candidate, -20 LUFS, 48 kHz mono (key: sha1(engine|voice|text)) +// <project>/narration/auditions/<key>.json { key, engine, voice, text, seconds, lufs, at, jobId, disclosure } +// <project>/narration/auditions/ref-<speaker>.wav an excerpt of the real voice, the same loudness (to listen to) +// <project>/narration/auditions/scores.json { version, rows: { "<key>|<speaker>": { score, speaker, at, model } } } +// +// Without a project the candidates are kept in <REPORTS_ROOT>/.umtool/cast/auditions/ and not scored. The same line +// in the same voice is never asked twice: a re-audition is a cache hit. +// +// Plain ESM: the CLI runs under bare node. +import { execFile } from "node:child_process"; +import { createHash } from "node:crypto"; +import { mkdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { promisify } from "node:util"; +import { draftScript, scriptParts } from "umtool-report-to-video/post-narration"; +import { cardText } from "umtool-report-to-video/post-item"; +import { handleKey, voiceRefOf, voiceSpecOf } from "umtool-report-to-video/post-say"; +import { ENGINE_WEIGHT, speakerFor } from "umtool-report-to-video/cast"; +import { REPORTS_ROOT } from "../paths.mjs"; + +const execFileP = promisify(execFile); +const FFMPEG = () => process.env.FFMPEG_BIN ?? "ffmpeg"; +const r3 = (v) => Math.round(v * 1000) / 1000; +const str = (v) => (typeof v === "string" ? v : ""); + +/** Where a project's auditions are kept (relative to it). */ +export const AUDITION_DIR = "narration/auditions"; +export const AUDITION_SCORES = `${AUDITION_DIR}/scores.json`; +/** The level every candidate (and the reference) is brought to. */ +export const AUDITION_LUFS = -20; +/** At most this many candidates in one audition; at most this many characters in its line. */ +export const AUDITION_MAX = 6; +export const AUDITION_TEXT_MAX = 400; +/** The line read when the character has none of its own in the project. */ +export const STOCK_LINE = "Well, here's the thing. I said it before, and I'll say it again: you cannot make this stuff up."; +/** How long the reference excerpt of the real voice is, at most. */ +export const REFERENCE_SECONDS = 12; + +export class AuditionError extends Error { + constructor(message) { + super(message); + this.name = "AuditionError"; + } +} + +/** A candidate's cache key: sha1 of `engine|voice|text`, 20 hex. */ +export const auditionKey = (engine, voice, text) => createHash("sha1").update(`${engine}|${voice}|${text}`).digest("hex").slice(0, 20); + +/** The candidates as `[{ engine, voice, spec, weight }]` from `kokoro:am_michael,orpheus:zac` (a bare voice: `engine`). */ +export function candidatesOf(list, engine = "kokoro") { + const out = []; + for (const raw of (Array.isArray(list) ? list : [list]).flatMap((x) => String(x ?? "").split(",")).map((x) => x.trim()).filter(Boolean)) { + const ref = voiceRefOf(raw, engine); + if (!ref?.engine) throw new AuditionError(`"${raw}" is not a stock voice ("kokoro:am_michael", "orpheus:zac"): a file or a recording is never a candidate`); + const spec = voiceSpecOf(ref); + if (!out.some((c) => c.spec === spec)) out.push({ engine: ref.engine, voice: ref.voice, spec, weight: ENGINE_WEIGHT[ref.engine] ?? "fast" }); + } + if (!out.length) throw new AuditionError("--voices names the candidates: --voices kokoro:am_michael,kokoro:am_onyx,orpheus:zac"); + if (out.length > AUDITION_MAX) throw new AuditionError(`at most ${AUDITION_MAX} candidates in one audition (got ${out.length})`); + return out; +} + +/** A line cut to what an audition reads: its first part (post-narration.mjs scriptParts), at most AUDITION_TEXT_MAX at a sentence end. */ +export function auditionText(text) { + const first = scriptParts(str(text).trim())[0]?.text ?? str(text).trim(); + if (first.length <= AUDITION_TEXT_MAX) return first; + const cut = first.slice(0, AUDITION_TEXT_MAX); + const at = Math.max(cut.lastIndexOf(". "), cut.lastIndexOf("? "), cut.lastIndexOf("! ")); + return (at > 80 ? cut.slice(0, at + 1) : cut).trim(); +} + +/** + * THE CHARACTER's LINES in a project, pure: `[{ item, text, own }]` -- each post item of theirs (its script, else its + * words cleaned to be spoken), then each context post of theirs another item carries (its words). `handles` keyed + * as the map keys them. + */ +export function characterLines(manifest, handles) { + const hs = new Set((handles ?? []).map(handleKey).filter(Boolean)); + const lines = []; + for (const e of Array.isArray(manifest?.timeline) ? manifest.timeline : []) { + if (e?.type !== "post") continue; + if (hs.has(handleKey(e.handle))) { + const t = str(e.narration?.script).trim() || draftScript(cardText(e)).script; + if (t) lines.push({ item: e.id, text: auditionText(t), own: true }); + } + const ctx = [...(Array.isArray(e.parents) ? e.parents : []), ...(e.quoted ? [e.quoted] : []), ...(Array.isArray(e.links) ? e.links : [])]; + for (const p of ctx) { + if (!hs.has(handleKey(p?.handle))) continue; + const t = draftScript(str(p.paraphrase) || str(p.text)).script; + if (t) lines.push({ item: e.id, text: auditionText(t), own: false, context: str(p.id) || null }); + } + } + return lines.filter((l, i) => lines.findIndex((x) => x.text === l.text) === i); +} + +/** The folder an audition is kept in: the project's, else the cast's own. */ +export const auditionDirOf = (project, reportsRoot = REPORTS_ROOT) => + project ? path.join(project.dir, ...AUDITION_DIR.split("/")) : path.join(/* turbopackIgnore: true */ reportsRoot, ".umtool", "cast", "auditions"); + +const fileThere = async (f) => !!(await stat(f).catch(() => null))?.isFile(); + +/** Each candidate's record and file: `[{ ...candidate, key, file, rel, cached, meta }]`. */ +export async function auditionPlan(dir, candidates, text, { relBase = AUDITION_DIR } = {}) { + const out = []; + for (const c of candidates) { + const key = auditionKey(c.engine, c.voice, text); + const file = path.join(dir, `${key}.wav`); + const meta = await readFile(path.join(dir, `${key}.json`), "utf8").then((t) => JSON.parse(t), () => null); + out.push({ ...c, key, file, rel: `${relBase}/${key}.wav`, cached: !!meta && (await fileThere(file)), meta }); + } + return out; +} + +/** A sound brought to AUDITION_LUFS, 48 kHz mono (one loudnorm pass), `from` -> `to`; `from` removed when asked. */ +export async function levelTo(from, to, { start = null, seconds = null } = {}) { + const tmp = `${to}.tmp-${process.pid}.wav`; + await execFileP(FFMPEG(), [ + "-nostdin", "-v", "error", "-y", ...(start !== null ? ["-ss", String(start)] : []), "-i", from, ...(seconds !== null ? ["-t", String(seconds)] : []), + "-vn", "-af", `loudnorm=I=${AUDITION_LUFS}:TP=-2:LRA=11`, "-ar", "48000", "-ac", "1", "-c:a", "pcm_s16le", tmp, + ], { maxBuffer: 1 << 24 }); + await rename(tmp, to); +} + +/** + * SYNTHESIZE THE CANDIDATES not kept yet: each asked of the editor's tts op in turn (`ask`: askEditorTts's shape, the + * tests' to stub), levelled, its record written. With an Orpheus candidate to make the transcription lane is held + * while they are asked (only when it was not held; released after -- `lanes`, renderMode.mjs editorLanes' shape, or + * null: none; `hold: false` leaves it alone). Returns the plan with `fresh` and the editor's `jobs`. + */ +export async function synthesizeAuditions(dir, plan, text, { ask = null, editor = null, emit = () => {}, hold = true, lanes: lanes0 = undefined } = {}) { + await mkdir(dir, { recursive: true }); + const todo = plan.filter((c) => !c.cached); + const jobs = []; + let release = async () => {}; + if (hold && todo.some((c) => c.engine === "orpheus")) { + let lanes = lanes0; + if (lanes === undefined) { + const { editorLanes } = await import("./renderMode.mjs"); + const { editorConfig } = await import("./fetchWindows.mjs"); + lanes = editorLanes(editorConfig(process.env)); + } + try { + if (lanes && !(await lanes.isHeld("transcription"))) { + await lanes.hold("transcription"); + emit("note", { message: "the transcription lane: held while Orpheus reads, released after" }); + release = async () => { + await lanes.release("transcription").catch((err) => emit("note", { message: `the transcription lane could NOT be released (${err?.message ?? err}): pnpm ops lane --json '{"lane":"transcription","held":false}'` })); + }; + } + } catch (err) { + emit("note", { message: `the transcription lane: not held (${err instanceof Error ? err.message : err})` }); + } + } + try { + const askTts = ask ?? (await import("umtool-report-to-video/narrate-via-editor")).askEditorTts; + for (const [n, c] of todo.entries()) { + emit("audition", { phase: "ask", n: n + 1, of: todo.length, voice: c.spec, weight: c.weight }); + emit("note", { message: `${c.spec}${c.weight === "heavy" ? " (heavy: Orpheus)" : ""}: asking the editor (${n + 1}/${todo.length})…` }); + const raw = path.join(dir, `${c.key}.raw.wav`); + let res; + try { + res = await askTts({ text, engine: c.engine, voice: c.voice, out: raw }, { ...(editor ? { editor } : {}), emit }); + } catch (err) { + throw new AuditionError(`${c.spec} was not synthesized: ${err instanceof Error ? err.message : err} -- the candidates made are kept; run it again`); + } + if (!(await fileThere(raw))) throw new AuditionError(`the editor's job ${res?.jobId ?? "?"} finished but ${c.key}.raw.wav is not there`); + await levelTo(raw, c.file); + await rm(raw, { force: true }); + const { measureTake } = await import("./postNarrationCli.mjs"); + const m = await measureTake(c.file); + const meta = { + key: c.key, engine: c.engine, voice: c.voice, text, seconds: m.seconds, lufs: m.lufs, at: new Date().toISOString(), + ...(res?.jobId ? { jobId: res.jobId } : {}), ...(typeof res?.result?.disclosure === "string" ? { disclosure: res.result.disclosure } : {}), + }; + await writeFile(path.join(dir, `${c.key}.json`), `${JSON.stringify(meta, null, 1)}\n`); + c.meta = meta; + c.cached = true; + c.fresh = true; + if (res?.jobId) jobs.push(res.jobId); + } + } finally { + await release(); + } + return { plan, fresh: todo.length, jobs }; +} + +// --------------------------------------------------------------------------- +// The closeness to the real voice (speaker-check's arithmetic, on the candidates). +// --------------------------------------------------------------------------- + +/** The project's audition scores (`{ rows: {} }` with none). */ +export async function readAuditionScores(dir) { + try { + const j = JSON.parse(await readFile(path.join(dir, ...AUDITION_SCORES.split("/")), "utf8")); + return j && typeof j.rows === "object" && j.rows ? j : { version: 1, rows: {} }; + } catch { + return { version: 1, rows: {} }; + } +} + +const slug = (s) => str(s).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "") || "voice"; +/** The reference excerpt's file for a speaker (relative to the project). */ +export const referenceRelOf = (speaker) => `${AUDITION_DIR}/ref-${slug(speaker)}.wav`; + +/** + * The project's REFERENCE for a character: the speakers.json voice it goes by (cast.mjs speakerFor: its `speakers`, + * its name, its id, its handles), or null. + */ +export async function referenceFor(project, character) { + const { readSpeakers } = await import("./speakerCheck.mjs"); + const speakers = await readSpeakers(project.dir).catch(() => []); + return speakerFor(character, speakers); +} + +/** + * SCORE THE CANDIDATES against the character's real voice in the project: one run of the speaker check's scorer + * (common/lib/montage/speakerCheck.mjs runSpeakerCheck: TitaNet-small, local; the test kit's fake embedder under + * VOICE_MATCH_*) with the candidates as the clips to check and the one reference voice, and an excerpt of that voice + * kept to listen to. Returns `{ speaker, rows: { key: { score, ... } }, reference: rel | null, why? }`. + */ +export async function scoreAuditions(project, character, plan, { engineOpts = {}, emit = () => {} } = {}) { + const speaker = await referenceFor(project, character); + if (!speaker) return { speaker: null, rows: {}, reference: null, why: `no reference voice for ${character?.name ?? character?.id ?? "it"} in ${project.id}'s speakers.json (umtool speaker-check ${project.id} --set 'Name=<clip>,<channel>/<id>')` }; + const { readManifest, channelsDirFor, hasShadowChannels } = await import("../projects/report.mjs"); + const { planSpeakerCheck } = await import("./speakerCheck.mjs"); + const { runSpeakerCheck } = await import("yt-dlp-transcript-common/lib/montage/speakerCheck.mjs"); + const { DEFAULT_THRESHOLDS, resolveEngine } = await import("yt-dlp-transcript-common/lib/montage/voiceMatch.mjs"); + const { REPO_ROOT } = await import("../paths.mjs"); + const manifest = await readManifest(project.dir); + if (!manifest) throw new AuditionError(`${project.id} has no manifest`); + const channelsDir = channelsDirFor(project.dir, manifest, { shadowExists: await hasShadowChannels(project.dir) }); + const ref = await planSpeakerCheck(project.dir, manifest, { clipIds: [], channelsDir, speakers: [speaker] }); + const voice = ref.voices[0]; + // The excerpt to listen to: the first piece of the reference set. + const firstClip = voice?.clipKeys?.map((k) => ref.clips.find((c) => c.key === k)).find((c) => c?.file) ?? null; + const firstItem = voice?.items?.[0] ?? null; + const src = firstClip ? { file: firstClip.file, start: firstClip.start, dur: firstClip.dur } : firstItem ? { file: firstItem.file, start: firstItem.start, dur: firstItem.dur } : null; + let reference = null; + if (src) { + const rel = referenceRelOf(speaker.name); + const abs = path.join(project.dir, ...rel.split("/")); + await mkdir(path.dirname(abs), { recursive: true }); + try { + await levelTo(src.file, abs, { start: Math.max(0, src.start), seconds: Math.min(REFERENCE_SECONDS, Math.max(1, src.dur)) }); + reference = rel; + } catch (err) { + emit("note", { message: `the reference excerpt was not made: ${err instanceof Error ? err.message : err}` }); + } + } + const made = plan.filter((c) => c.cached && c.meta?.seconds > 0); + if (!made.length) return { speaker: speaker.name, rows: {}, reference, why: "no candidate to score (synthesize them first)" }; + let settings = null; + try { + settings = JSON.parse(await readFile(process.env.SETTINGS_FILE ?? path.join(/* turbopackIgnore: true */ REPO_ROOT, "settings.json"), "utf8")); + } catch { + settings = null; + } + const engine = resolveEngine({ repoRoot: REPO_ROOT, settings, ...engineOpts }); + emit("audition", { phase: "score", n: made.length, speaker: speaker.name }); + const clips = [ + ...ref.clips.map((c) => (c.file ? { key: c.key, id: c.id, file: c.file, start: c.start, dur: c.dur, fallback: c.fallback ?? null } : { key: c.key, id: c.id, file: null, start: 0, dur: 0, missing: c.missing })), + ...made.map((c) => ({ key: `audition:${c.key}`, id: null, file: c.file, start: 0, dur: c.meta.seconds })), + ]; + const doc = await runSpeakerCheck({ + clips, + check: made.map((c) => `audition:${c.key}`), + speakers: ref.voices, + engine, + scratch: path.join(/* turbopackIgnore: true */ project.dir, ".cast-audition-work"), + thresholds: DEFAULT_THRESHOLDS, + }); + const scores = await readAuditionScores(project.dir); + const rows = {}; + const at = new Date().toISOString(); + for (const c of made) { + const row = /** @type {any} */ (doc.clips[`audition:${c.key}`]); + const s = row?.scores?.[0]; + rows[c.key] = s ? { score: r3(s.score), speaker: speaker.name, at, model: doc.model } : { score: null, speaker: speaker.name, at, why: row?.why ?? "not scored" }; + scores.rows[`${c.key}|${speaker.name}`] = rows[c.key]; + } + const file = path.join(project.dir, ...AUDITION_SCORES.split("/")); + await mkdir(path.dirname(file), { recursive: true }); + const tmp = `${file}.tmp-${process.pid}`; + await writeFile(tmp, `${JSON.stringify({ version: 1, rows: scores.rows }, null, 1)}\n`); + await rename(tmp, file); + return { speaker: speaker.name, rows, reference, pieces: doc.speakers?.[0]?.kept ?? null }; +} diff --git a/umtool/lib/report/castCli.mjs b/umtool/lib/report/castCli.mjs @@ -0,0 +1,403 @@ +// `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. +// +// umtool cast [ls] [--json] +// umtool cast add <id> --name "…" --voice <engine:voice> [--handles a,b] [--speakers Name,…] [--convert-engine e] +// [--convert-voice <engine:voice>] [--avatar …] [--note "…"] [--narrator] [--json] +// umtool cast set <id> [the same flags] [--add-handle h] [--remove-handle h] [--no-convert] [--no-narrator] [--json] +// umtool cast rm <id> [--json] · umtool cast undo [--json] +// umtool cast project <p> [--json] +// 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] +// umtool cast reread <p> <character|@handle> [--dry-run] [--json] +// +// Plain ESM: the CLI runs under bare node. +import path from "node:path"; +import { CAST_CONVERT_ENGINES, characterOf, charactersOf, findCharacter, isQualifiedVoice } from "umtool-report-to-video/cast"; +import { handleKey, voiceRefOf } 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"; + +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>] [--avatar …] [--note \"…\"] [--narrator] [--json]", + " umtool cast set <id> [those flags] [--add-handle h] [--remove-handle h] [--no-convert] [--no-narrator] [--json]", + " umtool cast rm <id> [--json]", + " umtool cast undo [--json]", + " umtool cast project <project> [--json]", + " umtool cast audition <character|@handle> --voices kokoro:am_michael,kokoro:am_onyx,orpheus:zac [--project <p>]", + " [--text \"…\" | --item <id> | --line <n>] [--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), 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.", + " 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.", +].join("\n"); + +const VALUED = new Set(["--name", "--voice", "--handles", "--speakers", "--convert-engine", "--convert-voice", "--avatar", "--note", "--add-handle", "--remove-handle", "--voices", "--project", "--text", "--item", "--line", "--progress"]); +const splitList = (v) => String(v ?? "").split(",").map((x) => x.trim()).filter(Boolean); + +function parse(args) { + const words = []; + /** @type {Map<string, string[]>} */ + const flags = new Map(); + for (let i = 0; i < args.length; i += 1) { + const a = args[i]; + if (VALUED.has(a)) { + if (i + 1 >= args.length) throw new CastError(`${a} needs a value`); + flags.set(a, [...(flags.get(a) ?? []), args[++i]]); + } else if (a.startsWith("--")) flags.set(a, [...(flags.get(a) ?? []), ""]); + else words.push(a); + } + return { words, flags, str: (k) => flags.get(k)?.at(-1) ?? null, has: (k) => flags.has(k), all: (k) => flags.get(k) ?? [] }; +} + +/** The fields `add`/`set` take from the flags (only those given). */ +function fieldsOf(p) { + const f = {}; + if (p.str("--name") !== null) f.name = p.str("--name").trim(); + if (p.str("--voice") !== null) { + const v = p.str("--voice").trim(); + if (!isQualifiedVoice(v)) throw new CastError(`--voice is a STOCK voice with its engine: kokoro:am_michael, orpheus:zac (got ${v})`); + f.voice = v; + } + if (p.str("--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 (p.str("--convert-engine") !== null || p.str("--convert-voice") !== 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 ")}`); + f.convert = { ...(ce ? { engine: ce } : {}), ...(p.str("--convert-voice") ? { voice: p.str("--convert-voice") } : {}) }; + } + return f; +} + +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}` : ""}${c.speakers?.length ? ` real voice: ${c.speakers.join(", ")}` : ""}${c.narrator ? " (the narrator)" : ""}${c.note ? ` -- ${c.note}` : ""}`; + +async function projectOf(ref, reportsRoot) { + const r = await resolveProject(ref, reportsRoot); + if (r.ambiguous) throw new CastError(`"${ref}" is the name of ${r.ambiguous.length} projects — pass its id`); + if (!r.project) throw new CastError(`no project matches "${ref}"`); + return r.project; +} + +/** A project's characters view (castProject.mjs projectCharacters) with the files it read. */ +export async function projectView(project, { reportsRoot = REPORTS_ROOT } = {}) { + const manifest = await readManifest(project.dir); + if (!manifest) throw new CastError(`${project.id} has no manifest`); + const { readVoiceMap } = await import("./postSay.mjs"); + const { readSpeakers } = await import("./speakerCheck.mjs"); + const { projectCharacters } = await import("./castProject.mjs"); + const castRead = await castForProject(project.dir, reportsRoot); + const 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 }; +} + +/** 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 ?? [])] }; + const h = handleKey(ref); + const row = view?.characters?.find((r) => r.handles.includes(h)) ?? null; + return { character: characterOf(castRead.cast, h), handles: [h], row }; +} + +/** + * `umtool cast …` + * @param {string[]} args + * @param {{ reportsRoot?: string, log?: (s: string) => void, err?: (s: string) => void, ask?: any, lanes?: any }} [o] + */ +export async function castCommand(args, { reportsRoot = REPORTS_ROOT, log = console.log, err = console.error, ask = undefined, lanes = undefined } = {}) { + let p; + try { + p = parse(args); + } catch (e) { + err(`umtool cast: ${e instanceof Error ? e.message : e}`); + return 2; + } + const json = p.has("--json"); + const out = (o, text) => log(json ? JSON.stringify(o, null, 2) : text); + const [sub = "ls", ...rest] = p.words; + if (p.has("--help") || sub === "help") { + log(CAST_USAGE); + return 0; + } + const file = castFile(reportsRoot); + try { + if (sub === "ls") { + const r = await readCast(reportsRoot); + const chars = charactersOf(r.cast); + out({ ok: true, file, token: r.token, characters: chars, ...(r.error ? { error: r.error } : {}) }, [ + `the cast: ${chars.length} character(s) (${file})${r.error ? `\n NOT READ: ${r.error}` : ""}${chars.length ? "" : " -- umtool cast add <id> --name \"…\" --voice kokoro:am_michael --handles <handle>"}`, + ...chars.map((c) => ` ${line(c)}`), + ].join("\n")); + return 0; + } + if (sub === "add" || sub === "set") { + const [id] = rest; + if (!id) throw new CastError(`cast ${sub} takes the character's id`); + const f = fieldsOf(p); + const r = await castWrite(file, (chars) => { + const at = chars.findIndex((c) => c.id === id); + if (sub === "add") { + if (at >= 0) throw new CastError(`${id} is in the cast already (umtool cast set ${id} …)`); + if (!f.name || !f.voice) throw new CastError('cast add takes --name "…" and --voice <engine:voice>'); + const c = { id, name: f.name, handles: f.handles ?? [], voice: f.voice, ...(f.convert ? { convert: f.convert } : {}), ...(f.speakers ? { speakers: f.speakers } : {}), ...(f.avatar ? { avatar: f.avatar } : {}), ...(f.note ? { note: f.note } : {}), ...(p.has("--narrator") ? { narrator: true } : {}) }; + 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)`); + const c = { ...chars[at], ...f }; + 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]; + 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)}`); + return 0; + } + if (sub === "rm" || sub === "remove") { + const [id] = rest; + if (!id) throw new CastError("cast rm takes the character's id"); + const r = await castWrite(file, (chars) => { + const at = chars.findIndex((c) => c.id === id); + if (at < 0) throw new CastError(`no ${id} in the cast`); + const [gone] = chars.splice(at, 1); + return { removed: gone }; + }, { what: `rm ${id}` }); + out({ ok: true, removed: r.removed, token: r.token }, `removed ${id} from the cast (umtool cast undo puts it back)`); + return 0; + } + if (sub === "undo") { + const r = await undoCast(file); + out({ ok: true, undone: r.undone, at: r.at, left: r.left, token: r.token }, `undone: ${r.undone} (${r.left} undo point(s) left)`); + return 0; + } + if (sub === "project") { + const [ref] = 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 (json) { + log(JSON.stringify({ ok: true, project: project.id, castFile: castRead.file, ...(castRead.error ? { castError: castRead.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}` : ""}`); + 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}` : ""}`); + 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)`); + return 0; + } + if (sub === "use") { + const [ref, who, voice] = rest; + if (!ref || !who || !voice) throw new CastError("cast use takes the project, the character (or @handle) and the voice: cast use quartering-diet thequartering kokoro:am_michael"); + const project = await projectOf(ref, reportsRoot); + const before = await projectView(project, { reportsRoot }); + const t = handlesOf(who, before.castRead, before.view); + 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"; + 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; + await castWrite(castPath, (chars) => { + const c = t.character ? chars.find((x) => x.id === t.character.id) : null; + if (c) c.voice = voice; + else { + const h = t.handles[0]; + const id = h.replace(/[^a-z0-9_-]/g, "-").replace(/^[^a-z0-9]+/, "").slice(0, 48) || "character"; + 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 }); + } + return {}; + }, { what: `${t.character?.id ?? `@${t.handles[0]}`} reads in ${voice} (from ${project.id})` }); + // Its voice everywhere -- here too: the project's own override of it goes. + for (const h of t.handles) { + if (h in before.map) { + await updateVoiceMap(project.dir, { remove: h }); + removed.push(h); + } + } + } else { + for (const h of t.handles) await updateVoiceMap(project.dir, { set: { handle: h, voice } }); + } + const after = await projectView(project, { reportsRoot }); + const { rereadPlan } = await import("./castProject.mjs"); + const plan = rereadPlan(project.id, after.manifest, after.view.characters.flatMap((c) => c.drift), t.handles); + out( + { ok: true, scope, handles: t.handles, voice, removed, 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(", ")})` : ""}`, + plan.items.length ? ` ${plan.items.length} item(s) read them in another voice -- umtool cast reread ${project.id} ${who}:` : " no picked read says them in another voice", + ...plan.items.map((x) => ` ${x.id} ${x.reads.map((r) => `${r.role} ${r.reads} -> ${r.want}`).join(", ")}`), + ].join("\n"), + ); + return 0; + } + if (sub === "reread") { + const [ref, who] = rest; + if (!ref || !who) throw new CastError("cast reread takes the project and the character (or @handle)"); + const project = await projectOf(ref, reportsRoot); + const v = await projectView(project, { reportsRoot }); + const t = handlesOf(who, v.castRead, v.view); + const { rereadPlan } = await import("./castProject.mjs"); + const plan = rereadPlan(project.id, v.manifest, v.view.characters.flatMap((c) => c.drift), t.handles); + if (p.has("--dry-run") || !plan.items.length) { + out({ ok: true, dryRun: p.has("--dry-run"), items: plan.items, skipped: plan.skipped }, [ + plan.items.length ? `${plan.items.length} item(s) to re-read:` : `no picked read says ${who} in another voice`, + ...plan.items.map((x) => ` umtool ${x.argv.join(" ")}`), + ...plan.skipped.map((s) => ` (not re-read: ${s.id} -- ${s.why})`), + ].join("\n")); + return 0; + } + const { postsCommand } = await import("./postsCli.mjs"); + const done = []; + for (const x of plan.items) { + const said = []; + const code = await postsCommand([...x.argv.slice(1), "--json"], { root: reportsRoot, out: (s) => said.push(s), err: (s) => said.push(s) }); + done.push({ id: x.id, code }); + if (!json) log(`${x.id}: ${code === 0 ? "re-read, picked (awaiting approval)" : `FAILED -- ${said.join(" ").slice(0, 300)}`}`); + } + const failed = done.filter((d) => d.code !== 0).length; + if (json) log(JSON.stringify({ ok: failed === 0, done, skipped: plan.skipped }, null, 2)); + return failed ? 1 : 0; + } + if (sub === "audition") return await auditionCommand(rest, p, { reportsRoot, log, err, ask, lanes }); + throw new CastError(`cast: ls, add, set, rm, undo, project, audition, use or reread (not ${sub})`); + } catch (e) { + if (e instanceof CastError || e?.name === "AuditionError" || e?.name === "SayError") { + if (json) log(JSON.stringify({ ok: false, error: e.message }, null, 2)); + err(`umtool cast: ${e.message}`); + return 1; + } + err(`umtool cast: ${e instanceof Error ? e.stack ?? e.message : String(e)}`); + return 1; + } +} + +/** `umtool cast audition …` */ +async function auditionCommand(rest, p, { reportsRoot, log, err, ask, lanes }) { + const A = await import("./castAudition.mjs"); + const [who] = rest; + if (!who) throw new CastError("cast audition takes the character (its id, or @handle)"); + const json = p.has("--json"); + const ndjson = p.str("--progress") === "ndjson"; + const say = (s) => (ndjson ? err(s) : !json && log(s)); + const emit = (ev, f = {}) => { + if (ev === "note") say(f.message); + else if (ndjson) log(JSON.stringify({ ev: "cast-audition", ...f })); + }; + const project = p.str("--project") ? await projectOf(p.str("--project"), reportsRoot) : null; + const castRead = project ? await castForProject(project.dir, reportsRoot) : await readCast(reportsRoot); + let manifest = null; + let character = findCharacter(castRead.cast, who.replace(/^@+/, "")); + if (who.startsWith("@") || !character) { + const h = handleKey(who); + const c = characterOf(castRead.cast, h); + if (c) character = c; + else { + manifest = project ? await readManifest(project.dir) : null; + const { authorsOf } = await import("./castProject.mjs"); + const a = manifest ? authorsOf(manifest).get(h) : null; + if (!a && !project) throw new CastError(`${who} is not in the cast (umtool cast ls), and no --project names it`); + if (!a) throw new CastError(`${who} is neither in the cast nor an author in ${project?.id}`); + character = { id: h, name: a.name || h, handles: [h], voice: null }; + } + } + manifest ??= project ? await readManifest(project.dir) : null; + // The line: --text, an item's, the n-th, the first of the character's, a stock line -- what a voice SAYS (the + // project's redaction, slur filter and lexicon applied). + let text = p.str("--text"); + let from = text ? "text" : null; + let item = null; + if (!text && manifest) { + const lines = A.characterLines(manifest, character.handles ?? []); + const pick = p.str("--item") ? lines.find((l) => l.item === p.str("--item")) : p.str("--line") ? lines[Number(p.str("--line")) - 1] : lines[0]; + if ((p.str("--item") || p.str("--line")) && !pick) throw new CastError(`${character.name} has no such line in ${project?.id} (cast project ${project?.id} lists them)`); + if (pick) { + text = pick.text; + from = `item:${pick.item}`; + item = manifest.timeline.find((e) => e?.id === pick.item) ?? null; + } + } + if (!text) { + text = A.STOCK_LINE; + from = "stock"; + } + text = A.auditionText(text); + if (project && manifest) { + const { projectRedaction } = await import("./postRedaction.mjs"); + const { spokenRead } = await import("umtool-report-to-video/post-redact"); + const red = await projectRedaction(project.dir, manifest); + text = spokenRead(text, item ?? { id: null }, red, { voice: "skip" }).text.trim() || text; + } + const candidates = A.candidatesOf(p.all("--voices")); + const dir = A.auditionDirOf(project, reportsRoot); + const relBase = project ? A.AUDITION_DIR : path.relative(reportsRoot, dir); + const plan = await A.auditionPlan(dir, candidates, text, { relBase }); + let fresh = 0; + let jobs = []; + if (!p.has("--score-only")) { + const r = await A.synthesizeAuditions(dir, plan, text, { ask, emit, hold: !p.has("--no-hold"), lanes }); + fresh = r.fresh; + jobs = r.jobs; + } + let score = null; + if (project && !p.has("--no-score")) score = await A.scoreAuditions(project, character, plan, { emit }); + const prior = project ? await A.readAuditionScores(project.dir) : { rows: {} }; + // Not scored this time: the scores kept for these candidates against the same real voice. + const speaker = score?.speaker ?? (project ? (await A.referenceFor(project, character))?.name ?? null : null); + const scoreOf = (k) => score?.rows?.[k]?.score ?? (speaker ? prior.rows[`${k}|${speaker}`]?.score : null) ?? null; + const rows = plan.map((c) => ({ + spec: c.spec, engine: c.engine, voice: c.voice, weight: c.weight, key: c.key, rel: c.rel, cached: c.cached, fresh: !!c.fresh, + seconds: c.meta?.seconds ?? null, lufs: c.meta?.lufs ?? null, score: scoreOf(c.key), ...(c.meta?.disclosure ? { disclosure: c.meta.disclosure } : {}), + })); + if (json) { + log(JSON.stringify({ ok: true, character: { id: character.id, name: character.name, handles: character.handles ?? [], voice: character.voice ?? null }, project: project?.id ?? null, text, from, candidates: rows, fresh, jobs, speaker, reference: score?.reference ?? (speaker ? A.referenceRelOf(speaker) : null), ...(score?.why ? { why: score.why } : {}) }, null, 2)); + return 0; + } + if (ndjson) { + log(JSON.stringify({ ev: "cast-audition", phase: "done", fresh, candidates: rows.length })); + return 0; + } + log(`${character.name}: "${text}" (${from})`); + for (const r of rows) log(` ${r.spec.padEnd(22)} ${r.weight === "heavy" ? "heavy" : "fast "} ${r.seconds ? `${r.seconds.toFixed(1)} s` : "-"} ${r.score !== null ? `closeness ${r.score.toFixed(3)}${speaker ? ` to ${speaker}` : ""}` : ""} ${r.rel}${r.fresh ? "" : " (kept)"}`); + if (score?.why) log(` not scored: ${score.why}`); + if (score?.reference) log(` the real voice (a reference, never a target): ${score.reference}`); + return 0; +} diff --git a/umtool/lib/report/castProject.mjs b/umtool/lib/report/castProject.mjs @@ -0,0 +1,160 @@ +// 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, 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 { 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. + */ +export function resolverFor({ map = {}, cast = null, render = {} }) { + const castMap = castVoiceMap(cast); + 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 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, + narrator: e.narration?.voice ?? k.voice, engine: e.narration?.engine ?? k.engine, + }); + }; +} + +/** The post items' authors and context authors: `Map<handle, { handle, name, items: id[], context: id[] }>`. */ +export function authorsOf(manifest) { + const out = new Map(); + const add = (h, name, id, own) => { + const key = handleKey(h); + if (!key || key === "*") return; + const a = out.get(key) ?? { handle: key, name: "", items: [], context: [] }; + if (!a.name && str(name)) a.name = str(name); + const list = own ? a.items : a.context; + if (!list.includes(id)) list.push(id); + out.set(key, a); + }; + for (const e of Array.isArray(manifest?.timeline) ? manifest.timeline : []) { + if (e?.type !== "post") continue; + add(e.handle, e.author, e.id, true); + for (const p of Array.isArray(e.parents) ? e.parents : []) add(p?.handle, p?.author, e.id, false); + if (e.quoted) add(e.quoted.handle, e.quoted.author, e.id, false); + for (const l of Array.isArray(e.links) ? e.links : []) add(l?.handle, l?.author, e.id, false); + } + return out; +} + +/** + * 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. + */ +export function projectCharacters(manifest, { map = {}, cast = null, speakers = [] } = {}) { + const render = manifest?.render ?? {}; + const k = postNarrationKnobs({}, render); + const resolve = resolverFor({ map, cast, render }); + const castMap = castVoiceMap(cast); + const drift = voiceDrift(manifest, resolve); + const groups = new Map(); + for (const a of authorsOf(manifest).values()) { + const c = 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: [] }; + 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); + groups.set(key, g); + } + const tl = Array.isArray(manifest?.timeline) ? manifest.timeline : []; + const reads = []; + 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; + 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 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, + 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) } } : {}), + 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)), + speaker: sp?.name ?? null, + lines: characterLines(manifest, g.handles).slice(0, 8), + }; + }); + 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"); + 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, + }; +} + +/** A thread take's `read` record as the argv that asks for it again, leaving out the overrides of `handles`. */ +export function threadArgvOf(read, { handles = [], author = null } = {}) { + if (!read || read.kind !== "thread") return []; + const drop = new Set(handles.map(handleKey)); + const a = []; + if (read.parents !== undefined && String(read.parents) !== "0") a.push("--parents", String(read.parents)); + for (const s of read.skip ?? []) a.push("--skip-parent", String(s)); + if (read.quoted === false) a.push("--no-quoted"); + if (read.linked === false) a.push("--no-linked"); + 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)); + return a; +} + +/** + * THE RE-READS a voice change for `handles` asks for, pure: every post item whose picked read says one of them in + * another voice than now -- `[{ id, take, thread, reads: [{ role, reads, want }], argv }]`, `argv` the umtool words + * that make the new take (a thread read again with its own options, the changed authors' overrides dropped; a + * single read). A read converted from a recording is not re-read by a voice (`skipped`: record it, or derive it again). + */ +export function rereadPlan(projectId, manifest, drift, handles) { + const want = new Set((handles ?? []).map(handleKey)); + const byItem = new Map(); + const skipped = []; + for (const d of drift) { + if (want.size && !want.has(d.handle)) continue; + if (d.kind === "converted") { + if (!skipped.some((s) => s.id === d.id)) skipped.push({ id: d.id, why: "a recording converted to a stock voice: derive it again (Import a recording, or the bench's Run AI on it)" }); + continue; + } + const row = byItem.get(d.id) ?? { id: d.id, thread: d.thread, reads: [] }; + row.reads.push({ role: d.role, handle: d.handle, reads: d.reads, want: d.want }); + byItem.set(d.id, row); + } + const tl = Array.isArray(manifest?.timeline) ? manifest.timeline : []; + const items = [...byItem.values()].map((r) => { + const e = tl.find((x) => x?.id === r.id); + const takes = e?.narration?.takes ?? []; + const t = takes[Number.isInteger(e?.narration?.pick) ? e.narration.pick : 0] ?? null; + const argv = ["posts", "narrate", projectId, r.id, "--take", ...(r.thread ? ["--thread", ...threadArgvOf(t?.read, { handles: [...want], author: e?.handle })] : [])]; + return { ...r, take: t?.file ?? null, argv }; + }); + return { items, skipped }; +} diff --git a/umtool/lib/report/lintCli.mjs b/umtool/lib/report/lintCli.mjs @@ -15,6 +15,8 @@ export const LINT_USAGE = [ " the manifest lint (report-to-video/lint.mjs, what a build runs before it renders) on the project's manifest, or", " with --take on the take's (its patches applied, as its render reads it), and the files its post items name: a", " picked read, an attachment, a context post's media not in the project is an ERROR; another named file a warning.", + " And the cast's guard (umtool cast): a picked read that says a cast character in another voice than now is a", + " warning (umtool cast reread); a cast voice the project's voice map overrides on purpose is a note.", " Exit 0 no error · 1 an error · 2 usage.", ].join("\n"); @@ -55,6 +57,29 @@ export async function namedFileProblems(manifest, dir) { } /** + * THE CAST's CONSISTENCY GUARD (umtool-report-to-video/cast.mjs castDrift): a WARNING for each picked read that says a + * cast character in another voice than it reads in now (stale: `umtool cast reread`), a NOTE for each cast voice the + * project's map overrides on purpose. A project that reads no cast says nothing. + * @param {Record<string, any>} manifest + * @param {{ id: string, dir: string }} project + */ +export async function castProblems(manifest, project, reportsRoot = REPORTS_ROOT) { + const { castForProject } = await import("./castStore.mjs"); + const castRead = await castForProject(project.dir, reportsRoot); + if (castRead.error) return { warnings: [`the cast is not read (${castRead.error})`], notes: [] }; + const { charactersOf, castDrift } = await import("umtool-report-to-video/cast"); + if (!charactersOf(castRead.cast).length) return { warnings: [], notes: [] }; + const { readVoiceMap } = await import("./postSay.mjs"); + const { resolverFor } = await import("./castProject.mjs"); + const map = await readVoiceMap(project.dir).catch(() => ({})); + const { drift, overrides } = castDrift(manifest, { cast: castRead.cast, map, resolve: resolverFor({ map, cast: castRead.cast, render: manifest?.render ?? {} }) }); + return { + warnings: drift.map((d) => `timeline ${d.id}: @${d.handle} (${d.character}) reads in ${d.reads} -- now ${d.want} (${d.from === "project" ? "the project's voice map" : d.from === "cast" ? "the cast" : d.from}): umtool cast reread ${project.id} ${d.character}`), + notes: overrides.map((o) => `@${o.handle} (${o.character}) reads in ${o.project} in this project -- the cast says ${o.cast} (an override on purpose; umtool posts voices ${project.id} remove ${o.handle} follows the cast)`), + }; +} + +/** * @param {string[]} args the words after `lint` * @param {{ reportsRoot?: string, log?: (s: string) => void, err?: (s: string) => void }} [opts] */ @@ -117,11 +142,13 @@ export async function lintCommand(args, { reportsRoot = REPORTS_ROOT, log = cons } const lint = await lintManifestFile(file, { variant, final: flags.has("--final") }); const files = await namedFileProblems(selectVariant(manifest, variant), project.dir); + const voices = await castProblems(selectVariant(manifest, variant), project, reportsRoot); const errors = [...lint.errors, ...files.errors]; - const warnings = [...lint.warnings, ...files.warnings]; - if (flags.has("--json")) log(JSON.stringify({ ok: errors.length === 0, project: project.id, take, variant, entries: manifest.timeline?.length ?? 0, errors, warnings }, null, 2)); + const warnings = [...lint.warnings, ...files.warnings, ...voices.warnings]; + if (flags.has("--json")) log(JSON.stringify({ ok: errors.length === 0, project: project.id, take, variant, entries: manifest.timeline?.length ?? 0, errors, warnings, notes: voices.notes }, null, 2)); else { for (const line of lintReport({ errors, warnings })) log(line); + for (const n of voices.notes) log(`note: ${n}`); log(`${project.id}${take ? ` take ${take}` : ""}: ${manifest.timeline?.length ?? 0} entries, ${errors.length ? "NOT ready to render" : "ready to render as far as the lint can tell"}`); } return errors.length ? 1 : 0; diff --git a/umtool/lib/report/postNarrationCli.mjs b/umtool/lib/report/postNarrationCli.mjs @@ -44,6 +44,7 @@ export const NARRATE_USAGE = [ " umtool posts narrate <project> <item> [--script \"…\"] [--take [--note \"…\"] [--voice v] [--engine e] [--speed s]]", " [--pick <n>] [--approve|--unapprove] [--off|--on] [lead=… tail=… ramp=… linger=… clip=read|full", " wet=… lowpass=… duck=on|off short=hold|loop attach=under|after lufs=… rate=… pace=fast|normal] [--json]", + " umtool posts narrate <project> <item> --recording <file> [--as <character>] [--no-clean] [--no-convert]", " umtool posts narrate <project> <item> --take --thread [--parents 0|all|none|<n>] [--skip-parent <id>]… [--no-quoted]", " [--no-linked] [--read-seen] [--voice-for <handle>=<voice>]… [--voice v] [--force] [--dry-run]", " umtool posts narrate <project> <item> … --in-take <take> any of these on a TAKE of the project: the pick, a new", @@ -64,6 +65,10 @@ export const NARRATE_USAGE = [ " A new take is picked; a new script or pick takes the approval away. Scripts are the post VERBATIM (cleaned", " for pronunciation only); add emotion with Orpheus's tags <sigh> <laugh> <chuckle> <groan> <gasp> ….", " --delete <n>: the take out of the list, its file moved to narration/posts/<postId>/.trash/ (soft).", + " --recording <file> [--as <character>] [--no-clean] [--no-convert] [--label operator]: a person's RECORDING of the", + " item made a character's read -- kept as a recorded take (the original), cleaned (the editor's voice-enhance), then", + " converted to the character's STOCK voice (umtool cast: its convert voice; default the post's author's, else the", + " narrator) -- each a new take, the last picked, the disclosure line said.", " --derive <n> --op enhance|convert [--engine e] [--voice v]: a NEW take made from take n by the editor's op", " (enhance: denoise, level; convert: the performance kept, the timbre a STOCK synthetic voice) -- the original kept.", " A narrated post lasts lead + its read + tail + linger (1.8 s); a longer video is cut to that -- its best part,", @@ -196,6 +201,7 @@ export function normalizeParts(raw) { // The text it reads (post-thread.mjs), the voice and the piece the batch read it in. ...(typeof p.role === "string" && /^(post|quoted|parent:\d|media:\d|linked:\d)$/.test(p.role) ? { role: p.role } : {}), ...(typeof p.voice === "string" && /^[A-Za-z0-9][A-Za-z0-9_.+-]{0,63}$/.test(p.voice) ? { voice: p.voice } : {}), + ...(typeof p.engine === "string" && /^(orpheus|kokoro|espeak-ng)$/.test(p.engine) ? { engine: p.engine } : {}), ...(Number.isInteger(p.piece) && p.piece >= 0 ? { piece: p.piece } : {}), })); } @@ -313,8 +319,11 @@ 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)`); - const eng = engine ?? e.narration?.engine ?? k.engine; - const vox = voice ?? e.narration?.voice ?? k.voice; + // The voice his own read is said in: the one asked for, the project's 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; const pid = postIdOf(e); const dir = path.join(project.dir, ...takesDirOf(pid).split("/")); @@ -509,6 +518,20 @@ export async function narrateCommand(project, words, flags, { json = false, dryR out(json ? JSON.stringify({ ok: true, id: e.id, narration: r.narration, token: r.token }, null, 2) : `${e.id}: take ${k} moved to the post's .trash/ (out of the list)\n${narrationLines(r.entry, render).join("\n")}`); return 0; } + if (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"), + emit: (_ev, f) => !json && f?.message && out(f.message), + }); + if (json) out(JSON.stringify({ ok: true, id: e.id, ...r }, null, 2)); + else { + out(`${e.id}: ${r.takes.map((t) => `${t.step} -> ${t.file}`).join(", ")}; picked ${r.picked}`); + for (const n of r.notes) out(` ${n}`); + if (r.disclosure) out(` disclosure: ${r.disclosure}`); + } + return 0; + } if (str("--derive") !== null) { const k = Number(str("--derive")); if (!Number.isInteger(k) || k < 1) throw new NarrateError("--derive takes a take's number as --list shows it (1 = the first)"); @@ -675,7 +698,8 @@ export async function deriveTake(project, e, { from, op, engine = null, voice = const ran = engine ?? (typeof said?.engine === "string" ? said.engine : null); const landed = op === "convert" ? (target ?? (typeof said?.voice === "string" ? said.voice : null)) : null; const take = { - file: rel, engine: "derived", voice: landed ?? t.voice ?? "?", seconds: m.seconds ?? t.seconds, + // A take's voice is the bare stock voice ("am_michael"); its step keeps the target as asked ("kokoro:am_michael"). + file: rel, engine: "derived", voice: (landed ? String(landed).split(":").pop() : null) ?? t.voice ?? "?", seconds: m.seconds ?? t.seconds, source: { kind: "take", from: takeIdOf(t) }, steps: [{ op, ...(ran ? { engine: ran } : {}), ...(landed ? { voice: landed } : {}), ...(params ? { params } : {}), ranAt: new Date().toISOString(), job: jobId }], script: t.script ?? e.narration?.script ?? "", at: new Date().toISOString(), jobId, @@ -686,6 +710,63 @@ export async function deriveTake(project, e, { from, op, engine = null, voice = } /** + * A RECORDING MADE A CHARACTER's READ (operator, 6 Nov: "running AI voice changing on a recording of me so I can + * provide the wording and such while you clean up any audio issues"): `file` (any sound or video ffmpeg reads) kept + * as a RECORDED take (postRecord.mjs keepRecording: trimmed, levelled -- the original, never overwritten), then a + * derived take CLEANED by the editor's voice-enhance (skipped, and said, when it has no engine for it), then a + * derived take CONVERTED by its voice-convert to the character's STOCK voice (cast.mjs convertTargetOf: its convert + * voice, else its voice) -- 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 }`. + */ +export async function importRecording(project, e0, file, { as = null, label = "operator", clean = true, convert = true, 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, convertTargetOf, findCharacter, narratorOf } = 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 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}` : ""}` }); + takes.push({ step: "recorded", file: kept.take.file }); + emit("note", { message: `kept as recorded: ${kept.take.file} (levelled ${kept.gain >= 0 ? "+" : ""}${kept.gain} dB)` }); + let e = await fresh(); + const indexOf = (rel) => (e?.narration?.takes ?? []).findIndex((t) => t.file === rel); + let from = indexOf(kept.take.file); + if (clean) { + try { + const r = await deriveTake(project, e, { from, op: "enhance", emit, editor, ask }); + takes.push({ step: "cleaned", file: r.take.file }); + e = await fresh(); + from = indexOf(r.take.file); + } catch (err) { + if (err?.name !== "OpNotInstalled" && !/not installed/i.test(String(err?.message))) throw err; + notes.push(`not cleaned: ${err.message} (archilyzer voice setup --engine deepfilternet)`); + } + } + 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 …)"); + else { + const target = convertTargetOf(character); + try { + const r = await deriveTake(project, e, { from, op: "convert", engine: target.engine, voice: target.voice, emit, editor, ask }); + takes.push({ step: `converted to ${target.voice}`, file: r.take.file }); + e = await fresh(); + } catch (err) { + if (err?.name !== "OpNotInstalled" && !/not installed/i.test(String(err?.message))) throw err; + notes.push(`not converted: ${err.message} (archilyzer voice setup --engine ${target.engine ?? "openvoice"})`); + } + } + } + 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 }; +} + +/** * DELETE A TAKE, SOFTLY: its file (and its parts) moved into the post's * `narration/posts/<postId>/.trash/`, the take out of the list (the pick * follows). Returns the write's result. diff --git a/umtool/lib/report/postsCli.mjs b/umtool/lib/report/postsCli.mjs @@ -194,7 +194,7 @@ export const POSTS_USAGE = [ " none: the rule as it stands", ].join("\n"); -const VALUED = new Set(["--in-take", "--set", "--attach", "--flag", "--author", "--id", "--crop", "--since", "--until", "--replies", "--order", "--limit", "--after", "--script", "--note", "--voice", "--engine", "--speed", "--pick", "--linger", "--derive", "--op", "--delete", "--match", "--target", "--occurrence", "--at", "--scale", "--hold", "--lead", "--ease", "--highlight", "--worker", "--without", "--drop-parts", "--text", "--place", "--rewind", "--zone", "--gap", "--from-scale", "--color", "--outline", "--outline-width", "--size", "--face", "--sfx", "--volume", "--bar", "--bar-style", "--tempo-for", "--tempo", "--parts", "--stretch", "--yell-gain", "--yell-style", "--pause", "--revoice", "--say", "--xfade", "--splice", "--parents", "--skip-parent", "--voice-for", "--item"]); +const VALUED = new Set(["--in-take", "--set", "--attach", "--flag", "--author", "--id", "--crop", "--since", "--until", "--replies", "--order", "--limit", "--after", "--script", "--note", "--voice", "--engine", "--speed", "--pick", "--linger", "--derive", "--op", "--delete", "--match", "--target", "--occurrence", "--at", "--scale", "--hold", "--lead", "--ease", "--highlight", "--worker", "--without", "--drop-parts", "--text", "--place", "--rewind", "--zone", "--gap", "--from-scale", "--color", "--outline", "--outline-width", "--size", "--face", "--sfx", "--volume", "--bar", "--bar-style", "--tempo-for", "--tempo", "--parts", "--stretch", "--yell-gain", "--yell-style", "--pause", "--revoice", "--say", "--xfade", "--splice", "--parents", "--skip-parent", "--voice-for", "--item", "--recording", "--as", "--label"]); /** The valued flags that may be given more than once (each value kept, in order). */ const MULTI = new Set(["--skip-parent", "--voice-for"]); const SLUG_RE = /^[A-Za-z0-9._-]+$/;