// A NARRATED POST ITEM (umtool/docs/report-video.md, "Narrated post items"): // a post item (post-item.mjs) read aloud by a stock synthetic voice, its own // attachment playing under the read -- its sound low-passed and quiet while // the narrator speaks, then crossfaded back to the clean, full sound. The // operator's demo (2 Nov 2026, narr-demo/mix.sh) is the reference: these // defaults ARE its numbers. // // entry.narration = { // script: "what is read (Orpheus tags … allowed)", // excerpt?: true, // drafted from the item's `excerpt` (post-item.mjs: verbatim spans, " … "-joined) // engine?, voice?, speed?, // the next take's (default: render.postNarration's) // takes: [{ file: "narration/posts//take-.-.wav", // engine, voice, seconds, script, at, note?, speed?, lufs?, jobId?, // words?: [{ w, start, end }] }], // its script's words, timed (posts narrate --words; word-zoom.mjs) // pick?: , // absent: the first // approved?: true, // the picked take on this script, approved // off?: true, // kept, but the item plays un-narrated // // the mix, per post (absent: render.postNarration's, else the defaults): // lead?, tail?, ramp?, linger?, clip?, wet?, lowpassHz?, duck?, short?, attach?, lufs?, rate? // window?: { media, start, end, score, reason, at } // why `posts fit` chose the attachment's span // } // // The takes are FILES OF THE PROJECT (`narration/posts//`), written by // the editor's tts op (`pnpm ops tts`, its `out`) -- umtool never synthesizes. // `narration/posts/index.json` is the hand-made batch's list of them, which // `umtool posts narrate

