Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit ac147eda95f61ed777f1fced4f16591bb9ad0d4a
parent 7747d3cfa66b2d9480f29e6388de53a3afc82877
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sun, 11 Oct 2026 12:18:52 -0400

tts: the spoken-form normalizer and the chunker, from the tuned Orpheus round

common/lib/ttsText.ts now carries the tuned round's normalize(): URLs to
their spoken host, @handles and #hashtags, abbreviations, em dashes, money,
percentages, ordinals, clock times, decades, years, grouped numbers,
decimals and integers, with its 17 self-tests as unit tests. Options per
engine: tags kept or stripped, the guarded year rule ("1950 people" is a
count) or T1's plain one (Kokoro keeps it), paragraphs kept or joined.

common/lib/ttsChunk.ts is its chunker (1-3 sentences, at most 250
characters, balanced, clause-boundary splits, the pause after each chunk by
how it ended) and the per-chunk token budget, held equal to the pipeline's
own output on the bake-off lines.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
Mcommon/lib/ttsApps.ts | 4++--
Acommon/lib/ttsChunk.test.ts | 213+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/ttsChunk.ts | 130+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/ttsText.test.ts | 61++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----
Mcommon/lib/ttsText.ts | 251+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------
5 files changed, 628 insertions(+), 31 deletions(-)

