Archilyzer · Source

archilyzer

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

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

cast: a character is a preset -- a synthetic one (voice, speed) and a recorded one (convert, enhance, trim and its pad, a direction for the reader); version 1's voice and convert read as them, the file's version 2; a project's own characters (anonymous ones under a shown name, Anon 1 …); the chain one read asks gains the item's own character and each layer's speed

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

Diffstat:
Mumtool/report-to-video/cast.mjs | 382+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------------
Aumtool/report-to-video/characters.test.mjs | 191+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/post-narration.mjs | 8++++++--
Mumtool/report-to-video/post-say.mjs | 70++++++++++++++++++++++++++++++++++++++++++++++++++++------------------
4 files changed, 574 insertions(+), 77 deletions(-)

diff --git a/umtool/report-to-video/cast.mjs b/umtool/report-to-video/cast.mjs @@ -1,26 +1,51 @@ // THE CAST (operator, 6 Nov 2026: "I'd like to be able to pick different voices // for different characters, and in UI alone be able to try rendering different // ones to compare … and try to maintain consistent voices for different -// repeating characters"): the CHARACTERS that recur across projects, each with -// the stock voice it reads in, stored ONCE for every project -// (`<REPORTS_ROOT>/.umtool/cast.json`, lib/report/castStore.mjs its one writer). +// repeating characters"): the CHARACTERS that recur across projects, stored +// ONCE for every project (`<REPORTS_ROOT>/.umtool/cast.json`, +// lib/report/castStore.mjs its one writer). // -// { "format": "umtool-cast", "version": 1, +// A CHARACTER IS A PRESET (operator, 11 Nov 2026: "a preset of voice and other +// settings … different presets for synthetic and human-filtered voices"): two +// of them, picked by how the read is made -- +// +// { "format": "umtool-cast", "version": 2, // "characters": [ { "id": "thequartering", "name": "TheQuartering", // "handles": ["thequartering"], // X handles / channel slugs (no @, lower case) -// "voice": "kokoro:am_michael", // <tts engine>:<stock voice> -// "convert": { "engine": "seed-vc", "voice": "kokoro:am_michael" }, // a recording made his (optional) -// // + "pitch": "source" | "contour" | "target", "semitones": -12…12 -- the pitch a -// // converted read lands on (seed-vc; the editor's voice-convert, CAST_CONVERT_PITCH) +// "synthetic": { "voice": "kokoro:am_michael", // <tts engine>:<stock voice> +// "speed": 1.1 }, // the tts op's speed, 0.5-2 (absent: 1) +// "recorded": { // a RECORDING made his read +// "convert": { "engine": "seed-vc", "voice": "kokoro:am_michael", +// "pitch": "contour", "semitones": 2 }, // CAST_CONVERT_PITCH, the editor's voice-convert +// "enhance": true, // cleaned first (DeepFilterNet); absent: yes +// "trim": { "on": true, "padMs": 120 }, // its edges trimmed to speech, the room kept (absent: on, RECORD_ROOM) +// "direction": "higher, brisk, amused" }, // one line for the PERSON reading -- never sent to a model // "speakers": ["Jeremy"], // his REAL voice's name in a project's speakers.json // "avatar": "…", "note": "…", "narrator": true } ] } // +// VERSION 1 kept the stock voice in `voice` and the convert entry in `convert` +// at the character's top: those keys are READ AS THE PRESETS (upgradeCharacter: +// `voice` is `synthetic.voice`, `convert` is `recorded.convert`), in a file of +// either version, and the writer writes version 2. A +// reader is handed a VIEW (charactersOf, characterView): the presets AND the +// `voice` / `convert` they answer to, so what read version 1 reads version 2. +// +// A PROJECT's OWN CHARACTERS (`<project>/narration/characters.json`, +// PROJECT_CHARACTERS_FORMAT; the same store) are the same shape, with no +// narrator and with `anonymous: true` + `shown` ("Anon 1") for a person who +// must not enter the pool: they live in that video only. +// // A project's `narration/voices.json` (post-say.mjs) stays the project's -// OVERRIDE LAYER. The voice a piece of a read is said in, in order: the read's -// own override (--voice-for, --voice), the project's map, the CAST, the -// narrator's (the item's own author), the map's "*", the engine's default -- -// post-say.mjs voiceForPiece, which every read goes through (a single post's -// take, each piece of a thread read), so they agree. +// OVERRIDE LAYER (a handle in it reads as a project character with only a +// synthetic voice). The preset one read is made with, FIRST HIT WINS: the +// command's flags (--voice-for, --voice, --speed, --as, --pitch …), the item's +// own character (`narration.character`), the project's character for the +// handle (characters.json, then voices.json), the CAST's, the narrator's (the +// item's own author), the map's "*", the engine's default -- post-say.mjs +// voiceSourceOf for a synthesized read (a single post's take, each piece of a +// thread read: they agree), characterForRead below for a recording. A layer +// answers for a preset it HAS: a project character with no synthetic voice +// leaves the voice to the layers under it. // // A voice is ALWAYS a stock synthetic one (`<engine>:<voice>`): a character's // REAL voice (`speakers`) is a reference to compare a candidate with @@ -33,9 +58,32 @@ import { CONTEXT_VOICE_DEFAULTS, TTS_ENGINE_IDS, handleKey, voiceRefOf, voiceSpe export { voiceRefOf, voiceSpecOf }; export const CAST_FORMAT = "umtool-cast"; -export const CAST_VERSION = 1; +export const CAST_VERSION = 2; +/** The versions a reader takes (1: `voice` / `convert` at the character's top). */ +export const CAST_VERSIONS_READ = Object.freeze([1, 2]); export const CAST_MAX = 300; -export const CAST_KEYS = Object.freeze(["id", "name", "handles", "voice", "convert", "speakers", "avatar", "note", "narrator"]); +export const CAST_KEYS = Object.freeze(["id", "name", "handles", "synthetic", "recorded", "speakers", "avatar", "note", "narrator"]); +/** Version 1's keys, read as the presets (upgradeCharacter). */ +export const CAST_LEGACY_KEYS = Object.freeze(["voice", "convert"]); +/** A character's two presets: how a SYNTHESIZED read is made, and how a RECORDED one is. */ +export const SYNTHETIC_KEYS = Object.freeze(["voice", "speed"]); +export const RECORDED_KEYS = Object.freeze(["convert", "enhance", "trim", "direction"]); +export const TRIM_KEYS = Object.freeze(["on", "padMs"]); +/** The tts op's speed (the editor's: 0.5-2), the room a trim may keep, a direction's length. */ +export const CAST_SPEED = Object.freeze([0.5, 2]); +export const TRIM_PAD_MAX_MS = 2000; +export const DIRECTION_MAX = 200; + +/** A project's own characters: the file (relative to the project's folder), its format, its extra keys. */ +export const PROJECT_CHARACTERS_FILE = "narration/characters.json"; +export const PROJECT_CHARACTERS_FORMAT = "umtool-project-characters"; +export const PROJECT_CHARACTERS_VERSION = 1; +export const PROJECT_CHARACTER_KEYS = Object.freeze([...CAST_KEYS.filter((k) => k !== "narrator"), "anonymous", "shown"]); +/** + * The name an anonymous character is shown under when none is given: "Anon 1", "Anon 2" … (`{n}` the first number + * the project does not use). THE ONE PLACE the pattern is written. + */ +export const ANON_NAME_PATTERN = "Anon {n}"; /** The tts engines a cast voice may name (the editor's tts op), and the convert engines (its voice-convert op). */ export const CAST_TTS_ENGINES = TTS_ENGINE_IDS; export const CAST_CONVERT_ENGINES = Object.freeze(["openvoice", "seed-vc"]); @@ -61,58 +109,182 @@ export const isQualifiedVoice = (spec) => !!voiceRefOf(spec) && str(spec).includ /** The empty cast. */ export const emptyCast = () => ({ format: CAST_FORMAT, version: CAST_VERSION, characters: [] }); +/** A project with no characters of its own. */ +export const emptyProjectCharacters = () => ({ format: PROJECT_CHARACTERS_FORMAT, version: PROJECT_CHARACTERS_VERSION, characters: [] }); -/** Every reason a cast document is refused (empty: it is fine). */ -export function validateCast(doc, where = "cast.json") { - if (!isObj(doc)) return [`${where} must be {"format": "${CAST_FORMAT}", "version": ${CAST_VERSION}, "characters": [...]}`]; +const KEY_ORDER = ["id", "name", "anonymous", "shown", "handles", "synthetic", "recorded", "speakers", "avatar", "note", "narrator"]; + +/** + * A character as VERSION 2 holds it, from either version (pure, a copy): `voice` read as `synthetic.voice`, `convert` + * as `recorded.convert`, and the keys in one order. A top-level `voice` / `convert`, where one is still written + * beside its preset, is the word that counts (a version 1 writer's `c.voice = …` on a character read as version 2; + * a view's own alias says what its preset says). Anything else is left as it is (validateCast says what is wrong). + */ +export function upgradeCharacter(c) { + if (!isObj(c)) return c; + const { voice, convert, synthetic, recorded, ...rest } = c; + const syn = synthetic !== undefined && !isObj(synthetic) ? synthetic : { ...(synthetic ?? {}), ...(voice !== undefined ? { voice } : {}) }; + const rec = recorded !== undefined && !isObj(recorded) ? recorded : { ...(recorded ?? {}), ...(convert !== undefined ? { convert } : {}) }; + const all = { ...rest, ...(!isObj(syn) || Object.keys(syn).length ? { synthetic: syn } : {}), ...(!isObj(rec) || Object.keys(rec).length ? { recorded: rec } : {}) }; + const out = {}; + for (const k of KEY_ORDER) if (k in all) out[k] = all[k]; + for (const k of Object.keys(all)) if (!(k in out)) out[k] = all[k]; + return out; +} + +/** A cast document as version 2 holds it (upgradeCharacter each); a document that is not one is returned as it is. */ +export function upgradeCast(doc) { + if (!isObj(doc) || !Array.isArray(doc.characters) || doc.format !== CAST_FORMAT || !CAST_VERSIONS_READ.includes(doc.version)) return doc; + return { ...doc, version: CAST_VERSION, characters: doc.characters.map(upgradeCharacter) }; +} + +/** A character's stock voice (`synthetic.voice`; version 1's `voice`), its speed, its convert entry -- of either shape. */ +export const characterVoice = (c) => (c?.voice !== undefined ? c.voice : isObj(c?.synthetic) ? c.synthetic.voice : undefined) ?? null; +export const characterSpeed = (c) => (isObj(c?.synthetic) && typeof c.synthetic.speed === "number" ? c.synthetic.speed : null); +export const characterConvert = (c) => (c?.convert !== undefined ? c.convert : isObj(c?.recorded) ? c.recorded.convert : undefined); + +/** + * A character as a READER is handed it: version 2's shape, AND the `voice` / `convert` its presets answer to (what + * version 1's readers ask). Never written: the writer's characters are upgradeCharacter's. + */ +export function characterView(c) { + if (!isObj(c)) return c; + const u = upgradeCharacter(c); + const voice = characterVoice(u); + const convert = characterConvert(u); + return { ...u, ...(voice !== null ? { voice } : {}), ...(convert !== undefined ? { convert } : {}) }; +} + +/** What is wrong with a convert entry (`{engine?, voice?, pitch?, semitones?}`), as sentences that start at `w`. */ +function convertErrors(cv, w) { + if (!isObj(cv) || Object.keys(cv).some((k) => !["engine", "voice", "pitch", "semitones"].includes(k))) return [`${w} must be {engine?, voice?, pitch?, semitones?}`]; + const errors = convertPitchErrors(cv).map((m) => `${w}.${m}`); + if (cv.engine !== undefined && !CAST_CONVERT_ENGINES.includes(cv.engine)) errors.push(`${w}.engine must be one of ${CAST_CONVERT_ENGINES.join(", ")}`); + if (cv.voice !== undefined && !isQualifiedVoice(cv.voice)) errors.push(`${w}.voice must be a STOCK voice, "<engine>:<voice>" (never a file or a recording)`); + return errors; +} + +/** + * What is wrong with ONE character (upgraded: upgradeCharacter), as sentences that start at `w`. `layer` "cast" (a + * stock voice is required; it may be the narrator) or "project" (a preset is optional -- the layers under it answer + * -- and it may be `anonymous`, with the name it is `shown` under). Both layers refuse a voice, or a convert target, + * that is not a STOCK synthetic one. + */ +export function characterErrors(c, w, { layer = "cast" } = {}) { + const keys = layer === "project" ? PROJECT_CHARACTER_KEYS : CAST_KEYS; + if (!isObj(c)) return [`${w} must be {id, name, handles, synthetic, …}`]; + const errors = []; + for (const k of Object.keys(c)) if (!keys.includes(k)) errors.push(`${w}.${k} is not a character key (${keys.join(", ")})`); + if (!CHARACTER_ID_RE.test(str(c.id))) errors.push(`${w}.id must be lower case letters, digits, - and _ (got ${JSON.stringify(c.id)})`); + if (!str(c.name).trim() || str(c.name).length > 80) errors.push(`${w}.name must be 1-80 characters`); + if (!Array.isArray(c.handles ?? [])) errors.push(`${w}.handles must be a list of handles`); + else { + if ((c.handles ?? []).length > 20) errors.push(`${w}.handles: at most 20`); + for (const h of c.handles ?? []) if (typeof h !== "string" || !HANDLE_RE.test(h) || h !== handleKey(h)) errors.push(`${w}.handles: "${h}" is not a handle as the cast keys it (lower case, no @)`); + } + const syn = c.synthetic; + if (syn === undefined) { + if (layer === "cast") errors.push(`${w}.voice must be a STOCK voice with its engine, "<${CAST_TTS_ENGINES.join("|")}>:<voice>" (got ${JSON.stringify(undefined)})`); + } else if (!isObj(syn) || Object.keys(syn).some((k) => !SYNTHETIC_KEYS.includes(k))) errors.push(`${w}.synthetic must be {voice, speed?}`); + else { + if (!isQualifiedVoice(syn.voice)) errors.push(`${w}.voice must be a STOCK voice with its engine, "<${CAST_TTS_ENGINES.join("|")}>:<voice>" (got ${JSON.stringify(syn.voice)})`); + if (syn.speed !== undefined && !(typeof syn.speed === "number" && Number.isFinite(syn.speed) && syn.speed >= CAST_SPEED[0] && syn.speed <= CAST_SPEED[1])) errors.push(`${w}.synthetic.speed must be a number from ${CAST_SPEED[0]} to ${CAST_SPEED[1]}`); + } + const rec = c.recorded; + if (rec !== undefined) { + if (!isObj(rec) || Object.keys(rec).some((k) => !RECORDED_KEYS.includes(k))) errors.push(`${w}.recorded must be {convert?, enhance?, trim?, direction?}`); + else { + if (rec.convert !== undefined) errors.push(...convertErrors(rec.convert, `${w}.recorded.convert`)); + if (rec.enhance !== undefined && typeof rec.enhance !== "boolean") errors.push(`${w}.recorded.enhance must be true or false`); + if (rec.trim !== undefined) { + const t = rec.trim; + if (!isObj(t) || Object.keys(t).some((k) => !TRIM_KEYS.includes(k)) || (t.on !== undefined && typeof t.on !== "boolean")) errors.push(`${w}.recorded.trim must be {on?: true | false, padMs?}`); + else if (t.padMs !== undefined && !(typeof t.padMs === "number" && Number.isFinite(t.padMs) && t.padMs >= 0 && t.padMs <= TRIM_PAD_MAX_MS)) errors.push(`${w}.recorded.trim.padMs must be a number of milliseconds from 0 to ${TRIM_PAD_MAX_MS}`); + } + if (rec.direction !== undefined && (typeof rec.direction !== "string" || !rec.direction.trim() || rec.direction.length > DIRECTION_MAX || /[\r\n]/.test(rec.direction))) errors.push(`${w}.recorded.direction must be one line for the person reading (at most ${DIRECTION_MAX} characters)`); + } + } + if (c.speakers !== undefined && !(Array.isArray(c.speakers) && c.speakers.length <= 10 && c.speakers.every((s) => typeof s === "string" && SPEAKER_RE.test(s)))) errors.push(`${w}.speakers must be the names his real voice goes by in a project's speakers.json (at most 10)`); + for (const k of ["avatar", "note"]) if (c[k] !== undefined && (typeof c[k] !== "string" || c[k].length > 500)) errors.push(`${w}.${k} must be a string (at most 500)`); + if (c.narrator !== undefined && c.narrator !== true) errors.push(`${w}.narrator must be true or absent`); + if (layer === "project") { + if (c.anonymous !== undefined && c.anonymous !== true) errors.push(`${w}.anonymous must be true or absent`); + if (c.shown !== undefined && (typeof c.shown !== "string" || !c.shown.trim() || c.shown.length > 80)) errors.push(`${w}.shown must be the name it is shown under (1-80 characters)`); + if (c.shown !== undefined && c.anonymous !== true) errors.push(`${w}.shown is an anonymous character's shown name (anonymous: true)`); + } + return errors; +} + +/** A list of characters refused: each one's reasons, an id twice, a handle two characters hold. */ +function listErrors(list, where, layer) { const errors = []; - if (doc.format !== CAST_FORMAT) errors.push(`${where}: format must be "${CAST_FORMAT}"`); - if (doc.version !== CAST_VERSION) errors.push(`${where}: version must be ${CAST_VERSION}`); - const list = doc.characters; - if (!Array.isArray(list)) return [...errors, `${where}.characters must be a list`]; - if (list.length > CAST_MAX) errors.push(`${where}: at most ${CAST_MAX} characters`); const ids = new Set(); const owner = new Map(); - let narrators = 0; - list.forEach((c, i) => { + list.forEach((c0, i) => { const w = `${where}.characters[${i}]`; - if (!isObj(c)) return errors.push(`${w} must be {id, name, handles, voice, …}`); - for (const k of Object.keys(c)) if (!CAST_KEYS.includes(k)) errors.push(`${w}.${k} is not a character key (${CAST_KEYS.join(", ")})`); - if (!CHARACTER_ID_RE.test(str(c.id))) errors.push(`${w}.id must be lower case letters, digits, - and _ (got ${JSON.stringify(c.id)})`); - else if (ids.has(c.id)) errors.push(`${w}: two characters are "${c.id}"`); - ids.add(c.id); - if (!str(c.name).trim() || str(c.name).length > 80) errors.push(`${w}.name must be 1-80 characters`); - if (!Array.isArray(c.handles ?? [])) errors.push(`${w}.handles must be a list of handles`); - else { - if ((c.handles ?? []).length > 20) errors.push(`${w}.handles: at most 20`); - for (const h of c.handles ?? []) { - if (typeof h !== "string" || !HANDLE_RE.test(h) || h !== handleKey(h)) errors.push(`${w}.handles: "${h}" is not a handle as the cast keys it (lower case, no @)`); - else if (owner.has(h) && owner.get(h) !== c.id) errors.push(`${w}.handles: @${h} is ${owner.get(h)}'s already (a handle is one character's)`); - else owner.set(h, c.id); - } + const c = upgradeCharacter(c0); + errors.push(...characterErrors(c, w, { layer })); + if (!isObj(c)) return; + if (CHARACTER_ID_RE.test(str(c.id))) { + if (ids.has(c.id)) errors.push(`${w}: two characters are "${c.id}"`); + ids.add(c.id); } - if (!isQualifiedVoice(c.voice)) errors.push(`${w}.voice must be a STOCK voice with its engine, "<${CAST_TTS_ENGINES.join("|")}>:<voice>" (got ${JSON.stringify(c.voice)})`); - if (c.convert !== undefined) { - const cv = c.convert; - if (!isObj(cv) || Object.keys(cv).some((k) => !["engine", "voice", "pitch", "semitones"].includes(k))) errors.push(`${w}.convert must be {engine?, voice?, pitch?, semitones?}`); - else { - errors.push(...convertPitchErrors(cv).map((m) => `${w}.convert.${m}`)); - if (cv.engine !== undefined && !CAST_CONVERT_ENGINES.includes(cv.engine)) errors.push(`${w}.convert.engine must be one of ${CAST_CONVERT_ENGINES.join(", ")}`); - if (cv.voice !== undefined && !isQualifiedVoice(cv.voice)) errors.push(`${w}.convert.voice must be a STOCK voice, "<engine>:<voice>" (never a file or a recording)`); - } + for (const h of Array.isArray(c.handles) ? c.handles : []) { + if (typeof h !== "string" || h !== handleKey(h)) continue; + if (owner.has(h) && owner.get(h) !== c.id) errors.push(`${w}.handles: @${h} is ${owner.get(h)}'s already (a handle is one character's)`); + else owner.set(h, c.id); } - if (c.speakers !== undefined && !(Array.isArray(c.speakers) && c.speakers.length <= 10 && c.speakers.every((s) => typeof s === "string" && SPEAKER_RE.test(s)))) errors.push(`${w}.speakers must be the names his real voice goes by in a project's speakers.json (at most 10)`); - for (const k of ["avatar", "note"]) if (c[k] !== undefined && (typeof c[k] !== "string" || c[k].length > 500)) errors.push(`${w}.${k} must be a string (at most 500)`); - if (c.narrator !== undefined && c.narrator !== true) errors.push(`${w}.narrator must be true or absent`); - if (c.narrator === true) narrators += 1; }); - if (narrators > 1) errors.push(`${where}: one character at most is the narrator`); return errors; } -/** The cast's characters (the invalid ones dropped, never fatal for a reader). */ +/** Every reason a cast document is refused (empty: it is fine). A version 1 document is read as version 2. */ +export function validateCast(doc, where = "cast.json") { + if (!isObj(doc)) return [`${where} must be {"format": "${CAST_FORMAT}", "version": ${CAST_VERSION}, "characters": [...]}`]; + const errors = []; + if (doc.format !== CAST_FORMAT) errors.push(`${where}: format must be "${CAST_FORMAT}"`); + if (!CAST_VERSIONS_READ.includes(doc.version)) errors.push(`${where}: version must be ${CAST_VERSION} (or ${CAST_VERSIONS_READ.filter((v) => v !== CAST_VERSION).join(", ")}, read as it)`); + const list = doc.characters; + if (!Array.isArray(list)) return [...errors, `${where}.characters must be a list`]; + if (list.length > CAST_MAX) errors.push(`${where}: at most ${CAST_MAX} characters`); + errors.push(...listErrors(list, where, "cast")); + if (list.filter((c) => isObj(c) && c.narrator === true).length > 1) errors.push(`${where}: one character at most is the narrator`); + return errors; +} + +/** Every reason a project's characters document is refused (empty: it is fine). */ +export function validateProjectCharacters(doc, where = "characters.json") { + if (!isObj(doc)) return [`${where} must be {"format": "${PROJECT_CHARACTERS_FORMAT}", "version": ${PROJECT_CHARACTERS_VERSION}, "characters": [...]}`]; + const errors = []; + if (doc.format !== PROJECT_CHARACTERS_FORMAT) errors.push(`${where}: format must be "${PROJECT_CHARACTERS_FORMAT}"`); + if (doc.version !== PROJECT_CHARACTERS_VERSION) errors.push(`${where}: version must be ${PROJECT_CHARACTERS_VERSION}`); + const list = doc.characters; + if (!Array.isArray(list)) return [...errors, `${where}.characters must be a list`]; + if (list.length > CAST_MAX) errors.push(`${where}: at most ${CAST_MAX} characters`); + errors.push(...listErrors(list, where, "project")); + return errors; +} + +/** The cast's characters, as views (characterView) -- the invalid ones dropped, never fatal for a reader. */ export function charactersOf(cast) { - return (Array.isArray(cast?.characters) ? cast.characters : []).filter((c) => isObj(c) && CHARACTER_ID_RE.test(str(c.id)) && isQualifiedVoice(c.voice)); + return (Array.isArray(cast?.characters) ? cast.characters : []).filter((c) => isObj(c) && CHARACTER_ID_RE.test(str(c.id)) && isQualifiedVoice(characterVoice(c))).map(characterView); +} + +/** A project's own characters, as views -- one needs an id and a name; its presets are optional. */ +export function projectCharactersOf(doc) { + return (Array.isArray(doc?.characters) ? doc.characters : []).filter((c) => isObj(c) && CHARACTER_ID_RE.test(str(c.id)) && str(c.name).trim()).map(characterView); +} + +/** The name a character goes by on screen and in a read: an anonymous one's `shown` name, never its own. */ +export const shownNameOf = (c) => (c?.anonymous === true ? str(c.shown).trim() || ANON_NAME_PATTERN.replace("{n}", "1") : str(c?.name)); + +/** The next unused shown name of ANON_NAME_PATTERN among a project's characters ("Anon 3"). */ +export function nextAnonName(characters) { + const used = new Set((Array.isArray(characters) ? characters : []).flatMap((c) => [str(c?.shown).trim().toLowerCase(), str(c?.name).trim().toLowerCase()])); + for (let n = 1; ; n += 1) { + const name = ANON_NAME_PATTERN.replace("{n}", String(n)); + if (!used.has(name.toLowerCase())) return name; + } } /** The character a handle belongs to, or null. */ @@ -141,6 +313,102 @@ export function castVoiceMap(cast) { return out; } +/** A character's SYNTHETIC preset as a layer's entry (post-say.mjs voiceSourceOf): `{ voice, speed?, character }`, or null when it has no stock voice. */ +export function presetEntryOf(c) { + const voice = characterVoice(c); + if (!isQualifiedVoice(voice)) return null; + const speed = characterSpeed(c); + return { voice, ...(speed !== null && speed !== 1 ? { speed } : {}), character: c.id }; +} + +/** The cast as a preset layer: `{ "<handle>": { voice, speed?, character } }` -- castVoiceMap with each character's speed and id. */ +export function castPresetMap(cast) { + const out = {}; + for (const c of charactersOf(cast)) for (const h of c.handles ?? []) out[h] = presetEntryOf(c); + return out; +} + +/** + * THE PROJECT's LAYER, pure: its voice map (`narration/voices.json`: a handle in it reads as a project character with + * only a synthetic voice; "*" kept) under its own characters (`narration/characters.json`: each handle of one that + * HAS a synthetic voice) -- `{ "<handle>": "<voice>" | { voice, speed?, character } }`, voiceSourceOf's `map`. + */ +export function projectPresetMap(doc, voiceMap = {}) { + const out = { ...(isObj(voiceMap) ? voiceMap : {}) }; + for (const c of projectCharactersOf(doc)) { + const entry = presetEntryOf(c); + if (entry) for (const h of c.handles ?? []) out[h] = entry; + } + return out; +} + +/** The character an id names, the project's own first: `{ character, layer: "project" | "cast" }`, or null. */ +export function characterById(id, { project = null, cast = null } = {}) { + const k = str(id).trim().toLowerCase(); + if (!k) return null; + const p = projectCharactersOf(project).find((c) => c.id === k); + if (p) return { character: p, layer: "project" }; + const c = charactersOf(cast).find((x) => x.id === k); + return c ? { character: c, layer: "cast" } : null; +} + +/** The character a post item names for its own read (`narration.character`): `{ id, character, layer }` (character null: no such one), or null. */ +export function itemCharacterOf(e, layers = {}) { + const id = str(e?.narration?.character).trim(); + if (!id) return null; + const hit = characterById(id, layers); + return { id, character: hit?.character ?? null, layer: hit?.layer ?? null }; +} + +/** The item's own character as a layer's entry (voiceSourceOf's `item`), or null: none named, no such one, or one with no synthetic voice. */ +export function itemPresetOf(e, layers = {}) { + const it = itemCharacterOf(e, layers); + return it?.character ? presetEntryOf(it.character) : null; +} + +/** Can a character be a RECORDED read's (it has a recorded preset, or a stock voice to convert to)? */ +const readsRecorded = (c) => !!c && (isObj(c.recorded) || isQualifiedVoice(characterVoice(c))); + +/** + * THE CHARACTER A RECORDING OF POST ITEM `e` IS MADE INTO, pure -- the chain a synthesized read asks, for the + * recorded preset: `as` (the command's --as: an id, a handle or a name, the project's own first), the item's own + * character, the project's character for its author, the cast's, the cast's narrator. `{ character, layer: "flag" | + * "item" | "project" | "cast" | "narrator" }`, or null: no one to convert to. `as` that names no one is `{ character: + * null, layer: "flag" }`. + */ +export function characterForRead(e, { project = null, cast = null, as = null } = {}) { + const pchars = projectCharactersOf(project); + if (str(as).trim()) { + const r = str(as).trim().replace(/^@+/, ""); + const low = r.toLowerCase(); + const p = pchars.find((c) => c.id === low) ?? (str(as).trim().startsWith("@") ? null : pchars.find((c) => str(c.name).toLowerCase() === low)) ?? pchars.find((c) => (c.handles ?? []).includes(handleKey(r)) && readsRecorded(c)); + return { character: p ?? findCharacter(cast, r), layer: "flag" }; + } + const it = itemCharacterOf(e, { project, cast }); + if (readsRecorded(it?.character)) return { character: it.character, layer: "item" }; + const h = handleKey(e?.handle); + const p = h ? pchars.find((c) => (c.handles ?? []).includes(h)) : null; + if (readsRecorded(p)) return { character: p, layer: "project" }; + const c = characterOf(cast, h); + if (c) return { character: c, layer: "cast" }; + const n = narratorOf(cast); + return n ? { character: n, layer: "narrator" } : null; +} + +/** + * A character's RECORDED preset, its defaults filled: `{ convert: convertTargetOf, enhance (true unless it says + * false), trim: { on (true unless false), padMs (null: the recorder's own room) }, direction (null: none) }`. + */ +export function recordedPresetOf(c) { + const rec = isObj(c?.recorded) ? c.recorded : {}; + return { + convert: convertTargetOf(c), + enhance: rec.enhance !== false, + trim: { on: rec.trim?.on !== false, padMs: typeof rec.trim?.padMs === "number" ? rec.trim.padMs : null }, + direction: typeof rec.direction === "string" && rec.direction.trim() ? rec.direction.trim() : null, + }; +} + /** * What is wrong with a convert entry's pitch (`{engine?, pitch?, semitones?}`), as sentences that start at the key: * the mode is one of CAST_CONVERT_PITCH, the semitones a number within CAST_SEMITONES_MAX, a followed pitch is an @@ -171,9 +439,9 @@ export function convertPitchLabel(cv) { * entry says one, the pitch the read lands on (`pitch`, `semitones`; absent: the editor's default). */ export function convertTargetOf(c) { - const cv = c?.convert; + const cv = characterConvert(c); return { - engine: cv?.engine ?? null, voice: cv?.voice ?? c?.voice ?? null, + engine: cv?.engine ?? null, voice: cv?.voice ?? characterVoice(c) ?? null, ...(cv?.pitch !== undefined ? { pitch: cv.pitch } : {}), ...(cv?.semitones !== undefined ? { semitones: cv.semitones } : {}), }; } diff --git a/umtool/report-to-video/characters.test.mjs b/umtool/report-to-video/characters.test.mjs @@ -0,0 +1,191 @@ +// A character is a preset (cast.mjs): version 1's `voice` / `convert` read as the synthetic and recorded presets and +// back (a view), what each layer refuses, a project's own characters (anonymous ones, "Anon 1"), the chain one read +// asks -- the command's flags, the item's own character, the project's, the cast's, the narrator's, the default +// (post-say.mjs voiceSourceOf for a synthesized read; characterForRead for a recording) -- and the speed a part is +// asked at. +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { + ANON_NAME_PATTERN, CAST_VERSION, PROJECT_CHARACTERS_FILE, castPresetMap, castVoiceMap, characterById, characterForRead, characterView, charactersOf, convertTargetOf, emptyCast, + emptyProjectCharacters, itemCharacterOf, itemPresetOf, nextAnonName, projectCharactersOf, projectPresetMap, recordedPresetOf, shownNameOf, upgradeCast, upgradeCharacter, validateCast, + validateProjectCharacters, +} from "./cast.mjs"; +import { readSpeedOf, resolvePieceVoice, voiceSourceOf } from "./post-say.mjs"; + +// Version 1, as the files on disk are today. +const V1 = { + format: "umtool-cast", version: 1, + characters: [ + { id: "thequartering", name: "TheQuartering", handles: ["thequartering"], voice: "kokoro:am_michael", speakers: ["Jeremy"], note: "the host" }, + { id: "savvy", name: "MadamSavvy", handles: ["madamsavvy"], voice: "orpheus:tara", convert: { engine: "seed-vc", pitch: "contour", semitones: 2 }, narrator: true }, + ], +}; + +test("migration on read: version 1's voice and convert are the synthetic and recorded presets, the version bumps", () => { + assert.deepEqual(validateCast(V1), [], "a version 1 file is fine as it is"); + const up = upgradeCast(V1); + assert.equal(up.version, CAST_VERSION); + assert.equal(CAST_VERSION, 2); + assert.deepEqual(up.characters[0], { id: "thequartering", name: "TheQuartering", handles: ["thequartering"], synthetic: { voice: "kokoro:am_michael" }, speakers: ["Jeremy"], note: "the host" }); + assert.deepEqual(up.characters[1], { id: "savvy", name: "MadamSavvy", handles: ["madamsavvy"], synthetic: { voice: "orpheus:tara" }, recorded: { convert: { engine: "seed-vc", pitch: "contour", semitones: 2 } }, narrator: true }); + assert.deepEqual(validateCast(up), []); + assert.deepEqual(upgradeCast(up), up, "upgrading version 2 changes nothing"); + assert.equal(V1.characters[0].synthetic, undefined, "a copy: the document read is not touched"); + // Not a cast, or a version nobody reads: left as it is, and refused in words. + assert.equal(upgradeCast({ format: "x", version: 1, characters: [] }).version, 1); + assert.match(validateCast({ ...V1, version: 3 })[0], /version must be 2 \(or 1, read as it\)/); +}); + +test("migration the other way: a reader is handed the presets AND the voice / convert they answer to", () => { + const v2 = upgradeCast(V1); + const views = charactersOf(v2); + assert.equal(views[0].voice, "kokoro:am_michael"); + assert.deepEqual(views[0].synthetic, { voice: "kokoro:am_michael" }); + assert.deepEqual(views[1].convert, { engine: "seed-vc", pitch: "contour", semitones: 2 }); + assert.deepEqual(charactersOf(V1), views, "either version reads the same"); + assert.deepEqual(castVoiceMap(V1), castVoiceMap(v2)); + assert.deepEqual(convertTargetOf(V1.characters[1]), convertTargetOf(v2.characters[1])); + assert.deepEqual(convertTargetOf(v2.characters[1]), { engine: "seed-vc", voice: "orpheus:tara", pitch: "contour", semitones: 2 }); + // A view written back is the same character: its `voice` says what its preset says. + assert.deepEqual(upgradeCharacter(views[1]), v2.characters[1]); + assert.deepEqual(characterView(views[1]), views[1]); + // A version 1 writer's `c.voice = …` on a character read as version 2 is the word that counts. + assert.deepEqual(upgradeCharacter({ ...v2.characters[0], voice: "kokoro:am_onyx" }).synthetic, { voice: "kokoro:am_onyx" }); + assert.deepEqual(upgradeCharacter({ ...v2.characters[0], synthetic: { voice: "kokoro:am_michael", speed: 1.1 }, voice: "kokoro:am_onyx" }).synthetic, { voice: "kokoro:am_onyx", speed: 1.1 }, "its speed kept"); +}); + +test("validation: the presets' shape, in the cast -- a voice and a convert target are STOCK voices, never a file", () => { + const one = (c) => validateCast({ ...emptyCast(), characters: [{ id: "q", name: "Q", handles: ["q"], synthetic: { voice: "kokoro:am_michael" }, ...c }] }); + assert.deepEqual(one({}), []); + assert.deepEqual(one({ synthetic: { voice: "kokoro:am_michael", speed: 1.15 }, recorded: { convert: { engine: "seed-vc", voice: "kokoro:am_onyx", pitch: "source" }, enhance: false, trim: { on: true, padMs: 120 }, direction: "higher, brisk, amused" } }), []); + assert.ok(one({ synthetic: undefined }).some((e) => /voice must be a STOCK voice with its engine/.test(e)), "a cast character has a stock voice"); + assert.ok(one({ synthetic: { voice: "/home/me/jeremy.wav" } }).some((e) => /STOCK voice with its engine/.test(e))); + assert.ok(one({ synthetic: { voice: "kokoro:am_michael", speed: 3 } }).some((e) => /synthetic\.speed must be a number from 0\.5 to 2/.test(e))); + assert.ok(one({ synthetic: { voice: "kokoro:am_michael", emotion: "on" } }).some((e) => /synthetic must be \{voice, speed\?\}/.test(e))); + assert.ok(one({ recorded: { convert: { voice: "me.wav" } } }).some((e) => /recorded\.convert\.voice must be a STOCK voice.*never a file or a recording/.test(e))); + assert.ok(one({ recorded: { convert: { voice: "seedvc:/home/me.wav" } } }).some((e) => /never a file or a recording/.test(e))); + assert.ok(one({ recorded: { convert: { engine: "openvoice", pitch: "contour" } } }).some((e) => /pitch "contour" is seed-vc's/.test(e))); + assert.ok(one({ recorded: { enhance: "yes" } }).some((e) => /recorded\.enhance must be true or false/.test(e))); + assert.ok(one({ recorded: { trim: { on: "off" } } }).some((e) => /recorded\.trim must be \{on\?: true \| false, padMs\?\}/.test(e))); + assert.ok(one({ recorded: { trim: { padMs: 5000 } } }).some((e) => /trim\.padMs must be a number of milliseconds from 0 to 2000/.test(e))); + assert.ok(one({ recorded: { direction: "two\nlines" } }).some((e) => /direction must be one line for the person reading/.test(e))); + assert.ok(one({ recorded: { direction: "x".repeat(201) } }).some((e) => /at most 200/.test(e))); + assert.ok(one({ recorded: { model: "x" } }).some((e) => /recorded must be \{convert\?, enhance\?, trim\?, direction\?\}/.test(e))); + assert.ok(one({ anonymous: true }).some((e) => /anonymous is not a character key/.test(e)), "an anonymous character is never the pool's"); +}); + +test("a project's own characters: the same shape, a preset optional, anonymous ones under a shown name, no narrator", () => { + const doc = (chars) => ({ ...emptyProjectCharacters(), characters: chars }); + assert.equal(PROJECT_CHARACTERS_FILE, "narration/characters.json"); + assert.deepEqual(validateProjectCharacters(doc([])), []); + const anon = { id: "anon-1", name: "the reply guy", anonymous: true, shown: "Anon 1", handles: ["replyguy99"], synthetic: { voice: "kokoro:am_puck", speed: 0.9 } }; + const bare = { id: "witness", name: "A witness", handles: ["w1"] }; + assert.deepEqual(validateProjectCharacters(doc([anon, bare])), [], "a character with no preset leaves the voice to the layers under it"); + assert.match(validateProjectCharacters({ format: "umtool-cast", version: 2, characters: [] })[0], /format must be "umtool-project-characters"/); + assert.ok(validateProjectCharacters(doc([{ ...anon, narrator: true }])).some((e) => /narrator is not a character key/.test(e))); + assert.ok(validateProjectCharacters(doc([{ ...bare, shown: "Anon 2" }])).some((e) => /shown is an anonymous character's shown name/.test(e))); + assert.ok(validateProjectCharacters(doc([{ ...anon, anonymous: false }])).some((e) => /anonymous must be true or absent/.test(e))); + assert.ok(validateProjectCharacters(doc([anon, { ...bare, handles: ["replyguy99"] }])).some((e) => /@replyguy99 is anon-1's already/.test(e))); + assert.ok(validateProjectCharacters(doc([anon, { ...bare, id: "anon-1" }])).some((e) => /two characters are "anon-1"/.test(e))); + // Both layers refuse a convert target that is not a stock synthetic voice. + assert.ok(validateProjectCharacters(doc([{ ...bare, recorded: { convert: { voice: "narration/me.wav" } } }])).some((e) => /never a file or a recording/.test(e))); + assert.ok(validateProjectCharacters(doc([{ ...bare, synthetic: { voice: "operator" } }])).some((e) => /STOCK voice with its engine/.test(e))); + // The shown name: an anonymous character's, never its own; the next unused one of the pattern. + assert.equal(ANON_NAME_PATTERN, "Anon {n}"); + assert.equal(shownNameOf(anon), "Anon 1"); + assert.equal(shownNameOf(bare), "A witness"); + assert.equal(nextAnonName([]), "Anon 1"); + assert.equal(nextAnonName([anon, bare]), "Anon 2"); + assert.equal(nextAnonName([anon, { id: "b", name: "x", anonymous: true, shown: "anon 2" }]), "Anon 3", "any case"); + assert.deepEqual(projectCharactersOf(doc([anon, bare])).map((c) => [c.id, c.voice ?? null]), [["anon-1", "kokoro:am_puck"], ["witness", null]]); +}); + +// The layers of one project: the cast (V1), the project's own characters, its voice map. +const cast = upgradeCast(V1); +const own = { + ...emptyProjectCharacters(), + characters: [ + { id: "anon-1", name: "the reply guy", anonymous: true, shown: "Anon 1", handles: ["replyguy99"], synthetic: { voice: "kokoro:am_puck", speed: 0.9 }, recorded: { enhance: false, direction: "flat, tired" } }, + { id: "savvy-here", name: "Savvy, this video", handles: ["madamsavvy"], synthetic: { voice: "kokoro:af_bella", speed: 1.2 } }, + { id: "witness", name: "A witness", handles: ["thequartering"] }, + { id: "guest-star", name: "Guest star", handles: [], synthetic: { voice: "kokoro:bm_george", speed: 1.1 }, recorded: { convert: { voice: "kokoro:bm_lewis" }, trim: { on: false } } }, + ], +}; +const voiceMap = { madamsavvy: "leah", someone: "dan", "*": "zoe" }; + +test("the layers as voiceSourceOf takes them: the project's characters over its voice map, the cast with its speeds", () => { + const map = projectPresetMap(own, voiceMap); + assert.deepEqual(map, { + madamsavvy: { voice: "kokoro:af_bella", speed: 1.2, character: "savvy-here" }, someone: "dan", "*": "zoe", + replyguy99: { voice: "kokoro:am_puck", speed: 0.9, character: "anon-1" }, + }, "a character with a voice wins its handle; one with none (witness) leaves it; voices.json is kept for the rest"); + assert.deepEqual(projectPresetMap(null, voiceMap), voiceMap, "no characters.json: the voice map as it is"); + assert.deepEqual(castPresetMap(cast), { thequartering: { voice: "kokoro:am_michael", character: "thequartering" }, madamsavvy: { voice: "orpheus:tara", character: "savvy" } }); + assert.deepEqual(characterById("savvy", { project: own, cast })?.layer, "cast"); + assert.deepEqual(characterById("anon-1", { project: own, cast })?.layer, "project"); + assert.equal(characterById("nobody", { project: own, cast }), null); +}); + +test("the chain for a synthesized read, first hit wins: flags, the item's character, the project's, the cast's, the narrator's, the default", () => { + const e = { id: "p-1", handle: "MadamSavvy", narration: { character: "guest-star" } }; + const layers = { project: own, cast }; + const full = { map: projectPresetMap(own, voiceMap), cast: castPresetMap(cast), item: itemPresetOf(e, layers), self: e.handle, narrator: "zac", engine: "orpheus" }; + const her = { handle: "MadamSavvy", role: "post" }; + // 1. the command's flags. + assert.deepEqual(voiceSourceOf(her, { ...full, overrides: { madamsavvy: "leo" }, voice: "dan" }), { spec: "leo", from: "override" }); + assert.deepEqual(voiceSourceOf(her, { ...full, voice: "dan" }), { spec: "dan", from: "override" }); + // 2. the item's own character. + assert.deepEqual(voiceSourceOf(her, full), { spec: "kokoro:bm_george", from: "item", speed: 1.1, character: "guest-star" }); + assert.deepEqual(resolvePieceVoice(her, full), { engine: "kokoro", voice: "bm_george", from: "item", speed: 1.1, character: "guest-star" }); + // 3. the project's character for the handle -- over its own voice map, which is next. + assert.deepEqual(voiceSourceOf(her, { ...full, item: null }), { spec: "kokoro:af_bella", from: "project", speed: 1.2, character: "savvy-here" }); + assert.deepEqual(voiceSourceOf(her, { ...full, item: null, map: voiceMap }), { spec: "leah", from: "project" }, "voices.json alone: a project character with only a synthetic voice"); + // 4. the cast's. + assert.deepEqual(voiceSourceOf(her, { ...full, item: null, map: {} }), { spec: "orpheus:tara", from: "cast", character: "savvy" }); + // 5. the narrator's (the item's own author), 6. the map's "*", the default. + assert.deepEqual(voiceSourceOf(her, { ...full, item: null, map: {}, cast: {} }), { spec: "zac", from: "narrator" }); + assert.deepEqual(voiceSourceOf({ handle: "stranger", role: "parent:0" }, full), { spec: "zoe", from: "project" }); + assert.deepEqual(voiceSourceOf({ handle: "stranger", role: "parent:0" }, { ...full, map: {} }), { spec: "leo", from: "default" }); + // The item's character is its OWN words' -- another author's piece of the same read asks its own layers. + assert.deepEqual(voiceSourceOf({ handle: "replyguy99", role: "parent:0" }, full), { spec: "kokoro:am_puck", from: "project", speed: 0.9, character: "anon-1" }); + assert.deepEqual(voiceSourceOf({ handle: "TheQuartering", role: "quoted" }, full), { spec: "kokoro:am_michael", from: "cast", character: "thequartering" }, "a project character with no voice leaves it to the cast"); + // An item naming a character nobody has, or one with no voice: the layers under it. + assert.deepEqual(itemCharacterOf({ narration: { character: "ghost" } }, layers), { id: "ghost", character: null, layer: null }); + assert.equal(itemPresetOf({ narration: { character: "ghost" } }, layers), null); + assert.equal(itemPresetOf({ narration: { character: "witness" } }, layers), null); + assert.equal(itemPresetOf({ narration: {} }, layers), null); +}); + +test("the speed a part is asked at: the flag, the preset's, the item's own -- none for Orpheus, or at 1", () => { + assert.equal(readSpeedOf({ flag: 1.3, preset: 1.1, own: 0.9, engine: "kokoro" }), 1.3); + assert.equal(readSpeedOf({ preset: 1.1, own: 0.9, engine: "kokoro" }), 1.1); + assert.equal(readSpeedOf({ own: 0.9, engine: "kokoro" }), 0.9); + assert.equal(readSpeedOf({ engine: "kokoro" }), null); + assert.equal(readSpeedOf({ flag: 1.3, engine: "orpheus" }), null, "Orpheus has no speed"); + assert.equal(readSpeedOf({ flag: 1, preset: 1.2, engine: "kokoro" }), null, "the flag wins, and 1 is no speed"); +}); + +test("the chain for a recording: --as, the item's character, the project's for the author, the cast's, the narrator", () => { + const layers = { project: own, cast }; + const e = { id: "p-1", handle: "MadamSavvy", narration: { character: "guest-star" } }; + assert.deepEqual([characterForRead(e, { ...layers, as: "anon-1" }).character.id, characterForRead(e, { ...layers, as: "anon-1" }).layer], ["anon-1", "flag"]); + assert.equal(characterForRead(e, { ...layers, as: "@replyguy99" }).character.id, "anon-1", "by a handle"); + assert.equal(characterForRead(e, { ...layers, as: "TheQuartering" }).character.id, "thequartering", "the cast's, when the project has none of that name"); + assert.deepEqual(characterForRead(e, { ...layers, as: "nobody" }), { character: null, layer: "flag" }); + assert.deepEqual([characterForRead(e, layers).character.id, characterForRead(e, layers).layer], ["guest-star", "item"]); + const plain = { id: "p-2", handle: "MadamSavvy" }; + assert.deepEqual([characterForRead(plain, layers).character.id, characterForRead(plain, layers).layer], ["savvy-here", "project"]); + assert.deepEqual([characterForRead(plain, { cast }).character.id, characterForRead(plain, { cast }).layer], ["savvy", "cast"]); + // A project character with neither a voice nor a recorded preset names someone: it is not what a recording is made into. + assert.deepEqual([characterForRead({ handle: "TheQuartering" }, layers).character.id, characterForRead({ handle: "TheQuartering" }, layers).layer], ["thequartering", "cast"]); + assert.deepEqual([characterForRead({ handle: "stranger" }, layers).character.id, characterForRead({ handle: "stranger" }, layers).layer], ["savvy", "narrator"]); + assert.equal(characterForRead({ handle: "stranger" }, { cast: { ...cast, characters: [cast.characters[0]] } }), null, "nobody to convert to"); +}); + +test("a recorded preset, its defaults filled: cleaned and trimmed unless it says not, the convert target a stock voice", () => { + const [anon, , , star] = projectCharactersOf(own); + assert.deepEqual(recordedPresetOf(anon), { convert: { engine: null, voice: "kokoro:am_puck" }, enhance: false, trim: { on: true, padMs: null }, direction: "flat, tired" }); + assert.deepEqual(recordedPresetOf(star), { convert: { engine: null, voice: "kokoro:bm_lewis" }, enhance: true, trim: { on: false, padMs: null }, direction: null }); + assert.deepEqual(recordedPresetOf(charactersOf(cast)[1]), { convert: { engine: "seed-vc", voice: "orpheus:tara", pitch: "contour", semitones: 2 }, enhance: true, trim: { on: true, padMs: null }, direction: null }); + assert.deepEqual(recordedPresetOf({ id: "x", name: "X", recorded: { trim: { padMs: 120 } } }).trim, { on: true, padMs: 120 }); +}); diff --git a/umtool/report-to-video/post-narration.mjs b/umtool/report-to-video/post-narration.mjs @@ -190,13 +190,15 @@ const MIX_KEYS = ["lead", "tail", "ramp", "linger", "clip", "wet", "lowpassHz", // `follow`: the cut's read-follow (read-follow.mjs) -- { on, dim, ease } -- kept here with the mix it rides on. // `thread`: the cut's thread reads (post-thread.mjs) -- what each context post is on screen, the shrink and dim. const RENDER_KEYS = new Set([...MIX_KEYS.filter((k) => k !== "attach"), "engine", "voice", "follow", "thread"]); -const ITEM_KEYS = new Set([...MIX_KEYS, "script", "excerpt", "engine", "voice", "speed", "takes", "pick", "approved", "off", "window"]); +// `character`: the character THIS item's own read is made with (cast.mjs: the project's own, else the cast's) -- absent: by its author's handle. +const ITEM_KEYS = new Set([...MIX_KEYS, "script", "excerpt", "engine", "voice", "speed", "character", "takes", "pick", "approved", "off", "window"]); const TAKE_KEYS = new Set(["file", "engine", "voice", "seconds", "script", "at", "note", "speed", "lufs", "jobId", "parts", "label", "source", "steps", "words", "slurs", "lexicon", "read"]); const STEP_KEYS = new Set(["op", "engine", "voice", "pitch", "semitones", "params", "ranAt", "job", "drop", "tempo", "spans", "pauses", "revoice"]); // `role` (post-thread.mjs): the text a part reads -- "post", "quoted", "parent:<i>", "media:<i>"; `voice`, `piece`: the batch's; // `engine`: the part's own when it is not the take's (a cast voice that names its engine: postThreadRead.mjs). // `tempo`: the part's reading speed in the take's file against its first read (a `tempo` step's; absent: 1). -const PART_KEYS = new Set(["n", "para", "text", "file", "start", "seconds", "gapBefore", "note", "at", "jobId", "role", "voice", "engine", "piece", "tempo"]); +// `speed`: the speed the part was synthesized at (its character's preset's, or the read's --speed; absent: 1). +const PART_KEYS = new Set(["n", "para", "text", "file", "start", "seconds", "gapBefore", "note", "at", "jobId", "role", "voice", "engine", "piece", "tempo", "speed"]); const VOICE_RE = /^[A-Za-z0-9][A-Za-z0-9_.+-]{0,63}$/; /** Orpheus's expressive tags (narration.mjs NARRATION_TAGS, the editor's list). */ const TAGS = ["laugh", "chuckle", "sigh", "cough", "sniffle", "groan", "yawn", "gasp"]; @@ -607,6 +609,7 @@ export function validatePostNarration(e) { if (n.script !== undefined) errors.push(...scriptErrors(n.script, `${w}.script`)); for (const k of ["excerpt", "approved", "off"]) if (n[k] !== undefined && typeof n[k] !== "boolean") errors.push(`${w}.${k} must be true or false`); if (n.speed !== undefined && !numIn(n.speed, POST_NARRATION_LIMITS.speed)) errors.push(`${w}.speed must be ${POST_NARRATION_LIMITS.speed.join("–")}`); + if (n.character !== undefined && !(typeof n.character === "string" && /^[a-z0-9][a-z0-9_-]{0,47}$/.test(n.character))) errors.push(`${w}.character must be a character's id (umtool posts character)`); if (n.window !== undefined) { const x = n.window; if (!isObj(x) || !Number.isInteger(x.media) || !fin(x.start) || !fin(x.end) || x.end <= x.start || (x.score !== undefined && !fin(x.score)) || (x.reason !== undefined && typeof x.reason !== "string")) { @@ -702,6 +705,7 @@ export function validatePostNarration(e) { if (!(fin(p.start) && p.start >= 0)) errors.push(`${pw}.start must be where it starts in the take, seconds`); if (!(fin(p.seconds) && p.seconds > 0)) errors.push(`${pw}.seconds must be its length`); if (p.text !== undefined && typeof p.text !== "string") errors.push(`${pw}.text must be the words it reads`); + if (p.speed !== undefined && !numIn(p.speed, POST_NARRATION_LIMITS.speed)) errors.push(`${pw}.speed must be ${POST_NARRATION_LIMITS.speed.join("–")} (the speed it was synthesized at)`); if (p.tempo !== undefined && !numIn(p.tempo, POST_NARRATION_LIMITS.tempo)) errors.push(`${pw}.tempo must be ${POST_NARRATION_LIMITS.tempo.join("–")} (its reading speed in the take)`); if (p.role !== undefined && !(typeof p.role === "string" && /^(post|quoted|parent:\d|media:\d|linked:\d)$/.test(p.role))) errors.push(`${pw}.role must be post, quoted, parent:<i>, linked:<i> or media:<i> (the text it reads)`); if (p.engine !== undefined && !POST_NARRATION_ENGINES.includes(p.engine)) errors.push(`${pw}.engine must be one of ${POST_NARRATION_ENGINES.join(", ")}`); diff --git a/umtool/report-to-video/post-say.mjs b/umtool/report-to-video/post-say.mjs @@ -40,9 +40,10 @@ // "*" is everyone the map does not name (default: CONTEXT_VOICE_DEFAULTS for // the engine). The map is the project's OVERRIDE LAYER over THE CAST // (cast.mjs: the characters that recur across projects, each with its voice): -// the read's own override, the map, the cast, the narrator's (the item's own -// author), the map's "*", the default -- voiceForPiece, the one function every -// read goes through. +// the read's own override, the item's own character, the map (and the +// project's own characters: cast.mjs projectPresetMap), the cast, the +// narrator's (the item's own author), the map's "*", the default -- +// voiceSourceOf, the one function every read goes through. // // PURE and dependency-free. @@ -259,27 +260,49 @@ export function voiceRefOf(spec, engine = null) { /** `{engine, voice}` as `engine:voice` (bare when there is no engine). */ export const voiceSpecOf = (r) => (r?.engine ? `${r.engine}:${r.voice}` : str(r?.voice)); +/** A layer's entry as `{ voice, speed?, character? }`: a voice as written ("tara"), or a character's preset; null when it names no voice. */ +function entryOf(v) { + if (typeof v === "string") return v ? { voice: v } : null; + return isObj(v) && typeof v.voice === "string" && v.voice ? v : null; +} +const hit = (entry, from) => ({ + spec: entry.voice, from, + ...(typeof entry.speed === "number" && Number.isFinite(entry.speed) ? { speed: entry.speed } : {}), + ...(typeof entry.character === "string" && entry.character ? { character: entry.character } : {}), +}); + /** - * The voice one piece of a read is said in, and WHERE IT CAME FROM, pure: `{ spec, from }` -- `spec` as written - * (bare or `engine:voice`), `from` one of "override" (`--voice-for`, `--voice`), "project" (the map), "cast" (the - * cast's character for the handle), "narrator" (the item's own author: the narrator's voice), "default". In order: - * the run's own `overrides` (`--voice-for`), the item's `voice` for its own post (`--voice`), the map's for the - * author, the CAST's, the narrator's for the item's own author, the map's "*", the engine's context default, the - * narrator's. + * The voice one piece of a read is said in, and WHERE IT CAME FROM, pure: `{ spec, from, speed?, character? }` -- + * `spec` as written (bare or `engine:voice`), `from` one of "override" (`--voice-for`, `--voice`), "item" (the item's + * own character: `narration.character`), "project" (the project's character for the author, or its voice map), + * "cast" (the cast's character for the handle), "narrator" (the item's own author: the narrator's voice), "default"; + * `speed` the preset's (a character's `synthetic.speed`) and `character` its id, when the layer that answered is a + * character's. FIRST HIT WINS, in order: the run's own `overrides` (`--voice-for`), the item's `voice` for its own + * post (`--voice`), the item's own character for its author's words (`item`), the project's for the author (`map`), + * the CAST's, the narrator's for the item's own author, the map's "*", the engine's context default, the narrator's. + * + * A layer's entry (`map[h]`, `cast[h]`, `item`) is a voice as written or a character's synthetic preset + * `{ voice, speed?, character }` (cast.mjs presetEntryOf, projectPresetMap, castPresetMap). * * @param {{ handle?: string | null, role: string }} piece - * @param {{ map?: Record<string, string>, cast?: Record<string, string>, overrides?: Record<string, string>, + * @param {{ map?: Record<string, any>, cast?: Record<string, any>, item?: any, overrides?: Record<string, string>, * self?: string | null, voice?: string | null, narrator: string, engine?: string }} o */ -export function voiceSourceOf(piece, { map = {}, cast = {}, overrides = {}, self = null, voice = null, narrator, engine = "orpheus" }) { +export function voiceSourceOf(piece, { map = {}, cast = {}, item = null, overrides = {}, self = null, voice = null, narrator, engine = "orpheus" }) { const h = handleKey(piece?.handle); const mine = piece?.role === "post" || (!!h && h === handleKey(self)); if (h && overrides[h]) return { spec: overrides[h], from: "override" }; if (piece?.role === "post" && voice) return { spec: voice, from: "override" }; - if (h && h !== VOICE_MAP_OTHER && map[h]) return { spec: map[h], from: "project" }; - if (h && h !== VOICE_MAP_OTHER && cast?.[h]) return { spec: cast[h], from: "cast" }; + const own = mine ? entryOf(item) : null; + if (own) return hit(own, "item"); + const named = h && h !== VOICE_MAP_OTHER; + const p = named ? entryOf(map?.[h]) : null; + if (p) return hit(p, "project"); + const c = named ? entryOf(cast?.[h]) : null; + if (c) return hit(c, "cast"); if (mine) return { spec: narrator, from: "narrator" }; - if (map[VOICE_MAP_OTHER]) return { spec: map[VOICE_MAP_OTHER], from: "project" }; + const other = entryOf(map?.[VOICE_MAP_OTHER]); + if (other) return { spec: other.voice, from: "project" }; return { spec: CONTEXT_VOICE_DEFAULTS[engine] ?? narrator, from: "default" }; } @@ -289,13 +312,24 @@ export function voiceForPiece(piece, o) { } /** - * The voice one piece is said in, RESOLVED: `{ engine, voice, from }` -- a bare voice in the read's `engine`, one that - * names its own engine in that one. The thread read and a single post's take both ask this. + * The voice one piece is said in, RESOLVED: `{ engine, voice, from, speed?, character? }` -- a bare voice in the + * read's `engine`, one that names its own engine in that one; `speed` and `character` as voiceSourceOf says them. + * The thread read and a single post's take both ask this. */ export function resolvePieceVoice(piece, o) { - const { spec, from } = voiceSourceOf(piece, o); + const { spec, from, speed, character } = voiceSourceOf(piece, o); const ref = voiceRefOf(spec, o.engine ?? "orpheus") ?? { engine: o.engine ?? "orpheus", voice: String(spec) }; - return { engine: ref.engine ?? o.engine ?? "orpheus", voice: ref.voice, from }; + return { engine: ref.engine ?? o.engine ?? "orpheus", voice: ref.voice, from, ...(speed !== undefined ? { speed } : {}), ...(character ? { character } : {}) }; +} + +/** + * THE SPEED A PART IS ASKED AT, pure: the command's (`flag`), else the preset's (`preset`: the character's that + * answered for the voice), else the item's own (`own`: `narration.speed`, for its own words) -- and none (null) for + * an engine that has no speed (Orpheus), or at 1. + */ +export function readSpeedOf({ flag = null, preset = null, own = null, engine = null } = {}) { + const v = [flag, preset, own].find((x) => typeof x === "number" && Number.isFinite(x)); + return v === undefined || engine === "orpheus" || v === 1 ? null : v; } /** `--voice-for h=v` words as `{ handle: voice }` (handles keyed as the map keys them); throws naming a bad one. */