--import` reads into the manifest. // // PURE and dependency-free (the build, Play, the bench, the writers and the // lint read it): the knobs and their defaults, the validator, which take // plays, the mix's schedule, the ffmpeg filters of the mix, a script drafted // from the post's words. The plan of what plays when is post-item.mjs's // (postItemPlan's narrated branch), which reads these. import { followKnobErrors } from "./read-follow.mjs"; import { threadKnobErrors } from "./post-thread.mjs"; import { takeLexiconErrors } from "./post-say.mjs"; import { tuningProblems } from "./narration.mjs"; /** The engines a post's narration may name (the editor's tts op). */ export const POST_NARRATION_ENGINES = Object.freeze(["orpheus", "kokoro", "espeak-ng"]); /** A take's engine: one of those, or `recorded` -- a person's own voice, recorded on the post bench (never synthesized). */ export const POST_TAKE_ENGINES = Object.freeze([...POST_NARRATION_ENGINES, "recorded", "derived"]); /** * WHAT A TAKE IS (operator, 2 Nov: "pure AI voice, record voice, and run AI on * recorded voice -- and re-run or re-record"): a `source` and the `steps` * applied to it, and the file that came out -- * * source { kind: "tts", engine, voice, script } a stock voice, the editor's tts op * { kind: "recorded", voice } a person's own read, recorded on the bench * { kind: "take", from: } DERIVED: a new take made from another * steps [{ op, engine?, params?, ranAt, job? }] the processing that made a derived take * (a convert's also `voice`, the stock target, and -- when the read's pitch was FOLLOWED rather than * flattened to the stock voice's -- `pitch: "source" | "contour"` and `semitones`, as the editor ran them) * * A derived take never overwrites the one it came from. Its ops are the * editor's (each a job, like tts): `enhance` (denoise, level, de-reverb) and * `convert` (voice conversion: the performance kept, the timbre swapped for a * STOCK synthetic voice -- never a real person's). A take's id is its file's * name without `.wav`. Takes from before this shape (engine and voice only) * read as their source (takeSourceOf). */ export const POST_DERIVE_OPS = Object.freeze(["enhance", "convert"]); /** * The ops umtool runs itself on a take's own file (no editor job, no TTS): `rejoin` -- its kept parts cut out and * joined again; `tempo` -- named parts time-stretched, pitch kept (lib/report/postReread.mjs); `yell` -- the words * he wrote in ALL CAPS raised, as a voice raised (lib/report/postYell.mjs); `pause` -- silence put in after words named, * everything after moved on (lib/report/postPause.mjs); `revoice` -- ONE phrase of it synthesized again (the editor's * TTS, that phrase only) and spliced in its place, the rest of the read untouched (lib/report/postRevoice.mjs). */ export const POST_LOCAL_OPS = Object.freeze(["rejoin", "tempo", "yell", "pause", "revoice"]); /** The editor's op route for each. */ export const POST_DERIVE_ROUTES = Object.freeze({ enhance: "/api/ops/voice-enhance", convert: "/api/ops/voice-convert" }); /** A take's id: its file's name without `.wav`. */ export const takeIdOf = (t) => String(t?.file ?? "").split("/").pop().replace(/\.wav$/i, ""); /** A take's source, its own or read from the older shape. */ export function takeSourceOf(t) { if (isObj(t?.source)) return t.source; if (t?.engine === "recorded") return { kind: "recorded", voice: t.voice ?? t.label ?? "operator" }; return { kind: "tts", engine: t?.engine ?? "orpheus", voice: t?.voice ?? "zac", ...(typeof t?.script === "string" ? { script: t.script } : {}) }; } /** The root of a take's chain (the source take a derived one came from, followed back), or the take itself. */ export function rootTakeOf(takes, t) { let cur = t; for (let i = 0; i < 20; i += 1) { const src = takeSourceOf(cur); if (src.kind !== "take") return cur; const up = takes.find((x) => takeIdOf(x) === src.from); if (!up) return cur; cur = up; } return cur; } /** The file a derived take of post `postId` is written to: take-.-.wav. */ export const derivedFileOf = (postId, n, op, engine) => `${takesDirOf(postId)}/take-${n}.${op}-${String(engine ?? "default").replace(/[^A-Za-z0-9_-]/g, "")}.wav`; /** * THE MIX's KNOBS and their defaults (`render.postNarration`, and the same * keys on one post's `narration`): the demo's numbers. * * lead 0.4 the narrator starts this far into the item * tail 0.3 the attachment stays muffled this long after the words * ramp 0.8 then crossfades back to its clean, full sound over this * linger 1.8 THE ITEM ENDS THIS LONG AFTER THE WORDS (operator, 2 Nov: "read out * every post, and not linger too long after finishing the read"): * the ramp back to the clean sound happens inside it * clip read an attachment longer than lead + read + tail + linger is cut to * that (its in point, or the best part `posts fit` chose); "full" * plays it whole (the demo's way) * wet 0.30 the muffled sound's level under the narrator * lowpassHz 650 the muffle: a low-pass at this frequency, twice * duck true muffle the attachment under the read (false: full under it) * short hold a video shorter than the read: its last frame held, or looped * attach under the attachments start with the read (under), or after it * (one post's knob only: it decides the card's layout) * lufs -21 the voice is levelled to this before the narrator's * compressor (-21 LUFS is where Orpheus `zac` reads: the * demo's chain was tuned there) * rate 1 the READ's speed (operator, 3 Nov: "read everything the * slightest bit faster"): the voice time-stretched by this, * its pitch kept (ffmpeg atempo; Play: playbackRate with * preservesPitch) -- the attachment untouched. Every second * the item takes from a take (its read, its parts, the * muffle's schedule, the item's length) is the take's * divided by it (readSecondsOf) * engine orpheus, voice zac what a new take is synthesized with */ export const POST_NARRATION_DEFAULTS = Object.freeze({ lead: 0.4, tail: 0.3, ramp: 0.8, linger: 1.8, clip: "read", wet: 0.3, lowpassHz: 650, duck: true, short: "hold", attach: "under", lufs: -21, rate: 1, engine: "orpheus", voice: "zac", // The pace (POST_PACES): normal is the cut's gaps; fast plays each post back to back. pace: "normal", }); export const POST_NARRATION_LIMITS = Object.freeze({ lead: [0, 5], tail: [0, 5], ramp: [0, 5], linger: [0, 30], wet: [0, 1], lowpassHz: [100, 8000], lufs: [-40, -10], speed: [0.5, 2], rate: [0.8, 1.5], /** A part's own tempo (a `tempo` step: the part time-stretched in the take's file, its pitch kept). */ tempo: [1, 1.6], /** A script is the whole post read aloud (operator, 2 Nov) -- or its `excerpt`'s spans (post-item.mjs, 6 Nov), the card showing the whole post; the editor's tts op takes 20,000. */ scriptChars: 20000, takes: 50, }); export const POST_NARRATION_SHORT = Object.freeze(["hold", "loop"]); export const POST_NARRATION_ATTACH = Object.freeze(["under", "after"]); /** * THE NARRATOR's CHAIN after the levelling gain: the demo's compressor and * make-up gain, then (over the whole mix) its limiter. */ export const POST_NARRATOR_COMPRESSOR = "acompressor=threshold=0.1:ratio=3:attack=5:release=120"; export const POST_NARRATOR_MAKEUP = 1.5; export const POST_NARRATION_LIMIT = 0.95; export const POST_NARRATION_CLIP = Object.freeze(["read", "full"]); /** * THE PACE (operator, 4 Nov: a burst "chronologically and quickly"): `pace: * "fast"` on one post (or the cut) plays it back to back -- the read starts at * once and the item ends just after the words. Its gap knobs, unless the post * sets one itself (its own lead/linger always win); "normal" is the cut's. */ export const POST_PACES = Object.freeze({ fast: Object.freeze({ lead: 0.1, tail: 0.15, ramp: 0.3, linger: 0.45 }), normal: Object.freeze({}) }); const MIX_KEYS = ["lead", "tail", "ramp", "linger", "clip", "wet", "lowpassHz", "duck", "short", "attach", "lufs", "rate", "pace"]; // `attach` is one post's (it decides the card's layout, which is drawn from the entry alone). // `follow`: the cut's read-follow (read-follow.mjs) -- { on, dim, ease } -- kept here with the mix it rides on. // `thread`: the cut's thread reads (post-thread.mjs) -- what each context post is on screen, the shrink and dim. const RENDER_KEYS = new Set([...MIX_KEYS.filter((k) => k !== "attach"), "engine", "voice", "follow", "thread"]); // `character`: the character THIS item's own read is made with (cast.mjs: the project's own, else the cast's) -- absent: by its author's handle. // `forReading` (lane line-rerun): the script is his words EDITED FOR READING -- the card follows the shown text // (post-item.mjs scriptEditOf). Set and cleared by the one writer that saves the script, never by hand. const ITEM_KEYS = new Set([...MIX_KEYS, "script", "excerpt", "engine", "voice", "speed", "character", "takes", "pick", "approved", "off", "window", "forReading"]); // `said`: what a synthesized read SAID when an anonymous handle made it differ from its script (post-anon.mjs; the // lint reads it); `speedAsked`: where its speed came from -- true (the command's --speed: kept as asked), "item" (the // item's own), "preset" (its character's: drift when that changes). Absent: unknown -- never speed drift. // `tuning`, `reading` (lane orpheus-tuning): what an Orpheus take was made with, as the editor's result said it -- // every tuning value (the defaults included) and the reading (0 = the first) -- so it can be made again exactly. // `forReading` (lane line-rerun): the take was made from words that are not the post's as drafted -- stamped by the // writer when it is made; while it plays the card follows the shown text (post-item.mjs readEditOf). // `tuningAsked` (lane character-tuning): where an Orpheus take's tuning came from -- true (its line's own: the // command's flags, the bench's Tune), "preset" (its character's: stale when that changes, cast.mjs tuningStale). // Absent: none was asked (the defaults), or unknown (made before it was recorded). // `tuningOwn` (lane reads-find): the LINE's own values exactly as asked (the flags, the bench's Tune; absent: it owned // none) -- what a plain press passes back; every other value is the character's or the settings', resolved anew. const TAKE_KEYS = new Set(["file", "engine", "voice", "seconds", "script", "at", "note", "speed", "lufs", "jobId", "parts", "label", "source", "steps", "words", "slurs", "lexicon", "read", "said", "speedAsked", "screenLine", "tuning", "reading", "forReading", "tuningAsked", "tuningOwn"]); const STEP_KEYS = new Set(["op", "engine", "voice", "pitch", "semitones", "params", "ranAt", "job", "drop", "tempo", "spans", "pauses", "revoice"]); // `role` (post-thread.mjs): the text a part reads -- "post", "quoted", "parent:", "media:"; `voice`, `piece`: the batch's; // `engine`: the part's own when it is not the take's (a cast voice that names its engine: postThreadRead.mjs). // `tempo`: the part's reading speed in the take's file against its first read (a `tempo` step's; absent: 1). // `speed`: the speed the part was synthesized at (its character's preset's, or the read's --speed; absent: 1). // `take`: a thread read's part that IS one of the item's takes (postThreadRead.mjs --post-take): that take's id. // `reading`, `tuning` (lane line-rerun): the reading and the tuning a thread read's part was asked at (absent: the // first reading, the defaults), as postThreadRead.mjs keys and asks it; `tuningAsked` where that tuning came from // (true: the read's own, "preset": the piece's character's -- a take's `tuningAsked`, per piece). const PART_KEYS = new Set(["n", "para", "text", "file", "start", "seconds", "gapBefore", "note", "at", "jobId", "role", "voice", "engine", "piece", "tempo", "speed", "take", "line", "speaker", "reading", "tuning", "tuningAsked"]); const VOICE_RE = /^[A-Za-z0-9][A-Za-z0-9_.+-]{0,63}$/; /** Orpheus's expressive tags (narration.mjs NARRATION_TAGS, the editor's list). */ const TAGS = ["laugh", "chuckle", "sigh", "cough", "sniffle", "groan", "yawn", "gasp"]; const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); const fin = (v) => typeof v === "number" && Number.isFinite(v); const numIn = (v, [lo, hi]) => fin(v) && v >= lo && v <= hi; const round3 = (v) => Math.round(v * 1000) / 1000; /** `render.postNarration` with every default filled in. */ export function resolvePostNarrationRender(render) { const r = isObj(render?.postNarration) ? render.postNarration : {}; return { ...POST_NARRATION_DEFAULTS, ...Object.fromEntries(Object.entries(r).filter(([k, v]) => RENDER_KEYS.has(k) && v !== undefined && v !== null)) }; } /** One post's mix knobs: its own, else the cut's, else the defaults. */ export function postNarrationKnobs(entry, render) { const base = resolvePostNarrationRender(render); const n = isObj(entry?.narration) ? entry.narration : {}; const out = { ...base, attach: POST_NARRATION_DEFAULTS.attach }; for (const k of [...MIX_KEYS, "engine", "voice"]) if (n[k] !== undefined && n[k] !== null) out[k] = n[k]; // Its pace (POST_PACES): the post's, else the cut's -- its gap knobs, unless the post sets one itself. const pace = POST_PACES[out.pace] ? out.pace : "normal"; for (const [k, v] of Object.entries(POST_PACES[pace])) if (n[k] === undefined || n[k] === null) out[k] = v; return out; } /** The take that plays (the picked one, else the first), or null. */ export function pickedTake(entry) { const n = entry?.narration; if (!isObj(n) || !Array.isArray(n.takes) || !n.takes.length) return null; const i = Number.isInteger(n.pick) ? n.pick : 0; const t = n.takes[i]; return isObj(t) && typeof t.file === "string" && fin(t.seconds) && t.seconds > 0 ? { ...t, index: i } : null; } /** Whitespace collapsed: two texts that differ only in their spacing are the same text to a read. */ const sameText = (t) => String(t ?? "").replace(/\s+/g, " ").trim(); /** * THE NEXT READING of `text` (lane line-rerun, "Read again"): one past the highest `reading` among the takes that * SYNTHESIZED those words (a missing reading is 0, the first), or 0 when none did -- the first reading of new words. * Pure: the bench, its route and `--reading next` share it. */ export function nextReadingOf(takes, text) { const want = sameText(text); let hi = -1; for (const t of Array.isArray(takes) ? takes : []) { if (!isObj(t) || takeSourceOf(t).kind !== "tts" || t.read?.kind === "thread" || sameText(t.script) !== want) continue; hi = Math.max(hi, Number.isInteger(t.reading) && t.reading >= 0 ? t.reading : 0); } return hi + 1; } /** The read's speed for a post (its `rate`, else the cut's, else 1), held to its limits. */ export function narrationRateOf(entry, render) { const r = Number(postNarrationKnobs(entry, render).rate); return numIn(r, POST_NARRATION_LIMITS.rate) ? r : 1; } /** A take's seconds AS THE ITEM PLAYS THEM: its length divided by the read's rate. */ export const readSecondsOf = (seconds, rate = 1) => round3(Number(seconds) / (fin(rate) && rate > 0 ? rate : 1)); /** Is the item narrated -- a take picked, and not switched off? */ export const isNarrated = (entry) => entry?.type === "post" && entry?.narration?.off !== true && !!pickedTake(entry); /** Narrated, its attachments starting WITH the read (the demo's way)? */ export const narratedUnder = (entry, render) => isNarrated(entry) && postNarrationKnobs(entry, render).attach !== "after"; /** * The seconds a narrated item plays to by its read (`clip: "read"`): lead + * the take + tail + linger. An attachment longer than this is cut to it. */ export function readSpanSeconds(entry, render) { const t = pickedTake(entry); if (!t) return null; const k = postNarrationKnobs(entry, render); return round3(k.lead + readSecondsOf(t.seconds, narrationRateOf(entry, render)) + k.tail + k.linger); } /** The postId a post item names (`/`). */ export const postIdOf = (entry) => String(entry?.post ?? "").split("/")[1] ?? ""; /** Where a post's takes live in the project. */ export const takesDirOf = (postId) => `narration/posts/${postId}`; /** The project-relative file of take `n` (1-based) of a post. */ export const takeFileOf = (postId, n, engine, voice) => `${takesDirOf(postId)}/take-${n}.${engine}-${voice}.wav`; /** The index of the hand-made batch. */ export const NARRATION_INDEX = "narration/posts/index.json"; /** The next take's number for a post: one past the highest `take-.` already named. */ export function nextTakeNumber(entry, files = []) { let hi = 0; const names = [...(entry?.narration?.takes ?? []).map((t) => t?.file), ...files]; for (const f of names) { const m = /take-(\d+)\./.exec(String(f ?? "")); if (m) hi = Math.max(hi, Number(m[1])); } return hi + 1; } /** * THE MIX's SCHEDULE on the item's clock, for a narrated item: when the * voice starts and ends, when the muffle ends and the clean sound is back. * `seconds` the read's length on the item's clock (the take's, divided by * `rate`); `takeSeconds` the take's own. The render and Play both read this. * * @returns {{ at: number, seconds: number, takeSeconds: number, rate: number, voiceEnd: number, rampEnd: number, wet: number, lowpassHz: number, duck: boolean, attach: string, lufs: number }} */ export function narrationSchedule(entry, render, { pre = 0 } = {}) { const t = pickedTake(entry); const k = postNarrationKnobs(entry, render); const rate = narrationRateOf(entry, render); const seconds = t ? readSecondsOf(t.seconds, rate) : 0; // `pre`: seconds before the lead that are the JOIN's (post-join.mjs: the card morphing from the item before's). const lead = k.lead + (Number.isFinite(pre) && pre > 0 ? pre : 0); const voiceEnd = round3(lead + seconds + k.tail); return { at: round3(lead), seconds: round3(seconds), takeSeconds: round3(t ? t.seconds : 0), rate, voiceEnd, rampEnd: round3(voiceEnd + k.ramp), wet: k.wet, lowpassHz: k.lowpassHz, // After the read, nothing plays under the voice: nothing to muffle. duck: k.duck !== false && k.attach !== "after", attach: k.attach, lufs: k.lufs, }; } /** The muffled sound's gain at item second `t` (the wet branch). */ export function wetGainAt(sch, t) { if (!sch.duck) return 0; if (t < sch.voiceEnd) return sch.wet; const r = sch.rampEnd - sch.voiceEnd; if (r > 0 && t < sch.rampEnd) return sch.wet * (1 - (t - sch.voiceEnd) / r); return 0; } /** The clean sound's gain at item second `t` (the dry branch). */ export function dryGainAt(sch, t) { if (!sch.duck) return 1; if (t < sch.voiceEnd) return 0; const r = sch.rampEnd - sch.voiceEnd; if (r > 0 && t < sch.rampEnd) return (t - sch.voiceEnd) / r; return 1; } /** "muffled" | "ramp" | "clean": what Play and the bench say of the attachment's sound at `t`. */ export function mixPhaseAt(sch, t) { if (!sch.duck) return "clean"; if (t < sch.voiceEnd) return "muffled"; if (t < sch.rampEnd) return "ramp"; return "clean"; } /** A number for a filter argument: 6 decimals, no trailing zeros. */ const f6 = (v) => { const s = (Math.round(Number(v) * 1e6) / 1e6).toFixed(6).replace(/\.?0+$/, ""); return s === "-0" ? "0" : s; }; /** The levelling gain: the take measured at `measured` LUFS to the knob's `target`, held to ±12 dB; 0 unmeasured. */ export function narrationLevelDb(measured, target) { if (!fin(measured) || !fin(target)) return 0; return Math.round(Math.max(-12, Math.min(12, target - measured)) * 100) / 100; } /** * THE MIX's FILTERS, pure (the mix.sh chain, inside the segment's graph): * `media` the label of the item's own sound (its attachments' audio over * silence, the item's length), `voice` the label of the take's input, `out` * the label of the result. Returns the filter_complex parts. * * media -> asplit -> wet: lowpass F twice, gain W until voiceEnd, ramping to 0 over the ramp * -> dry: 0 until voiceEnd, ramping to 1 over the ramp * voice -> resampled, sped up by the read's rate (atempo: its pitch kept), stereo, levelled, the narrator's * compressor and make-up gain, delayed by lead * wet + dry + voice -> amix (no normalising, the item's length) -> limiter * * Without `duck`, the media's sound plays as it is under the voice. The * attachment's sound is never sped: only the voice is (`sch.rate`). */ export function postNarrationFilters({ media, voice, out, sch, gainDb = 0, audioRate = 48000 }) { const E = f6(sch.voiceEnd); const R = f6(Math.max(0.001, sch.rampEnd - sch.voiceEnd)); const W = f6(sch.wet); const F = Math.round(sch.lowpassHz); const ms = Math.round(sch.at * 1000); const rate = fin(sch.rate) && sch.rate > 0 ? sch.rate : 1; const tempo = Math.abs(rate - 1) > 1e-6 ? `atempo=${f6(rate)},` : ""; const parts = [ `[${voice}]aresample=${audioRate},${tempo}aformat=sample_fmts=fltp:channel_layouts=stereo,volume=${f6(gainDb)}dB,${POST_NARRATOR_COMPRESSOR},volume=${f6(POST_NARRATOR_MAKEUP)},adelay=${ms}:all=1[pnv]`, ]; if (sch.duck) { parts.push( `[${media}]asplit=2[pnd][pnw]`, `[pnw]lowpass=f=${F},lowpass=f=${F},volume='if(lt(t,${E}),${W},if(lt(t,${E}+${R}),${W}*(1-(t-${E})/${R}),0))':eval=frame[pnwet]`, `[pnd]volume='if(lt(t,${E}),0,if(lt(t,${E}+${R}),(t-${E})/${R},1))':eval=frame[pndry]`, `[pnwet][pndry][pnv]amix=inputs=3:normalize=0:duration=first,alimiter=limit=${f6(POST_NARRATION_LIMIT)}[${out}]`, ); } else { parts.push(`[${media}][pnv]amix=inputs=2:normalize=0:duration=first,alimiter=limit=${f6(POST_NARRATION_LIMIT)}[${out}]`); } return parts; } // --------------------------------------------------------------------------- // A script, drafted from the post's words. // --------------------------------------------------------------------------- /** * The post's words AS A VOICE READS THEM -- verbatim (operator, 2 Nov: "stick * to the script!"), cleaned only for pronunciation: a repost's "RT @x:", * the leading @handles of a reply, links and emoji dropped (a handle inside the sentence is kept and said "at …"); * "plan(s)" read "plans", "w/" "with", * "&" "and"; the spacing tidied. Nothing is cut: a shorter read is only ever * the operator's own edit. */ /** Caps a TTS should still spell out (a shouted ordinary word is said, not spelled). */ export const SPOKEN_ACRONYMS = Object.freeze(new Set([ "AI", "ASMR", "ASMRS", "BS", "CEO", "CIA", "DM", "DMS", "DOJ", "FBI", "FTC", "GTA", "ID", "IQ", "IRL", "JK", "KF", "LGBT", "LGBTQ", "NFA", "NPC", "NSA", "OK", "PC", "RPG", "TV", "UK", "US", "USA", "VPN", "VR", "VTUBER", "VTUBERS", "XD", ])); /** * SHOUTED WORDS (operator, 3 Nov: Orpheus spelled them; "it should both say them right and yell them"): an ALL-CAPS * word that is not an acronym is lowercased so it is said, and the sentence holding it ends with "!" -- the * shout is carried by punctuation, the words are unchanged. Tags () and acronyms are left alone. */ export function speakShouts(script) { return String(script ?? "").replace(/\bMR\.\s*/g, "Mister ").replace(/\bMRS\.\s*/g, "Missus ").split(/(?<=[.!?…])(\s+)/).map((sentence) => { let shouted = false; const said = sentence.replace(/(<[^<>]*>)|\b([A-Z][A-Z']+)\b/g, (m, tag, word) => { if (tag) return tag; if (SPOKEN_ACRONYMS.has(word.replace(/'S$/, "S").replace(/'/g, ""))) return word; shouted = true; return word.toLowerCase().replace(/^i(?=')|^i$/, "I"); }); return shouted ? said.replace(/\.(["')\]]*)\s*$/, "!$1").replace(/\?(["')\]]*)\s*$/, "?!$1") : said; }).join(""); } // --------------------------------------------------------------------------- // LINKS ARE NEVER SPOKEN (operator, 4 Nov: a quoted post's links were read // aloud -- "https://. web.archive.org slash web slash 2021032015 ..."). X // draws a long link over lines ("https://" / "web.archive.org/web/2021…" / // "1733/https://twitter.com/…" / "…"), so the old `https?://\S+` ate only its // first line. The link is put back together first, then dropped whole. // --------------------------------------------------------------------------- /** The top-level domains a bare `host.tld/…` link is recognised by (no scheme, no www.). */ const URL_TLDS = "com|org|net|io|co|tv|gg|me|ly|be|us|uk|ca|de|fr|ru|jp|app|dev|xyz|info|live|link|news|site|online|social|art|fm|to|is|ph|li|gl|eu|au|nz|in|sh|so|ai|cc|ws|biz|edu|gov"; /** A host as a voice would say it (no path): a domain on one of those. */ const HOST_RE = new RegExp(`\\b(?:[a-z0-9-]+\\.)+(?:${URL_TLDS})\\b`, "gi"); /** A link as written: a scheme, a www., a bare host.tld/path, or X's t.co. */ const URL_RE = new RegExp(`(?:https?:\\/\\/\\S*|\\bwww\\.[^\\s]+|\\b(?:[a-z0-9-]+\\.)+(?:${URL_TLDS})\\/\\S*|\\bt\\.co\\/\\S+)`, "gi"); /** A line ending in a link (its last token one). */ const ENDS_IN_LINK = /(?:https?:\/\/|\bwww\.|\b(?:[a-z0-9-]+\.)+(?:com|org|net|io|co|tv|gg|me|ly|be|app|dev|xyz)\/)\S*$/i; /** What a link's continuation line looks like: one token of a link's characters. */ const LINK_TAIL = /^[\w\-./?=&%#:~+@!,;]+$/; /** X's "…" after a link cut short. */ const ELLIPSIS_LINE = /^(?:…|\.{3})$/; /** * A text with X's SPLIT LINKS put back on one line: "https://" and the host on * the next line joined, a link's continuation lines (one token, a link's * characters, with a "/" or all digits) joined onto it, and a lone "…" line * after a link dropped. Pure. */ export function joinSplitLinks(text) { const lines = String(text ?? "").replace(/(https?:\/\/)[ \t]*\n[ \t]*(?=\S)/gi, "$1").split("\n"); const out = []; for (const raw of lines) { const line = raw.trim(); const last = out.length ? out[out.length - 1] : null; const linked = last !== null && ENDS_IN_LINK.test(last.trim()); if (linked && line && LINK_TAIL.test(line) && (line.includes("/") || /^\d+$/.test(line))) { out[out.length - 1] = `${last.replace(/\s+$/, "")}${line}`; continue; } if (linked && ELLIPSIS_LINE.test(line)) continue; out.push(raw); } return out.join("\n"); } /** A text with every link dropped (joinSplitLinks first). */ export function dropUrls(text) { return joinSplitLinks(text).replace(URL_RE, " "); } /** * WHAT A READ WOULD SAY THAT IS A LINK, pure: the links (and the pieces a * voice reads of one -- "https:", "web.archive.org", "1733/") in `text`, a * script or a part's words. Empty: nothing a voice would say is a link. */ export function spokenUrls(text) { // A voice's "slash" put back, so a spelled-out link is one again. const t = joinSplitLinks(String(text ?? "")).replace(/\s+slash\s+/gi, "/"); const out = []; for (const m of t.matchAll(URL_RE)) out.push(m[0]); // A link a script already spelled out ("https://. web.archive.org slash web slash …"): its scheme, a host. const rest = t.replace(URL_RE, " "); for (const m of rest.matchAll(/\bhttps?:\/*/gi)) out.push(m[0]); for (const m of rest.matchAll(HOST_RE)) if (!/^(?:e\.g|i\.e)$/i.test(m[0])) out.push(m[0]); return out; } /** Whether `text` is only links (and the dots, slashes and digits a split link leaves): a part that is nothing but one. */ export function isOnlyUrls(text) { const t = joinSplitLinks(String(text ?? "")).replace(/\s+slash\s+/gi, "/"); if (!spokenUrls(t).length) return false; return !t .replace(URL_RE, " ") .replace(/\bhttps?:\/*/gi, " ") .replace(HOST_RE, " ") .replace(/[\d\s./:…,;!?\-]+/g, "") .trim(); } export function speakableText(text) { const clean = dropUrls(String(text ?? "")) .replace(/^RT @[A-Za-z0-9_]+:\s*/, "") // X's reply prefix -- the run of @handles a reply OPENS with -- is dropped; a handle inside the sentence is // part of what he wrote ("its good advice @grok don't you agree?") and stays, for the lexicon and the voice // (operator, 5 Nov: "the "@grok" in "@grok don't you agree" should be read out"; spokenRead says it "at …"). .replace(/^(?:[\s,]*@[A-Za-z0-9_]{1,30}\b)+[\s,:]*/, "") .replace(/[\p{Extended_Pictographic}\u{1F1E6}-\u{1F1FF}\u{FE0F}\u{200D}\u{20E3}]/gu, "") .replace(/\b(\w+)\(s\)/g, "$1s") .replace(/(^|\s)w\/(?=\s|$)/gi, "$1with") .replace(/(^|\s)w\/(?=\S)/gi, "$1with ") // "this/that" is read as he writes it: "this slash that" (operator, 3 Nov -- a pattern of his). .replace(/(\w)\/(?=\w)/g, "$1 slash ") .replace(/\s&\s/g, " and ") .replace(/&/g, "and") .replace(/[ \t]+/g, " "); // Its paragraphs (blank lines) stay paragraphs -- a long read is recorded and synthesized by them (scriptParts). const paras = clean .split(/\n[ \t]*\n/) .map((para) => para .split("\n") .map((l) => l.trim()) .filter(Boolean) // A line break is a pause: a line that ends unpunctuated gets its full stop. .map((l, i, all) => (i < all.length - 1 && !/[.!?…,;:—-]["')\]]*$/.test(l) ? `${l}.` : l)) .join(" ") .replace(/\s+([,.!?;:])/g, "$1") .replace(/^[,.;:]\s*/, "") .trim(), ) .filter(Boolean); return speakShouts(paras.map((p, i) => (i < paras.length - 1 && !/[.!?…,;:—-]["')\]]*$/.test(p) ? `${p}.` : p)).join("\n\n")); } /** * A DRAFT SCRIPT from the words it is given: the whole post (speakableText) -- * or, from the CLI, its `excerpt`'s spans (post-item.mjs postReadText). Emotion * is the operator's to add (Orpheus's tags, …). * * @returns {{ script: string, words: number }} */ export function draftScript(text) { const script = speakableText(text); return { script, words: script ? script.split(/\s+/).length : 0 }; } // --------------------------------------------------------------------------- // The validator. // --------------------------------------------------------------------------- function relFile(v, what) { if (typeof v !== "string" || !v.trim()) return `${what} must be a file path relative to the manifest`; if (v.startsWith("/") || v.startsWith("~") || /^[A-Za-z]:[\\/]/.test(v) || v.split(/[\\/]/).includes("..")) return `${what} must stay inside the project: ${v}`; if (!/\.(wav|mp3|m4a|flac|ogg)$/i.test(v)) return `${what} must be a sound file (wav, mp3, m4a, flac, ogg): ${v}`; return null; } function scriptErrors(s, where) { if (typeof s !== "string") return [`${where} must be the words to read (a string)`]; const errors = []; if (s.length > POST_NARRATION_LIMITS.scriptChars) errors.push(`${where} is longer than ${POST_NARRATION_LIMITS.scriptChars} characters`); for (const m of s.matchAll(/<([^<>]*)>/g)) { if (!TAGS.includes(m[1])) errors.push(`${where}: <${m[1]}> is not an expressive tag (${TAGS.map((t) => `<${t}>`).join(" ")})`); } return errors; } function mixErrors(o, where) { const errors = []; for (const k of ["lead", "tail", "ramp", "linger", "wet", "lowpassHz", "lufs", "rate"]) { if (o[k] !== undefined && !numIn(o[k], POST_NARRATION_LIMITS[k])) errors.push(`${where}.${k} must be ${POST_NARRATION_LIMITS[k][0]}–${POST_NARRATION_LIMITS[k][1]}`); } if (o.duck !== undefined && typeof o.duck !== "boolean") errors.push(`${where}.duck must be true or false`); if (o.pace !== undefined && !Object.keys(POST_PACES).includes(o.pace)) errors.push(`${where}.pace must be ${Object.keys(POST_PACES).join(" or ")}`); if (o.clip !== undefined && !POST_NARRATION_CLIP.includes(o.clip)) errors.push(`${where}.clip must be ${POST_NARRATION_CLIP.join(" or ")}`); if (o.short !== undefined && !POST_NARRATION_SHORT.includes(o.short)) errors.push(`${where}.short must be ${POST_NARRATION_SHORT.join(" or ")}`); if (o.attach !== undefined && !POST_NARRATION_ATTACH.includes(o.attach)) errors.push(`${where}.attach must be ${POST_NARRATION_ATTACH.join(" or ")}`); if (o.engine !== undefined && !POST_NARRATION_ENGINES.includes(o.engine)) errors.push(`${where}.engine must be one of ${POST_NARRATION_ENGINES.join(", ")}`); if (o.voice !== undefined && (typeof o.voice !== "string" || !VOICE_RE.test(o.voice))) errors.push(`${where}.voice must be a stock voice's id`); return errors; } /** Every reason `render.postNarration` cannot be built. */ export function validatePostNarrationRender(render) { const r = render?.postNarration; if (r === undefined || r === null) return []; if (!isObj(r)) return ["render.postNarration must be an object of the mix's knobs"]; const errors = []; for (const k of Object.keys(r)) if (!RENDER_KEYS.has(k)) errors.push(`render.postNarration.${k} is not a knob (${[...RENDER_KEYS].join(", ")})`); return [...errors, ...mixErrors(r, "render.postNarration"), ...followKnobErrors(r.follow, "render.postNarration.follow"), ...threadKnobErrors(r.thread, "render.postNarration.thread")]; } /** Every reason one post item's `narration` cannot be built (empty: it can). */ export function validatePostNarration(e) { const n = e?.narration; if (n === undefined) return []; const w = `timeline ${e?.id ?? "?"}.narration`; if (!isObj(n)) return [`${w} must be an object ({ script, takes, pick, … })`]; const errors = []; for (const k of Object.keys(n)) if (!ITEM_KEYS.has(k)) errors.push(`${w}.${k} is not a narration key`); if (n.script !== undefined) errors.push(...scriptErrors(n.script, `${w}.script`)); for (const k of ["excerpt", "approved", "off"]) if (n[k] !== undefined && typeof n[k] !== "boolean") errors.push(`${w}.${k} must be true or false`); if (n.forReading !== undefined && n.forReading !== true) errors.push(`${w}.forReading must be true (or absent)`); if (n.speed !== undefined && !numIn(n.speed, POST_NARRATION_LIMITS.speed)) errors.push(`${w}.speed must be ${POST_NARRATION_LIMITS.speed.join("–")}`); if (n.character !== undefined && !(typeof n.character === "string" && /^[a-z0-9][a-z0-9_-]{0,47}$/.test(n.character))) errors.push(`${w}.character must be a character's id (umtool posts character)`); if (n.window !== undefined) { const x = n.window; if (!isObj(x) || !Number.isInteger(x.media) || !fin(x.start) || !fin(x.end) || x.end <= x.start || (x.score !== undefined && !fin(x.score)) || (x.reason !== undefined && typeof x.reason !== "string")) { errors.push(`${w}.window must be { media, start, end, score?, reason?, at? } (posts fit's choice)`); } } errors.push(...mixErrors(n, w)); if (n.takes !== undefined) { if (!Array.isArray(n.takes)) errors.push(`${w}.takes must be a list`); else { if (n.takes.length > POST_NARRATION_LIMITS.takes) errors.push(`${w}.takes: at most ${POST_NARRATION_LIMITS.takes}`); n.takes.forEach((t, i) => { const tw = `${w}.takes[${i}]`; if (!isObj(t)) { errors.push(`${tw} must be an object`); return; } for (const k of Object.keys(t)) if (!TAKE_KEYS.has(k)) errors.push(`${tw}.${k} is not a take key`); const fe = relFile(t.file, `${tw}.file`); if (fe) errors.push(fe); if (!(fin(t.seconds) && t.seconds > 0 && t.seconds <= 600)) errors.push(`${tw}.seconds must be its length (measured when it came in)`); if (t.engine !== undefined && !POST_TAKE_ENGINES.includes(t.engine)) errors.push(`${tw}.engine must be one of ${POST_TAKE_ENGINES.join(", ")}`); if (t.voice !== undefined && (typeof t.voice !== "string" || !VOICE_RE.test(t.voice))) errors.push(`${tw}.voice must be a stock voice's id`); if (t.script !== undefined && typeof t.script !== "string") errors.push(`${tw}.script must be the words it read`); for (const k of ["note", "at", "jobId"]) if (t[k] !== undefined && typeof t[k] !== "string") errors.push(`${tw}.${k} must be a string`); if (t.lufs !== undefined && t.lufs !== null && !fin(t.lufs)) errors.push(`${tw}.lufs must be a number`); if (t.speed !== undefined && !numIn(t.speed, POST_NARRATION_LIMITS.speed)) errors.push(`${tw}.speed must be ${POST_NARRATION_LIMITS.speed.join("–")}`); if (t.label !== undefined && (typeof t.label !== "string" || !VOICE_RE.test(t.label))) errors.push(`${tw}.label must be a short name (a recorded voice's)`); if (t.source !== undefined) { const src = t.source; const ok = isObj(src) && ( (src.kind === "tts" && POST_NARRATION_ENGINES.includes(src.engine) && typeof src.voice === "string") || (src.kind === "recorded" && typeof src.voice === "string" && VOICE_RE.test(src.voice)) || (src.kind === "take" && typeof src.from === "string" && n.takes.some((x) => takeIdOf(x) === src.from && x !== t)) ); if (!ok) errors.push(`${tw}.source must be {kind: "tts", engine, voice}, {kind: "recorded", voice} or {kind: "take", from: }`); } // What its audio does with the slurs its script holds (post-slurs.mjs): said (a beep or a mute covers them), left out, or a stand-in said. if (t.slurs !== undefined && !["said", "skip", "placeholder"].includes(t.slurs)) errors.push(`${tw}.slurs must be said, skip or placeholder`); // The pronunciation entries its read applied (post-say.mjs), and how a thread read was asked for (postThreadRead.mjs). errors.push(...takeLexiconErrors(t.lexicon, `${tw}.lexicon`)); if (t.said !== undefined && (typeof t.said !== "string" || t.said.length > 50000)) errors.push(`${tw}.said must be the words its read said`); if (t.speedAsked !== undefined && t.speedAsked !== true && t.speedAsked !== "item" && t.speedAsked !== "preset") errors.push(`${tw}.speedAsked must be true, "item" or "preset"`); if (t.tuningAsked !== undefined && t.tuningAsked !== true && t.tuningAsked !== "preset") errors.push(`${tw}.tuningAsked must be true (its line's own tuning) or "preset" (its character's)`); errors.push(...tuningProblems(t.tuning, t.reading, tw)); if (t.tuningOwn !== undefined && (!isObj(t.tuningOwn) || !Object.keys(t.tuningOwn).length)) errors.push(`${tw}.tuningOwn must be the line's own tuning values (or absent: it owned none)`); else if (t.tuningOwn !== undefined) errors.push(...tuningProblems(t.tuningOwn, undefined, `${tw}.tuningOwn`).map((x) => x.replace(`${tw}.tuningOwn.tuning`, `${tw}.tuningOwn`))); if (t.forReading !== undefined && t.forReading !== true) errors.push(`${tw}.forReading must be true (or absent)`); if (t.read !== undefined && !(isObj(t.read) && t.read.kind === "thread" && JSON.stringify(t.read).length <= 4000)) errors.push(`${tw}.read must be {kind: "thread", …} (how the thread read was asked for)`); // A RECORDING OF ONE SCREEN LINE (postScreensCli.mjs `posts screen … record`, post-screens.mjs): the line it was // recorded for -- its screen, its index, its words as a read writes them, its speaker. Never the item's read. if (t.screenLine !== undefined) { const sl = t.screenLine; // `heard` (--check-words): what the editor's transcription heard it say, against which words, when. const heardOk = sl?.heard === undefined || (isObj(sl.heard) && typeof sl.heard.at === "string" && typeof sl.heard.against === "string" && sl.heard.against.length <= 2000 && typeof sl.heard.words === "string" && sl.heard.words.length <= 2000 && Object.keys(sl.heard).every((kk) => ["at", "against", "words"].includes(kk))); if (!(isObj(sl) && typeof sl.screen === "string" && /^[a-z0-9][a-z0-9-]{0,23}$/.test(sl.screen) && Number.isInteger(sl.n) && sl.n >= 0 && sl.n < 60 && typeof sl.said === "string" && sl.said.length <= 2000 && typeof sl.speaker === "string" && sl.speaker.length <= 64 && heardOk && Object.keys(sl).every((kk) => ["screen", "n", "said", "speaker", "heard"].includes(kk)))) { errors.push(`${tw}.screenLine must be { screen, n, said, speaker, heard? } (the screen line it is a recording of)`); } } if (t.words !== undefined) { // Its script's words, timed in take seconds (the editor's transcription, aligned: word-zoom.mjs scriptWordTimes). const ws = t.words; // `estimated: true`: a word a re-voice put in, timed from its piece's sound, not aligned (a later --words refines it). const bad = !Array.isArray(ws) || ws.length > 20000 ? -2 : ws.findIndex((x) => !isObj(x) || typeof x.w !== "string" || !fin(x.start) || !fin(x.end) || x.start < 0 || x.end < x.start || (x.estimated !== undefined && x.estimated !== true) || Object.keys(x).some((kk) => kk !== "w" && kk !== "start" && kk !== "end" && kk !== "estimated")); if (bad === -2) errors.push(`${tw}.words must be a list of { w, start, end } (its words, timed; at most 20000)`); else if (bad >= 0) errors.push(`${tw}.words[${bad}] must be { w, start, end, estimated? } (take seconds, end ≥ start)`); } if (t.steps !== undefined) { if (!Array.isArray(t.steps) || t.steps.length > 20) errors.push(`${tw}.steps must be a list (at most 20)`); else t.steps.forEach((st, k) => { if (!isObj(st) || !(POST_DERIVE_OPS.includes(st.op) || POST_LOCAL_OPS.includes(st.op))) errors.push(`${tw}.steps[${k}].op must be one of ${[...POST_DERIVE_OPS, ...POST_LOCAL_OPS].join(", ")}`); else { for (const key of Object.keys(st)) if (!STEP_KEYS.has(key)) errors.push(`${tw}.steps[${k}].${key} is not a step key`); // A convert's followed pitch, as the editor ran it. if (st.pitch !== undefined && !["target", "source", "contour"].includes(st.pitch)) errors.push(`${tw}.steps[${k}].pitch must be target, source or contour`); if (st.semitones !== undefined && !(fin(st.semitones) && Math.abs(st.semitones) <= 12)) errors.push(`${tw}.steps[${k}].semitones must be a number from -12 to 12`); // A re-join's record: what it left out (a piece, "part ", "url"). if (st.drop !== undefined && !(Array.isArray(st.drop) && st.drop.length <= 200 && st.drop.every((d) => typeof d === "string"))) errors.push(`${tw}.steps[${k}].drop must be a list of what it left out`); // A tempo step's record: each run of parts ("4-16", "21") and the tempo it reads at. if (st.tempo !== undefined && !(isObj(st.tempo) && Object.keys(st.tempo).length <= 200 && Object.entries(st.tempo).every(([r, v]) => /^\d{1,3}(-\d{1,3})?$/.test(r) && numIn(v, POST_NARRATION_LIMITS.tempo)))) errors.push(`${tw}.steps[${k}].tempo must be {"[-]": ${POST_NARRATION_LIMITS.tempo.join("–")}}`); // A yell step's record: the take seconds it raised. if (st.spans !== undefined && !(Array.isArray(st.spans) && st.spans.length <= 500 && st.spans.every((x) => Array.isArray(x) && x.length === 2 && fin(x[0]) && fin(x[1]) && x[0] >= 0 && x[1] > x[0]))) errors.push(`${tw}.steps[${k}].spans must be a list of [from, to] (take seconds)`); // A pause step's record: each pause, after word (its index in the take's words), cut at (the source take's seconds). // A re-voice's record: the words it replaced (from word , of them: ), what it said instead, in // which voice, the source take's seconds cut out [from, to), the new piece's length, its gain and crossfade. if (st.revoice !== undefined) { const rv = st.revoice; const ok = isObj(rv) && Number.isInteger(rv.word) && rv.word >= 0 && Number.isInteger(rv.count) && rv.count >= 1 && fin(rv.from) && fin(rv.to) && rv.from >= 0 && rv.to > rv.from && fin(rv.seconds) && rv.seconds > 0 && rv.seconds <= 60 && typeof rv.say === "string" && rv.say.length <= 2000 && (rv.phrase === undefined || typeof rv.phrase === "string") && (rv.said === undefined || typeof rv.said === "string") && typeof rv.voice === "string" && VOICE_RE.test(rv.voice) && (rv.engine === undefined || typeof rv.engine === "string") && (rv.gain === undefined || numIn(rv.gain, [-6, 6])) && (rv.xfade === undefined || numIn(rv.xfade, [0, 0.2])) && (rv.key === undefined || typeof rv.key === "string") && (rv.words === undefined || (Number.isInteger(rv.words) && rv.words >= 0)); if (!ok) errors.push(`${tw}.steps[${k}].revoice must be {word, count, phrase, say, said, voice, engine, from, to, seconds, gain (±6 dB), xfade (0–0.2 s)}`); } if (st.pauses !== undefined && !(Array.isArray(st.pauses) && st.pauses.length <= 200 && st.pauses.every((x) => isObj(x) && Number.isInteger(x.word) && x.word >= 0 && fin(x.at) && x.at >= 0 && numIn(x.seconds, [0.05, 3]) && (x.w === undefined || typeof x.w === "string")))) errors.push(`${tw}.steps[${k}].pauses must be a list of {word, w, at, seconds} (seconds 0.05–3)`); } }); } if (t.parts !== undefined) { // A take COMPOSED OF PARTS (a long post read paragraph by paragraph): the joined file is the take's. if (!Array.isArray(t.parts) || t.parts.length > 200) errors.push(`${tw}.parts must be a list (at most 200)`); else t.parts.forEach((p, k) => { const pw = `${tw}.parts[${k}]`; if (!isObj(p)) return errors.push(`${pw} must be an object`); for (const key of Object.keys(p)) if (!PART_KEYS.has(key)) errors.push(`${pw}.${key} is not a part key`); if (p.file !== undefined) { const pe = relFile(p.file, `${pw}.file`); if (pe) errors.push(pe); } if (!(fin(p.start) && p.start >= 0)) errors.push(`${pw}.start must be where it starts in the take, seconds`); if (!(fin(p.seconds) && p.seconds > 0)) errors.push(`${pw}.seconds must be its length`); if (p.text !== undefined && typeof p.text !== "string") errors.push(`${pw}.text must be the words it reads`); if (p.line !== undefined && typeof p.line !== "string") errors.push(`${pw}.line must be the screen line it was made from (its words)`); if (p.speaker !== undefined && typeof p.speaker !== "string") errors.push(`${pw}.speaker must be the screen line's speaker it was made for`); if (p.speed !== undefined && !numIn(p.speed, POST_NARRATION_LIMITS.speed)) errors.push(`${pw}.speed must be ${POST_NARRATION_LIMITS.speed.join("–")} (the speed it was synthesized at)`); if (p.tempo !== undefined && !numIn(p.tempo, POST_NARRATION_LIMITS.tempo)) errors.push(`${pw}.tempo must be ${POST_NARRATION_LIMITS.tempo.join("–")} (its reading speed in the take)`); if (p.reading !== undefined || p.tuning !== undefined) errors.push(...tuningProblems(p.tuning, p.reading, pw)); if (p.tuningAsked !== undefined && p.tuningAsked !== true && p.tuningAsked !== "preset") errors.push(`${pw}.tuningAsked must be true (the read's own tuning) or "preset" (its character's)`); if (p.role !== undefined && !(typeof p.role === "string" && /^(post|quoted|parent:\d|media:\d|linked:\d|screen:[a-z0-9][a-z0-9-]{0,23}:\d{1,2})$/.test(p.role))) errors.push(`${pw}.role must be post, quoted, parent:, linked:, media: or screen:: (the text it reads)`); if (p.engine !== undefined && !POST_NARRATION_ENGINES.includes(p.engine)) errors.push(`${pw}.engine must be one of ${POST_NARRATION_ENGINES.join(", ")}`); if (p.take !== undefined && !(typeof p.take === "string" && n.takes.some((x) => x !== t && takeIdOf(x) === p.take))) errors.push(`${pw}.take must be the id of another of its takes (the take this part is)`); }); } }); } } if (n.pick !== undefined && !(Number.isInteger(n.pick) && n.pick >= 0 && Array.isArray(n.takes) && n.pick < n.takes.length)) { errors.push(`${w}.pick must be the index of one of its takes (0–${Math.max(0, (n.takes?.length ?? 1) - 1)})`); } // A take of ONE SCREEN LINE is a piece of a read (--line-take), never the item's read itself. const pk = Array.isArray(n.takes) && n.takes.length ? (Number.isInteger(n.pick) && n.pick >= 0 && n.pick < n.takes.length ? n.pick : 0) : -1; const pt = pk >= 0 ? n.takes[pk] : null; if (isObj(pt) && isObj(pt.screenLine)) errors.push(`${w}.pick: take ${pk + 1} is a recording of line ${pt.screenLine.n} of screen ${pt.screenLine.screen} -- a line take is read inside the item's read (posts screen

