"""Arabic (MSA) + English code-switching front end: text -> phoneme tokens with a stress feature. Same interface as the MSA, Egyptian, Persian and Urdu front ends, so the model, annotation and training code are unchanged. text -> digits outside English names read as Arabic words (numbers.expand_numbers) -> phrases (split at pause punctuation, kept as tokens) -> runs of Arabic words and runs of Latin-script words Arabic runs: CATT diacritizer -> MSA rules (arabic_frontend), exactly as tiny-voca-arabic English runs: dizione (CMUdict + a small G2P model + rules; Apache-2.0), the front end of tiny-voca / tiny-voca-english "الـ" written before an English word (الـ meeting, بالـ email, للـ team) is the Arabic article: l, assimilated to a following coronal like before an Arabic sun letter (الـ team = at-team); inside a phrase its vowel is optional. * A token is one phoneme. Arabic and English phonemes written the same in IPA (b t d k s z f m n l h w j ʃ θ ð ...) are one token; the rest are separate (English ɹ p v ɡ ŋ tʃ, its vowels and diphthongs; Arabic ħ ʕ q x ɣ, emphatics ...). * Stress is a parallel feature: Arabic 0/1 from syllable weight, English 0/1/2 from the lexicon. * Punctuation, word boundaries and the utterance edges are tokens that may last zero frames. * ``Phonemized.optional`` marks Arabic case endings inside a phrase and the article's vowel; the aligner keeps them only when the recording has them, inference always says them. """ from dataclasses import dataclass, field import hashlib import json import os import re import unicodedata from . import arabic_frontend as af from .numbers import expand_numbers FRONTEND_VERSION = "arcs-1" FRONTENDS = ("arcs",) FRONTEND_VARIABLE = "TINY_VOCA_FRONTEND" _frontend = "arcs" PAD, BOS, EOS, SP, UNK = "", "", "", "", "" SPECIALS = (PAD, BOS, EOS, SP, UNK) PUNCTUATION = (",", ".", "?", "!", ";", ":", "…") _PUNCT_MAP = {"،": ",", ",": ",", ".": ".", "؟": "?", "?": "?", "!": "!", "؛": ";", ";": ";", ":": ":", "…": "…"} PAUSE_PUNCT = "،,.؟?!:;؛…" AR_CONSONANTS = tuple(af.CONSONANTS) AR_VOWELS = tuple(af.VOWELS) EN_CONSONANTS = ("p", "b", "t", "d", "k", "ɡ", "f", "v", "θ", "ð", "s", "z", "ʃ", "ʒ", "h", "m", "n", "ŋ", "l", "ɹ", "j", "w", "tʃ", "dʒ", "ɾ", "ʔ") EN_VOWELS = ("ə", "ɐ", "ɚ", "ᵻ", "ɪ", "i", "iː", "ɛ", "æ", "ʌ", "ɑː", "ɔ", "ɔː", "ʊ", "uː", "ɜː", "eɪ", "aɪ", "ɔɪ", "oʊ", "aʊ", "iə", "oː", "ɑːɹ", "ɔːɹ", "oːɹ", "ɪɹ", "ɛɹ", "ʊɹ", "aɪɚ", "aɪə", "əl", "n̩") _uniq = lambda seq: tuple(dict.fromkeys(seq)) CONSONANTS = _uniq(AR_CONSONANTS + EN_CONSONANTS) VOWELS = _uniq(p for p in AR_VOWELS + EN_VOWELS if p not in CONSONANTS) PHONES = CONSONANTS + VOWELS # Append-only: changing the order or removing a symbol invalidates checkpoints. SYMBOLS = SPECIALS + PUNCTUATION + PHONES SYMBOL_TO_ID = {symbol: index for index, symbol in enumerate(SYMBOLS)} PHONE_SET = frozenset(PHONES) PHONE_IDS = frozenset(SYMBOL_TO_ID[p] for p in PHONES) | {SYMBOL_TO_ID[UNK]} VOICELESS = frozenset(af.VOICELESS) | frozenset(("p", "t", "k", "f", "θ", "s", "ʃ", "h", "tʃ")) VOWEL_SET = frozenset(VOWELS) SUN_EN = frozenset(("t", "d", "s", "z", "n", "l", "ɹ", "ʃ", "θ", "ð")) # English onsets the Arabic article assimilates to class NothingToPronounce(ValueError): """The text has nothing to say.""" @dataclass(frozen=True) class Phonemized: symbols: tuple ids: tuple stress: tuple unknown: tuple optional: tuple = field(default=()) diacritized: tuple = field(default=()) # diacritized Arabic runs and the English runs, for inspection def __len__(self): return len(self.ids) def frontend(): return _frontend def set_frontend(name): if name not in FRONTENDS: raise ValueError(f"front end must be one of {FRONTENDS}, not {name!r}") def _dizione(): import dizione return dizione def frontend_identity(): return {"frontend_version": FRONTEND_VERSION, "phonemizer": "tiny_voca.arabic_frontend + dizione", "diacritizer": "catt-tashkeel ed_model v2", "symbols": list(SYMBOLS)} def frontend_runtime(): h = hashlib.sha256() for name in ("text.py", "arabic_frontend.py", "numbers.py"): h.update(open(os.path.join(os.path.dirname(__file__), name), "rb").read()) try: dz = _dizione().identity() except Exception as e: dz = f"unavailable: {e!r}" return {"phonemizer": h.hexdigest(), "dizione": dz} def frontend_fingerprint(): return hashlib.sha256(json.dumps(frontend_identity(), sort_keys=True, ensure_ascii=False).encode()).hexdigest() def sentence_addressee(text): return None def passage_addressee(text): return None _cache = None def _diacritized(phrases): global _cache if _cache is None: _cache = {} path = os.environ.get("TINY_VOCA_DIACRITIZED") if path and os.path.exists(path): with open(path, encoding="utf-8") as f: for line in f: r = json.loads(line); _cache[r["p"]] = r["d"] missing = [p for p in dict.fromkeys(phrases) if p not in _cache] if missing: for p, d in zip(missing, af.diacritize(missing)): _cache[p] = d return [_cache[p] for p in phrases] _AR_LETTER = re.compile(r"[ء-يٱ]") # the Arabic article written for an English word: (و|ف)? (ب|ك)? ال + tatweel, or (و|ف)? لل + tatweel _ARTICLE = re.compile(r"^(?P
[وف]?[بك]?)(?Pال|لل)ـ$")
_LATIN_TOKEN = re.compile(r"^[A-Za-z0-9']+$")


