"""Thai TTS front-end: normalization + word segmentation + G2P + sentence chunking. Deterministic, off-hot-path component shared by the teacher data engine (M1) and the student inference runtime. Wraps two Apache-2.0 libraries: - FastThaiG2P : text normalization (numbers, dates, units, abbreviations, English code-switching) + grapheme-to-phoneme (IPA with lexical tones) - PyThaiNLP : newmm maximum-matching word segmentation Why it matters for Thai: Thai has no inter-word spaces, 5 lexical tones, and heavy numerals / Thai-English code-switching in real text. Feeding the acoustic model explicit, normalized, tone-marked IPA removes the single largest source of "reads wrong" errors and lets a small student model punch above its weight. """ from __future__ import annotations import re from dataclasses import dataclass, field from typing import List, Optional from fastthaig2p import G2P from fastthaig2p.fallback import fallback_g2p from fastthaig2p.normalizer import ENGLISH_ABBREVS, UNITS, normalize as _g2p_normalize from pythainlp.tokenize import word_tokenize from frontend.english import english_to_ipa # Strong boundaries only: newlines and 2+ spaces/tabs. We deliberately do NOT split on # single spaces (Thai uses them as clause breaks, but English phrases like "New York" # must stay intact); length-based packing handles the rest. _SENT_SPLIT_RE = re.compile(r"[\n\r]+|[ \t]{2,}") # Word-ish tokens for length packing. Digit runs include common separators so that # "1,250", "081-234-5678", "2.5%" stay ATOMIC (a number must never be split across # synthesis chunks, or the reading becomes digit-by-digit garbage). _WORD_RE = re.compile( r"[\u0E00-\u0E7F]+|[A-Za-z]+|[0-9][0-9,./:%\-]*", re.UNICODE ) BRAND_OVERRIDES = { "iPhone": "ไอโฟน", "iPad": "ไอแพด", "iMac": "ไอแมค", "MacBook": "แมคบุ๊ก", "AirPods": "แอร์พอดส์", "Google": "กูเกิล", "YouTube": "ยูทูบ", "Facebook": "เฟซบุ๊ก", "Instagram": "อินสตาแกรม", "Netflix": "เน็ตฟลิกซ์", "Microsoft": "ไมโครซอฟท์", "Android": "แอนดรอยด์", "Samsung": "ซัมซุง", "Tesla": "เทสลา", } # A Latin word standing on its own: not part of an e-mail, URL, model number (A10G) or hyphenated code. _LATIN_WORD_RE = re.compile(r"(? กรี๊ด, จ้าาา -> จ้า, 5555 -> a laugh. _STRETCH_CONS_RE = re.compile(r"([\u0E01-\u0E2E])\1{2,}") _STRETCH_VOWEL_RE = re.compile(r"([\u0E30-\u0E3A\u0E40-\u0E4E])\1+") _STRETCH_LATIN_RE = re.compile(r"([A-Za-z])\1{2,}") _LAUGH_RE = re.compile( r"(? segment -> chunk -> phonemize.""" def __init__(self, g2p: G2P | None = None, chat: bool = True, english: bool = True, repair: bool = True): self._g2p = g2p if g2p is not None else G2P() self.chat = chat # stretched letters and "555" laughs, as people type them self.english = english # read English words the Thai way instead of spelling them self.repair = repair # put a cut-off final consonant back on its word (แม่ + ง -> แม่ง) self.original = not (chat or english or repair) # everything off = the pipeline before tuning # -- segmentation --------------------------------------------------------- def segment(self, text: str) -> List[str]: """newmm word segmentation (whitespace stripped).""" return word_tokenize(text, engine="newmm", keep_whitespace=False) # -- normalization + G2P -------------------------------------------------- def phonemize(self, text: str, punct: str = "none") -> str: """Normalize + convert to IPA in one deterministic call (FastThaiG2P). Handles numerals, dates, units, %, abbreviations, emails, phones, Thai numerals, mai-yamok (ๆ), and English brand-word transliteration. """ text = self.normalize_text(text) if punct == "pause": # a space between two Thai words is a clause break text = _THAI_BREAK_RE.sub(", ", text) if not self.repair and not self.english: # the original behaviour, kept for comparisons return self._g2p.convert(text) if not self.english: return self._thai_ipa(text, punct) out: List[str] = [] pos = 0 for m in _LATIN_WORD_RE.finditer(text): word = m.group(0) if word.lower() in _KEEP_FOR_G2P: # km, wifi, facebook...: the library knows these continue ipa = english_to_ipa(word, self._g2p._ipa) if not ipa: # an abbreviation: spelled by the library continue out.append(self._thai_ipa(text[pos:m.start()], punct)) out.append(ipa) pos = m.end() out.append(self._thai_ipa(text[pos:], punct)) return " ".join(x for x in out if x) def _thai_ipa(self, text: str, punct: str = "none") -> str: """FastThaiG2P's convert(), plus one repair: the tokenizer cuts words it does not know and leaves a single consonant behind (แม่ง -> แม่ + ง, read "แม่ งอ"). That consonant is put back on the word before it. punct: "none" = words only (used for scoring); "keep" = , . ! ? stay as bare tokens for the model; "pause" = "keep", and a space between two Thai words (a clause break in Thai writing) becomes a comma.""" if not text.strip(): return "" g = self._g2p tokens = g._tokenizer.tokenize(_g2p_normalize(text)) merged: List[str] = [] for t in tokens: if not t.strip(): continue if t.strip() in _PUNCT: if punct != "none": merged.append(_PUNCT[t.strip()]) elif _SYMBOL_RE.match(t): continue elif (self.repair and merged and _THAI_CONSONANT_RE.match(t) and t not in g._ipa and _THAI_END_RE.search(merged[-1])): merged[-1] += t else: merged.append(t) out: List[str] = [] for i, t in enumerate(merged): if t in _PUNCT.values(): if out and out[-1].startswith("/"): out.append(t) else: out.append((THAI_OVERRIDES.get(t) if self.repair else None) or g._ipa.get(t) or fallback_g2p(t)) return " ".join(out) def normalize_text(self, text: str) -> str: """Apply brand/loanword overrides so English names read correctly. Replaces known English brand/tech words with their standard Thai loanword reading BEFORE G2P, so they do not fall into FastThaiG2P's letter-by-letter fallback (e.g. "iPhone" -> ไอ-พี-เอช-โอ-เอน). Case-insensitive, bounded to ASCII letters so it never splits a word. """ out = text if self.chat: out = _STRETCH_VOWEL_RE.sub(r"\1", _STRETCH_CONS_RE.sub(r"\1", out)) out = _STRETCH_LATIN_RE.sub(r"\1\1", out) out = _LAUGH_RE.sub( lambda m: m.group(0) if _NUMBER_CONTEXT_RE.search(out[:m.start()]) else " ฮ่า ฮ่า ฮ่า ", out) for word, thai in BRAND_OVERRIDES.items(): out = re.sub( r"(? List[str]: """Split into synthesis-friendly chunks, hard-capped at word boundaries. Splits on newlines / 2+ spaces first, then greedily packs words up to max_chars. Original characters (including punctuation like "1,250") are preserved; fallback char-splits only for a single unbroken run longer than the cap. """ text = text.strip() if not text: return [] chunks: List[str] = [] for part in _SENT_SPLIT_RE.split(text): part = part.strip() if part: chunks.extend(self._pack(part, max_chars)) return chunks @staticmethod def _pack(text: str, max_chars: int) -> List[str]: """Pack text into <=max_chars chunks, breaking only at word boundaries. Slices the ORIGINAL text (so punctuation/glue is never dropped); the word spans are used only to find safe break points. """ if len(text) <= max_chars: return [text] spans = [m.span() for m in _WORD_RE.finditer(text)] if not spans: # no tokenizable content -> plain char cap return [text[i:i + max_chars] for i in range(0, len(text), max_chars)] chunks: List[str] = [] cur = 0 word_end = spans[0][1] for s, e in spans[1:]: if e - cur <= max_chars: word_end = e continue # this word would overflow: finalize up to the previous word's end if word_end > cur: chunks.append(text[cur:word_end].rstrip()) cur = s word_end = e if word_end > cur: chunks.append(text[cur:word_end].rstrip()) # safety: a single word longer than the cap gets char-split out: List[str] = [] for c in chunks: if len(c) <= max_chars: out.append(c) else: out.extend(c[i:i + max_chars] for i in range(0, len(c), max_chars)) return [c for c in out if c] # -- combined ------------------------------------------------------------- def process(self, text: str, max_chars: int = 160) -> Normalized: chunks = self.chunk_sentences(text, max_chars) return Normalized( raw=text, ipa=self.phonemize(text), tokens=self.segment(text), chunks=chunks, chunk_ipa=[self.phonemize(c) for c in chunks], )