${e?.id ?? ""} read --line-take …), never picked as it: pick another take`); return errors; } /** The take files a post item's narration names, as `{ where, src }` (the lint checks each is there). */ export function postNarrationFiles(entry) { const takes = Array.isArray(entry?.narration?.takes) ? entry.narration.takes : []; const w = `timeline ${entry?.id ?? "?"}.narration`; // Only the one that plays must be there to build; the rest may have been pruned. const t = takes.length && isNarrated(entry) ? pickedTake(entry) : null; return t ? [{ where: `${w}.takes[${t.index}]`, src: t.file }] : []; } /** The disclosure line a narrated post item's cut carries (narration.mjs's wording). */ export function postNarrationDisclosure(entry) { const t = pickedTake(entry); if (!t || !isNarrated(entry)) return null; const takes = entry.narration.takes ?? []; // A voice converted to a stock synthetic one says so; enhanced, the chain's root decides. const convert = (t.steps ?? []).find((st) => st?.op === "convert"); if (convert) return `Narration: voice converted to a synthetic voice (${convert.engine ?? "?"} · ${convert.voice ?? "?"})`; const root = rootTakeOf(takes, t); // A recorded take is a person's own voice: nothing synthetic to disclose. if (root.engine === "recorded" || takeSourceOf(root).kind === "recorded") return null; if (root !== t) return postNarrationDisclosure({ ...entry, narration: { ...entry.narration, takes: [root], pick: 0 } }); const labelOf = (e) => ({ orpheus: "Orpheus", kokoro: "Kokoro-82M", "espeak-ng": "eSpeak NG" })[e] ?? e ?? "a stock voice"; // A read joined from two engines' parts (a cast voice naming its own engine): each engine with its voices. const parts = Array.isArray(t.parts) ? t.parts.filter((p) => typeof p?.voice === "string") : []; // A THREAD READ WITH A TAKE FOR A PART (postThreadRead.mjs --post-take): each part said truthfully -- the // synthesized ones as above, a recorded line converted to a stock voice as such, a raw recording as a recorded // reading -- never "synthetic voice" over a human line. if (parts.some((p) => typeof p.take === "string")) { const syn = parts.filter((p) => typeof p.take !== "string"); const bits = []; if (syn.length) { const engs = [...new Set(syn.map((p) => p.engine ?? t.engine))]; const voicesOf = (e) => [...new Set(syn.filter((p) => (p.engine ?? t.engine) === e).map((p) => p.voice))].join("+"); bits.push(engs.length > 1 ? `synthetic voices (${engs.map((e) => `${labelOf(e)} · ${voicesOf(e)}`).join("; ")})` : `synthetic voice (${labelOf(engs[0])} · ${voicesOf(engs[0])})`); } const seen = new Set(); for (const p of parts.filter((x) => typeof x.take === "string")) { if (seen.has(p.take)) continue; seen.add(p.take); const src = takes.find((x) => x !== t && isObj(x) && (x.file === p.file || takeIdOf(x) === p.take)) ?? null; const conv = (src?.steps ?? []).find((st) => st?.op === "convert"); if (conv) bits.push(`a recorded reading converted to a stock voice (${conv.engine ?? "?"} · ${conv.voice ?? "?"})`); else if (!src) bits.push("a recorded reading"); else { const r = rootTakeOf(takes, src); if (r.engine === "recorded" || takeSourceOf(r).kind === "recorded") bits.push("a recorded reading"); else bits.push(String(postNarrationDisclosure({ ...entry, narration: { ...entry.narration, takes: [r], pick: 0 } }) ?? "a recorded reading").replace(/^Narration: /, "")); } } return `Narration: ${bits.join("; ")}`; } const engines = [...new Set(parts.map((p) => p.engine ?? t.engine))]; if (engines.length > 1) { return `Narration: synthetic voices (${engines.map((e) => `${labelOf(e)} · ${[...new Set(parts.filter((p) => (p.engine ?? t.engine) === e).map((p) => p.voice))].join("+")}`).join("; ")})`; } return `Narration: synthetic voice (${labelOf(t.engine)} · ${t.voice ?? "?"})`; } // --------------------------------------------------------------------------- // A long read, PART BY PART (operator, 2 Nov: "some of these massive posts // will need to compose multiple read paragraphs and can't be one-shot"): the // script split into parts -- its paragraphs (blank lines), a paragraph over // POST_PART_WORDS words split at its sentence ends -- each synthesized or // recorded on its own and joined with a pause between them. // --------------------------------------------------------------------------- /** A part reads at most this many words (a paragraph longer than it is split at a sentence end). */ export const POST_PART_WORDS = 60; /** The pause the parts are joined with: between paragraphs, inside one, and between the pieces of a thread read (lib/report/postThreadRead.mjs). */ export const POST_PART_GAP = Object.freeze({ para: 0.6, inside: 0.25, piece: 0.8 }); const wordsOf = (t) => (String(t).trim() ? String(t).trim().split(/\s+/).length : 0); /** * The script's PARTS, pure: `[{ n, para, text }]` (n from 1, para the * paragraph's index from 0). A script of one short paragraph is one part. */ export function scriptParts(script, max = POST_PART_WORDS) { const paras = String(script ?? "").split(/\n\s*\n/).map((p) => p.replace(/\s+/g, " ").trim()).filter(Boolean); const out = []; paras.forEach((p, para) => { if (wordsOf(p) <= max) { out.push({ para, text: p }); return; } const sentences = p.match(/[^.!?…]+[.!?…]+["')\]]*\s*|[^.!?…]+$/g) ?? [p]; let cur = ""; for (const sen of sentences) { if (cur && wordsOf(cur) + wordsOf(sen) > max) { out.push({ para, text: cur.trim() }); cur = ""; } cur += sen; } if (cur.trim()) out.push({ para, text: cur.trim() }); }); return out.map((p, i) => ({ n: i + 1, ...p })); } /** The pause before part `k` of `parts` (0 before the first). */ export const partGapBefore = (parts, k) => (k === 0 ? 0 : parts[k].para !== parts[k - 1].para ? POST_PART_GAP.para : POST_PART_GAP.inside); /** Where part `p` of the picked take starts on the item's clock (its start in the take, at the read's rate). */ export const partStartOnItem = (sch, p) => round3((sch?.at ?? 0) + readSecondsOf(p.start, sch?.rate ?? 1)); /** The part being read at item second `s` (the picked take's parts, on the item's clock), or null. */ export function partAt(entry, sch, s) { const t = pickedTake(entry); const parts = Array.isArray(t?.parts) ? t.parts : []; if (!parts.length || !sch) return null; let cur = null; for (const p of parts) if (s >= partStartOnItem(sch, p) - 0.05) cur = p; return cur; }