def normalize(text):
    text = unicodedata.normalize("NFC", text).replace("’", "'").replace("‘", "'")
    text = re.sub(r"ـ(?!\s*[A-Za-z0-9])", "", text)                     # tatweel, except the article before Latin
    text = re.sub(r"(?<=[A-Za-z0-9])\+\+", " plus plus", text)
    text = re.sub(r"(?<=[A-Za-z0-9])\s*\+\s*(?=[A-Za-z0-9])", " plus ", text)
    text = re.sub(r"(?<=[A-Za-z])\s*&\s*(?=[A-Za-z])", " and ", text).replace("&", " و ")
    # digits inside an English name (iPhone 15, GPT-4, Windows 11, 5G) stay for the English reader; the rest become Arabic words
    protected = {}
    def keep(m):
        key = f"{chr(0xE100 + len(protected))}"; protected[key] = m.group(0); return key
    text = re.sub(r"[A-Za-z][A-Za-z'.]*(?:[ \-]?[0-9]+(?:\.[0-9]+)?)+[A-Za-z]*|[0-9]+[A-Za-z]+", keep, text)
    text = expand_numbers(text)
    for k, v in protected.items():
        text = text.replace(k, v)
    text = re.sub(r"[\"«»“”()\[\]{}<>*_~`|/\\]", " ", text)
    text = re.sub(r"(?<=[A-Za-z0-9])-(?=[A-Za-z0-9])", " ", text)       # check-in, USB-C, GPT-4
    text = re.sub(r"\s*-\s*", " ", text)
    text = re.sub(r"(?<=[A-Za-z])\.(?=[A-Za-z])", " dot ", text)        # Node.js, Booking.com
    text = re.sub(r"(?<=[0-9])\.(?=[0-9])", " point ", text)
    text = re.sub(r"ـ\s*", "ـ ", text)
    return re.sub(r"\s+", " ", text).strip()


def split_phrases(text):
    """[(phrase, punct)] split at pause punctuation; punct is the closing mark or '' at the end."""
    parts = re.split(f"([{re.escape(PAUSE_PUNCT)}]+)", normalize(text))
    out = []
    for i in range(0, len(parts), 2):
        ph = parts[i].strip(); pu = parts[i + 1][0] if i + 1 < len(parts) else ""
        if ph and (_AR_LETTER.search(ph) or re.search(r"[A-Za-z0-9]", ph)):
            out.append((ph, pu))
        elif pu and out:
            out[-1] = (out[-1][0], out[-1][1] or pu)
    return out


def runs(phrase):
    """[(kind, text, article)]: kind 'ar' or 'en'; article = (prefix, al) of an English run written with الـ, else None."""
    out = []
    for w in phrase.split():
        m = _ARTICLE.match(w)
        if m:
            out.append(["art", (m.group("pre"), m.group("al")), None]); continue
        if _LATIN_TOKEN.match(w):
            kind = "en"
        elif _AR_LETTER.search(w):
            kind = "ar"
        else:
            continue
        if out and out[-1][0] == kind:
            out[-1][1] += " " + w
        else:
            article = out.pop()[1] if out and out[-1][0] == "art" else None
            if article and kind != "en":                   # الـ before an Arabic word: just Arabic
                pre, al = article; w = pre + al + w; article = None
            out.append([kind, w, article])
    return [(k, t, a) for k, t, a in out if k != "art"]


