"""Vietnamese text frontend: number fixes -> misaki ViCleaner normaliser -> characters + tone stream. Each syllable becomes one token per letter (tone marks stripped; ă â ê ô ơ ư đ kept). Its tone (1 ngang, 2 huyền, 3 sắc, 4 hỏi, 5 ngã, 6 nặng) goes in a parallel stream, +7 on the first letter of each word. Punctuation is one token with tone 0. Mirrors web/tts.js exactly.""" import re import unicodedata WORD_RE = re.compile(r"\w+|[^\w\s]") TONE_MARK = {"̀": 2, "́": 3, "̉": 4, "̃": 5, "̣": 6} LETTERS = list("aăâbcdđeêfghijklmnoôơpqrstuưvwxyz0123456789") PUNCT = list(",.!?;:-…\"'()") SYMBOLS = ["", ""] + LETTERS + PUNCT SID = {s: i for i, s in enumerate(SYMBOLS)} NUM_TONES = 14 # ---- number fixes applied before the normaliser (misaki ViCleaner mis-reads decimal commas and '.' thousands) ---- D = ["không", "một", "hai", "ba", "bốn", "năm", "sáu", "bảy", "tám", "chín"] def _read3(n, full): h, t, u = n // 100, (n // 10) % 10, n % 10 w = [] if h > 0 or full: w += [D[h], "trăm"] if t > 1: w += [D[t], "mươi"] w += {1: ["mốt"], 4: ["tư"], 5: ["lăm"], 0: []}.get(u, [D[u]]) elif t == 1: w.append("mười") if u == 5: w.append("lăm") elif u > 0: w.append(D[u]) elif u > 0: if h > 0 or full: w.append("linh") w.append(D[u]) return w def read_int(s): s = re.sub(r"^0+(?=\d)", "", s) if s == "0": return "không" units = ["", "nghìn", "triệu", "tỷ", "nghìn tỷ", "triệu tỷ"] groups, i = [], len(s) while i > 0: groups.insert(0, int(s[max(0, i - 3):i])); i -= 3 out = [] for k, g in enumerate(groups): if g == 0: continue out += _read3(g, k > 0) if units[len(groups) - 1 - k]: out.append(units[len(groups) - 1 - k]) return " ".join(out) def _digits(s): return " ".join(D[int(c)] for c in s) def fix_numbers(t): t = re.sub(r"\s*°\s*([CF])\b", r" độ \1", t) # 18°C -> 18 độ C (misaki leaves "°c") t = t.replace("°", " độ") t = re.sub(r"(\d+,\d+)(?=[^\W\d_])", r"\1 ", t) # 3,5kg -> 3,5 kg (else "ba phẩy nămkg") t = re.sub(r"(\d{1,3}(?:\.\d{3})+|\d+)(?:,(\d+))?\s*(đ|vnđ|vnd|đồng)(?![^\W\d_])", lambda m: read_int(m[1].replace(".", "")) + (" phẩy " + _digits(m[2]) if m[2] else "") + " đồng", t, flags=re.I) t = re.sub(r"(? "... độ xê giá"), merging # sentences. Spell a lone capital letter ourselves when sentence punctuation follows, and keep the punctuation. LETTER_NAMES = {"A": "ây", "B": "bê", "C": "xê", "D": "dê", "Đ": "đê", "E": "e", "F": "ép", "G": "gờ", "H": "hát", "I": "ai", "J": "chây", "K": "kây", "L": "lờ", "M": "em mờ", "N": "en nờ", "O": "ô", "P": "pê", "Q": "kiu", "R": "rờ", "S": "ét", "T": "ti", "U": "u", "V": "vi", "W": "vê kép", "X": "ít", "Y": "i", "Z": "dét"} def fix_letters(t): return re.sub(r"(? normalised lower-case Vietnamese (numbers, dates, units, currency spelled out). "_" between two words joins them (no pause): each "_"-separated part is normalised on its own and the parts are glued with JOIN.""" return JOIN.join(p for p in (normalize_part(t) for t in text.split("_")) if p) def normalize_part(text): global _cleaner text = fix_letters(fix_numbers(text)) try: if _cleaner is None: from misaki.vi_cleaner.cleaner import ViCleaner _cleaner = ViCleaner() text = _cleaner.clean_text(text) except Exception: pass text = unicodedata.normalize("NFC", text).lower().strip() # misaki turns "ngày 20-11" into "ngày ngày hai mươi ...": drop the doubled word only before a spelled-out number return re.sub(r"\b(ngày|tháng) \1 (?=(?:mùng|mồng|một|hai|ba|bốn|năm|sáu|bảy|tám|chín|mười)\b)", r"\1 ", text) def split_sentences(norm, max_chars=180): """Chunks the model handles well (trained on 1-15 s utterances): split on . ! ? ; … then on commas.""" out = [] for p in [s.strip() for s in re.split(r"(?<=[.!?;…])\s+", norm) if s.strip()]: if len(p) <= max_chars: out.append(p); continue cur = "" for piece in re.split(r"(?<=,)\s+", p): if len((cur + " " + piece).strip()) > max_chars and cur: out.append(cur.strip()); cur = piece else: cur = (cur + " " + piece).strip() if cur: out.append(cur) return out def apply_breaks(ids, tones, words, w2c, breaks): """Manual phrasing. breaks: {syllable word index i: "join" | "," | "."} sets the boundary BEFORE word i: any punctuation already there is removed, then "," / "." is inserted ("join" inserts nothing). Returns new (ids, tones, words, w2c) plus `bound`: for every token-word, the syllable index whose preceding boundary it belongs to (punctuation -> next syllable, -1 if none).""" alnum = [w[0].isalnum() for w in words] nxt, j = [-1] * len(words), -1 for i in range(len(words) - 1, -1, -1): if alnum[i]: j = i nxt[i] = j out = ([], [], [], [], []) k = 0 for i, (w, n) in enumerate(zip(words, w2c)): seg = (ids[k:k + n], tones[k:k + n]); k += n b = breaks.get(nxt[i]) if breaks else None if not alnum[i] and b is not None: continue # existing punctuation replaced by the manual choice if alnum[i] and breaks and breaks.get(i) in (",", "."): p = breaks[i]; out[0].append(SID[p]); out[1].append(0); out[2].append(p); out[3].append(1); out[4].append(i) out[0].extend(seg[0]); out[1].extend(seg[1]); out[2].append(w); out[3].append(n); out[4].append(i if alnum[i] else nxt[i]) return out VOWELS = set("aăâeêioôơuưy") def floor_durations(dur, ids, words, w2c, min_frames): """The model sometimes rushes syllables (e.g. long numbers: "năm" 120 ms, "mươi" 160 ms) until they get swallowed. Give every syllable at least `min_frames` (40 ms each), adding the missing frames to its vowels. Longer syllables are untouched. 4 frames (160 ms) cut word errors on number-heavy text from 10.0% to 6.0% with ordinary text unchanged.""" if not min_frames: return dur k = 0 for w, n in zip(words, w2c): if w[0].isalnum() and dur[k:k + n].sum() < min_frames: vow = [k + j for j in range(n) if SYMBOLS[ids[k + j]] in VOWELS] or [k + n - 1] for q in range(int(min_frames - dur[k:k + n].sum())): dur[vow[q % len(vow)]] += 1 k += n return dur def join_durations(dur, words, w2c, bound, breaks): """"join": no pause before word i -> its first letter <= 1 frame, its other letters and the last letter of the previous word <= 2 frames (40 ms each). Only shortens, toward the model's typical lengths.""" starts = [0] for n in w2c[:-1]: starts.append(starts[-1] + n) for t, (w, n) in enumerate(zip(words, w2c)): if not w[0].isalnum() or not breaks or breaks.get(bound[t]) != "join": continue s = starts[t] dur[s] = min(dur[s], 1) for q in range(s + 1, s + n): dur[q] = min(dur[q], 2) if t > 0 and words[t - 1][0].isalnum(): dur[s - 1] = min(dur[s - 1], 2) return dur def joins_of(norm): """{syllable word index: "join"} for the words preceded by JOIN (same indexing as encode)""" out, n, join = {}, 0, False for w in WORD_RE.findall(norm): if w == JOIN: join = True; continue if join and w[0].isalnum(): if n: out[n] = "join" join = False n += 1 return out def encode(norm): """normalised text -> ids, tones, words, tokens-per-word (JOIN marks are skipped; see joins_of)""" ids, tones, words, w2c = [], [], [], [] for w in WORD_RE.findall(norm): if w == JOIN: continue words.append(w); n0 = len(ids) if w[0].isalnum(): tone, base = 1, [] for ch in unicodedata.normalize("NFD", w.lower()): if ch in TONE_MARK: tone = TONE_MARK[ch] else: base.append(ch) for k, ch in enumerate(unicodedata.normalize("NFC", "".join(base))): ids.append(SID.get(ch, 1)); tones.append(tone + (7 if k == 0 else 0)) else: ids.append(SID.get(w, 1)); tones.append(0) w2c.append(len(ids) - n0) return ids, tones, words, w2c