// THE CHUNKER for an engine that speaks a few sentences per call (release 25 // T1b: Orpheus), ported from the tuned round's pipeline (run_orpheus2.py // `chunk()`), with its expected-length budget. // // Normalized text (lib/ttsText.ts, paragraphs kept as "\n\n") → chunks of 1–5 // sentences, at most 420 characters, packed for the fewest chunks first and // then the most even lengths. A fragment under six words ("No title.") counts // as half a sentence. A sentence over the limit is cut at `; :` first, then at // a comma before a conjunction, then at any comma — never mid-phrase. A blank // line always ends a chunk. Each chunk carries the pause that follows it, by // how it ended: a sentence 0.20 s, a clause 0.10 s, a paragraph 0.40 s, // nothing after the last. // // Pure, no imports beyond the tag set. scripts/tts_orpheus.py renders what // this returns; it does not chunk. import { TTS_EXPRESSIVE_TAGS } from "./ttsText"; // Longer chunks and shorter joins than the tuned round's 250/3 and 0.3/0.15/0.6: // fewer prosody restarts, which the operator heard as an inhuman cadence // (2026-10-12, the commentary audition). export const CHUNK_MAX_CHARS = 420; export const CHUNK_MAX_SENTENCES = 5; export const CHUNK_PAUSE = { sentence: 0.2, clause: 0.1, paragraph: 0.4, end: 0 } as const; export type ChunkEnding = keyof typeof CHUNK_PAUSE; export type TtsChunk = { text: string; ends: ChunkEnding; pauseAfter: number }; // The limits a chunking uses; the defaults are the constants above. export type TtsChunking = { maxChars: number; maxSentences: number; pause: Record; }; export const DEFAULT_TTS_CHUNKING: TtsChunking = { maxChars: CHUNK_MAX_CHARS, maxSentences: CHUNK_MAX_SENTENCES, pause: CHUNK_PAUSE, }; const TAG = `<(?:${TTS_EXPRESSIVE_TAGS.join("|")})>`; const TAG_G = new RegExp(TAG, "g"); const CONJ = "(?:and|but|so|because|which|while|or|yet|when|although|though|where|since|until|unless|then)"; /** Words in a chunk, tags not counted. */ export function wordsIn(text: string): number { return (text.replace(TAG_G, " ").match(/[A-Za-z0-9]+(?:'[A-Za-z]+)?/g) ?? []).length; } /** A paragraph's sentences. A reaction tag after a sentence joins it; a lowercase start is an ellipsis continuation. */ export function splitSentences(par: string): string[] { const pieces = par.trim().split(/(?<=[.!?]["')\]])\s+|(?<=[.!?])\s+/); const lead = new RegExp(`^(?:${TAG}\\s*)+`); const out: string[] = []; for (const raw of pieces) { let p = raw.trim(); if (!p) continue; const m = lead.exec(p); if (m && out.length) { out[out.length - 1] += ` ${m[0].trim()}`; p = p.slice(m[0].length).trim(); if (!p) continue; } if (out.length && /^[a-z]/.test(p)) out[out.length - 1] += ` ${p}`; else out.push(p); } return out; } /** One over-long sentence cut at clause boundaries, never mid-phrase. */ export function splitLong(s: string, limit = CHUNK_MAX_CHARS): string[] { if (s.length <= limit) return [s]; const mid = s.length / 2; for (const pat of [/[;:]\s+/g, new RegExp(`,\\s+(?=${CONJ}\\b)`, "g"), /,\s+/g]) { const cuts = [...s.matchAll(pat)] .filter((m) => m.index! >= 40 && m.index! <= s.length - 40) .map((m) => m.index! + m[0].length); if (cuts.length) { const c = cuts.reduce((a, b) => (Math.abs(b - mid) < Math.abs(a - mid) ? b : a)); return [...splitLong(s.slice(0, c).trim(), limit), ...splitLong(s.slice(c).trim(), limit)]; } } let c = s.lastIndexOf(" ", Math.floor(mid)); if (c <= 0) c = Math.floor(mid); return [...splitLong(s.slice(0, c).trim(), limit), ...splitLong(s.slice(c).trim(), limit)]; } // Balanced packing (DP): fewest chunks, then the least sum of squared lengths. function pack(units: string[], lim: TtsChunking): string[] { const n = units.length; const wt = units.map((u) => (wordsIn(u) < 6 ? 0.5 : 1)); const best: [number, number, number][] = [[0, 0, -1]]; for (let i = 1; i <= n; i++) best.push([Infinity, Infinity, -1]); for (let i = 1; i <= n; i++) { let w = 0; for (let j = i - 1; j >= 0; j--) { w += wt[j]; const L = units.slice(j, i).join(" ").length; if (i - j > 1 && (L > lim.maxChars || w > lim.maxSentences)) break; const c: [number, number, number] = [best[j][0] + 1, best[j][1] + L * L, j]; if (c[0] < best[i][0] || (c[0] === best[i][0] && c[1] < best[i][1])) best[i] = c; } } const out: string[] = []; for (let i = n; i > 0; i = best[i][2]) out.push(units.slice(best[i][2], i).join(" ")); return out.reverse(); } function ending(text: string): ChunkEnding { const core = text.replace(TAG_G, "").replace(/[ "')\]]+$/, ""); return /[.!?]$/.test(core) ? "sentence" : "clause"; } /** Normalized text (paragraphs as "\n\n") → chunks, each with the pause after it. */ export function chunkTtsText(normalized: string, lim: TtsChunking = DEFAULT_TTS_CHUNKING): TtsChunk[] { const paras = normalized.split("\n\n").filter((p) => p.trim()); const chunks: TtsChunk[] = []; paras.forEach((par, pi) => { const units = splitSentences(par).flatMap((s) => splitLong(s, lim.maxChars)); const packed = pack(units, lim); packed.forEach((text, ci) => { const lastInPar = ci === packed.length - 1; const ends: ChunkEnding = lastInPar && pi === paras.length - 1 ? "end" : lastInPar ? "paragraph" : ending(text); chunks.push({ text, ends, pauseAfter: lim.pause[ends] }); }); }); return chunks; } // SNAC 24 kHz: 7 tokens per frame of 2048 samples — 82.03 tokens a second of audio. export const ORPHEUS_TOKENS_PER_AUDIO_S = (7 * 24000) / 2048; // The least a chunk's budget expects, in seconds of audio. export const NPREDICT_MIN_EXPECTED_S = 4; /** * The token budget for one chunk: its expected seconds × 82.03 tokens/s × 1.6, * rounded up to a whole 7-token frame, so a runaway take is cut (and flagged, * never kept). Expected seconds = words ÷ 2.5 + 0.9 a tag + 0.3 an "..." + 0.6, * at least NPREDICT_MIN_EXPECTED_S: a four-word line ("Well, then this drops.") * was cut on every take at its 2.2 s budget and failed the synthesis. */ export function nPredictFor(text: string): number { const tags = (text.match(TAG_G) ?? []).length; const ellipses = text.split("...").length - 1; const expS = Math.max(NPREDICT_MIN_EXPECTED_S, wordsIn(text) / 2.5 + 0.9 * tags + 0.3 * ellipses + 0.6); return Math.ceil((expS * ORPHEUS_TOKENS_PER_AUDIO_S * 1.6) / 7) * 7; }