// 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, stored // ONCE for every project (`/.umtool/cast.json`, // lib/report/castStore.mjs its one writer). // // 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) // "synthetic": { "voice": "kokoro:am_michael", // : // "speed": 1.1, // the tts op's speed, 0.5-2 (absent: 1) // "tuning": { "temperature": 0.75, "top_p": 0.92, // ORPHEUS's tuning (absent: its // "repeat_penalty": 1.25, "takes": 4 } }, // defaults; a value equal to one is left out) // "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 (`/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. (The shown name is // what umtool's own surfaces call them, and what the cut's cards draw them as: post-anon.mjs.) // // A project's `narration/voices.json` (post-say.mjs) stays the project's // 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 (`:`): a character's // REAL voice (`speakers`) is a reference to compare a candidate with // (`umtool cast audition`, the Voices panel), never a target -- the editor's // convert op refuses a file as a target, and this file holds no path to one. // // PURE, no I/O (the CLI, the app and the lint read it); its one import outside this package is the tuning's ranges // and defaults (yt-dlp-transcript-common/lib/ttsTuning.mjs, plain ESM). import { CHARACTER_TUNING_FIELDS, ORPHEUS_DEFAULT_TAKES, ORPHEUS_TUNING_DEFAULTS, normalizeTtsTuning, parseTtsTuning, quantizeTtsTuningValue, ttsTuningValueError } from "yt-dlp-transcript-common/lib/ttsTuning.mjs"; import { CONTEXT_VOICE_DEFAULTS, TTS_ENGINE_IDS, handleKey, voiceRefOf, voiceSpecOf } from "./post-say.mjs"; export { voiceRefOf, voiceSpecOf }; export const CAST_FORMAT = "umtool-cast"; 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", "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", "tuning"]); 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"]); /** * The pitch a converted read lands on (the editor's voice-convert, common/lib/voiceApps.ts VoicePitch): the stock * voice's own (`target`), the pitch it was read at (`source`), or the read's rises and falls at the stock voice's * register (`contour`); `semitones` moves a followed one. The engines that can follow a pitch. */ export const CAST_CONVERT_PITCH = Object.freeze(["target", "source", "contour"]); export const CAST_PITCH_ENGINES = Object.freeze(["seed-vc"]); export const CAST_SEMITONES_MAX = 12; /** Which engine is heavy to run (the operator's rule: Orpheus pins ~8.5 GB; Kokoro first). */ export const ENGINE_WEIGHT = Object.freeze({ kokoro: "fast", "espeak-ng": "fast", orpheus: "heavy" }); const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); const str = (v) => (typeof v === "string" ? v : ""); export const CHARACTER_ID_RE = /^[a-z0-9][a-z0-9_-]{0,47}$/; const HANDLE_RE = /^[a-z0-9_.-]{1,64}$/; const SPEAKER_RE = /^[^\s/=,][^/=,]{0,47}$/; /** A stock voice with its engine named (a cast voice): "kokoro:am_michael". */ export const isQualifiedVoice = (spec) => !!voiceRefOf(spec) && str(spec).includes(":"); /** 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: [] }); 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. Where a preset says the key too, THE PRESET WINS: a top-level * `voice` / `convert` beside it is a view's alias (characterView), which may be stale -- a view whose * `synthetic.voice` was changed folds to the new value. (A writer's mutation that SETS `c.voice` the old way is told * apart by what the character was before: foldWritten.) 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 : { ...(voice !== undefined ? { voice } : {}), ...(synthetic ?? {}) }; const rec = recorded !== undefined && !isObj(recorded) ? recorded : { ...(convert !== undefined ? { convert } : {}), ...(recorded ?? {}) }; 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 character AS A WRITE LEAVES IT, folded to version 2 (pure): `c` what the mutation left, `before` the character it * was handed (version 2's, no aliases; null: a new one). A top-level `voice` / `convert` on it was put there by the * mutation -- the old way of setting one (`c.voice = …`) -- and is the newer word WHEN THE PRESET IS AS IT WAS; a * preset the mutation changed itself wins (the top-level key is then a stale alias: a view written back). */ export function foldWritten(c, before = null) { if (!isObj(c)) return c; const out = { ...c }; const same = (a, b) => JSON.stringify(a ?? null) === JSON.stringify(b ?? null); if (out.voice !== undefined && isObj(out.synthetic) && out.synthetic.voice !== undefined && before && same(before.synthetic?.voice, out.synthetic.voice)) out.synthetic = { ...out.synthetic, voice: out.voice }; if (out.convert !== undefined && isObj(out.recorded) && out.recorded.convert !== undefined && before && same(before.recorded?.convert, out.recorded.convert)) out.recorded = { ...out.recorded, convert: out.convert }; return upgradeCharacter(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) => (isObj(c?.synthetic) && c.synthetic.voice !== undefined ? c.synthetic.voice : c?.voice) ?? null; export const characterSpeed = (c) => (isObj(c?.synthetic) && typeof c.synthetic.speed === "number" ? c.synthetic.speed : null); export const characterConvert = (c) => (isObj(c?.recorded) && c.recorded.convert !== undefined ? c.recorded.convert : c?.convert); // --------------------------------------------------------------------------- // A CHARACTER's ORPHEUS TUNING (lane character-tuning, S2 of plans/orpheus-retune.md): `synthetic.tuning`, any of // temperature, top_p, repeat_penalty and takes (common/lib/ttsTuning.mjs CHARACTER_TUNING_FIELDS, its ranges). Kept // NORMALISED: a value equal to its default is left out (`takes` against ORPHEUS_DEFAULT_TAKES, as a re-read's flags // are: readTuning.mjs), and a tuning with nothing left is no key at all. It is the default for every Orpheus read the // character's preset answers for; a line's own tuning beats it (post-say.mjs readTuningOf). Kokoro and eSpeak NG // ignore it, as Orpheus ignores a speed. // --------------------------------------------------------------------------- /** A tuning as a character keeps it: the character fields only, quantised, each equal to its default left out. */ export const characterTuningNormal = (t) => { const n = normalizeTtsTuning(t, { takes: ORPHEUS_DEFAULT_TAKES }); const out = {}; for (const k of CHARACTER_TUNING_FIELDS) if (n[k] !== undefined) out[k] = n[k]; return out; }; /** A character's tuning (`synthetic.tuning`), normalised: `{}` for none. */ export const characterTuning = (c) => characterTuningNormal(isObj(c?.synthetic) ? c.synthetic.tuning : null); /** What is wrong with a character's tuning, as sentences that start at `w`. */ export function characterTuningErrors(t, w) { if (!isObj(t)) return [`${w} must be {${CHARACTER_TUNING_FIELDS.join("?, ")}?}`]; const errors = []; for (const k of Object.keys(t)) if (!CHARACTER_TUNING_FIELDS.includes(k)) errors.push(`${w}.${k} is not a character's tuning field (${CHARACTER_TUNING_FIELDS.join(", ")})`); if (errors.length) return errors; const parsed = parseTtsTuning(t, { name: w }); if (!parsed.ok) return [parsed.error.replace(/^"|"(?= must)/g, "")]; // parseTtsTuning leaves a null or undefined value out (an ask's "not given"); a kept tuning names numbers only. for (const k of Object.keys(t)) if (!(k in parsed.value)) errors.push(ttsTuningValueError(k, t[k], `${w}.${k}`)); if (errors.length) return errors; if (!Object.keys(t).length) return [`${w} names no value (leave it out for the defaults)`]; return []; } /** * The tuning a character's reads are ASKED WITH, every field filled: its own values over Orpheus's defaults, and * `takes` its own else `settingTakes` (the editor's tts.orpheus.takes: what a read with no takes of its own gets -- * never a number the read would not use). `{ temperature, top_p, top_k, min_p, repeat_penalty, takes }`. */ export function effectiveCharacterTuning(tuning, settingTakes = ORPHEUS_DEFAULT_TAKES) { const t = characterTuningNormal(tuning); return { ...ORPHEUS_TUNING_DEFAULTS, ...Object.fromEntries(Object.entries(t).filter(([k]) => k !== "takes")), takes: t.takes ?? settingTakes }; } /** * 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, ":" (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("|")}>:" (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?, tuning?}`); else { if (syn.tuning !== undefined) errors.push(...characterTuningErrors(syn.tuning, `${w}.synthetic.tuning`)); if (!isQualifiedVoice(syn.voice)) errors.push(`${w}.voice must be a STOCK voice with its engine, "<${CAST_TTS_ENGINES.join("|")}>:" (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 = []; const ids = new Set(); const owner = new Map(); list.forEach((c0, i) => { const w = `${where}.characters[${i}]`; 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); } 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); } }); return errors; } /** 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", { manifests = [] } = {}) { 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")); // Two anonymous characters are never shown under one name (on screen they would be one person). const shownSeen = new Map(); list.forEach((c, i) => { if (!isObj(c) || c.anonymous !== true || !str(c.shown).trim()) return; const k = str(c.shown).trim().toLowerCase(); if (shownSeen.has(k)) errors.push(`${where}.characters[${i}]: "${str(c.shown).trim()}" is ${shownSeen.get(k)}'s shown name already (two anonymous characters are never shown alike)`); else shownSeen.set(k, str(c.id)); }); // A shown name that is another character's handle, or (with the project's manifests) a real author's. errors.push(...anonShownClashes(list, manifests).map((m) => `${where}: ${m}`)); if (doc.proposed !== undefined) { if (!Array.isArray(doc.proposed)) errors.push(`${where}.proposed must be a list`); else { if (doc.proposed.length > CAST_MAX) errors.push(`${where}: at most ${CAST_MAX} proposed characters`); const taken = new Set(list.filter(isObj).map((c) => c.id)); const seen = new Set(); doc.proposed.forEach((p, i) => { const w = `${where}.proposed[${i}]`; errors.push(...proposalErrors(p, w)); if (!isObj(p)) return; if (taken.has(p.id)) errors.push(`${w}: "${p.id}" is a character already (accept makes it one)`); if (seen.has(p.id)) errors.push(`${w}: two proposals are "${p.id}"`); seen.add(p.id); }); } } return errors; } // --------------------------------------------------------------------------- // PROPOSED characters (C3, `umtool cast assign`): a project character a RULE (or, on request, a model) proposes for // an author with none -- held apart in the project's characters file (`proposed`, the same writer and undo), applied // to nothing until a person accepts it. // --------------------------------------------------------------------------- /** * THE STOCK VOICES a proposal may name, by engine -- common/lib/ttsApps.ts KOKORO_VOICES and ORPHEUS_VOICES (a test * holds them equal; this file does not import the editor's TypeScript). Kokoro's are `a*` American, `b*` British, `?f_` female, `?m_` male. */ export const STOCK_VOICES = Object.freeze({ kokoro: Object.freeze([ "af_alloy", "af_aoede", "af_bella", "af_heart", "af_jessica", "af_kore", "af_nicole", "af_nova", "af_river", "af_sarah", "af_sky", "am_adam", "am_echo", "am_eric", "am_fenrir", "am_liam", "am_michael", "am_onyx", "am_puck", "am_santa", "bf_alice", "bf_emma", "bf_isabella", "bf_lily", "bm_daniel", "bm_fable", "bm_george", "bm_lewis", ]), orpheus: Object.freeze(["tara", "leah", "jess", "leo", "dan", "mia", "zac", "zoe"]), }); /** Is `spec` one of the STOCK voices with its engine named ("kokoro:am_michael")? */ export const isStockVoice = (spec) => { const r = voiceRefOf(spec); return !!r?.engine && (STOCK_VOICES[r.engine] ?? []).includes(r.voice); }; /** A proposal's keys: a project character's, and who proposed it (`by`), why, and the model that did. */ export const PROPOSAL_KEYS = Object.freeze([...PROJECT_CHARACTER_KEYS, "by", "why", "model"]); /** Who a proposal's row is: the rule's, the model's, or a PERSON's (changed by hand: never re-sent to a model, never overwritten). */ export const PROPOSAL_BY = Object.freeze(["rule", "model", "person"]); export const PROPOSAL_WHY_MAX = 300; /** The character a proposal becomes when it is accepted (its own keys dropped), version 2's shape. */ export function proposalCharacter(p) { if (!isObj(p)) return p; const { by: _b, why: _w, model: _m, ...c } = p; return upgradeCharacter(c); } /** * What is wrong with ONE proposed character, as sentences that start at `w`: a project character's rules, and more -- * one handle at least, a SYNTHETIC preset whose voice is one of STOCK_VOICES (never a file, never a convert target: * a proposal's recorded preset is a direction line at most), who proposed it, a one-line why. */ export function proposalErrors(p, w) { if (!isObj(p)) return [`${w} must be {id, name, handles, synthetic, by, …}`]; const errors = []; for (const k of Object.keys(p)) if (!PROPOSAL_KEYS.includes(k)) errors.push(`${w}.${k} is not a proposal's key (${PROPOSAL_KEYS.join(", ")})`); const c = proposalCharacter(Object.fromEntries(Object.entries(p).filter(([k]) => PROPOSAL_KEYS.includes(k)))); errors.push(...characterErrors(c, w, { layer: "project" })); if (!Array.isArray(c.handles) || !c.handles.length) errors.push(`${w}.handles: a proposal is for an author (one handle at least)`); if (!isObj(c.synthetic) || !isStockVoice(c.synthetic.voice)) errors.push(`${w}.synthetic.voice must be one of the stock voices (${Object.keys(STOCK_VOICES).map((e) => `${e}:…`).join(", ")}), got ${JSON.stringify(c.synthetic?.voice)}`); if (c.recorded !== undefined && (!isObj(c.recorded) || Object.keys(c.recorded).some((k) => k !== "direction"))) errors.push(`${w}.recorded: a proposal carries a direction line at most (a convert target is set by a person)`); if (!PROPOSAL_BY.includes(p.by)) errors.push(`${w}.by must be ${PROPOSAL_BY.join(" or ")}`); if (p.why !== undefined && (typeof p.why !== "string" || p.why.length > PROPOSAL_WHY_MAX || /[\r\n]/.test(p.why))) errors.push(`${w}.why must be one line (at most ${PROPOSAL_WHY_MAX} characters)`); if (p.model !== undefined && (typeof p.model !== "string" || !p.model.trim() || p.model.length > 80)) errors.push(`${w}.model must be the model's name (at most 80 characters)`); return errors; } /** A project's PROPOSED characters (the valid-looking ones: an id and a handle), as they are held. */ export function proposalsOf(doc) { return (Array.isArray(doc?.proposed) ? doc.proposed : []).filter((p) => isObj(p) && CHARACTER_ID_RE.test(str(p.id)) && Array.isArray(p.handles) && p.handles.length); } /** An id for a handle's new character ("kirsche.verstahl" -> "kirsche-verstahl"). */ export const idOfHandle = (h) => str(h).toLowerCase().replace(/[^a-z0-9_-]/g, "-").replace(/^[^a-z0-9]+/, "").slice(0, 48) || "character"; /** 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(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 where umtool names it (the Voices page, `umtool cast project`, a recording's note): an * anonymous one's `shown` name, never its own -- the cut's on-screen card too (post-anon.mjs). */ export const shownNameOf = (c) => (c?.anonymous === true ? str(c.shown).trim() || ANON_NAME_PATTERN.replace("{n}", "1") : str(c?.name)); /** * EVERY anonymous character's shown name, distinct, pure: `Map` -- its own `shown`, else (a hand-made file: * the writers always set one) the next free "Anon n" in id order, past every shown name and name in the project. */ export function anonShownMap(characters) { const list = (Array.isArray(characters) ? characters : []).filter((c) => isObj(c) && c.anonymous === true && CHARACTER_ID_RE.test(str(c.id))); const out = new Map(); const used = new Set((Array.isArray(characters) ? characters : []).flatMap((c) => [str(c?.shown).trim().toLowerCase(), str(c?.name).trim().toLowerCase()]).filter(Boolean)); for (const c of list) if (str(c.shown).trim()) out.set(c.id, str(c.shown).trim()); for (const c of [...list].sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0))) { if (out.has(c.id)) continue; for (let n = 1; ; n += 1) { const name = ANON_NAME_PATTERN.replace("{n}", String(n)); if (used.has(name.toLowerCase())) continue; used.add(name.toLowerCase()); out.set(c.id, name); break; } } return out; } /** The shown name as a handle ("Anon 1" -> "Anon_1"): post-anon.mjs pseudonymOf's rule, here for the validator. */ const pseudonymKey = (shown) => str(shown).replace(/[^A-Za-z0-9_]+/g, "_").replace(/^_+|_+$/g, "").slice(0, 64).toLowerCase() || "anon"; /** * Every anonymous character's shown name (or its pseudonym) that is ALSO a real author's handle or display name in * `manifests` (their posts, parents, quoted, linked, repost, popups -- an author an anonymous character covers * excepted) or ANY other character's handle, case-insensitive: sentences naming characters, never a real handle. * `only`: these shown names alone. */ export function anonShownClashes(characters, manifests = [], { only = null } = {}) { const list = (Array.isArray(characters) ? characters : []).filter(isObj); const shown = anonShownMap(list); const covered = new Set(list.filter((c) => c.anonymous === true).flatMap((c) => (Array.isArray(c.handles) ? c.handles : []).map((h) => handleKey(h)))); const real = new Map(); const note = (v, what) => { const k = str(v).trim().toLowerCase().replace(/^@+/, ""); if (k && !real.has(k)) real.set(k, what); }; for (const m of manifests) { for (const e of [...(Array.isArray(m?.timeline) ? m.timeline : []).filter((x) => x?.type === "post"), ...(Array.isArray(m?.posts) ? m.posts : [])]) { for (const w of [e, ...(Array.isArray(e?.parents) ? e.parents : []), ...(Array.isArray(e?.links) ? e.links : []), e?.quoted, e?.repostedBy].filter(isObj)) { if (covered.has(handleKey(w.handle))) continue; note(w.handle, `an author's handle in ${str(e.id) || "a post"}`); note(w.author, `an author's name in ${str(e.id) || "a post"}`); } } } const errors = []; for (const c of list.filter((x) => x.anonymous === true)) { const s = shown.get(c.id); if (!s || (only && !only.has(s))) continue; for (const o of list) if (o !== c) for (const h of Array.isArray(o.handles) ? o.handles : []) if ([s.toLowerCase(), pseudonymKey(s)].includes(handleKey(h))) errors.push(`${c.id}'s shown name "${s}" is ${o.id}'s handle: an anonymous author's posts would be pinned on another -- give it another shown name`); const hit = real.get(s.toLowerCase()) ?? real.get(pseudonymKey(s)); if (hit) errors.push(`${c.id}'s shown name "${s}" is also ${hit}: an anonymous author's posts would be pinned on a real one -- give it another shown name`); } return errors; } /** 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. */ export function characterOf(cast, handle) { const h = handleKey(handle); if (!h) return null; return charactersOf(cast).find((c) => (c.handles ?? []).includes(h)) ?? null; } /** The character `ref` names: its id, a handle of it, or its name (any case). */ export function findCharacter(cast, ref) { const r = str(ref).trim(); if (!r) return null; const low = r.toLowerCase(); const list = charactersOf(cast); return list.find((c) => c.id === low) ?? characterOf(cast, r) ?? list.find((c) => str(c.name).toLowerCase() === low) ?? null; } /** The narrator character (`narrator: true`), or null. */ export const narratorOf = (cast) => charactersOf(cast).find((c) => c.narrator === true) ?? null; /** The cast as a voice map for its handles: `{ "": ":" }` (voiceForPiece's `cast`). */ export function castVoiceMap(cast) { const out = {}; for (const c of charactersOf(cast)) for (const h of c.handles ?? []) out[h] = c.voice; return out; } /** * A character's SYNTHETIC preset as a layer's entry (post-say.mjs voiceSourceOf): `{ voice, speed?, tuning?, character }`, * or null when it has no stock voice. `tuning` only when it has one: a character without is the entry it always was. */ export function presetEntryOf(c) { const voice = characterVoice(c); if (!isQualifiedVoice(voice)) return null; const speed = characterSpeed(c); const tuning = characterTuning(c); return { voice, ...(speed !== null && speed !== 1 ? { speed } : {}), ...(Object.keys(tuning).length ? { tuning } : {}), character: c.id }; } /** The cast as a preset layer: `{ "": { 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) -- `{ "": "" | { 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 * engine's that can follow one (CAST_PITCH_ENGINES; an entry with no engine takes the editor's default, which answers * for itself), and semitones move a FOLLOWED pitch. The editor's op refuses the same things in its own words. */ export function convertPitchErrors(cv) { const errors = []; const { engine, pitch, semitones } = cv ?? {}; if (pitch !== undefined && !CAST_CONVERT_PITCH.includes(pitch)) errors.push(`pitch must be one of ${CAST_CONVERT_PITCH.join(", ")}`); if (semitones !== undefined && !(typeof semitones === "number" && Number.isFinite(semitones) && Math.abs(semitones) <= CAST_SEMITONES_MAX)) errors.push(`semitones must be a number from -${CAST_SEMITONES_MAX} to ${CAST_SEMITONES_MAX}`); if (errors.length) return errors; const follows = pitch === "source" || pitch === "contour"; if (follows && engine !== undefined && !CAST_PITCH_ENGINES.includes(engine)) errors.push(`pitch "${pitch}" is ${CAST_PITCH_ENGINES.join(", ")}'s: ${engine} lands every read on the target's own pitch`); if (semitones && !follows) errors.push(`semitones moves a followed pitch: it needs pitch source or contour`); return errors; } /** How a convert entry's (or a step's) pitch is said: "contour +2 st", "source", "" for the target's own. */ export function convertPitchLabel(cv) { if (!cv?.pitch || cv.pitch === "target") return ""; const n = Number(cv.semitones) || 0; return n ? `${cv.pitch} ${n > 0 ? "+" : "−"}${Math.abs(n)} st` : cv.pitch; } /** * A character's convert target -- what a recording is made into: its convert voice, else its voice -- and, when the * entry says one, the pitch the read lands on (`pitch`, `semitones`; absent: the editor's default). */ export function convertTargetOf(c) { const cv = characterConvert(c); return { engine: cv?.engine ?? null, voice: cv?.voice ?? characterVoice(c) ?? null, ...(cv?.pitch !== undefined ? { pitch: cv.pitch } : {}), ...(cv?.semitones !== undefined ? { semitones: cv.semitones } : {}), }; } /** The names a character's real voice may go by in a project's speakers.json (lower case, no punctuation). */ const nameKey = (s) => str(s).toLowerCase().replace(/[^a-z0-9]/g, ""); export function speakerFor(character, speakers) { const names = [...(character?.speakers ?? []), character?.name, character?.id, ...(character?.handles ?? [])].map(nameKey).filter(Boolean); return (Array.isArray(speakers) ? speakers : []).find((s) => names.includes(nameKey(s?.name))) ?? null; } // --------------------------------------------------------------------------- // Who reads what in a project's picked takes, and where it drifts from the cast. // --------------------------------------------------------------------------- /** The handle a piece of a read is by: a role ("post", "parent:", "quoted", "linked:") of post item `e`. */ export function handleOfRole(e, role) { const r = str(role); if (r === "post") return str(e?.handle) || null; const m = /^parent:(\d)$/.exec(r); if (m) return str((Array.isArray(e?.parents) ? e.parents : [])[Number(m[1])]?.handle) || null; if (r === "quoted") return str(e?.quoted?.handle) || null; const l = /^linked:(\d)$/.exec(r); if (l) return str((Array.isArray(e?.links) ? e.links : [])[Number(l[1])]?.handle) || null; return null; } /** The take an item plays (narration.pick, else the first) -- post-narration.mjs pickedTake's rule, dependency-free. */ function playing(e) { const takes = Array.isArray(e?.narration?.takes) ? e.narration.takes : []; if (!takes.length || e?.narration?.off === true) return null; const k = Number.isInteger(e.narration.pick) && e.narration.pick >= 0 && e.narration.pick < takes.length ? e.narration.pick : 0; return takes[k] ?? null; } /** * WHAT A PICKED TAKE READS EACH AUTHOR IN, pure: `[{ handle, role, engine, voice, kind, speed? }]` -- a thread read by its * parts (each part's role and voice; its engine, else the take's), a single read as his post; `kind` "tts", * "recorded" (a person's own voice: `voice` is its label) or "converted" (a recording made a stock voice). `speed`: the * speed a synthesized read was asked at (a part's, a single take's), when it was asked one. */ export function takeReads(e, take = playing(e)) { if (!take) return []; const src = isObj(take.source) ? take.source : null; const steps = Array.isArray(take.steps) ? take.steps : []; const conv = steps.find((s) => s?.op === "convert"); if (conv) { const ref = voiceRefOf(conv.voice); return [{ handle: str(e?.handle) || null, role: "post", engine: ref?.engine ?? null, voice: ref?.voice ?? str(take.voice), kind: "converted" }]; } if (take.engine === "recorded" || src?.kind === "recorded") return [{ handle: str(e?.handle) || null, role: "post", engine: null, voice: str(take.voice || src?.voice || "operator"), kind: "recorded" }]; if (take.engine === "derived" || src?.kind === "take") return []; const parts = Array.isArray(take.parts) ? take.parts : []; if (parts.some((p) => typeof p?.role === "string" && typeof p?.voice === "string")) { const seen = new Map(); const takes = Array.isArray(e?.narration?.takes) ? e.narration.takes : []; for (const p of parts) { if (typeof p?.role !== "string" || typeof p?.voice !== "string") continue; const key = p.role; if (seen.has(key)) continue; // A part that IS another take of the item (a thread read's --post-take): read as that take reads. if (typeof p.take === "string") { const src = takes.find((x) => x !== take && isObj(x) && typeof x.file === "string" && (x.file === p.file || x.file.split("/").pop().replace(/\.wav$/i, "") === p.take)); const r = src && !isThreadTake(src) ? takeReads(e, src)[0] : null; seen.set(key, r ? { ...r, role: p.role, handle: handleOfRole(e, p.role) } : { handle: handleOfRole(e, p.role), role: p.role, engine: null, voice: p.voice, kind: "recorded" }); continue; } seen.set(key, { handle: handleOfRole(e, p.role), role: p.role, engine: str(p.engine) || str(take.engine) || null, voice: p.voice, kind: "tts", ...(typeof p.speed === "number" ? { speed: p.speed } : {}) }); } return [...seen.values()]; } return [{ handle: str(e?.handle) || null, role: "post", engine: str(take.engine) || null, voice: str(take.voice), kind: "tts", ...(typeof take.speed === "number" ? { speed: take.speed } : {}) }]; } /** Two voices the same (`{engine, voice}`; an engine unknown on either side compares by the voice). */ export const sameVoice = (a, b) => !!a && !!b && a.voice === b.voice && (!a.engine || !b.engine || a.engine === b.engine); /** A speed as the drift compares it: none, or 1, is the voice's own. */ const speedKey = (s) => (typeof s === "number" && Number.isFinite(s) && s !== 1 ? s : null); /** Two speeds the same (none and 1 are one). */ export const sameSpeed = (a, b) => speedKey(a) === speedKey(b); /** A voice as a drift row says it: "kokoro:am_michael", with its speed when it has one ("kokoro:am_michael ×1.1"). */ const driftSpec = (v, speed) => `${voiceSpecOf(v)}${speedKey(speed) !== null ? ` ×${speedKey(speed)}` : ""}`; /** Is a take a thread read (its parts in their authors' voices)? */ export const isThreadTake = (t) => t?.read?.kind === "thread" || /-thread\.wav$/.test(str(t?.file)) || (Array.isArray(t?.parts) && new Set(t.parts.map((p) => p?.voice).filter(Boolean)).size > 1); /** * EVERY PICKED READ IN ANOTHER VOICE THAN THE ONE IT WOULD BE READ IN NOW, pure: `[{ id, handle, role, reads, want, * from, kind, thread }]` -- `resolve(e, role, handle, take, read)` says the voice now (`{ engine, voice, from, speed? }`, * or null: nothing to compare). A synthesized read AT ANOTHER SPEED than its preset's now is one too (its `reads` and * `want` say the speeds: "kokoro:am_michael ×1.1"). A recorded read (a person's own voice) is never one. */ export function voiceDrift(manifest, resolve) { const rows = []; for (const e of Array.isArray(manifest?.timeline) ? manifest.timeline : []) { if (e?.type !== "post") continue; const take = playing(e); for (const r of takeReads(e, take)) { if (!r.handle || r.kind === "recorded") continue; const want = resolve(e, r.role, r.handle, take, r); // A converted read is compared by its voice alone (a recording has no tts speed). const speedToo = r.kind === "tts"; if (!want || (sameVoice({ engine: r.engine, voice: r.voice }, want) && (!speedToo || sameSpeed(r.speed, want.speed)))) continue; const withSpeed = speedToo && (speedKey(r.speed) !== null || speedKey(want.speed) !== null); rows.push({ id: e.id, handle: handleKey(r.handle), role: r.role, reads: withSpeed ? driftSpec({ engine: r.engine, voice: r.voice }, r.speed) : voiceSpecOf({ engine: r.engine, voice: r.voice }), want: withSpeed ? driftSpec(want, want.speed) : voiceSpecOf(want), from: want.from ?? null, kind: r.kind, thread: isThreadTake(take), }); } } return rows; } /** * WHERE A PROJECT DRIFTS FROM THE CAST, pure -- the consistency guard (`umtool lint`, the Voices panel): * drift a cast character whose picked read is in another voice than the one it reads in now (stale: re-read * it) -- voiceDrift's rows for the cast's handles, each with its `character` * overrides a cast character the project's map gives another voice ON PURPOSE -- fine, shown: * `[{ handle, character, cast, project }]` * * @param {Record} manifest * @param {{ cast: any, map?: Record, resolve: Function }} o */ export function castDrift(manifest, { cast, map = {}, resolve }) { const drift = voiceDrift(manifest, resolve).flatMap((r) => { const c = characterOf(cast, r.handle); return c ? [{ ...r, character: c.id }] : []; }); const overrides = []; for (const [h, v] of Object.entries(map ?? {})) { const c = characterOf(cast, h); if (!c) continue; if (voiceSpecOf(voiceRefOf(v, voiceRefOf(c.voice)?.engine)) !== c.voice) overrides.push({ handle: h, character: c.id, cast: c.voice, project: v }); } return { drift, overrides }; } // --------------------------------------------------------------------------- // STALE READS (lane character-tuning): a picked Orpheus read made with other settings than its character's now. // --------------------------------------------------------------------------- const SAMPLER_FIELDS = Object.freeze(["temperature", "top_p", "top_k", "min_p", "repeat_penalty"]); /** A tuning's sampler values, every one filled (a missing one is Orpheus's default), quantised. */ const samplerOf = (t) => Object.fromEntries(SAMPLER_FIELDS.map((k) => { const q = quantizeTtsTuningValue(k, isObj(t) ? t[k] : undefined); return [k, typeof q === "number" && Number.isFinite(q) ? q : ORPHEUS_TUNING_DEFAULTS[k]]; })); /** The take of item `e` a thread read's part names (`{ take: "", file }`): the item's take with that file or id, else null. */ function partSourceTake(e, take, part) { const takes = Array.isArray(e?.narration?.takes) ? e.narration.takes : []; return takes.find((x) => x !== take && isObj(x) && typeof x.file === "string" && (x.file === part.file || x.file.split("/").pop().replace(/\.wav$/i, "") === part.take)) ?? null; } /** * HOW ONE READ OF A PICKED TAKE WAS MADE (`role`): `{ tuning, asked, reading }` -- the tuning as the editor reported it * (a thread read's synthesized part of that role, else the take's own; null when it records none: made with the * defaults), where it came from (the take's `tuningAsked`: true, "preset" or undefined) and its reading. A thread * read's part that IS another take of the item (`{ take: "" }`, --post-take) answers as that take does. */ export function madeOf(e, take, role = "post", seen = new Set()) { const parts = Array.isArray(take?.parts) ? take.parts : []; const ref = parts.find((p) => p?.role === role && typeof p?.take === "string"); if (ref && !seen.has(take)) { const src = partSourceTake(e, take, ref); if (src && !isThreadTake(src)) return madeOf(e, src, "post", new Set([...seen, take])); } const part = parts.find((p) => p?.role === role && typeof p?.take !== "string" && isObj(p?.tuning)); // Where it came from: the piece's own part says so (one asked its explicit defaults has a provenance and no tuning). const said = parts.find((p) => p?.role === role && typeof p?.take !== "string" && p?.tuningAsked !== undefined); // THE VALUES ITS LINE OWNED (lane reads-find, review 1): a thread piece's `read.tuned[role].tuning` (the read's own // values for it), else the take's `tuningOwn` -- never judged against a character's (a plain press passes them back). const tuned = isObj(take?.read?.tuned) && isObj(take.read.tuned[role]) ? take.read.tuned[role] : null; const own = tuned ? (isObj(tuned.tuning) ? tuned.tuning : null) : role === "post" || !parts.some((p) => p?.role === role) ? (isObj(take?.tuningOwn) ? take.tuningOwn : null) : null; return { tuning: part ? part.tuning : isObj(take?.tuning) ? take.tuning : null, // A thread read's part says where its own tuning came from; else the take does. asked: said?.tuningAsked ?? part?.tuningAsked ?? take?.tuningAsked, reading: Number.isInteger(take?.reading) ? take.reading : 0, own, }; } /** * A thread read's SCREEN LINES as reads (`[{ handle, role, engine, voice, kind: "tts" }]`, one per line): each line * synthesized in its speaker's voice, its handle the speaker as written (a line whose speaker is a handle answers to * that handle's character; one named otherwise answers to none here). takeReads leaves them out (drift does not judge * them); the stale list does. */ function screenReadsOf(take) { const seen = new Map(); for (const p of Array.isArray(take?.parts) ? take.parts : []) { if (typeof p?.role !== "string" || !p.role.startsWith("screen:") || typeof p.take === "string" || typeof p.voice !== "string" || seen.has(p.role)) continue; const h = handleKey(str(p.speaker)); if (!h) continue; seen.set(p.role, { handle: h, role: p.role, engine: str(p.engine) || str(take.engine) || null, voice: p.voice, kind: "tts" }); } return [...seen.values()]; } /** * EVERY PICKED ORPHEUS READ OF A CHARACTER MADE WITH OTHER SETTINGS THAN ITS TUNING NOW, pure -- `[{ id, handle, role, * character, made, want, reading, thread }]`. `resolve(e, role, handle, take, read)` says the voice now as castProject.mjs * resolverFor does (`{ engine, voice, character?, tuning? }`). A read is STALE when all of these hold: * - it is synthesized, by Orpheus (a recorded, converted or derived read never is) -- a post's take, a thread read's * pieces, and its screen lines (screenReadsOf); * - a character's preset answers for it now (the item's own, this video's, the cast's), in the voice it was made * in (another voice is drift: cast.mjs voiceDrift); * - its tuning was not ASKED BY THE LINE: the take's `tuningAsked` is not true -- and a take that says nothing of * where its tuning came from but records a SAMPLER value off the defaults was asked so (S1's flags; its takes are * never looked at here: they record the editor's setting at the time, which may have changed since); * a thread read's part that is another take answers as that take does (madeOf); * - a value its line OWNS (the take's `tuningOwn`, a thread piece's `read.tuned[role].tuning`; lane reads-find) is * never compared, its takes included; * - the tuning it was made with (none recorded: the defaults) differs from the character's: the sampler's five * values, each a default when unsaid; `takes` ONLY when the character names its takes (a read with none of its own * records the editor's setting, `settingTakes`); the reading is never compared (a reading is a pick, not a setting). */ export function tuningStale(manifest, resolve, { settingTakes = ORPHEUS_DEFAULT_TAKES } = {}) { const rows = []; const defaults = samplerOf(null); for (const e of Array.isArray(manifest?.timeline) ? manifest.timeline : []) { if (e?.type !== "post") continue; const take = playing(e); if (!take) continue; for (const r of [...takeReads(e, take), ...screenReadsOf(take)]) { if (r.kind !== "tts" || !r.handle || r.engine !== "orpheus") continue; const want = resolve(e, r.role, r.handle, take, r); if (!want?.character || want.engine !== "orpheus" || !sameVoice({ engine: r.engine, voice: r.voice }, want)) continue; const how = madeOf(e, take, r.role); const made = how.tuning; const madeS = samplerOf(made); const madeTakes = isObj(made) && Number.isInteger(made.takes) ? made.takes : null; // Asked by its line: said so, or (saying nothing) a sampler value off the defaults -- never judged by its takes. const off = SAMPLER_FIELDS.some((k) => madeS[k] !== defaults[k]); if (how.asked === true || (how.asked === undefined && off)) continue; const wantT = characterTuningNormal(want.tuning); const wantS = samplerOf(wantT); // A value the line OWNS (madeOf's `own`, takes included) is the line's, never the character's: not compared. const owns = (k) => isObj(how.own) && typeof how.own[k] === "number"; const differs = SAMPLER_FIELDS.some((k) => !owns(k) && madeS[k] !== wantS[k]) || (!owns("takes") && wantT.takes !== undefined && (madeTakes ?? settingTakes) !== wantT.takes); if (!differs) continue; rows.push({ id: e.id, handle: handleKey(r.handle), role: r.role, character: want.character, made: { ...madeS, takes: madeTakes ?? settingTakes }, want: effectiveCharacterTuning(wantT, settingTakes), reading: how.reading, thread: isThreadTake(take), }); } } return rows; } /** The voice an engine reads a context author in when nothing names one (re-exported for the panel). */ export { CONTEXT_VOICE_DEFAULTS };