// A PROJECT's CAST (the Voices panel; `umtool cast project
`): every character the project's reads use -- the
// post items' authors, the authors of the posts they answer, quote and link, and the narrator -- with the voice each
// reads in NOW and where it comes from (the item's own character, the project's own characters and its map, the
// cast, the narrator's, the default: post-say.mjs voiceSourceOf, the chain every read asks), how many items it
// reads, what its picked reads are actually in (stale ones: DRIFT), its real-voice reference (speakers.json) and its
// lines to audition; and THE RE-READS a voice change asks for, as the commands that make them.
//
// Plain ESM.
import { postNarrationKnobs } from "umtool-report-to-video/post-narration";
import { handleKey, readSpeedOf, resolvePieceVoice, voiceRefOf, voiceSpecOf } from "umtool-report-to-video/post-say";
import {
castDrift, castPresetMap, characterForRead, characterOf, charactersOf, convertTargetOf, itemCharacterOf, itemPresetOf, narratorOf, projectCharactersOf, projectPresetMap, proposalsOf, recordedPresetOf,
shownNameOf, speakerFor, takeReads, tuningStale, voiceDrift, ENGINE_WEIGHT,
} from "umtool-report-to-video/cast";
import { characterLines } from "./castAudition.mjs";
import { tuningArgvOf } from "./readTuning.mjs";
/**
* A take's reading asked again, and none of its tuning: a take whose tuning was its CHARACTER's (`tuningAsked`
* "preset", lane character-tuning) is re-read with the character's tuning as it is then, never pinned to the old one.
*/
const readingArgvOf = (t) => (Number.isInteger(t?.reading) && t.reading > 0 ? ["--reading", String(t.reading)] : []);
const str = (v) => (typeof v === "string" ? v : "");
/**
* The voice a piece of a picked read would be said in NOW, as the read that made it would ask (its own --voice-for
* and --voice kept: an override made on purpose): `(e, role, handle, take, read) => { engine, voice, from, speed?,
* character? }`. `speed` is the speed it would be asked at now, as the read would ask it (post-say.mjs readSpeedOf: the
* thread read's own --speed, else the item's own for his words, else the preset's; none for Orpheus or at 1) -- so a
* preset whose speed changed shows its reads as drift. A read converted from a recording is compared with its
* character's convert target (the chain's: cast.mjs characterForRead), else not at all. `project` is the project's
* own characters (characters.json's document).
*/
export function resolverFor({ map = {}, cast = null, project = null, render = {} }) {
const castMap = castPresetMap(cast);
const layer = projectPresetMap(project, map);
return (e, role, handle, take, read = null) => {
if (read?.kind === "converted") {
const who = characterForRead(e, { project, cast });
const ref = who?.character && who.layer !== "narrator" ? voiceRefOf(convertTargetOf(who.character).voice) : null;
return ref ? { ...ref, from: who.layer } : null;
}
const k = postNarrationKnobs(e, render);
const tr = take?.read?.kind === "thread" ? take.read : null;
const v = resolvePieceVoice({ handle, role }, {
map: layer, cast: castMap, item: itemPresetOf(e, { project, cast }), overrides: tr?.voiceFor ?? {}, voice: tr?.voice ?? null, self: e.handle ?? null,
narrator: e.narration?.voice ?? k.voice, engine: e.narration?.engine ?? k.engine,
});
const own = role === "post" && handleKey(handle) === handleKey(e.handle) ? e.narration?.speed ?? null : null;
const { speed: _preset, ...rest } = v;
// SPEED DRIFT is claimed only where the take says where its speed came from (`speedAsked`: "preset" / "item" --
// the speed it would be asked at now is compared). Asked by its command (true, a thread read's `read.speed`): kept as
// asked. A take that says nothing (made before it was recorded) is never speed drift: its own speed is the answer.
const prov = take?.speedAsked ?? (typeof tr?.speed === "number" ? true : undefined);
if (read?.kind === "tts" && prov !== "preset" && prov !== "item") return { ...rest, ...(typeof read.speed === "number" ? { speed: read.speed } : {}) };
const asked = typeof tr?.speed === "number" ? tr.speed : null;
const speed = readSpeedOf({ flag: asked, preset: v.speed ?? null, own, engine: v.engine });
return { ...rest, ...(speed !== null ? { speed } : {}) };
};
}
/** A character as a row carries it: its id, name, presets (and the `voice` / `convert` they answer to), what it is. */
const rowCharacter = (c, layer) => ({
id: c.id, name: c.name, layer, ...(c.voice ? { voice: c.voice } : {}), ...(c.convert ? { convert: c.convert } : {}),
...(c.synthetic ? { synthetic: c.synthetic } : {}), ...(c.recorded ? { recorded: c.recorded } : {}),
...(c.note ? { note: c.note } : {}), ...(c.narrator ? { narrator: true } : {}), ...(c.anonymous ? { anonymous: true, shown: shownNameOf(c) } : {}),
});
/** The post items' authors and context authors: `Map`. */
export function authorsOf(manifest) {
const out = new Map();
const add = (h, name, id, own) => {
const key = handleKey(h);
if (!key || key === "*") return;
const a = out.get(key) ?? { handle: key, name: "", items: [], context: [] };
if (!a.name && str(name)) a.name = str(name);
const list = own ? a.items : a.context;
if (!list.includes(id)) list.push(id);
out.set(key, a);
};
for (const e of Array.isArray(manifest?.timeline) ? manifest.timeline : []) {
if (e?.type !== "post") continue;
add(e.handle, e.author, e.id, true);
for (const p of Array.isArray(e.parents) ? e.parents : []) add(p?.handle, p?.author, e.id, false);
if (e.quoted) add(e.quoted.handle, e.quoted.author, e.id, false);
for (const l of Array.isArray(e.links) ? e.links : []) add(l?.handle, l?.author, e.id, false);
}
return out;
}
/**
* THE PROJECT's CHARACTERS, pure: `{ narrator, characters: [...], drift, overrides, own, itemCharacters }` -- each
* character `{ key, character, name, handles, items, context, itemIds, contextIds, voice: {engine, voice, spec, from,
* speed?, character?}, contextVoice?, recorded?, reads: [{ id, role, spec, kind }], drift: [...], speaker, lines,
* weight }`, the most-read first. A handle's character is the project's own (characters.json) before the cast's;
* `character.layer` says which. `own` is every character the project holds, in the cut or not; `itemCharacters` the
* post items that name their own (`narration.character`), each with the character it names (`found: false`: no such
* one -- the read falls to the layers under it). `tuningStale` every picked Orpheus read made with other settings than
* its character's tuning now (cast.mjs tuningStale; `settingTakes` the editor's tts.orpheus.takes), and each
* character row its own (`stale`).
*/
export function projectCharacters(manifest, { map = {}, cast = null, project = null, speakers = [], settingTakes = undefined } = {}) {
const render = manifest?.render ?? {};
const k = postNarrationKnobs({}, render);
const resolve = resolverFor({ map, cast, project, render });
const castMap = castPresetMap(cast);
const layer = projectPresetMap(project, map);
const pchars = projectCharactersOf(project);
const drift = voiceDrift(manifest, resolve);
const stale = tuningStale(manifest, resolve, settingTakes !== undefined ? { settingTakes } : {});
const groups = new Map();
for (const a of authorsOf(manifest).values()) {
const own = pchars.find((c) => (c.handles ?? []).includes(a.handle)) ?? null;
const c = own ?? characterOf(cast, a.handle);
const key = c ? c.id : `@${a.handle}`;
const g = groups.get(key) ?? { key, character: c, layer: c ? (own ? "project" : "cast") : null, name: c ? shownNameOf(c) : a.name ?? a.handle, handles: [], itemIds: [], contextIds: [] };
g.handles.push(a.handle);
for (const id of a.items) if (!g.itemIds.includes(id)) g.itemIds.push(id);
for (const id of a.context) if (!g.contextIds.includes(id)) g.contextIds.push(id);
groups.set(key, g);
}
const tl = Array.isArray(manifest?.timeline) ? manifest.timeline : [];
const reads = [];
for (const e of tl) if (e?.type === "post") for (const r of takeReads(e)) reads.push({ id: e.id, ...r });
const rows = [...groups.values()].map((g) => {
const h = g.handles[0];
// The handle's own voice: an item that names its own character answers for itself (itemCharacters), not for the handle.
const plain = (e) => !e?.narration?.character;
const first = tl.find((e) => e?.type === "post" && g.itemIds.includes(e.id) && plain(e)) ?? null;
const ctxItem = tl.find((e) => e?.type === "post" && g.contextIds.includes(e.id) && plain(e)) ?? null;
const own = first ? resolve(first, "post", h, null) : null;
const ctx = ctxItem ? resolve(ctxItem, "parent:0", h, null) : resolvePieceVoice({ handle: h, role: "parent:0" }, { map: layer, cast: castMap, narrator: k.voice, engine: k.engine });
const now = own ?? ctx;
const mine = new Set(g.handles);
const sp = speakerFor(g.character ?? { name: g.name, handles: g.handles, id: h }, speakers);
return {
key: g.key, name: g.name, handles: g.handles,
character: g.character ? rowCharacter(g.character, g.layer) : null,
items: g.itemIds.length, context: g.contextIds.length, itemIds: g.itemIds, contextIds: g.contextIds,
voice: { ...now, spec: voiceSpecOf(now) },
...(own && ctx && voiceSpecOf(own) !== voiceSpecOf(ctx) ? { contextVoice: { ...ctx, spec: voiceSpecOf(ctx) } } : {}),
// What a recording of them is made into (the recorded preset, its defaults filled) -- a character's only.
...(g.character ? { recorded: recordedPresetOf(g.character) } : {}),
weight: ENGINE_WEIGHT[now.engine] ?? "fast",
reads: reads.filter((r) => r.handle && mine.has(handleKey(r.handle))).map((r) => ({ id: r.id, role: r.role, spec: voiceSpecOf({ engine: r.engine, voice: r.voice }), kind: r.kind })),
drift: drift.filter((d) => mine.has(d.handle)),
// Its reads made with other settings than its tuning now (stale, never re-made by itself).
stale: g.character ? stale.filter((d) => d.character === g.character.id) : [],
speaker: sp?.name ?? null,
lines: characterLines(manifest, g.handles).slice(0, 8),
};
});
rows.sort((a, b) => b.items + b.context - (a.items + a.context) || a.name.localeCompare(b.name));
const nar = narratorOf(cast);
const recorded = reads.filter((r) => r.kind === "recorded" || r.kind === "converted");
const itemCharacters = tl.filter((e) => e?.type === "post" && e.narration?.character).map((e) => {
const it = itemCharacterOf(e, { project, cast });
const v = resolve(e, "post", e.handle ?? null, null);
return { id: e.id, handle: handleKey(e.handle) || null, character: it.id, found: !!it.character, layer: it.layer, ...(it.character ? { name: shownNameOf(it.character) } : {}), voice: { ...v, spec: voiceSpecOf(v) } };
});
return {
narrator: { engine: k.engine, voice: k.voice, spec: `${k.engine}:${k.voice}`, from: render?.postNarration?.voice ? "project" : "default", character: nar ? { id: nar.id, name: nar.name, voice: nar.voice } : null, recorded: recorded.map((r) => ({ id: r.id, kind: r.kind, voice: r.voice })) },
characters: rows,
...castDrift(manifest, { cast, map, resolve }),
tuningStale: stale,
cast: charactersOf(cast).length,
own: pchars.map((c) => rowCharacter(c, "project")).map((c, i) => ({ ...c, handles: pchars[i].handles ?? [] })),
itemCharacters,
// The PROPOSED characters (`umtool cast assign`): applied to nothing until a person accepts -- each with the post
// items of its author's it would be named on (those that name no character of their own).
proposed: proposalsOf(project).map((x) => ({
...x,
...(x.anonymous ? { shown: shownNameOf(x) } : {}),
items: tl.filter((e) => e?.type === "post" && (x.handles ?? []).includes(handleKey(e.handle)) && !str(e.narration?.character).trim()).map((e) => e.id),
})),
};
}
/**
* A thread take's `read` record as the argv that asks for it again, leaving out the overrides of `handles`. A read
* whose own line was a take (`postTake`) names that take again by its number NOW (`takes`: the item's, found by file).
*/
export function threadArgvOf(read, { handles = [], author = null, takes = null } = {}) {
if (!read || read.kind !== "thread") return [];
const drop = new Set(handles.map(handleKey));
const a = [];
if (read.parents !== undefined && String(read.parents) !== "0") a.push("--parents", String(read.parents));
for (const s of read.skip ?? []) a.push("--skip-parent", String(s));
if (read.quoted === false) a.push("--no-quoted");
if (read.linked === false) a.push("--no-linked");
if (read.seen === true) a.push("--read-seen");
for (const [h, v] of Object.entries(read.voiceFor ?? {})) if (!drop.has(handleKey(h))) a.push("--voice-for", `${h}=${v}`);
if (read.voice && !(author && drop.has(handleKey(author)))) a.push("--voice", String(read.voice));
if (typeof read.speed === "number") a.push("--speed", String(read.speed));
if (read.postTake && typeof read.postTake.file === "string") {
const at = Array.isArray(takes) ? takes.findIndex((t) => t?.file === read.postTake.file) : -1;
a.push("--post-take", String(at >= 0 ? at + 1 : read.postTake.n));
}
// Its screens (post-screens.mjs): left out, or lines from takes (found again by their files).
if (read.screens === false) a.push("--no-screens");
for (const [r, x] of Object.entries(read.lineTakes ?? {})) {
if (typeof x?.file !== "string") continue;
const at = Array.isArray(takes) ? takes.findIndex((t) => t?.file === x.file) : -1;
a.push("--line-take", `${r}=${at >= 0 ? at + 1 : x.n}`);
}
// Each piece's reading and tuning (lane line-rerun, `read.tuned`): asked again exactly.
for (const [r, x] of Object.entries(read.tuned ?? {})) {
const kv = [...(Number.isInteger(x?.reading) && x.reading > 0 ? [`reading:${x.reading}`] : []), ...Object.entries(x?.tuning ?? {}).map(([k, v]) => `${k}:${v}`)];
if (kv.length) a.push("--tuned", `${r}=${kv.join(",")}`);
}
return a;
}
/**
* THE RE-READS a voice change for `handles` asks for, pure: every post item whose picked read says one of them in
* another voice than now -- `[{ id, take, thread, reads: [{ role, reads, want }], argv }]`, `argv` the umtool words
* that make the new take (a thread read again with its own options, the changed authors' overrides dropped; a
* single read). A read converted from a recording is not re-read by a voice (`skipped`: record it, or derive it again).
*/
export function rereadPlan(projectId, manifest, drift, handles) {
const want = new Set((handles ?? []).map(handleKey));
const byItem = new Map();
const skipped = [];
for (const d of drift) {
if (want.size && !want.has(d.handle)) continue;
if (d.kind === "converted") {
if (!skipped.some((s) => s.id === d.id)) skipped.push({ id: d.id, why: "a recording converted to a stock voice: derive it again (Import a recording, or the bench's Run AI on it)" });
continue;
}
const row = byItem.get(d.id) ?? { id: d.id, thread: d.thread, reads: [] };
row.reads.push({ role: d.role, handle: d.handle, reads: d.reads, want: d.want });
byItem.set(d.id, row);
}
const tl = Array.isArray(manifest?.timeline) ? manifest.timeline : [];
const items = [...byItem.values()].map((r) => {
const e = tl.find((x) => x?.id === r.id);
const takes = e?.narration?.takes ?? [];
const t = takes[Number.isInteger(e?.narration?.pick) ? e.narration.pick : 0] ?? null;
// A single take's own speed is asked again -- an old read never comes back at another speed -- unless it came
// from the character's preset or the item (that is what a re-read takes anew). Its own tuning and reading too
// (readTuning.mjs: what is not Orpheus's default) -- a reading picked by ear is read again the same way.
const keepSpeed = !r.thread && typeof t?.speed === "number" && t.speed !== 1 && t.speedAsked !== "preset" && t.speedAsked !== "item";
const argv = ["posts", "narrate", projectId, r.id, "--take", ...(r.thread ? ["--thread", ...threadArgvOf(t?.read, { handles: [...want], author: e?.handle, takes })] : [...(keepSpeed ? ["--speed", String(t.speed)] : []), ...(t?.tuningAsked === "preset" ? readingArgvOf(t) : tuningArgvOf(t))])];
return { ...r, take: t?.file ?? null, argv };
});
return { items, skipped };
}