SmallBE_TTS_Advanced / be_ipa_map.py
archivartaunik's picture
Add SmallBE_TTS_Advanced model, offline BelG2P+StressML pipeline, and inference scripts
c48b587 verified
Raw History Blame Contribute Delete
13.4 kB
"""Belarusian BelG2P -> tiny-voca phoneme inventory & lv-60 CTC aligner adapter.
Validated by A/B audit on ``archivartaunik/Jevanhielle_Zyhamont0_10_Checked``
against ``facebook/wav2vec2-lv-60-espeak-cv-ft`` (24 kHz, hop=256).
Key design points:
1. Canonicalizes both BelG2P ``converter.ipa`` (``out_ipa.txt``) and
``converter.ipa2tts`` (``out_ipa_tts.txt``) outputs into one clean TTS
phoneme inventory (``BE_PHONES``) with redundant dental/retracted diacritics
stripped and geminates preserved with ``ː``.
2. Maps every canonical Belarusian phone to empirically verified ``lv-60``
eSpeak CTC tokens (``LV60_ALIGNER_MAP``).
3. Implements Mode B geminate alignment (expanding ``Cː`` -> ``[C, C]`` for
``forced_align`` / ``token_spans`` and collapsing the two CTC spans back
into one acoustic span ``(first_1, last_2)`` for ``tiny_voca.align.assemble``).
"""
from dataclasses import dataclass
import re
import unicodedata
import numpy as np
# ---------------------------------------------------------------------------
# 1. tiny-voca compatible special tokens & punctuation
# ---------------------------------------------------------------------------
PAD, BOS, EOS, SP, UNK = "<pad>", "<bos>", "<eos>", "<sp>", "<unk>"
SPECIALS = (PAD, BOS, EOS, SP, UNK)
PUNCTUATION = (",", ".", "?", "!", ";", ":", '"', "'", "(", ")", "—", "…")
_PUNCTUATION_SET = frozenset(PUNCTUATION)
_QUOTES_TRANS = str.maketrans({
"‘": "'", "’": "'", "‚": "'", "‛": "'", "`": "'", "´": "'",
"“": '"', "”": '"', "„": '"', "‟": '"', "«": '"', "»": '"',
"–": "—", "―": "—", "[": "(", "{": "(", "]": ")", "}": ")",
})
STRESS_MARKS = {"ˈ": 1, "ˌ": 2}
# ---------------------------------------------------------------------------
# 2. Canonical Belarusian TTS phoneme inventory
# ---------------------------------------------------------------------------
BE_VOWELS = ("a", "ɐ", "ɛ", "i", "ɔ", "u", "ɨ", "ə", "ɪ")
BE_SINGLE_CONSONANTS = (
"p", "pʲ", "b", "bʲ",
"t", "tʲ", "d", "dʲ",
"k", "kʲ", "ɡ", "ɡʲ",
"f", "fʲ", "v", "vʲ",
"s", "sʲ", "z", "zʲ",
"ʂ", "ʐ",
"x", "xʲ", "ɣ", "ɣʲ",
"t͡s", "t͡sʲ", "d͡z", "d͡zʲ",
"t͡ʂ", "d͡ʐ",
"m", "mʲ", "ɱ",
"n", "nʲ",
"ɫ", "lʲ", "r",
"j", "w", "β", "βʲ",
)
# Geminated consonants observed or productively formed in Belarusian speech.
BE_GEMINATE_CONSONANTS = tuple(
c + "ː" for c in (
"p", "pʲ", "b", "bʲ",
"t", "tʲ", "d", "dʲ",
"k", "kʲ", "ɡ",
"f", "fʲ", "v", "vʲ",
"s", "sʲ", "z", "zʲ",
"ʂ", "ʐ",
"x", "ɣ",
"t͡s", "t͡sʲ", "d͡z", "d͡zʲ", "t͡ʂ", "d͡ʐ",
"m", "mʲ", "n", "nʲ", "ɫ", "lʲ", "r",
)
)
BE_CONSONANTS = BE_SINGLE_CONSONANTS + BE_GEMINATE_CONSONANTS
BE_PHONES = BE_CONSONANTS + BE_VOWELS
BE_SYMBOLS = SPECIALS + PUNCTUATION + BE_PHONES
BE_SYMBOL_TO_ID = {s: i for i, s in enumerate(BE_SYMBOLS)}
BE_PHONE_SET = frozenset(BE_PHONES)
BE_PHONE_IDS = frozenset(BE_SYMBOL_TO_ID[p] for p in BE_PHONES) | {BE_SYMBOL_TO_ID[UNK]}
BE_VOWEL_SET = frozenset(BE_VOWELS)
# Voiceless set for tiny_voca.annotate.boundary_offsets / quality checks.
# Note: ɣ is voiced even when its lv-60 CTC proxy is 'x', so ɣ is NOT here.
BE_VOICELESS = frozenset(
p for p in BE_CONSONANTS
if p.rstrip("ːʲ") in ("p", "t", "k", "f", "s", "ʂ", "x", "t͡s", "t͡ʂ")
)
# ---------------------------------------------------------------------------
# 3. BelG2P (out_ipa.txt & out_ipa_tts.txt) -> Canonical BE_PHONES
# ---------------------------------------------------------------------------
_RAW_BELG2P_TO_CANONICAL = {
# Vowels
"a": "a", "ɐ": "ɐ", "ɛ": "ɛ", "i": "i", "ɔ": "ɔ", "u": "u",
"ɨ": "ɨ", "ə": "ə", "ɪ": "ɪ",
# Labials / labiodentals / bilabials
"p": "p", "pʲ": "pʲ", "b": "b", "bʲ": "bʲ",
"f": "f", "fʲ": "fʲ", "ʋ": "v", "ʋʲ": "vʲ",
"β\u031E": "β", "β\u031Eʲ": "βʲ", "β": "β", "βʲ": "βʲ",
"w": "w", "u̯": "w",
"m": "m", "mʲ": "mʲ", "ɱ": "ɱ",
# Dentals / alveolars (strip redundant \u032A / \u0331)
"t\u032A": "t", "t\u032Aʲ": "tʲ", "t": "t", "tʲ": "tʲ",
"d\u032A": "d", "d\u032Aʲ": "dʲ", "d": "d", "dʲ": "dʲ",
"s\u032A": "s", "s\u0331ʲ": "sʲ", "s": "s", "sʲ": "sʲ",
"z\u032A": "z", "z\u0331ʲ": "zʲ", "z": "z", "zʲ": "zʲ",
"n\u032A": "n", "n": "n", "nʲ": "nʲ",
"ɫ": "ɫ", "lʲ": "lʲ", "r": "r",
# Affricates (normalize tie-bar/underline variants to standard tie-bar)
"t͡s\u032A": "t͡s", "t͡s": "t͡s",
"t͡\u035Fsʲ": "t͡sʲ", "t͡sʲ": "t͡sʲ",
"d͡z\u032A": "d͡z", "d͡z": "d͡z",
"d͡\u035Fzʲ": "d͡zʲ", "d͡zʲ": "d͡zʲ",
# Postalveolars / retroflexes (unify ipa & ipa2tts)
"ʂ": "ʂ", "ʃ": "ʂ",
"ʐ": "ʐ", "ʒ": "ʐ",
"t͡ʂ": "t͡ʂ", "t͡ʃ": "t͡ʂ",
"d͡ʐ": "d͡ʐ", "d͡ʒ": "d͡ʐ",
# Palatal / velar / glottal
"j": "j",
"k": "k", "kʲ": "kʲ",
"g": "ɡ", "gʲ": "ɡʲ", "ɡ": "ɡ", "ɡʲ": "ɡʲ",
"x": "x", "xʲ": "xʲ",
"ɣ": "ɣ", "ɣʲ": "ɣʲ", "ɦ": "ɣ", "ɦʲ": "ɣʲ",
}
BELG2P_TO_CANONICAL = {}
for _k, _v in _RAW_BELG2P_TO_CANONICAL.items():
_kn = unicodedata.normalize("NFC", _k)
BELG2P_TO_CANONICAL[_kn] = _v
BELG2P_TO_CANONICAL[_kn + "ː"] = _v + "ː" if (_v + "ː" in BE_PHONE_SET) else _v
_BELG2P_KEYS_BY_LEN = sorted(BELG2P_TO_CANONICAL.keys(), key=len, reverse=True)
# ---------------------------------------------------------------------------
# 4. Canonical BE_PHONES -> facebook/wav2vec2-lv-60-espeak-cv-ft CTC tokens
# ---------------------------------------------------------------------------
# Validated against the 392-token eSpeak vocab:
# - ʐ/ʂ -> ʒ/ʃ, v/β -> v, ɔ -> o, ɛ -> e, ɨ -> i, ɫ -> ɭ, lʲ -> ɭʲ
# - t͡sʲ -> tʲ, d͡zʲ -> dʲ, w -> u, ɣ -> x (or ʁ), ɣʲ -> j
# - Geminates Cː expand via Mode B to [base_tok, base_tok] in aligner.
LV60_ALIGNER_MAP = {
# Vowels
"a": ("a",), "ɐ": ("ɐ",), "ɛ": ("e",), "i": ("i",),
"ɔ": ("o",), "u": ("u",), "ɨ": ("i",), "ə": ("ə",), "ɪ": ("ɪ",),
# Single consonants
"p": ("p",), "pʲ": ("pʲ",), "b": ("b",), "bʲ": ("bʲ",),
"t": ("t",), "tʲ": ("tʲ",), "d": ("d",), "dʲ": ("dʲ",),
"k": ("k",), "kʲ": ("kʲ",), "ɡ": ("ɡ",), "ɡʲ": ("ɡʲ",),
"f": ("f",), "fʲ": ("fʲ",), "v": ("v",), "vʲ": ("vʲ",),
"β": ("v",), "βʲ": ("vʲ",),
"s": ("s",), "sʲ": ("sʲ",), "z": ("z",), "zʲ": ("ʒ",),
"ʂ": ("ʃ",), "ʐ": ("ʒ",),
"x": ("x",), "xʲ": ("xʲ",),
"ɣ": ("x",), "ɣʲ": ("j",), # Switchable to ("ʁ",) if voiced proxy preferred
"t͡s": ("ts",), "t͡sʲ": ("tʲ",),
"d͡z": ("d", "z"), "d͡zʲ": ("dʲ",),
"t͡ʂ": ("tʃ",), "d͡ʐ": ("dʒ",),
"m": ("m",), "mʲ": ("mʲ",), "ɱ": ("m",),
"n": ("n",), "nʲ": ("nʲ",),
"ɫ": ("ɭ",), "lʲ": ("ɭʲ",), "r": ("r",),
"j": ("j",), "w": ("u",),
}
# Mode B: double the base token sequence for every geminate Cː.
for _gem in BE_GEMINATE_CONSONANTS:
_base = _gem[:-1]
_base_seq = LV60_ALIGNER_MAP[_base]
LV60_ALIGNER_MAP[_gem] = _base_seq + _base_seq
LV60_UNK_FALLBACK = ("<unk>",)
# ---------------------------------------------------------------------------
# 5. BelG2P IPA -> tiny-voca Phonemized tokenizer
# ---------------------------------------------------------------------------
@dataclass(frozen=True)
class Phonemized:
"""Drop-in equivalent of ``tiny_voca.text.Phonemized``."""
symbols: tuple
ids: tuple
stress: tuple
unknown: tuple
def __len__(self) -> int:
return len(self.ids)
def _normalize_ipa_punctuation(text: str) -> str:
text = unicodedata.normalize("NFC", text).translate(_QUOTES_TRANS)
text = re.sub(r"\.{3,}", "…", text)
text = re.sub(r"-{2,}|\s-\s", "—", text)
text = text.replace("-", " ")
return text
def phonemize_from_belg2p_ipa(ipa_text: str) -> Phonemized:
"""Parse BelG2P IPA string (``converter.ipa`` or ``converter.ipa2tts``) into ``Phonemized``.
* Converts ``ˈ`` syllable stress marks into vowel-level ``stress=1`` (0 elsewhere),
matching ``tiny_voca.text.Phonemized``.
* Preserves punctuation tokens and inserts ``<sp>`` between adjacent words.
* Raises ``ValueError`` if no pronounceable phone is present.
"""
if not isinstance(ipa_text, str) or not ipa_text.strip():
raise ValueError("ipa_text must not be empty")
s = _normalize_ipa_punctuation(ipa_text)
symbols = [BOS]
stress = [0]
unknown = []
pending_stress = 0
pending_space = False
i = 0
n = len(s)
while i < n:
ch = s[i]
if ch in STRESS_MARKS:
pending_stress = pending_stress or STRESS_MARKS[ch]
i += 1
continue
if ch.isspace():
pending_space = True
i += 1
continue
if ch in _PUNCTUATION_SET:
pending_space = False
pending_stress = 0
if symbols[-1] != ch:
symbols.append(ch)
stress.append(0)
i += 1
continue
matched = None
for key in _BELG2P_KEYS_BY_LEN:
if s.startswith(key, i):
matched = key
break
if matched is not None:
canon = BELG2P_TO_CANONICAL[matched]
if pending_space and (symbols[-1] in BE_PHONE_SET or symbols[-1] == UNK):
symbols.append(SP)
stress.append(0)
pending_space = False
symbols.append(canon)
if canon in BE_VOWEL_SET and pending_stress:
stress.append(pending_stress)
pending_stress = 0
else:
stress.append(0)
i += len(matched)
else:
# Skip standalone combining/format chars (or stray 'ː') that weren't attached, log real unknown chars.
if ch != "ː" and unicodedata.category(ch) not in ("Cf", "Mn"):
if pending_space and (symbols[-1] in BE_PHONE_SET or symbols[-1] == UNK):
symbols.append(SP)
stress.append(0)
pending_space = False
unknown.append(ch)
symbols.append(UNK)
stress.append(0)
i += 1
symbols.append(EOS)
stress.append(0)
if not any(sym in BE_PHONE_SET or sym == UNK for sym in symbols):
raise ValueError("BelG2P IPA string contains no pronounceable phonemes")
return Phonemized(
symbols=tuple(symbols),
ids=tuple(BE_SYMBOL_TO_ID[sym] for sym in symbols),
stress=tuple(stress),
unknown=tuple(unknown),
)
# ---------------------------------------------------------------------------
# 6. Mode B CTC expansion & span collapse helpers for tiny_voca.align
# ---------------------------------------------------------------------------
def expand_phones_for_aligner(symbols, vocabulary, aligner_map=LV60_ALIGNER_MAP):
"""Expand ``phonemized.symbols`` into ``(ctc_labels, phone_groups)``.
Each element of ``phone_groups`` is ``(symbol_index, count_of_ctc_labels)``.
In Mode B, geminates (``Cː``) expand to 2 CTC labels ``[C, C]`` so CTC forces
a real doubled duration before collapsing back to one ``Cː`` phone span.
"""
ctc_labels = []
phone_groups = []
for sym_idx, sym in enumerate(symbols):
if sym not in BE_PHONE_SET and sym != UNK:
continue
tok_seq = LV60_UNK_FALLBACK if sym == UNK else aligner_map.get(sym, LV60_UNK_FALLBACK)
ids = []
for tok in tok_seq:
if tok not in vocabulary:
raise KeyError(f"Aligner vocabulary missing token {tok!r} for phone {sym!r}")
ids.append(int(vocabulary[tok]))
ctc_labels.extend(ids)
phone_groups.append((sym_idx, len(ids)))
return ctc_labels, phone_groups
def collapse_mode_b_spans(flat_spans, phone_groups, log_probs=None, ctc_labels=None):
"""Collapse expanded Mode B CTC spans back to 1 span per Belarusian phone.
Returns ``(collapsed_spans, token_probabilities)``:
* ``collapsed_spans`` has length ``len(phone_groups)`` with ``(first_1, last_k)``,
ready to pass straight into ``tiny_voca.align.assemble()``.
* ``token_probabilities`` (if ``log_probs`` and ``ctc_labels`` are given) gives
one probability per Belarusian phone (mean over its 1 or 2 CTC sub-tokens).
"""
collapsed = []
token_probs = [] if (log_probs is not None and ctc_labels is not None) else None
pos = 0
for _, k in phone_groups:
sub = flat_spans[pos : pos + k]
if len(sub) != k:
raise ValueError("flat_spans length does not match phone_groups")
collapsed.append((sub[0][0], sub[-1][1]))
if token_probs is not None:
sub_ids = ctc_labels[pos : pos + k]
sub_p = [
float(np.exp(np.mean([log_probs[f, tid] for f in range(sa, sb + 1)])))
for (sa, sb), tid in zip(sub, sub_ids)
]
token_probs.append(float(np.mean(sub_p)))
pos += k
if pos != len(flat_spans):
raise ValueError("Unused trailing spans in collapse_mode_b_spans")
return collapsed, token_probs