// THE TEXT PRE-PASS EVERY SPEECH ENGINE'S INPUT GOES THROUGH (release 25 T1, // widened by T1b to the tuned Orpheus round's spoken-form normalizer). // // One shared normalizer; each engine in lib/ttsApps.ts picks its options with // its own `normalize` hook. What it does: // // 1. Expressive tags. Narration may carry the tag set below (``, // ``, ...). An engine that performs them (Orpheus) gets them as // written; one that cannot (Kokoro, espeak-ng) has them STRIPPED, so // nothing reads "less-than laugh" aloud. Any OTHER `<...>` is refused // before a job exists (`unknownTtsTags`, called by controller/ttsFile.ts): // a typo must never be spoken. // 2. Spoken form, on the text between the tags, in this order (URLs and // handles hold dots and digits, so they go first): typography, URLs (the // spoken host only), @handles and #hashtags, abbreviations (Dr. Mr. vs. // e.g. i.e. etc. No.), an em dash as a comma pause and a dash between // numbers as "to", money ($ £ € with cents and "million"), percentages, // ordinals, clock times, decades, years, grouped numbers, decimals, plain // integers. Years 1900-2099 are said as years ("twenty twenty-four", // "two thousand five", "nineteen oh five"); with `years: "guarded"` a year // followed by a count noun is a number ("1950 people"), with `"plain"` // (Kokoro's rule since T1) it is a year either way. // 3. Whitespace. Inside a paragraph every whitespace run is one space, no // space before punctuation, ends trimmed. Paragraphs (blank lines) are kept // as "\n\n" for an engine that chunks by them (Orpheus) or joined — so the // cache key (controller/ttsFile.ts) does not change with a re-wrapped // paragraph. // // Pure, no imports: umtool's validator may import or mirror TTS_EXPRESSIVE_TAGS. // The expressive tags a script may carry (Orpheus's set). Lowercase, exact. export const TTS_EXPRESSIVE_TAGS = [ "laugh", "chuckle", "sigh", "cough", "sniffle", "groan", "yawn", "gasp", ] as const; export type TtsExpressiveTag = (typeof TTS_EXPRESSIVE_TAGS)[number]; const TAG_SET: ReadonlySet = new Set(TTS_EXPRESSIVE_TAGS); // Anything that reads as a tag: `<`, no angle brackets, `>`. const ANY_TAG = /<[^<>]*>/g; /** Every `<...>` in `text` that is not one of TTS_EXPRESSIVE_TAGS, in order, de-duplicated. */ export function unknownTtsTags(text: string): string[] { const out: string[] = []; for (const m of text.matchAll(ANY_TAG)) { const inner = m[0].slice(1, -1); if (TAG_SET.has(inner)) continue; if (!out.includes(m[0])) out.push(m[0]); } return out; } /** The refusal for the tags `unknownTtsTags` found, or null when there are none. */ export function unknownTtsTagsError(text: string): string | null { const bad = unknownTtsTags(text); if (bad.length === 0) return null; const hints = bad .map((t) => { const inner = t.slice(1, -1).trim().toLowerCase(); return TAG_SET.has(inner) ? `${t} (did you mean <${inner}>?)` : t; }) .join(", "); return ( `the text holds ${bad.length === 1 ? "a tag" : "tags"} no engine knows: ${hints} — ` + `the expressive tags are ${TTS_EXPRESSIVE_TAGS.map((t) => `<${t}>`).join(" ")}` ); } /** `text` with every expressive tag removed and the whitespace around it closed up. */ export function stripTtsTags(text: string): string { const stripped = text.replace(ANY_TAG, (tag) => TAG_SET.has(tag.slice(1, -1)) ? " " : tag, ); // A tag between two commas ("Well, , fine.") leaves two. return collapseTtsWhitespace(stripped).replace(/([.,!?;:]),/g, "$1"); } /** One space for every whitespace run, none before punctuation, trimmed. */ export function collapseTtsWhitespace(text: string): string { return text .replace(/\s+/g, " ") .replace(/ +([.,!?;:])/g, "$1") .trim(); } // --- years ------------------------------------------------------------------- const ONES = [ "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen", ]; const TENS = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"]; const TENS_PLURAL = ["", "tens", "twenties", "thirties", "forties", "fifties", "sixties", "seventies", "eighties", "nineties"]; /** 0-99 in words: "seven", "fourteen", "twenty-four". */ export function twoDigitWords(n: number): string { if (!Number.isInteger(n) || n < 0 || n > 99) throw new RangeError(`not 0-99: ${n}`); if (n < 20) return ONES[n]; const t = Math.floor(n / 10); const o = n % 10; return o === 0 ? TENS[t] : `${TENS[t]}-${ONES[o]}`; } /** * A year 1900-2099 as it is said: 1900 "nineteen hundred", 1905 "nineteen oh * five", 1999 "nineteen ninety-nine", 2000 "two thousand", 2005 "two thousand * five", 2010 "twenty ten", 2024 "twenty twenty-four". With `plural` (a decade, * "the 1990s") the last word is pluralised: "nineteen nineties", "two * thousands", "twenty twenties". */ export function yearWords(year: number, plural = false): string { if (!Number.isInteger(year) || year < 1900 || year > 2099) { throw new RangeError(`not a year 1900-2099: ${year}`); } const c = Math.floor(year / 100); const r = year % 100; if (plural) { if (r % 10 !== 0) throw new RangeError(`not a decade: ${year}`); if (year === 1900) return "nineteen hundreds"; if (year === 2000) return "two thousands"; return `${twoDigitWords(c)} ${TENS_PLURAL[r / 10]}`; } if (year === 2000) return "two thousand"; if (c === 20 && r < 10) return `two thousand ${ONES[r]}`; if (r === 0) return `${twoDigitWords(c)} hundred`; if (r < 10) return `${twoDigitWords(c)} oh ${ONES[r]}`; return `${twoDigitWords(c)} ${twoDigitWords(r)}`; } // A standalone four-digit 19xx/20xx, optionally a decade's "s". Not part of a // longer number, an amount, a decimal, a time, a date written with slashes or // a percentage: those are left to the engine. const YEAR = /(? { const year = Number(digits); if (s) return year % 10 === 0 ? yearWords(year, true) : whole; return yearWords(year); }); } // --- numbers (the tuned Orpheus round's readers, ported) ---------------------- const SCALES: [number, string][] = [ [1e12, "trillion"], [1e9, "billion"], [1e6, "million"], [1e3, "thousand"], ]; const ORD_IRREG: Record = { one: "first", two: "second", three: "third", five: "fifth", eight: "eighth", nine: "ninth", twelve: "twelfth", }; /** 3812 → "three thousand eight hundred twelve" (US style, no "and"). */ export function sayInt(n: number): string { if (n < 0) return `minus ${sayInt(-n)}`; if (n < 100) return twoDigitWords(n); if (n < 1000) { const h = Math.floor(n / 100); const r = n % 100; return `${ONES[h]} hundred${r ? ` ${sayInt(r)}` : ""}`; } for (const [v, name] of SCALES) { if (n >= v) { const q = Math.floor(n / v); const r = n - q * v; return `${sayInt(q)} ${name}${r ? ` ${sayInt(r)}` : ""}`; } } return String(n); } /** 21 → "twenty-first", 103 → "one hundred third", 40 → "fortieth". */ export function sayOrdinal(n: number): string { const words = sayInt(n); const sp = words.lastIndexOf(" "); const head = words.slice(0, sp + 1); const last = words.slice(sp + 1); const hy = last.lastIndexOf("-"); const pre = last.slice(0, hy + 1); let tail = last.slice(hy + 1); if (ORD_IRREG[tail]) tail = ORD_IRREG[tail]; else if (tail.endsWith("y")) tail = `${tail.slice(0, -1)}ieth`; else tail += "th"; return head + pre + tail; } /** "3.5" → "three point five", "1,200.75" → "one thousand two hundred point seven five". */ export function sayDecimal(s: string): string { const [whole, frac] = s.replace(/,/g, "").split("."); const out = sayInt(Number(whole || "0")); return frac ? `${out} point ${[...frac].map((d) => ONES[Number(d)]).join(" ")}` : out; } function pluralDecade(words: string): string { const sp = words.lastIndexOf(" "); const last = words.slice(sp + 1); return words.slice(0, sp + 1) + (last.endsWith("y") ? `${last.slice(0, -1)}ies` : `${last}s`); } const CURRENCY: Record = { $: ["dollar", "dollars", "cent", "cents"], "£": ["pound", "pounds", "penny", "pence"], "€": ["euro", "euros", "cent", "cents"], }; function money(sym: string, num: string, scale: string | undefined): string { const [one, many, sub1, subn] = CURRENCY[sym]; if (scale) return `${sayDecimal(num)} ${scale.toLowerCase()} ${many}`; const [whole, cents] = num.replace(/,/g, "").split("."); const w = Number(whole || "0"); let out = `${sayInt(w)} ${w === 1 ? one : many}`; if (cents) { const c = Number(cents.padEnd(2, "0").slice(0, 2)); if (c) out += ` and ${sayInt(c)} ${c === 1 ? sub1 : subn}`; } return out; } function speakDomain(host: string): string { return host .toLowerCase() .replace(/^www\./, "") .split(".") .filter(Boolean) .map((p) => p.replace(/-/g, " ")) .join(" dot "); } function clock(h: number, mm: number): string { if (mm === 0) return `${sayInt(h)} o'clock`; return `${sayInt(h)} ${mm < 10 ? `oh ${ONES[mm]}` : sayInt(mm)}`; } // A four-digit number followed by one of these is a count, not a year ("1950 people"). const COUNT_NOUNS = [ "people", "viewers", "views", "subscribers", "followers", "videos", "streams", "clips", "comments", "times", "dollars", "users", "members", "posts", "hours", "minutes", "seconds", "words", "messages", "likes", "votes", "copies", "files", "miles", "pounds", "units", "donations", "watchers", ]; const GUARDED_YEAR = new RegExp( String.raw`(? string); const ABBREV: [RegExp, Rep][] = [ [/\bDr\.(?=\s+[A-Z])/g, "Doctor"], [/\bMr\./g, "Mister"], [/\bMrs\./g, "Missus"], [/\bMs\./g, "Miz"], [/\bJr\./g, "Junior"], [/\bSr\./g, "Senior"], [/\bSt\.(?=\s+[A-Z])/g, "Saint"], [/\bProf\./g, "Professor"], [/\b[Vv]s\.?(?=\s)/g, "versus"], [/\be\.g\.,?/g, "for example,"], [/\bi\.e\.,?/g, "that is,"], [/\betc\.(?=\s+[a-z])/g, "et cetera"], [/\betc\./g, "et cetera."], [/\bapprox\./g, "approximately"], [/\b[Nn]o\.\s*(?=\d)/g, "number "], [/#(?=\d)/g, "number "], [/\b([ap])\.m\./g, (_m, a) => `${a.toUpperCase()} M`], [/\b([AP])M\b/g, "$1 M"], [/\bU\.S\.A?\.?/g, (m) => [...m].filter((c) => /[A-Za-z]/.test(c)).join(" ")], [/\bU\.K\./g, "U K"], ]; function sub(t: string, re: RegExp, rep: Rep): string { return typeof rep === "string" ? t.replace(re, rep) : t.replace(re, rep as (...a: string[]) => string); } // One run of text holding no expressive tag, to its spoken form. function spokenPlain(input: string, years: "plain" | "guarded"): string { let t = input .replace(/[’‘]/g, "'") .replace(/[“”]/g, '"') .replace(/…/g, "...") .replace(/[  ]/g, " "); // URLs → the spoken host only ("example dot com"); paths and queries dropped. t = t.replace(/\bhttps?:\/\/([^\s/]+)\S*/g, (_m, host: string) => speakDomain(host)); t = t.replace(/\bwww\.([a-z0-9-]+(?:\.[a-z0-9-]+)+)\S*/gi, (_m, host: string) => speakDomain(host)); t = t.replace( /\b([a-z0-9-]+(?:\.[a-z0-9-]+)*\.(?:com|org|net|dev|io|tv|gg|co|uk|me|app))\b(\/\S*)?/gi, (_m, host: string) => speakDomain(host), ); // @handles and #hashtags (underscores read as spaces). t = t.replace(/(? `at ${h.replace(/_/g, " ")}`); t = t.replace(/(? `hashtag ${h.replace(/_/g, " ")}`); for (const [re, rep] of ABBREV) t = sub(t, re, rep); t = t.replace(/\s&\s/g, " and "); // A range between numbers is "to"; an em dash (or --, or a spaced en dash) is a pause. t = t.replace(/(?<=\d)\s*[–—-]\s*(?=\d)/g, " to "); t = t.replace(/\s*(?:—|--|\s–\s)\s*/g, ", "); // Money, percent, ordinals, clock times. t = t.replace( /([$£€])((?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d+)?)(?:\s*(million|billion|trillion|thousand)\b)?/gi, (_m, sym: string, num: string, scale?: string) => money(sym, num, scale), ); t = t.replace(/((?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d+)?)\s?%/g, (_m, n: string) => `${sayDecimal(n)} percent`); t = t.replace(/\b(\d+)(?:st|nd|rd|th)\b/g, (_m, n: string) => sayOrdinal(Number(n))); t = t.replace(/\b(\d{1,2}):(\d{2})\b/g, (_m, h: string, mm: string) => clock(Number(h), Number(mm))); // Decades: 1990s → nineteen nineties, '90s → nineties. t = t.replace(/\b(19|20)(\d)0s\b/g, (_m, c: string, d: string) => pluralDecade(yearWords(Number(`${c}${d}0`)))); t = t.replace(/'(\d)0s\b/g, (_m, d: string) => pluralDecade(sayInt(Number(d) * 10))); // Years 1900-2099. t = years === "guarded" ? t.replace(GUARDED_YEAR, (_m, y: string) => yearWords(Number(y))) : speakYears(t); // Grouped numbers (3,812), decimals (3.5), plain integers. t = t.replace(/\b\d{1,3}(?:,\d{3})+(?:\.\d+)?\b/g, (m) => sayDecimal(m)); t = t.replace(/\b\d+\.\d+\b/g, (m) => sayDecimal(m)); t = t.replace(/\b\d{1,15}\b/g, (m) => sayInt(Number(m))); // Tidy. t = t.replace(/\s+([,.;:!?])/g, "$1"); t = t.replace(/,\s*,/g, ","); t = t.replace(/[ \t]+/g, " "); return t; } // --- the normalizer ---------------------------------------------------------- export type TtsNormalizeOptions = { // "strip" for an engine that cannot perform the expressive tags; "keep" for // one that does (passed through as written). tags: "strip" | "keep"; // "guarded": a year followed by a count noun is a number (Orpheus, the // tuned round's rule). "plain": every 1900-2099 is a year (Kokoro's, T1). years: "plain" | "guarded"; // "keep": paragraphs (blank lines) stay "\n\n" for a chunking engine; // "join": one line. paragraphs: "keep" | "join"; }; const EXPRESSIVE = new RegExp(`(<(?:${TTS_EXPRESSIVE_TAGS.join("|")})>)`); /** The pre-pass: per paragraph, the spoken form of the text between the tags, then the tags (see the header). */ export function normalizeTtsText(text: string, opts: TtsNormalizeOptions): string { const paras = text .normalize("NFC") .trim() .split(/\n\s*\n/) .filter((p) => p.trim()); const out: string[] = []; for (const p of paras) { const parts = p.replace(/\n/g, " ").split(EXPRESSIVE); let s = parts.map((x) => (EXPRESSIVE.test(x) && /^<[^<>]*>$/.test(x) ? x : spokenPlain(x, opts.years))).join(""); s = s.replace(/\s+/g, " ").trim(); if (opts.tags === "strip") s = stripTtsTags(s); if (s) out.push(collapseTtsWhitespace(s)); } return out.join(opts.paragraphs === "keep" ? "\n\n" : " "); }