File size: 7,540 Bytes
4a58e48 daa9f5e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 | // Pure text helpers: cleanup, sentence splitting, language guess.
// No DOM, no browser APIs — unit-tested in tests/unit.
const MAX_CHUNK = 170; // characters per spoken chunk: short chunks start playing sooner (≈10 s of audio max)
/** Normalise whitespace, join hyphenated line breaks, keep paragraph breaks. */
export function cleanText(raw: string): string {
return raw
.replace(/\r\n?/g, '\n')
.replace(/\u00ad/g, '') // soft hyphen
.replace(/(\p{L})-\n(\p{Ll})/gu, '$1$2') // hyphen-\nated -> hyphenated
.replace(/[ \t\f\v\u00a0]+/g, ' ')
.replace(/ *\n */g, '\n')
.replace(/\n{3,}/g, '\n\n')
.trim();
}
// words after which a period does not end a sentence
const ABBREV = new Set(
'mr mrs ms dr prof sr jr st vs etc e.g i.e a.m p.m u.s u.k vol fig ch pp cf approx dept est sra dra srta mme mlle m av gen col lt sgt rev'.split(' '),
);
/** Split text into speakable chunks (sentences, long ones cut at commas/spaces). */
export function splitSentences(text: string): string[] {
const out: string[] = [];
const paragraphs = text.split(/\n{2,}|\n(?=\s*[-•*]\s)/);
for (const para of paragraphs) {
const p = para.replace(/\s*\n\s*/g, ' ').trim();
if (!p) continue;
// candidate ends: terminal punctuation (+ closing quotes/brackets) followed by whitespace
const re = /[.!?…]+["'”’»)\]]*(?=\s)|[。!?]+[」』”’))]*/g;
let start = 0;
let m: RegExpExecArray | null;
while ((m = re.exec(p))) {
const end = m.index + m[0].length;
const after = p.slice(end).trimStart();
const next = after[0] || '';
const before = p.slice(start, m.index);
const lastWord = (before.match(/(\S+)$/)?.[1] || '').replace(/^["'“‘«(\[]+/, '');
const punct = m[0];
if (/^[。!?]/.test(punct)) {
// CJK: full stops end sentences with no space after them
pushChunk(out, p.slice(start, end).trim());
start = end;
continue;
}
if (punct.startsWith('.') && !punct.startsWith('...')) {
if (ABBREV.has(lastWord.toLowerCase().replace(/\.$/, ''))) continue; // Dr. Smith, 10 a.m. today
// "No. 5" / "no. 12"
if (/^no$/i.test(lastWord) && /^\d/.test(next)) continue;
// initials (J. R. R. Tolkien) but not a real end like "Plan B. Then rain."
if (/^\p{Lu}$/u.test(lastWord)) {
const prevWord = before.trim().split(/\s+/).slice(-2, -1)[0] || '';
const nextWord = after.split(/\s+/)[0] || '';
const isInitial = (w: string) => /^\p{Lu}\.$/u.test(w);
if (!prevWord || isInitial(prevWord) || isInitial(nextWord)) continue;
}
if (/^(\p{L}\.)+\p{L}$/u.test(lastWord)) continue; // U.S. / e.g.
}
// the next sentence must start like a sentence: capital, digit, quote or dash
if (next && !/[\p{Lu}\p{N}"'“‘«(\[¿¡—–-]/u.test(next) && !/^\p{Lo}/u.test(next)) continue;
pushChunk(out, p.slice(start, end).trim());
start = end;
}
const rest = p.slice(start).trim();
if (rest) pushChunk(out, rest);
}
return out.filter((s) => /[\p{L}\p{N}]/u.test(s));
}
function pushChunk(out: string[], s: string) {
if (s.length <= MAX_CHUNK) {
out.push(s);
return;
}
// cut at the last comma/semicolon/colon/dash before the limit, else last space
let rest = s;
while (rest.length > MAX_CHUNK) {
const window = rest.slice(0, MAX_CHUNK);
let cut = Math.max(window.lastIndexOf(', '), window.lastIndexOf('; '), window.lastIndexOf(': '), window.lastIndexOf(' — '), window.lastIndexOf('、'), window.lastIndexOf(','));
if (cut < MAX_CHUNK * 0.4) cut = window.lastIndexOf(' ');
if (cut <= 0) cut = MAX_CHUNK;
out.push(rest.slice(0, cut + 1).trim());
rest = rest.slice(cut + 1).trim();
}
if (rest) out.push(rest);
}
const STOP: Record<string, string[]> = {
en: ['the', 'and', 'of', 'to', 'is', 'was', 'that', 'with', 'for', 'it', 'he', 'she', 'you'],
pt: ['de', 'que', 'não', 'uma', 'com', 'para', 'os', 'como', 'mas', 'ele', 'ela', 'você', 'são'],
fr: ['le', 'les', 'des', 'est', 'une', 'pas', 'que', 'dans', 'pour', 'qui', 'avec', 'sur', 'nous'],
es: ['el', 'los', 'que', 'una', 'por', 'con', 'para', 'pero', 'como', 'del', 'las', 'está', 'muy'],
de: ['der', 'die', 'und', 'nicht', 'ist', 'das', 'ein', 'ich', 'mit', 'sie', 'auf', 'den', 'auch'],
it: ['il', 'che', 'non', 'per', 'una', 'sono', 'della', 'con', 'gli', 'questo', 'anche', 'come', 'più'],
};
const SCRIPTS: [RegExp, string][] = [
[/\p{Script=Cyrillic}/gu, 'ru'],
[/\p{Script=Greek}/gu, 'el'],
[/\p{Script=Arabic}/gu, 'ar'],
[/\p{Script=Hebrew}/gu, 'he'],
[/\p{Script=Hangul}/gu, 'ko'],
[/[\p{Script=Hiragana}\p{Script=Katakana}]/gu, 'ja'],
[/\p{Script=Han}/gu, 'zh'],
[/\p{Script=Devanagari}/gu, 'hi'],
[/\p{Script=Thai}/gu, 'th'],
];
/** Rough language guess: writing system first, then stopwords. Returns ISO 639-1, or 'und' when unsure. */
export function guessLanguage(text: string): string {
const sample = text.slice(0, 20000);
const letters = (sample.match(/\p{L}/gu) || []).length;
if (!letters) return 'und';
for (const [re, lang] of SCRIPTS) {
const n = (sample.match(re) || []).length;
// Japanese mixes kana with Han: any real share of kana means Japanese
if (lang === 'ja' ? n > letters * 0.05 : n > letters * 0.3) return lang;
}
const words = sample.toLowerCase().match(/\p{L}+/gu) || [];
if (words.length < 20) return words.length ? 'en' : 'und';
const counts: Record<string, number> = {};
for (const w of words) counts[w] = (counts[w] || 0) + 1;
let best = 'und';
let bestScore = 0;
for (const [lang, list] of Object.entries(STOP)) {
const score = list.reduce((n, w) => n + (counts[w] || 0), 0);
if (score > bestScore) {
best = lang;
bestScore = score;
}
}
return bestScore >= words.length * 0.02 ? best : 'und';
}
/** Approximate listening time for a text at 1x (≈ 155 words per minute). */
export function minutesFor(text: string): number {
const words = (text.match(/\S+/g) || []).length;
return Math.max(1, Math.round(words / 155));
}
export function formatDuration(min: number): string {
if (min < 60) return `${min} min`;
const h = Math.floor(min / 60);
const m = min % 60;
return m ? `${h} h ${m} min` : `${h} h`;
}
/**
* Kokoro (fp16) returns pure silence for some inputs, deterministically: e.g. Heart on "Poor Alice!" or on a
* sentence ending in an unmatched quote mark. These are rewordings that sound the same, tried in order.
*/
export function speechVariants(text: string): string[] {
const noQuotes = text.replace(/["\u201c\u201d]/g, '').replace(/\s{2,}/g, ' ').trim();
const calm = (t: string) => t.replace(/!/g, '.');
return [...new Set([noQuotes, calm(text), calm(noQuotes)])].filter((t) => t && t !== text);
}
/** The same check on a 16-bit PCM WAV file (audio saved before the retry existed may be silent). */
export function isSilentWav(buf: ArrayBuffer): boolean {
if (buf.byteLength <= 44) return true;
const dv = new DataView(buf);
for (let i = 44; i + 1 < buf.byteLength; i += 2) if (Math.abs(dv.getInt16(i, true)) > 32) return false; // > -60 dBFS
return true;
}
/** True when generated audio has no sound at all (or is broken: NaN). */
export function isSilent(pcm: Float32Array): boolean {
let peak = 0;
for (let i = 0; i < pcm.length; i++) {
const v = Math.abs(pcm[i]);
if (v !== v) return true; // NaN
if (v > peak) peak = v;
}
return peak < 1e-3;
}
|