// A VIDEO's READS (lane reads-find, S4 of plans/orpheus-retune.md; umtool/docs/knobs.md, "The reads of a video"): // every line a voice reads in a project -- a post's script, a piece of a thread read, a screen line, a card's // narration -- with the words it SAYS (never what is shown: operator ruling 3), where those words are kept, the take // that plays, and whether that take still says them as a plain press would make them now. ONE model: `umtool reads`, // the Reads page and the re-read queue (readsQueue.mjs) read it; the stale rule is defined here and nowhere else. // // A READ, `{ id, kind, item, role, n, character, voice, spoken, said, storedAt, shownSpoken, editable, why, take, // newTake, state, because, legacy }`: // id "" for a single read or a card, "/" for a piece of a thread read // kind post (a post's script, read alone) | thread (a piece of a thread read: his own words, a parent, the // quoted post, a linked post) | screen (a screen's line, a piece of the thread read) | card // spoken what the voice says, AS WRITTEN (what Find searches and Replace edits): the script, the screen line's // "said as" (else the line as shown), a context piece's words as shown, the card's narration // said the same after the redaction, the slurs and the pronunciation lexicon (what the editor is asked) // storedAt where `spoken` is kept; `shownSpoken`: it is still the SHOWN text (a replace creates its override) // editable whether These reads can rewrite it (a parent, the quoted or a linked post has no spoken-only words: // "said as shown: only Everywhere changes this"; a recorded read is yours) // take the take that plays: `{ index, takeFile, file, files, key, reading, tuning, tunedBy: "line" | "character" | // null }` -- `takeFile` the take's own file, `files` what THIS read plays (a thread piece: its parts' files) // ask the tuning a plain press asks for it now (tuneAsk.mjs plainPressAskOf: only what its line owned; the // character's and the settings' resolved anew) -- what its re-read asks (readAgainArgv.mjs) // newTake (state unpicked) the newer take that would be fresh if picked // // THE STATES: // recorded the take that plays is recorded, converted or derived (or the piece comes from a take): never stale // none no synthesized take reads it yet // stale the take that plays is synthesized and, for any of `because`: // words it says other words than the spoken text now (a single read: its script, or the lexicon -- // post-say.mjs staleLexicon; a thread piece: its parts against the read a press makes now, // postThreadRead.mjs upToDate first; a card: no reading kept at its key now) // settings made with other settings than its character's tuning now (cast.mjs tuningStale, the very // rows `umtool cast stale` and the bench's "made with other settings" count) // voice made in another voice than it reads in now (cast.mjs voiceDrift, the Voices page's drift) // unpicked stale, and a newer synthesized take of the item would be fresh if picked (a re-read waits for a Pick) // fresh none of these // // Plain ESM: the CLI runs it under bare node. import { readManifest } from "../projects/report.mjs"; import { REPORTS_ROOT } from "../projects/core.mjs"; import { LEGACY_EDIT_TEXT, legacyReadOf, shownDraftOf } from "umtool-report-to-video/post-item"; import { pickedTake, takeSourceOf } from "umtool-report-to-video/post-narration"; import { parseScreenRole, saidAsOf, screenLineSaid, screensOf } from "umtool-report-to-video/post-screens"; import { spokenRead } from "umtool-report-to-video/post-redact"; import { staleLexicon } from "umtool-report-to-video/post-say"; import { narrationsOf } from "umtool-report-to-video/narration"; import { lineOwnOf, madeOwnOf, pieceOwnOf, plainPressAskOf } from "./tuneAsk.mjs"; export const READ_KINDS = Object.freeze({ post: "post script", thread: "thread part", screen: "screen line", card: "card narration" }); export const READ_STATES = Object.freeze(["fresh", "stale", "unpicked", "none", "recorded"]); /** Why a context piece cannot be rewritten by These reads (said in the UI where it applies). */ export const SAID_AS_SHOWN = "said as shown: only Everywhere changes this"; const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); const str = (v) => (typeof v === "string" ? v : ""); const norm = (t) => str(t).replace(/\s+/g, " ").trim(); /** A read's id: the item's id, and the piece's role for a piece of a thread read. */ export const readIdOf = (item, role = null) => (role ? `${item}/${role}` : item); /** * Every id the model makes (readIdOf): an item's id -- any timeline id, no slash, no space -- and, for a piece of a * thread read, its role (post, quoted, parent:, linked:, screen::). */ export const READ_ID_RE = /^[^/\s]{1,200}(?:\/(?:post|quoted|parent:\d|linked:\d|screen:[a-z0-9][a-z0-9-]{0,23}:\d{1,2}))?$/; /** * A list of read ids as a caller hands it (`only`): `{ ids }`, or `{ error }` naming what is refused -- not a list, * empty, or an id no read could have. Never silently narrowed: a list that names one bad id is refused whole. */ export function readIdsOf(list) { if (!Array.isArray(list)) return { error: "only is a list of read ids" }; const bad = list.filter((x) => typeof x !== "string" || !READ_ID_RE.test(x)); if (bad.length) return { error: `not a read's id: ${bad.slice(0, 5).map((x) => JSON.stringify(x)).join(", ")}` }; if (!list.length) return { error: "only names no read" }; return { ids: [...new Set(list)] }; } /** A thread take's `read` record as threadTake's options (as the read that plays was asked: castProject.mjs threadArgvOf). */ export function threadOptsOfRead(read, takes = []) { const r = isObj(read) ? read : {}; const byFile = (f) => { const at = (Array.isArray(takes) ? takes : []).findIndex((t) => t?.file === f); return at >= 0 ? at + 1 : null; }; const lineTakes = {}; for (const [role, x] of Object.entries(isObj(r.lineTakes) ? r.lineTakes : {})) { const n = typeof x?.file === "string" ? byFile(x.file) : null; if (n) lineTakes[role] = n; } return { parents: r.parents ?? "0", skip: Array.isArray(r.skip) ? r.skip : [], quoted: r.quoted !== false, linked: r.linked !== false, readSeen: r.seen === true, overrides: isObj(r.voiceFor) ? r.voiceFor : {}, voice: typeof r.voice === "string" ? r.voice : null, speed: typeof r.speed === "number" ? r.speed : null, postTake: isObj(r.postTake) && typeof r.postTake.file === "string" ? byFile(r.postTake.file) : null, screens: r.screens !== false, lineTakes, inherit: isObj(r.tuned) ? r.tuned : {}, }; } /** Whose a take's tuning is: the line's own, its character's, or not said. */ const tunedByOf = (t) => (t?.tuningAsked === true ? "line" : t?.tuningAsked === "preset" ? "character" : null); /** * THE PLAIN PRESS's TUNING for a read (tuneAsk.mjs plainPressAskOf: the bench's untouched Read again, and the re-read * queue's): `made` how it was last made (`{ tuning, tuningAsked }`), `own` what its line owned, `want` its voice now * (resolverFor's: its character and the character's tuning). Null: nothing of its own -- the character's, or the * defaults, as they are when it is read. An engine with no sampler asks none. */ function plainAskOf(made, own, want, names) { if ((want?.engine ?? "orpheus") !== "orpheus") return null; const baseline = { character: want?.character ? { name: names.get(want.character) ?? want.character, tuning: want.tuning ?? null } : null, madeOwn: madeOwnOf(made?.tuning ?? null, made?.tuningAsked) }; return plainPressAskOf({ madeWith: made?.tuning ?? null, baseline, own }); } /** A take as a read row carries it. */ const takeView = (t, extra = {}) => (t ? { index: Number.isInteger(t.index) ? t.index : null, takeFile: t.file ?? null, file: t.file ?? null, files: typeof t.file === "string" ? [t.file] : [], key: null, reading: Number.isInteger(t.reading) ? t.reading : 0, tuning: isObj(t.tuning) ? t.tuning : null, tunedBy: tunedByOf(t), ...extra } : null); /** * THE CONTEXT a project's reads are judged in, loaded once: the manifest, the redaction (its lexicon), the lexicon, * the character layers (characterLayers.mjs), the voices view's inputs (castCli.mjs projectView: the same layers * `umtool cast stale` reads) and each card's readings. `red` / `lexicon` stand in for the project's own (a preview). * * @param {{ id: string, dir: string }} project * @param {{ reportsRoot?: string, manifest?: any, red?: any, lexicon?: any[] }} [o] */ export async function readsContext(project, { reportsRoot = REPORTS_ROOT, manifest = undefined, red = undefined, lexicon = undefined } = {}) { const m = manifest ?? (await readManifest(project.dir)); if (!m) throw new Error(`${project.id} has no manifest`); const { projectRedaction } = await import("./postRedaction.mjs"); const { readLexicon } = await import("./postSay.mjs"); const lex = lexicon ?? (await readLexicon(project.dir)); const r = red !== undefined ? red : await projectRedaction(project.dir, m); const { readLayers } = await import("./characterLayers.mjs"); const { characterNames } = await import("./postThreadRead.mjs"); const L = await readLayers(project.dir).catch(() => null); const { projectView } = await import("./castCli.mjs"); const v = await projectView(project, { reportsRoot }); const { orpheusTakesSetting } = await import("./characterTuning.mjs"); const settingTakes = await orpheusTakesSetting(); const { allCardReadings } = await import("./cardNarrationCli.mjs"); const cards = await allCardReadings(project.dir); return { project, manifest: m, red: r, lexicon: lex, L, names: L ? characterNames(L) : {}, layers: { map: v.map, cast: v.castRead.cast, project: v.ownRead.doc, speakers: v.speakers }, settingTakes, cards, reportsRoot }; } /** The voices view of a manifest (castProject.mjs projectCharacters: its tuningStale and its drift), and a resolver. */ async function voicesOf(ctx, m) { const { projectCharacters, resolverFor } = await import("./castProject.mjs"); const view = projectCharacters(m, { map: ctx.layers.map, cast: ctx.layers.cast, project: ctx.layers.project, speakers: ctx.layers.speakers, settingTakes: ctx.settingTakes }); const resolve = resolverFor({ map: ctx.layers.map, cast: ctx.layers.cast, project: ctx.layers.project, render: m.render ?? {} }); const names = new Map(); for (const c of view.characters ?? []) if (c.character?.id) names.set(c.character.id, c.character.name ?? c.name); for (const c of view.own ?? []) if (c?.id) names.set(c.id, c.name ?? c.id); const key = (id, role) => `${id}\u0000${role}`; return { view, resolve, names, settings: new Set((view.tuningStale ?? []).map((r) => key(r.id, r.role))), voice: new Set((view.characters ?? []).flatMap((c) => c.drift ?? []).map((d) => key(d.id, d.role))), key, }; } const characterRow = (vs, id) => (id ? { id, name: vs.names.get(id) ?? id } : null); /** The rows of ONE post item, as the manifest `m` has it (its pick). */ async function postRows(ctx, m, vs, e, n) { const n0 = e.narration; if (!isObj(n0) || n0.off === true) return []; const take = pickedTake(e); const base = { item: e.id, n, legacy: !!take && legacyReadOf(e) }; const slur = ctx.red?.slurs?.voice === "beep" ? { voice: "skip" } : {}; if (!take) { const spoken = str(n0.script) || shownDraftOf(e); if (!norm(spoken)) return []; const want = vs.resolve(e, "post", e.handle ?? null, null); return [{ ...base, id: readIdOf(e.id), kind: "post", role: null, character: characterRow(vs, want?.character), voice: want ? `${want.engine}:${want.voice}` : null, spoken, said: spokenRead(spoken, e, ctx.red, slur).text, storedAt: str(n0.script) ? "narration.script" : null, shownSpoken: !str(n0.script), editable: true, why: null, take: null, newTake: null, ask: null, state: "none", because: [] }]; } if (take.read?.kind === "thread") return threadRows(ctx, m, vs, e, take, base); const src = takeSourceOf(take).kind; const spoken = str(n0.script) || str(take.script); const want = vs.resolve(e, "post", e.handle ?? null, take); const row = { ...base, id: readIdOf(e.id), kind: "post", role: null, character: characterRow(vs, want?.character), voice: `${take.engine ?? "?"}:${take.voice ?? "?"}`, spoken, said: spokenRead(spoken, e, ctx.red, slur).text, storedAt: str(n0.script) ? "narration.script" : null, shownSpoken: !str(n0.script), editable: src === "tts", why: src === "tts" ? null : "a recorded read is yours: record it again", take: takeView(take), newTake: null, ask: src === "tts" ? plainAskOf(take, lineOwnOf(take), want ?? { engine: take.engine }, vs.names) : null, }; if (src !== "tts") return [{ ...row, state: "recorded", because: [] }]; const because = []; if (norm(take.script) !== norm(spoken)) because.push("words"); else if (staleLexicon(e, take, ctx.lexicon).length) because.push("lexicon"); if (vs.settings.has(vs.key(e.id, "post"))) because.push("settings"); if (vs.voice.has(vs.key(e.id, "post"))) because.push("voice"); return [{ ...row, state: because.length ? "stale" : "fresh", because }]; } /** The pieces of a picked THREAD read, each a row: judged against the read a press would make now. */ async function threadRows(ctx, m, vs, e, take, base) { const { threadTake } = await import("./postThreadRead.mjs"); const takes = e.narration?.takes ?? []; let dry; try { dry = await threadTake(ctx.project, e, { manifest: m, red: ctx.red, map: ctx.L?.map ?? {}, cast: ctx.L?.castMap ?? {}, item: ctx.L?.itemOf?.(e) ?? null, names: ctx.names, dryRun: true, ...threadOptsOfRead(take.read, takes), }); } catch (err) { // The read as it was asked cannot be made now (a take it named is gone, a line changed under a recording): one row // that says so -- stale, re-made from the bench. return [{ ...base, id: readIdOf(e.id, "post"), kind: "thread", role: "post", character: null, voice: str(take.voice) || null, spoken: str(e.narration?.script), said: null, storedAt: "narration.script", shownSpoken: false, editable: true, why: null, take: takeView(take), newTake: null, ask: null, state: "stale", because: ["words"], error: err instanceof Error ? err.message : String(err) }]; } const parts = Array.isArray(take.parts) ? take.parts : []; const sayNow = (role) => dry.parts.filter((p) => p.role === role).map((p) => norm(p.text)).join(" "); const saidThen = (role) => parts.filter((p) => p?.role === role && typeof p?.take !== "string").map((p) => norm(p.text)).join(" "); const rows = []; for (const pc of dry.plan.pieces) { const sc = parseScreenRole(pc.role); const kind = sc ? "screen" : "thread"; const screen = sc ? screensOf(e).find((s) => s.id === sc.id) ?? null : null; const own = pc.role === "post"; const as = screen ? saidAsOf(screen, sc.n) : null; const j = screen ? screensOf(e).indexOf(screen) : -1; const storedAt = own ? (str(e.narration?.script) ? "narration.script" : null) : sc ? (as !== null ? `screens[${j}].saidAs.${sc.n}` : null) : null; const editable = own || !!sc; const want = pc.handle ? vs.resolve(e, pc.role, pc.handle, take) : null; const part = parts.find((p) => p?.role === pc.role && typeof p?.take !== "string") ?? null; const roleFiles = parts.filter((p) => p?.role === pc.role && typeof p?.take !== "string" && typeof p?.file === "string").map((p) => p.file); const row = { ...base, id: readIdOf(e.id, pc.role), kind, role: pc.role, character: characterRow(vs, pc.character ?? want?.character), voice: `${pc.engine ?? take.engine ?? "?"}:${pc.voice ?? "?"}`, spoken: sc ? (as ?? screenLineSaid(screen, sc.n)) : str(pc.written), said: pc.text, storedAt, shownSpoken: own ? !str(e.narration?.script) : sc ? as === null : true, editable: editable && !pc.take, why: pc.take ? "read from a take (a recording): record it again" : editable ? null : SAID_AS_SHOWN, // ITS PART's files (a paragraph each), in order -- what it says in the take, never the whole joined read. take: takeView(take, part ? { file: roleFiles[0] ?? take.file, files: roleFiles, reading: Number.isInteger(part.reading) ? part.reading : 0, tuning: isObj(part.tuning) ? part.tuning : null, tunedBy: tunedByOf(part) ?? tunedByOf(take) } : {}), newTake: null, ask: pc.take ? null : plainAskOf(part ? { tuning: part.tuning, tuningAsked: part.tuningAsked ?? take.tuningAsked } : null, pieceOwnOf(take, pc.role), want ?? { engine: pc.engine, character: pc.character, tuning: pc.tuningAsked === "preset" ? pc.tuning : null }, vs.names), }; if (pc.take) { // A PIECE READ FROM ANOTHER TAKE of the item (`--post-take`, a line's chosen take): judged as that take is -- // a recording, or one converted from one, is yours; a SYNTHESIZED one is stale as cast.mjs madeOf follows it // (`cast stale` lists it), its re-read that take's own (not queued here: re-read it on the bench, then this). const src = takes.find((t) => t?.file === pc.take.file) ?? null; if (!src || takeSourceOf(src).kind !== "tts") { rows.push({ ...row, state: "recorded", because: [] }); continue; } // Its WORDS: the source take's, against what this piece says now (his script; a screen line's said-as or line). const now = own ? (str(e.narration?.script) || str(dry.plan.script) || str(pc.written)) : sc ? (as ?? screenLineSaid(screen, sc.n)) : str(pc.written); const then = sc ? (str(src.screenLine?.said) || str(src.said) || str(src.script)) : str(src.script) || str(src.said); const because = []; if (norm(then) !== norm(now)) because.push("words"); if (vs.settings.has(vs.key(e.id, pc.role))) because.push("settings"); if (vs.voice.has(vs.key(e.id, pc.role))) because.push("voice"); rows.push({ ...row, why: `${pc.role === "post" ? "his line" : pc.role} is take ${pc.take.n} (synthesized): read it again on the bench, then this thread read`, queueable: false, state: because.length ? "stale" : "fresh", because }); continue; } const because = []; if (!dry.upToDate && sayNow(pc.role) !== saidThen(pc.role)) because.push("words"); if (vs.settings.has(vs.key(e.id, pc.role))) because.push("settings"); if (vs.voice.has(vs.key(e.id, pc.role))) because.push("voice"); rows.push({ ...row, state: because.length ? "stale" : "fresh", because }); } return rows; } /** The rows of ONE narrated card: its key now, and the readings kept beside the build. */ function cardRows(ctx, n, at) { const readings = ctx.cards.get(n.id) ?? []; const plays = readings.find((r) => r.key === n.key) ?? null; const same = readings.some((r) => norm(r.text) === norm(n.text)); const state = plays ? "fresh" : readings.length ? "stale" : "none"; return [{ id: readIdOf(n.id), kind: "card", item: n.id, role: null, n: at, character: null, voice: `${n.engine}:${n.voice}`, spoken: n.text, said: n.text, storedAt: "narration.text", shownSpoken: false, editable: true, why: null, legacy: false, take: plays ? { index: null, file: null, key: plays.key, reading: Number.isInteger(plays.askedReading) ? plays.askedReading : plays.reading ?? 0, tuning: plays.askedTuning ?? null, tunedBy: "line" } : null, newTake: null, ask: null, state, because: state === "stale" ? [same ? "settings" : "words"] : [], readings: readings.map((r) => ({ key: r.key, text: r.text, createdAt: r.createdAt ?? null })), }]; } /** Every read of `m` (cut order), as judged in `ctx`. */ async function rowsOf(ctx, m) { const vs = await voicesOf(ctx, m); const cards = new Map(narrationsOf(m).map((x) => [x.id, x])); const rows = []; const tl = Array.isArray(m.timeline) ? m.timeline : []; for (let i = 0; i < tl.length; i += 1) { const e = tl[i]; if (e?.type === "post") rows.push(...(await postRows(ctx, m, vs, e, i))); else if (cards.has(e?.id)) rows.push(...cardRows(ctx, cards.get(e.id), i)); } return { rows, vs }; } /** * EVERY READ OF A PROJECT: `{ rows, counts, tuningStale }` -- `tuningStale` the voices view's own rows (what `cast stale` * lists), so every count of reads "made with other settings" is this one. A stale post read with a newer synthesized * take that would be fresh if picked is `unpicked` (its `newTake`). * * @param {{ id: string, dir: string }} project * @param {Parameters[1] & { ctx?: any }} [o] */ export async function projectReads(project, o = {}) { const ctx = o.ctx ?? (await readsContext(project, o)); const m = ctx.manifest; const { rows, vs } = await rowsOf(ctx, m); // UNPICKED: for each item with a stale read, its other synthesized takes, newest first -- picked in a copy, judged by // the same rule. const staleItems = [...new Set(rows.filter((r) => r.state === "stale" && r.kind !== "card").map((r) => r.item))]; for (const id of staleItems) { const at = m.timeline.findIndex((x) => x?.id === id); const e = m.timeline[at]; const takes = Array.isArray(e?.narration?.takes) ? e.narration.takes : []; const pick = Number.isInteger(e.narration.pick) ? e.narration.pick : 0; const mine = rows.filter((r) => r.item === id && r.state === "stale"); for (let j = takes.length - 1; j >= 0 && mine.some((r) => !r.newTake); j -= 1) { if (j === pick || takeSourceOf(takes[j]).kind !== "tts") continue; const m2 = { ...m, timeline: m.timeline.map((x, k) => (k === at ? { ...x, narration: { ...x.narration, pick: j } } : x)) }; const vs2 = await voicesOf(ctx, m2); const again = await postRows(ctx, m2, vs2, m2.timeline[at], at); for (const r of mine) { if (r.newTake) continue; const twin = again.find((x) => x.id === r.id); if (twin?.state === "fresh") { r.state = "unpicked"; r.newTake = twin.take; } } } } const counts = Object.fromEntries(READ_STATES.map((s) => [s, rows.filter((r) => r.state === s).length])); return { rows, counts, tuningStale: vs.view.tuningStale ?? [], ctx }; } /** The reads a row filter keeps: `stale` (stale or unpicked: what a re-read is for), a character's (its id). */ export function filterReads(rows, { stale = false, character = null } = {}) { return rows.filter((r) => (!stale || r.state === "stale" || r.state === "unpicked") && (!character || r.character?.id === character)); } // --------------------------------------------------------------------------- // FIND: plain text, case on or off, whole word -- over the SPOKEN text only. // --------------------------------------------------------------------------- const escRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); /** The pattern Find matches `text` with (a phrase across any spaces; regex characters literal), or null for none. */ export function findPattern(text, { matchCase = false, word = false } = {}) { const t = str(text).replace(/\s+/g, " ").trim(); if (!t) return null; const body = t.split(" ").map(escRe).join("\\s+"); return new RegExp(word ? `(? (re ? [...str(s).matchAll(re)].filter((x) => x[0]).map((x) => ({ start: x.index, end: x.index + x[0].length })) : []); /** * FIND over the reads' spoken text: `{ rows: [{ ...row, matches }], matches, lines }` -- only the rows with a match, * each with where its matches stand in `spoken`. */ export function findInReads(rows, text, opts = {}) { const re = findPattern(text, opts); const hit = rows.map((r) => ({ ...r, matches: matchesIn(r.spoken, re) })).filter((r) => r.matches.length); return { rows: hit, matches: hit.reduce((a, r) => a + r.matches.length, 0), lines: hit.length }; } /** `s` with every match of `re` replaced by `to` (literally: no `$` patterns). */ export const replaceIn = (s, re, to) => str(s).replace(re, () => to); /** Said when a replace leaves a post whose playing take predates the rule (post-item.mjs). */ export { LEGACY_EDIT_TEXT };