diff --git a/common/lib/ttsApps.ts b/common/lib/ttsApps.ts @@ -143,7 +143,7 @@ const kokoro: TtsEngine = { voices: KOKORO_VOICES, defaultVoice: "af_heart", speedRange: [0.5, 2], - normalize: (text) => normalizeTtsText(text, { tags: "strip", years: true }), + normalize: (text) => normalizeTtsText(text, { tags: "strip", years: "plain", paragraphs: "join" }), setup: { kind: "python-venv", python: "3.12", @@ -181,7 +181,7 @@ const espeakNg: TtsEngine = { voices: ["en-us", "en-gb", "en"], defaultVoice: "en-us", speedRange: [0.5, 2], - normalize: (text) => normalizeTtsText(text, { tags: "strip", years: true }), + normalize: (text) => normalizeTtsText(text, { tags: "strip", years: "plain", paragraphs: "join" }), setup: { kind: "system", bin: "espeakNgBin", hint: "install espeak-ng from the system's packages" }, build: ({ textFile, outWav, voice, speed, bins }) => ({ argv: [ diff --git a/common/lib/ttsChunk.test.ts b/common/lib/ttsChunk.test.ts @@ -0,0 +1,213 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { CHUNK_MAX_CHARS, chunkTtsText, nPredictFor, splitLong, splitSentences, wordsIn } from "./ttsChunk"; +import { normalizeTtsText } from "./ttsText"; + +// Run with: +// pnpm --filter yt-dlp-transcript-common exec tsx --test lib/ttsChunk.test.ts +// +// The chunker against the tuned round's own (run_orpheus2.py chunk(normalize())): +// the bake-off lines (synthetic text written for the bake-off) and the +// chunks, endings, pauses and token budgets that pipeline produced for them, +// pasted here as data. + +const ORPHEUS = { tags: "keep", years: "guarded", paragraphs: "keep" } as const; +const LINES: Record<string, string> = { + "card": "Two weeks later, the same channel posted the opposite claim — and deleted the first video.", + "numbers": "On March 14th, 2024, he said fifteen thousand people watched; the stream's own counter showed 3,812.", + "quote": "In his words: \"I never said that.\" The clip below is from forty minutes earlier.", + "podcast": "Welcome back to the archive. Every video we cover here has a transcript on file, saved the day it was published, so when a claim changes we can show exactly what was said before. That matters, because memories drift and old uploads quietly disappear. Each clip you hear comes with a citation: the channel, the date, and the minute it was spoken, so you can check it yourself. Nothing is paraphrased when the original words are available, and if you are new here, every source we use is linked in the description. Today, we follow one story across three years of streams, and let the record speak for itself.", + "podcast-tagged": "Welcome back to the archive. <chuckle> Every video we cover here has a transcript on file, saved the day it was published, so when a claim changes we can show exactly what was said before. That matters, because memories drift and old uploads quietly disappear. <sigh> Each clip you hear comes with a citation: the channel, the date, and the minute it was spoken, so you can check it yourself. Nothing is paraphrased when the original words are available, and if you are new here, every source we use is linked in the description. Today, we follow one story across three years of streams, and let the record speak for itself.", + "quote-tagged": "In his words: \"I never said that.\" <chuckle> The clip below is from forty minutes earlier.", + "story": "Nobody was supposed to find it. <sigh> The video had been gone for three years. Deleted on a quiet Tuesday night... without a single word.\n\nThe channel moved on. The comments moved on. And honestly? So did I.\n\nThen, one rainy afternoon, I was clearing out an old hard drive. Folders inside folders. Files called final, and final two, and final-final. <chuckle> You know the kind.\n\nAnd then... there it was. One file. No title. Just a date.\n\nI almost deleted it. Why wouldn't I? But something made me press play.\n\n<gasp> It was the video. The whole thing. Every word, every pause, exactly the way it was said the first time.\n\nHere's the thing about the internet. It feels like it forgets. It doesn't. Not always. Somewhere, somebody hit save.\n\nSo the next time someone tells you it never happened... ask them one simple question. Are you sure?", + "story-card": "Three years ago, it vanished without a word. Everyone said it was gone for good... They were wrong.", + "story-plain": "An archivist found a copy of a video that had been deleted three years earlier. The video was removed on a Tuesday night without explanation, and the channel and its audience moved on. The copy was found while the archivist was clearing out an old hard drive that contained many nested folders, with files named final, final two, and final-final. One untitled file was labelled only with a date. The archivist considered deleting it, but played it first. It was the deleted video, complete, with every statement intact as it was originally recorded. This shows that online content is not always permanently lost, because copies are sometimes saved. Claims that something never happened can therefore be checked against preserved records." +}; +const EXPECTED: Record<string, { text: string; ends: string; pauseAfter: number }[]> = { + "card": [ + { + "text": "Two weeks later, the same channel posted the opposite claim, and deleted the first video.", + "ends": "end", + "pauseAfter": 0.0 + } + ], + "numbers": [ + { + "text": "On March fourteenth, twenty twenty-four, he said fifteen thousand people watched; the stream's own counter showed three thousand eight hundred twelve.", + "ends": "end", + "pauseAfter": 0.0 + } + ], + "quote": [ + { + "text": "In his words: \"I never said that.\" The clip below is from forty minutes earlier.", + "ends": "end", + "pauseAfter": 0.0 + } + ], + "podcast": [ + { + "text": "Welcome back to the archive. Every video we cover here has a transcript on file, saved the day it was published, so when a claim changes we can show exactly what was said before.", + "ends": "sentence", + "pauseAfter": 0.3 + }, + { + "text": "That matters, because memories drift and old uploads quietly disappear. Each clip you hear comes with a citation: the channel, the date, and the minute it was spoken, so you can check it yourself.", + "ends": "sentence", + "pauseAfter": 0.3 + }, + { + "text": "Nothing is paraphrased when the original words are available, and if you are new here, every source we use is linked in the description. Today, we follow one story across three years of streams, and let the record speak for itself.", + "ends": "end", + "pauseAfter": 0.0 + } + ], + "podcast-tagged": [ + { + "text": "Welcome back to the archive. <chuckle> Every video we cover here has a transcript on file, saved the day it was published, so when a claim changes we can show exactly what was said before.", + "ends": "sentence", + "pauseAfter": 0.3 + }, + { + "text": "That matters, because memories drift and old uploads quietly disappear. <sigh> Each clip you hear comes with a citation: the channel, the date, and the minute it was spoken, so you can check it yourself.", + "ends": "sentence", + "pauseAfter": 0.3 + }, + { + "text": "Nothing is paraphrased when the original words are available, and if you are new here, every source we use is linked in the description. Today, we follow one story across three years of streams, and let the record speak for itself.", + "ends": "end", + "pauseAfter": 0.0 + } + ], + "quote-tagged": [ + { + "text": "In his words: \"I never said that.\" <chuckle> The clip below is from forty minutes earlier.", + "ends": "end", + "pauseAfter": 0.0 + } + ], + "story": [ + { + "text": "Nobody was supposed to find it. <sigh> The video had been gone for three years. Deleted on a quiet Tuesday night... without a single word.", + "ends": "paragraph", + "pauseAfter": 0.6 + }, + { + "text": "The channel moved on. The comments moved on. And honestly? So did I.", + "ends": "paragraph", + "pauseAfter": 0.6 + }, + { + "text": "Then, one rainy afternoon, I was clearing out an old hard drive. Folders inside folders. Files called final, and final two, and final-final. <chuckle> You know the kind.", + "ends": "paragraph", + "pauseAfter": 0.6 + }, + { + "text": "And then... there it was. One file. No title. Just a date.", + "ends": "paragraph", + "pauseAfter": 0.6 + }, + { + "text": "I almost deleted it. Why wouldn't I? But something made me press play.", + "ends": "paragraph", + "pauseAfter": 0.6 + }, + { + "text": "<gasp> It was the video. The whole thing. Every word, every pause, exactly the way it was said the first time.", + "ends": "paragraph", + "pauseAfter": 0.6 + }, + { + "text": "Here's the thing about the internet. It feels like it forgets. It doesn't. Not always. Somewhere, somebody hit save.", + "ends": "paragraph", + "pauseAfter": 0.6 + }, + { + "text": "So the next time someone tells you it never happened... ask them one simple question. Are you sure?", + "ends": "end", + "pauseAfter": 0.0 + } + ], + "story-card": [ + { + "text": "Three years ago, it vanished without a word. Everyone said it was gone for good... They were wrong.", + "ends": "end", + "pauseAfter": 0.0 + } + ], + "story-plain": [ + { + "text": "An archivist found a copy of a video that had been deleted three years earlier. The video was removed on a Tuesday night without explanation, and the channel and its audience moved on.", + "ends": "sentence", + "pauseAfter": 0.3 + }, + { + "text": "The copy was found while the archivist was clearing out an old hard drive that contained many nested folders, with files named final, final two, and final-final.", + "ends": "sentence", + "pauseAfter": 0.3 + }, + { + "text": "One untitled file was labelled only with a date. The archivist considered deleting it, but played it first. It was the deleted video, complete, with every statement intact as it was originally recorded.", + "ends": "sentence", + "pauseAfter": 0.3 + }, + { + "text": "This shows that online content is not always permanently lost, because copies are sometimes saved. Claims that something never happened can therefore be checked against preserved records.", + "ends": "end", + "pauseAfter": 0.0 + } + ] +}; +const N_PREDICT: Record<string, number> = { + "Nobody was supposed to find it. <sigh> The video had been gone for three years. Deleted on a quiet Tuesday night... without a single word.": 1498, + "The channel moved on. The comments moved on. And honestly? So did I.": 763, + "Then, one rainy afternoon, I was clearing out an old hard drive. Folders inside folders. Files called final, and final two, and final-final. <chuckle> You know the kind.": 1673, + "And then... there it was. One file. No title. Just a date.": 749, + "I almost deleted it. Why wouldn't I? But something made me press play.": 763, + "<gasp> It was the video. The whole thing. Every word, every pause, exactly the way it was said the first time.": 1253, + "Here's the thing about the internet. It feels like it forgets. It doesn't. Not always. Somewhere, somebody hit save.": 1078, + "So the next time someone tells you it never happened... ask them one simple question. Are you sure?": 1064 +}; + +test("every bake-off line chunks exactly as the tuned pipeline did", () => { + for (const [key, text] of Object.entries(LINES)) { + assert.deepEqual(chunkTtsText(normalizeTtsText(text, ORPHEUS)), EXPECTED[key], key); + } +}); + +test("the pipeline's own chunker assertions", () => { + const pod = chunkTtsText(normalizeTtsText(LINES.podcast, ORPHEUS)); + assert.ok(pod.every((c) => c.text.length <= CHUNK_MAX_CHARS)); + assert.ok(pod.length >= 2 && pod.length <= 4); + assert.equal(pod[pod.length - 1].ends, "end"); + assert.ok(pod.slice(0, -1).every((c) => c.ends === "sentence")); + const q = chunkTtsText(normalizeTtsText(LINES["quote-tagged"], ORPHEUS)); + assert.equal(q.length, 1); + assert.ok(q[0].text.includes("<chuckle>")); + const st = chunkTtsText(normalizeTtsText(LINES.story, ORPHEUS)); + assert.equal(st.filter((c) => c.ends === "paragraph").length, LINES.story.split("\n\n").length - 1); + assert.ok(st.map((c) => c.text).join("").includes("<gasp>")); + assert.ok(st.every((c) => c.pauseAfter === { sentence: 0.3, clause: 0.15, paragraph: 0.6, end: 0 }[c.ends])); +}); + +test("a long sentence is cut at clause boundaries, never mid-phrase", () => { + const long = "word ".repeat(20) + "and this keeps going; " + "more words here, ".repeat(12) + "but then it ends."; + const parts = splitLong(long); + assert.deepEqual(parts, ["word word word word word word word word word word word word word word word word word word word word and this keeps going;", "more words here, more words here, more words here, more words here, more words here, more words here, more words here, more words here, more words here, more words here, more words here, more words here, but then it ends."]); + assert.ok(parts.every((p) => p.length <= CHUNK_MAX_CHARS)); +}); + +test("sentences: a reaction tag joins the sentence before it; an ellipsis continues one", () => { + assert.deepEqual(splitSentences("It was gone. <sigh> Then... it was back. And then... there it was."), [ + "It was gone. <sigh>", + "Then... it was back.", + "And then... there it was.", + ]); + assert.deepEqual(splitSentences("Deleted on a Tuesday night... without a word."), ["Deleted on a Tuesday night... without a word."]); + assert.equal(wordsIn("It's <laugh> one file."), 3); +}); + +test("the token budget follows the words, tags and beats", () => { + for (const [text, n] of Object.entries(N_PREDICT)) assert.equal(nPredictFor(text), n, text); + assert.equal(nPredictFor("x") % 7, 0); +}); diff --git a/common/lib/ttsChunk.ts b/common/lib/ttsChunk.ts @@ -0,0 +1,130 @@ +// 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–3 +// sentences, at most 250 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.30 s, a clause 0.15 s, a paragraph 0.60 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"; + +export const CHUNK_MAX_CHARS = 250; +export const CHUNK_MAX_SENTENCES = 3; +export const CHUNK_PAUSE = { sentence: 0.3, clause: 0.15, paragraph: 0.6, end: 0 } as const; +export type ChunkEnding = keyof typeof CHUNK_PAUSE; + +export type TtsChunk = { text: string; ends: ChunkEnding; pauseAfter: number }; + +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[]): 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 > CHUNK_MAX_CHARS || w > CHUNK_MAX_SENTENCES)) 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): 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)); + const packed = pack(units); + 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: CHUNK_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 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. + */ +export function nPredictFor(text: string): number { + const tags = (text.match(TAG_G) ?? []).length; + const ellipses = text.split("...").length - 1; + const expS = 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; +} diff --git a/common/lib/ttsText.test.ts b/common/lib/ttsText.test.ts @@ -4,6 +4,9 @@ import { TTS_EXPRESSIVE_TAGS, collapseTtsWhitespace, normalizeTtsText, + sayDecimal, + sayInt, + sayOrdinal, speakYears, stripTtsTags, twoDigitWords, @@ -117,16 +120,64 @@ test("whitespace collapses, so a re-wrapped paragraph is the same text", () => { assert.equal(collapseTtsWhitespace(" a\n\n b\t c "), "a b c"); assert.equal(collapseTtsWhitespace("a , b ."), "a, b."); assert.equal( - normalizeTtsText("In 2024,\n the <laugh> show\nended .", { tags: "strip", years: true }), + normalizeTtsText("In 2024,\n the <laugh> show\nended .", { tags: "strip", years: "plain", paragraphs: "join" }), "In twenty twenty-four, the show ended.", ); assert.equal( - normalizeTtsText("In 2024 <laugh> it ended.", { tags: "keep", years: false }), - "In 2024 <laugh> it ended.", + normalizeTtsText("In 2024 <laugh> it ended.", { tags: "keep", years: "guarded", paragraphs: "keep" }), + "In twenty twenty-four <laugh> it ended.", ); // NFC: a decomposed accent is the same text as a composed one. assert.equal( - normalizeTtsText("café", { tags: "strip", years: true }), - normalizeTtsText("café", { tags: "strip", years: true }), + normalizeTtsText("café", { tags: "strip", years: "plain", paragraphs: "join" }), + normalizeTtsText("café", { tags: "strip", years: "plain", paragraphs: "join" }), ); }); + +// The tuned Orpheus round's 17 self-tests (run_orpheus2.py selftest), ported +// as they stand: tags kept, the guarded year rule, paragraphs kept. +const ORPHEUS = { tags: "keep", years: "guarded", paragraphs: "keep" } as const; +const SELFTEST: [string, string][] = [ + ["On March 14th, 2024, he said", "On March fourteenth, twenty twenty-four, he said"], + ["the counter showed 3,812.", "the counter showed three thousand eight hundred twelve."], + ["in 2005 and 1999 and 1905 and 1900 and 2010", "in two thousand five and nineteen ninety-nine and nineteen oh five and nineteen hundred and twenty ten"], + ["1950 people", "one thousand nine hundred fifty people"], + ["the 1990s and the \u201990s", "the nineteen nineties and the nineties"], + ["21st, 22nd, 103rd, 12th, 40th", "twenty-first, twenty-second, one hundred third, twelfth, fortieth"], + ["up 45% or 3.5%", "up forty-five percent or three point five percent"], + ["$12.50, $1, $3.5 million, $1,200", "twelve dollars and fifty cents, one dollar, three point five million dollars, one thousand two hundred dollars"], + ["Dr. Smith vs. Mr. Jones, e.g. today", "Doctor Smith versus Mister Jones, for example, today"], + ["the claim \u2014 and the video", "the claim, and the video"], + ["from 2019\u20132021", "from twenty nineteen to twenty twenty-one"], + ["see https://example.pages.dev/c/x?y=1 now", "see example dot pages dot dev now"], + ["ask @some_handle about #TrueCrime", "ask at some handle about hashtag TrueCrime"], + ["at 3:45 and 10:00 and 7:05", "at three forty-five and ten o'clock and seven oh five"], + ["He laughed. <laugh> 2024 was <sigh> long.", "He laughed. <laugh> twenty twenty-four was <sigh> long."], + ["It\u2019s 3.14 and 0.5", "It's three point one four and zero point five"], + ["No. 5 & #1", "number five and number one"], +]; + +test("the spoken-form normalizer passes the tuned round's 17 self-tests", () => { + assert.equal(SELFTEST.length, 17); + for (const [src, want] of SELFTEST) assert.equal(normalizeTtsText(src, ORPHEUS), want, src); +}); + +test("numbers: cardinals, ordinals, decimals", () => { + assert.equal(sayInt(0), "zero"); + assert.equal(sayInt(115), "one hundred fifteen"); + assert.equal(sayInt(1_000_001), "one million one"); + assert.equal(sayInt(-3), "minus three"); + assert.equal(sayOrdinal(1), "first"); + assert.equal(sayOrdinal(30), "thirtieth"); + assert.equal(sayOrdinal(1002), "one thousand second"); + assert.equal(sayDecimal("1,200.75"), "one thousand two hundred point seven five"); +}); + +test("Kokoro keeps T1's year rule; Orpheus guards counts; paragraphs kept or joined", () => { + const kokoro = { tags: "strip", years: "plain", paragraphs: "join" } as const; + assert.equal(normalizeTtsText("1950 people came.", kokoro), "nineteen fifty people came."); + assert.equal(normalizeTtsText("1950 people came.", ORPHEUS), "one thousand nine hundred fifty people came."); + assert.equal(normalizeTtsText("It was 42 <sigh> episodes.", kokoro), "It was forty-two episodes."); + assert.equal(normalizeTtsText("One.\n\n\nTwo <gasp> three.\nFour.", ORPHEUS), "One.\n\nTwo <gasp> three. Four."); + assert.equal(normalizeTtsText("One.\n\nTwo <gasp> three.", kokoro), "One. Two three."); +}); diff --git a/common/lib/ttsText.ts b/common/lib/ttsText.ts @@ -1,24 +1,30 @@ -// THE TEXT PRE-PASS EVERY SPEECH ENGINE'S INPUT GOES THROUGH (release 25 T1). +// 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, in order: +// its own `normalize` hook. What it does: // // 1. Expressive tags. Narration may carry the tag set below (`<laugh>`, -// `<sigh>`, ...) for an engine that performs them. An engine that cannot -// (Kokoro, espeak-ng) has them STRIPPED here, 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. Years. A four-digit year 1900-2099 is written out the way it is said -// ("twenty twenty-four", "nineteen ninety-nine", "two thousand five", the -// decade plural "the nineteen nineties") — Kokoro reads "2024" as "two -// thousand twenty-four". Every other number is left to the engine. A count -// that happens to be 1900-2099 ("2024 people") is read as a year too: the -// price of a pre-pass that has no grammar. -// 3. Whitespace. Every run of whitespace, line breaks included, becomes one -// space, a space left before punctuation by a stripped tag goes, and the -// ends are trimmed — so the cache key (controller/ttsFile.ts) does not -// change with a re-wrapped paragraph. +// `<sigh>`, ...). 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. @@ -144,20 +150,217 @@ export function speakYears(text: string): string { }); } +// --- numbers (the tuned Orpheus round's readers, ported) ---------------------- + +const SCALES: [number, string][] = [ + [1e12, "trillion"], + [1e9, "billion"], + [1e6, "million"], + [1e3, "thousand"], +]; +const ORD_IRREG: Record<string, string> = { + 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<string, [string, string, string, string]> = { + $: ["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`(?<![\d,.])\b(19\d\d|20\d\d)\b(?!\d|,\d|\.\d)(?!\s+(?:${COUNT_NOUNS.join("|")})\b)`, + "g", +); + +type Rep = string | ((...m: string[]) => 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(/(?<![\w@])@([A-Za-z0-9_]+)/g, (_m, h: string) => `at ${h.replace(/_/g, " ")}`); + t = t.replace(/(?<![\w#])#([A-Za-z][A-Za-z0-9_]*)/g, (_m, h: string) => `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"; - // Write years out as they are said. - years: boolean; + // "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"; }; -/** The pre-pass: tags, then years, then whitespace (see the header). */ +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 { - let out = text.normalize("NFC"); - if (opts.tags === "strip") out = stripTtsTags(out); - if (opts.years) out = speakYears(out); - return collapseTtsWhitespace(out); + 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" : " "); }