// AUTO-ASSIGNMENT BY RULE (characters C3; `umtool cast assign`, the Voices page's Propose): every post item's author // gets a character -- the one the layers already give them (the item's own, this video's, its voice map's, the // cast's) or, for an author with none, a PROPOSED character of this video (cast.mjs proposalErrors): an id from the // handle, the author's name, and a STOCK synthetic voice chosen by rotation through the voices this project does not // use yet, in one fixed order. A gender hint comes only from the profile's OWN stated pronouns, when the capture // carries them (`pronouns`, or "she/her" … in `bio`); otherwise the rotation is neutral. No model: a model's // proposals (`--model`) are laid over these rows by mergeModelProposal, never instead of them. // // PURE and dependency-free beyond cast.mjs / post-say.mjs (the CLI and the tests read it). import { CAST_SPEED, CHARACTER_ID_RE, DIRECTION_MAX, STOCK_VOICES, characterOf, charactersOf, idOfHandle, isStockVoice, projectCharactersOf, proposalErrors, proposalsOf } from "./cast.mjs"; import { handleKey, voiceRefOf, voiceSpecOf } from "./post-say.mjs"; import { anonymousHandles } from "./post-anon.mjs"; const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); const str = (v) => (typeof v === "string" ? v : ""); /** The engine a rule's proposal reads in (Kokoro: fast, on the CPU -- the operator's rule, Orpheus heavy). */ export const ASSIGN_ENGINE = "kokoro"; /** A Kokoro voice's gender by its name (`?f_` / `?m_`), or null. */ export const voiceGender = (voice) => (/^[ab]f_/.test(str(voice)) ? "f" : /^[ab]m_/.test(str(voice)) ? "m" : null); /** * THE ROTATION, in one fixed order: Kokoro's American voices, a male and a female in turn, then its British ones the * same way -- so a neutral rotation alternates. Every stock Kokoro voice is in it once. */ export const ASSIGN_ROTATION = Object.freeze((() => { const all = STOCK_VOICES.kokoro; const turn = (a, b) => Array.from({ length: Math.max(a.length, b.length) }, (_, i) => [a[i], b[i]]).flat().filter(Boolean); const of = (re) => all.filter((v) => re.test(v)); return [...turn(of(/^am_/), of(/^af_/)), ...turn(of(/^bm_/), of(/^bf_/))].map((v) => `${ASSIGN_ENGINE}:${v}`); })()); /** * The pronouns an author's profile STATES, read from the capture's own words only: `pronouns` ("she/her"), else a * "she/her" / "he/him" / "they/them" in `bio` -- `"she" | "he" | "they"`, or null (nothing stated: no hint). */ export function statedPronounsOf(who) { const said = [str(who?.pronouns), str(who?.bio)].join(" ").toLowerCase(); const m = /\b(she|he|they)\s*\/\s*(her|hers|him|his|them|theirs|she|he|they)\b/.exec(said); if (!m) return null; return m[1]; } /** The gender a voice is chosen by for stated pronouns: "f", "m", or null (they: the neutral rotation). */ const hintOf = (pronouns) => (pronouns === "she" ? "f" : pronouns === "he" ? "m" : null); /** * The next voice of the rotation: the first not in `used` (specs, compared whole) whose gender is the hint's (none: * any); when every one is used, the one used least among `taken` (this run's proposals) in the rotation's order. */ export function rotationVoice(used, { hint = null, taken = [] } = {}) { const fits = ASSIGN_ROTATION.filter((s) => !hint || voiceGender(voiceRefOf(s)?.voice) === hint); const pool = fits.length ? fits : ASSIGN_ROTATION; const free = pool.find((s) => !used.has(s)); if (free) return free; const count = (s) => taken.filter((t) => t === s).length; return [...pool].sort((a, b) => count(a) - count(b) || pool.indexOf(a) - pool.indexOf(b))[0]; } /** The post items' authors in the order they come on: `[{ handle, name, items: id[], named: id[], post: e }]` (`named`: items that name their own character). */ export function itemAuthorsOf(manifest) { const out = new Map(); for (const e of Array.isArray(manifest?.timeline) ? manifest.timeline : []) { if (e?.type !== "post") continue; const h = handleKey(e.handle); if (!h || h === "*") continue; const a = out.get(h) ?? { handle: h, name: "", items: [], named: [], post: e }; if (!a.name && str(e.author).trim()) a.name = str(e.author).trim(); a.items.push(e.id); if (str(e.narration?.character).trim()) a.named.push(e.id); out.set(h, a); } return [...out.values()]; } /** A free id for a handle's proposal: idOfHandle, then `-2`, `-3` … past every id in `taken`. */ export function freeIdOf(h, taken) { const base = idOfHandle(h); if (!taken.has(base)) return base; for (let n = 2; ; n += 1) { const id = `${base.slice(0, 48 - String(n).length - 1)}-${n}`; if (!taken.has(id)) return id; } } /** * THE PLAN, pure: for every post item's author, what gives them a character now and, for one with none, the proposal * -- `{ authors: [{ handle, name, items, state, character?, voice?, proposal? }], proposals: [new], moot: [ids] }`. * state "anonymous" an anonymous character covers them (post-anon.mjs anonymousHandles: its handles, or an item * naming it): left alone, and never sent to a model * "item" every item of theirs names its own character (a person chose: left alone) * "project" this video's character holds the handle "map" its voice map names them (voices.json) * "cast" the cast's character holds it "proposed" a proposal for them is held already * "propose" none: `proposal` is the new one * `moot`: held proposals whose author has a character now (a write drops them). `used` are the voice specs the * project reads in now (the Voices view's: every author's, the narrator's), laid over the layers' own. * * @param {Record} manifest * @param {{ project?: any, cast?: any, map?: Record, used?: string[] }} [o] */ export function assignPlan(manifest, { project = null, cast = null, map = {}, used = [] } = {}) { const own = projectCharactersOf(project); const held = proposalsOf(project); const castChars = charactersOf(cast); const usedSet = new Set(used.filter(Boolean)); for (const c of own) if (c.voice) usedSet.add(c.voice); for (const c of castChars) if (c.voice) usedSet.add(c.voice); for (const v of Object.values(isObj(map) ? map : {})) { const spec = typeof v === "string" ? v : str(v?.voice); const r = voiceRefOf(spec, ASSIGN_ENGINE); if (r) usedSet.add(voiceSpecOf(r)); } for (const p of held) if (p.synthetic?.voice) usedSet.add(p.synthetic.voice); const ids = new Set([...own.map((c) => c.id), ...castChars.map((c) => c.id), ...held.map((p) => p.id)]); // ANONYMITY BELONGS TO THE HANDLE (post-anon.mjs): an author an anonymous character covers is never proposed for. const anon = anonymousHandles(project, manifest); const authors = []; const proposals = []; const taken = []; const answered = new Set(); for (const a of itemAuthorsOf(manifest)) { const row = { handle: a.handle, name: a.name || a.handle, items: a.items }; const p = own.find((c) => (c.handles ?? []).includes(a.handle)); const c = characterOf(cast, a.handle); const inMap = isObj(map) && Object.prototype.hasOwnProperty.call(map, a.handle); const prop = held.find((x) => (x.handles ?? []).includes(a.handle)); if (anon.has(a.handle)) authors.push({ ...row, state: "anonymous" }); else if (a.named.length === a.items.length) authors.push({ ...row, state: "item" }); else if (p) authors.push({ ...row, state: "project", character: p.id, ...(p.voice ? { voice: p.voice } : {}) }); else if (inMap) authors.push({ ...row, state: "map", voice: typeof map[a.handle] === "string" ? map[a.handle] : str(map[a.handle]?.voice) }); else if (c) authors.push({ ...row, state: "cast", character: c.id, voice: c.voice }); else if (prop) authors.push({ ...row, state: "proposed", character: prop.id, voice: prop.synthetic?.voice ?? null, proposal: prop }); else { const pronouns = statedPronounsOf(a.post); const hint = hintOf(pronouns); const exhausted = ASSIGN_ROTATION.every((s) => usedSet.has(s)); const voice = rotationVoice(usedSet, { hint, taken }); usedSet.add(voice); taken.push(voice); const id = freeIdOf(a.handle, ids); ids.add(id); const proposal = { id, name: row.name.slice(0, 80), handles: [a.handle], synthetic: { voice }, by: "rule", why: `no character: ${exhausted ? "every stock voice is in use here; the one this run used least" : "the next stock voice this project does not use"}${pronouns ? ` (their profile states ${pronouns}/…)` : ""}`.slice(0, 300), }; proposals.push(proposal); authors.push({ ...row, state: "propose", character: id, voice, proposal }); } if (authors.at(-1).state !== "proposed" && authors.at(-1).state !== "propose") answered.add(a.handle); } // A held proposal whose author has a character now (or is no longer in the cut) is moot. const inCut = new Set(authors.map((a) => a.handle)); const moot = held.filter((p) => (p.handles ?? []).every((h) => answered.has(h) || !inCut.has(h))).map((p) => p.id); return { authors, proposals, moot }; } // --------------------------------------------------------------------------- // The MODEL's answer, merged into the rule's rows (C3, `--model`): untrusted text, schema-checked field by field. // --------------------------------------------------------------------------- /** What a model is asked for, per author: its JSON schema (the local route's `format`, the API's tool input). */ export const CAST_ASSIGN_SCHEMA = Object.freeze({ type: "object", properties: { authors: { type: "array", items: { type: "object", properties: { handle: { type: "string" }, character: { type: "string" }, voice: { type: "string", enum: Object.entries(STOCK_VOICES).flatMap(([e, vs]) => vs.map((v) => `${e}:${v}`)) }, speed: { type: "number", minimum: CAST_SPEED[0], maximum: CAST_SPEED[1] }, direction: { type: "string" }, }, required: ["handle", "character", "voice"], }, }, }, required: ["authors"], }); /** A short plain line from a model: control characters stripped, white space folded, at most `max`. */ export const plainLine = (v, max) => str(v).replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029]+/g, " ").replace(/\s+/g, " ").trim().slice(0, max); /** * ONE AUTHOR's answer from the model checked, field by field (pure): `{ name?, voice?, speed?, direction? }` with each * field it got right, and `refused: [why]` for each it did not -- the voice one of STOCK_VOICES, the speed within * CAST_SPEED, the direction one plain short line, the character name a plain short line. */ export function checkModelAnswer(a) { const out = { refused: [] }; if (!isObj(a)) return { refused: ["not an object"] }; const name = plainLine(a.character, 80); if (name) out.name = name; else if (a.character !== undefined) out.refused.push("character: not a name"); const voice = str(a.voice).trim(); if (isStockVoice(voice)) out.voice = voice; else if (a.voice !== undefined) out.refused.push(`voice ${JSON.stringify(a.voice).slice(0, 40)}: not a stock voice`); if (a.speed !== undefined && a.speed !== null) { const s = Number(a.speed); if (typeof a.speed === "number" && Number.isFinite(s) && s >= CAST_SPEED[0] && s <= CAST_SPEED[1]) out.speed = Math.round(s * 100) / 100; else out.refused.push(`speed ${JSON.stringify(a.speed).slice(0, 20)}: not ${CAST_SPEED[0]}-${CAST_SPEED[1]}`); } const direction = plainLine(a.direction, DIRECTION_MAX); if (direction) out.direction = direction; return out; } /** * A rule's proposal with the model's checked answer laid over it (pure): its voice, speed, name and direction where * the model gave a valid one -- and the rule's row as it was when nothing valid came back. `by` is "model" when * anything of the model's was kept. The result is held to proposalErrors; a result it refuses is the rule's row. */ export function mergeModelProposal(rule, answer, { model = null } = {}) { const ok = checkModelAnswer(answer); const kept = ["name", "voice", "speed", "direction"].filter((k) => ok[k] !== undefined); if (!kept.length) return { proposal: rule, kept, refused: ok.refused }; const p = JSON.parse(JSON.stringify(rule)); if (ok.name) p.name = ok.name; p.synthetic = { ...(p.synthetic ?? {}), ...(ok.voice ? { voice: ok.voice } : {}), ...(ok.speed !== undefined && ok.speed !== 1 ? { speed: ok.speed } : {}) }; if (ok.direction) p.recorded = { direction: ok.direction }; p.by = "model"; if (model) p.model = plainLine(model, 80); p.why = plainLine(`the model's proposal (${kept.join(", ")})${ok.refused.length ? `; refused: ${ok.refused.join("; ")}` : ""}`, 300); if (proposalErrors(p, "proposal").length) return { proposal: rule, kept: [], refused: [...ok.refused, ...proposalErrors(p, "proposal")] }; return { proposal: p, kept, refused: ok.refused }; } /** Is `id` a proposal id the store would take? */ export const isProposalId = (id) => CHARACTER_ID_RE.test(str(id));