Spaces:
Running
Running
Download tiny_voca/text.py from oddadmix/tiny-voca-persian: direct link, hf CLI and curl.
- Browser
- Download file 10.5 kB
-
https://huggingface.co/spaces/oddadmix/tiny-voca-persian/resolve/main/tiny_voca/text.py
- Command line
-
hf download hf://spaces/oddadmix/tiny-voca-persian/tiny_voca/text.py
-
curl -L -o text.py https://huggingface.co/spaces/oddadmix/tiny-voca-persian/resolve/main/tiny_voca/text.py
10.5 kB
| """Persian (Farsi) front end: text -> phoneme tokens with a stress feature. | |
| Same interface as the Egyptian front end it replaces, so the model, annotation and training code are unchanged. | |
| text -> fa_normalize.normalize (numbers in words, letter forms, ZWNJ) -> phrases (split at pause punctuation, kept as | |
| tokens) -> persian-g2p-tiny per phrase (ByT5 G2P with ezafe and homograph handling, "Repr. 1" romanization) | |
| -> tokens | |
| * A token is one phoneme. Repr. 1 -> tokens: a æ (written a), A ɑː, e, o, i iː, u uː, S ʃ, Z ʒ, C tʃ, j dʒ, y j, ? ʔ, | |
| q q (ق/غ), g ɡ; the rest are themselves. A doubled letter is a geminate: two identical tokens. | |
| * The ezafe (-e / -ye) is part of its word and never stressed. | |
| * Stress is a parallel feature on one vowel per word (1 = primary), by rule: the last vowel of the word; the first vowel | |
| of a verb with the prefix می / نمی; none on clitic function words (va, be, az, rA ...). | |
| * Punctuation, word boundaries and the utterance edges are tokens that may last zero frames. | |
| The G2P runs on CUDA when available (TV_FA_G2P_DEVICE overrides). ``prefetch(texts)`` phonemizes many texts in batches | |
| (annotation). Phrase phonemes can also come from a cache file (TINY_VOCA_FA_CACHE = jsonl of {"p": phrase, "ph": repr1}). | |
| """ | |
| from dataclasses import dataclass, field | |
| import hashlib | |
| import json | |
| import os | |
| import re | |
| from .fa_normalize import normalize | |
| FRONTEND_VERSION = "fa-1" | |
| FRONTENDS = ("fa",) | |
| FRONTEND_VARIABLE = "TINY_VOCA_FRONTEND" | |
| _frontend = "fa" | |
| G2P_MODEL = "mehdi-hf/persian-g2p-tiny" | |
| G2P_REVISION = os.environ.get("TV_FA_G2P_REVISION") # None = latest; annotation records what was used | |
| PAD, BOS, EOS, SP, UNK = "<pad>", "<bos>", "<eos>", "<sp>", "<unk>" | |
| SPECIALS = (PAD, BOS, EOS, SP, UNK) | |
| PUNCTUATION = (",", ".", "?", "!", ";", ":", "…") | |
| PAUSE_PUNCT = "،,.؟?!:;؛…" | |
| _PUNCT_MAP = {"،": ",", ",": ",", ".": ".", "؟": "?", "?": "?", "!": "!", "؛": ";", ";": ";", ":": ":", "…": "…"} | |
| CONSONANTS = ("b", "t", "d", "k", "ɡ", "q", "ʔ", "f", "v", "p", "s", "z", "ʃ", "ʒ", "x", "h", "tʃ", "dʒ", | |
| "m", "n", "l", "r", "j") | |
| VOWELS = ("a", "ɑː", "e", "o", "iː", "uː") | |
| 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(("p", "t", "k", "q", "ʔ", "f", "s", "ʃ", "x", "h", "tʃ")) | |
| VOWEL_SET = frozenset(VOWELS) | |
| _REPR1 = {"a": "a", "A": "ɑː", "e": "e", "o": "o", "i": "iː", "u": "uː", "S": "ʃ", "Z": "ʒ", "C": "tʃ", "j": "dʒ", | |
| "y": "j", "?": "ʔ", "q": "q", "g": "ɡ", "b": "b", "t": "t", "d": "d", "k": "k", "f": "f", "v": "v", "p": "p", | |
| "s": "s", "z": "z", "x": "x", "h": "h", "m": "m", "n": "n", "l": "l", "r": "r"} | |
| # clitic function words: no stress of their own | |
| _UNSTRESSED = frozenset(("va", "be", "az", "?az", "dar", "tA", "ke", "bA", "rA", "yA", "bar", "na", "?o", "o")) | |
| _FA_WORD = re.compile(r"[-ۿ]+") | |
| class NothingToPronounce(ValueError): | |
| """The text has no Persian word to say.""" | |
| class Phonemized: | |
| symbols: tuple | |
| ids: tuple | |
| stress: tuple | |
| unknown: tuple | |
| optional: tuple = field(default=()) | |
| diacritized: tuple = field(default=()) # here: the G2P romanization of each phrase, 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 frontend_identity(): | |
| return {"frontend_version": FRONTEND_VERSION, "phonemizer": f"{G2P_MODEL} (Repr. 1) + rule stress", | |
| "symbols": list(SYMBOLS)} | |
| def _g2p_revision(): | |
| try: | |
| from huggingface_hub import HfApi | |
| return G2P_REVISION or HfApi().model_info(G2P_MODEL).sha | |
| except Exception: | |
| return G2P_REVISION or "unknown" | |
| def frontend_runtime(): | |
| h = hashlib.sha256() | |
| for name in ("text.py", "fa_normalize.py"): | |
| h.update(open(os.path.join(os.path.dirname(__file__), name), "rb").read()) | |
| return {"phonemizer": h.hexdigest(), "g2p_model": G2P_MODEL, "g2p_revision": _g2p_revision()} | |
| def frontend_fingerprint(): | |
| return hashlib.sha256(json.dumps(frontend_identity(), sort_keys=True, ensure_ascii=False).encode()).hexdigest() | |
| _g2p = None | |
| _cache = None | |
| _mem = {} | |
| def _get_g2p(): | |
| global _g2p | |
| if _g2p is None: | |
| import torch | |
| from transformers import AutoTokenizer, T5ForConditionalGeneration | |
| device = os.environ.get("TV_FA_G2P_DEVICE") or ("cuda" if torch.cuda.is_available() else "cpu") | |
| tok = AutoTokenizer.from_pretrained(G2P_MODEL, revision=G2P_REVISION) | |
| model = T5ForConditionalGeneration.from_pretrained(G2P_MODEL, revision=G2P_REVISION).eval().to(device) | |
| _g2p = (tok, model, device) | |
| return _g2p | |
| def _run_g2p(phrases, batch=128): | |
| import torch | |
| tok, model, device = _get_g2p() | |
| order = sorted(range(len(phrases)), key=lambda i: len(phrases[i])) | |
| res = [None] * len(phrases) | |
| for s in range(0, len(order), batch): | |
| idx = order[s:s + batch] | |
| enc = tok([phrases[i] for i in idx], padding=True, truncation=True, max_length=512, return_tensors="pt").to(device) | |
| with torch.no_grad(): | |
| gen = model.generate(enc["input_ids"], attention_mask=enc["attention_mask"], num_beams=4, max_new_tokens=384) | |
| for i, o in zip(idx, tok.batch_decode(gen, skip_special_tokens=True)): | |
| res[i] = " ".join(o.split()) | |
| return res | |
| def _load_cache(): | |
| global _cache | |
| if _cache is None: | |
| _cache = {} | |
| path = os.environ.get("TINY_VOCA_FA_CACHE") | |
| 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["ph"] | |
| return _cache | |
| def _phonemes(phrases): | |
| cache = _load_cache() | |
| todo = [p for p in dict.fromkeys(phrases) if p not in cache and p not in _mem] | |
| if todo: | |
| for p, r in zip(todo, _run_g2p(todo)): | |
| _mem[p] = r | |
| return [cache[p] if p in cache else _mem[p] for p in phrases] | |
| def prefetch(texts): | |
| """Phonemize the phrases of many texts in large batches (annotation); later phonemize() calls hit memory.""" | |
| _phonemes([p for t in texts for p, _ in split_phrases(normalize(t))]) | |
| def sentence_addressee(text): | |
| """Interface parity with the Egyptian front end (Persian has no addressee-gender readings).""" | |
| return None | |
| def passage_addressee(text): | |
| return None | |
| 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)}]+)", text) | |
| out = [] | |
| for i in range(0, len(parts), 2): | |
| ph = " ".join(parts[i].split()); pu = parts[i + 1][0] if i + 1 < len(parts) else "" | |
| if ph and _FA_WORD.search(ph): | |
| out.append((ph, pu)) | |
| elif pu and out: | |
| out[-1] = (out[-1][0], out[-1][1] or pu) | |
| return out | |
| def _word_tokens(word): | |
| """Repr. 1 word -> (symbols, indices of the stem's vowels, unknown). The ezafe after '-' joins the word.""" | |
| stem, _, ezafe = word.partition("-") | |
| symbols, unknown, stem_vowels = [], [], [] | |
| for part, is_stem in ((stem, True), (ezafe, False)): | |
| for ch in part: | |
| sym = _REPR1.get(ch) | |
| if sym is None: | |
| symbols.append(UNK); unknown.append(ch); continue | |
| if is_stem and sym in VOWEL_SET: | |
| stem_vowels.append(len(symbols)) | |
| symbols.append(sym) | |
| return symbols, stem_vowels, unknown | |
| def tokenize_repr1(repr1, words_fa=None): | |
| """Repr. 1 string of one phrase -> (symbols, stress, unknown). ``words_fa``: the phrase's Persian words, used to | |
| find verbs with the prefix می/نمی when the G2P kept the word count.""" | |
| words = repr1.split() | |
| prefixed = None | |
| if words_fa is not None and len(words_fa) == len(words): | |
| prefixed = [w.startswith(("می", "نمی")) for w in words_fa] | |
| symbols, stress, unknown = [], [], [] | |
| for w, word in enumerate(words): | |
| if w: | |
| symbols.append(SP); stress.append(0) | |
| s, vowels, unk = _word_tokens(word) | |
| st = [0] * len(s) | |
| if vowels and word.split("-")[0] not in _UNSTRESSED: | |
| first = prefixed[w] if prefixed is not None else (word.startswith(("mi", "nemi")) and len(vowels) >= 3) | |
| st[vowels[0] if first else vowels[-1]] = 1 | |
| symbols += s; stress += st; unknown += unk | |
| return symbols, stress, unknown | |
| 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(normalize(text)) | |
| if not parts: | |
| raise NothingToPronounce("the text has nothing to pronounce") | |
| reprs = _phonemes([p for p, _ in parts]) | |
| symbols, stress, unknown, shown = [BOS], [0], [], [] | |
| for (phrase, pu), r in zip(parts, reprs): | |
| r = (r or "").strip() | |
| if not r: | |
| continue | |
| s, st, unk = tokenize_repr1(r, _FA_WORD.findall(phrase)) | |
| if symbols[-1] != BOS and symbols[-1] not in PUNCTUATION: | |
| symbols.append(SP); stress.append(0) | |
| symbols += s; stress += st; unknown += unk; shown.append(r) | |
| if pu: | |
| symbols.append(_PUNCT_MAP.get(pu, ",")); stress.append(0) | |
| symbols.append(EOS); stress.append(0) | |
| 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(0 for _ in symbols), tuple(shown)) | |
| def drop(ph, remove): | |
| """Copy of ``ph`` without the token positions in ``remove`` (interface parity; no optional tokens here).""" | |
| 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] | |