_CONJ = {"و": ["w", "a"], "ف": ["f", "a"]}
_PREFIX = {"و": ["w", "a"], "ف": ["f", "a"], "ب": ["b", "i"], "ك": ["k", "a"]}


def _article(pre, al, first_phone, phrase_initial):
    """Phones and optional flags of the article before an English word."""
    ph, opt = [], []
    for ch in pre:
        ph += _PREFIX[ch]; opt += [0, 0]
    if al == "لل":                                           # للـ = li + l
        ph += ["l", "i"]; opt += [0, 0]
    elif not pre:
        ph, opt = (["ʔ", "a"], [1, 0]) if phrase_initial else (["a"], [1])
    ph.append(first_phone if first_phone in SUN_EN else "l"); opt.append(0)
    return ph, opt


def _english(run):
    """dizione on one English run -> list of words, each [(phone, stress)]."""
    words = []
    for is_punct, value in _dizione().pieces(run):
        if not is_punct:
            words += value
    return words


def _arabic(run, diacritized):
    """MSA rules on one Arabic run -> list of words, each [(phone, stress, optional)]."""
    res = af.phonemize(run, [diacritized])
    words, cur = [], []
    for x in res.phones:
        if x.p in ("^", "$") or x.word < 0:
            if cur:
                words.append(cur); cur = []
            continue
        cur.append((x.p, x.stress, int(x.optional)))
    if cur:
        words.append(cur)
    return words


def prefetch(texts):
    """Diacritize every Arabic run of ``texts`` in one batch."""
    todo = []
    for t in texts:
        try:
            todo += [r for p, _ in split_phrases(t) for k, r, _ in runs(p) if k == "ar"]
        except Exception:
            continue
    if todo:
        _diacritized(list(dict.fromkeys(todo)))


def phonemize(text, addressee=None):
    """``addressee`` is accepted for interface parity and ignored."""
    if not isinstance(text, str) or not text.strip():
        raise ValueError("text must not be empty")
    parts = split_phrases(text)
    if not parts:
        raise NothingToPronounce("the text has nothing to pronounce")
    phrase_runs = [runs(p) for p, _ in parts]
    ar = [t for rs in phrase_runs for k, t, _ in rs if k == "ar"]
    dia = dict(zip(ar, _diacritized(ar))) if ar else {}
    symbols, stress, optional, shown, unknown = [BOS], [0], [0], [], []

    def add(sym, st=0, op=0):
        symbols.append(sym); stress.append(st); optional.append(op)

    for (phrase, punct), rs in zip(parts, phrase_runs):
        first = True
        for kind, run, article in rs:
            if kind == "ar":
                words = _arabic(run, dia[run]); shown.append(dia[run])
                first_word = run.split()[0]
                if words and first_word in _CONJ:                 # و / ف standing before an English word: wa / fa
                    words[0] = [(p, 0, 0) for p in _CONJ[first_word]]
                elif words and not first and first_word[:1] == "ا" and len(words[0]) > 1 and words[0][0][0] == "ʔ":
                    words[0][0] = (words[0][0][0], words[0][0][1], 1)   # hamzat al-wasl inside a phrase: optional
                    words[0][1] = (words[0][1][0], words[0][1][1], 1)
            else:
                words = [[(p, s, 0) for p, s in w] for w in _english(run)]; shown.append(run)
                if words and words[0] and article:
                    ph, op = _article(*article, words[0][0][0], first)
                    words[0] = [(p, 0, o) for p, o in zip(ph, op)] + words[0]
            for w in words:
                if not w:
                    continue
                if symbols[-1] not in (BOS,) + PUNCTUATION:
                    add(SP)
                for p, st, op in w:
                    if p in PHONE_SET:
                        add(p, st, op)
                    else:
                        unknown.append(p); add(UNK)
                first = False
        if punct and symbols[-1] not in (BOS,) + PUNCTUATION:
            add(_PUNCT_MAP.get(punct, ","))
    add(EOS)
    if not any(s in PHONE_SET for s in symbols):
        raise NothingToPronounce("the text has nothing to pronounce")
    return Phonemized(tuple(symbols), tuple(SYMBOL_TO_ID[s] for s in symbols), tuple(stress), tuple(unknown),
                      tuple(optional), tuple(shown))


def drop(ph, remove):
    """Copy of ``ph`` without the token positions in ``remove`` (dropped optional tokens)."""
    remove = set(remove)
    keep = [i for i in range(len(ph.symbols)) if i not in remove]
    pick = lambda seq: tuple(seq[i] for i in keep) if seq else seq
    return Phonemized(pick(ph.symbols), pick(ph.ids), pick(ph.stress), ph.unknown, pick(ph.optional), ph.diacritized)


def is_phone(token_ids):
    return [int(i) in PHONE_IDS for i in token_ids]