Skip to content

Clone your own voice on your own computer: speak any text in 60+ languages and dub videos into another language in your voice. Fully local. Early version.

20.8 KB
Raw Blame
"""Spell out digits, symbols and abbreviations that OmniVoice would misread. Standalone: the OmniVoice worker loads
this file by its path in its own interpreter, so it imports nothing else from ``mimvox_engine``."""

import importlib.util
import re
import unicodedata
from pathlib import Path

try:
    from num2words import num2words as _n2w
except ImportError:  # pragma: no cover - the worker venv has it; without it digits stay digits
    _n2w = None


def _load_stress():
    path = Path(__file__).absolute().parent / "omnivoice_stress.py"
    spec = importlib.util.spec_from_file_location("mimvox_omnivoice_stress", path)
    mod = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(mod)
    return mod


_stress = _load_stress()

_SPACES = re.compile(r"[ \t  ]+")
# 1 000 000 / 1,000,000 / 1 000,5 -> plain digits (a thin or normal space between groups of three)
_GROUPED = re.compile(r"(?<![\d,.])(\d{1,3})((?:[   ]\d{3})+)(?![\d])")


def _ungroup(text):
    return _GROUPED.sub(lambda m: m.group(1) + re.sub(r"\D", "", m.group(2)), text)


def _words(n, lang, **kw):
    if _n2w is None:
        return str(n)
    try:
        # num2words writes "eight thousand, eight hundred": the comma made a pause, and a place to cut the text.
        return _n2w(n, lang=lang, **kw).replace(",", "")
    except (NotImplementedError, OverflowError, ValueError, TypeError, KeyError, AttributeError):
        return str(n)


_RANGE_WORDS = {
    "en": ("", "to"),
    "uk": ("від", "до"),
    "ru": ("от", "до"),
    "be": ("ад", "да"),
    "pl": ("od", "do"),
    "cs": ("", "až"),
    "sk": ("", "až"),
    "de": ("", "bis"),
    "nl": ("", "tot"),
    "fr": ("", "à"),
    "es": ("", "a"),
    "it": ("", "a"),
    "pt": ("", "a"),
    "sv": ("", "till"),
    "da": ("", "til"),
    "no": ("", "til"),
}
_RANGE = re.compile(r"(\d)\s*[–—]\s*(\d)")


def _ranges(text, lang):
    """8–15 is read "eight fifteen" by every model; spoken it is "eight to fifteen"."""
    words = _RANGE_WORDS.get(lang)
    if words is None:
        return text
    before, between = words
    return _RANGE.sub(lambda m: f"{before} {m.group(1)} {between} {m.group(2)}".lstrip(), text)


def _int(s):
    s = str(s)
    if len(s) > 4300:  # int() raises above Python's 4300-digit conversion limit; leave the run unexpanded
        return None
    return int(s)


def _n2w_lang(lang):
    """None when num2words does not know the language."""
    if _n2w is None:
        return None
    alias = {"zh": "zh", "no": "no", "pt": "pt", "sr": "sr", "fa": "fa", "he": "he", "be": "be", "kk": "kz"}
    code = alias.get(lang, lang)
    try:
        _n2w(1, lang=code)
        return code
    except (NotImplementedError, OverflowError, ValueError, KeyError, AttributeError):
        return None


def normalize(text, lang):
    lang = (lang or "").lower()
    text = _stress.user_marks(unicodedata.normalize("NFC", text), lang)
    text = _ranges(_SPACES.sub(" ", text), lang)
    if lang == "uk":
        return _stress.auto(_uk(text), lang)
    if lang == "en":
        return _en(text)
    code = _n2w_lang(lang)
    if code is None:
        return text
    text = _roman_numerals(text, lang)
    text = _ungroup(text)
    text = re.sub(r"(\d+)[.,](\d+)", lambda m: _words(float(f"{m.group(1)}.{m.group(2)}"), code), text)

    def num(m):
        n = _int(m.group())
        return m.group() if n is None else _words(n, code)

    return re.sub(r"\d+(?!\.\s+[A-ZÀ-ÞĀ-ſА-Я])", num, text)


_EN_UNITS = {"%": ("percent", "percent"), "$": ("dollar", "dollars"), "€": ("euro", "euros"), "£": ("pound", "pounds")}


def _en(text):
    text = _roman_numerals(text, "en")
    text = _ungroup(re.sub(r"(?<=\d),(?=\d{3}\b)", "", text))
    text = re.sub(
        r"([$€£])\s?(\d+)\.(\d\d)\b",
        lambda m: (
            f"{m.group(2)} {_EN_UNITS[m.group(1)][1]} and "
            f"{int(m.group(3))} {'cent' if int(m.group(3)) == 1 else 'cents'}"
        ),
        text,
    )
    text = re.sub(r"([$€£])\s?(\d+(?:\.\d+)?)", lambda m: f"{m.group(2)} {_EN_UNITS[m.group(1)][1]}", text)
    text = re.sub(
        r"\b(\d{1,2}):(\d{2})\b",
        lambda m: (
            _words(int(m.group(1)), "en")
            + " "
            + (
                "o'clock"
                if m.group(2) == "00"
                else ("oh " if m.group(2)[0] == "0" else "") + _words(int(m.group(2)), "en")
            )
        ),
        text,
    )

    def ordinal(m):
        n = _int(m.group(1))
        return m.group(0) if n is None else _words(n, "en", to="ordinal")

    text = re.sub(r"\b(\d+)(st|nd|rd|th)\b", ordinal, text)

    def decimal(m):
        n = _int(m.group(1))
        if n is None:
            return m.group(0)
        return _words(n, "en") + " point " + " ".join(_words(int(d), "en") for d in m.group(2))

    text = re.sub(r"(\d+)\.(\d+)", decimal, text)
    text = re.sub(r"(\d+(?:\s\w+)*?)\s?%", lambda m: m.group(1) + " percent", text)

    def num(m):
        s = m.group()
        n = _int(s)
        if n is None:
            return s
        if len(s) == 4 and 1100 <= n <= 2099:
            return _words(n, "en", to="year")
        return _words(n, "en")

    text = re.sub(r"\d+", num, text)
    return text.replace("&", " and ")


# Prepositions after which a number is in the genitive.
_UK_GEN = {
    "до",
    "від",
    "з",
    "із",
    "зі",
    "після",
    "близько",
    "без",
    "для",
    "біля",
    "коло",
    "крім",
    "замість",
    "протягом",
    "понад?",
    "більше",
    "менше",
    "щонайменше",
    "щонайбільше",
    "кількох",
    "серед",
    "навколо",
}
_UK_GEN.discard("понад?")  # "понад" takes the accusative ("понад триста років")
_UK_LOC = {"у", "в", "на", "при", "об"}  # + a number + a locative noun ("у 5 містах") -- only with a known noun ending

_UK_MONTHS_GEN = (
    "січня",
    "лютого",
    "березня",
    "квітня",
    "травня",
    "червня",
    "липня",
    "серпня",
    "вересня",
    "жовтня",
    "листопада",
    "грудня",
)

_UK_ABBR = [
    (r"і т\.\s?д\.", "і так далі"),
    (r"т\.\s?д\.", "так далі"),
    (r"і т\.\s?п\.", "і тому подібне"),
    (r"т\.\s?п\.", "тому подібне"),
    (r"і т\.\s?ін\.", "і таке інше"),
    (r"та ін\.", "та інші"),
    (r"т\.\s?зв\.", "так званий"),
    (r"т\.\s?ч\.", "тому числі"),
    (r"напр\.", "наприклад"),
    (r"див\.", "дивись"),
    (r"вул\.", "вулиця"),
    (r"просп\.", "проспект"),
    (r"обл\.", "область"),
    (r"р-н", "район"),
    (r"ім\.", "імені"),
    (r"проф\.", "професор"),
    (r"акад\.", "академік"),
    (r"д-р", "доктор"),
    (r"№", "номер"),
]
# Abbreviated units, recognized only right after a number ("5 км", "100 грн", "3 тис.", "2026 р.").
_UK_UNIT_ABBR = r"(грн|тис|млн|млрд|км|кг|см|мм|год|хв|сек|рр|р|ст)\.?"
# Units that agree with the number before them: (one, few, many, genitive singular for fractions).
_UK_UNITS = {
    "грн": ("гривня", "гривні", "гривень", "гривні"),
    "тис": ("тисяча", "тисячі", "тисяч", "тисячі"),
    "млн": ("мільйон", "мільйони", "мільйонів", "мільйона"),
    "млрд": ("мільярд", "мільярди", "мільярдів", "мільярда"),
    "км": ("кілометр", "кілометри", "кілометрів", "кілометра"),
    "кг": ("кілограм", "кілограми", "кілограмів", "кілограма"),
    "см": ("сантиметр", "сантиметри", "сантиметрів", "сантиметра"),
    "мм": ("міліметр", "міліметри", "міліметрів", "міліметра"),
    "год": ("година", "години", "годин", "години"),
    "хв": ("хвилина", "хвилини", "хвилин", "хвилини"),
    "сек": ("секунда", "секунди", "секунд", "секунди"),
    "%": ("відсоток", "відсотки", "відсотків", "відсотка"),
    "$": ("долар", "долари", "доларів", "долара"),
    "€": ("євро", "євро", "євро", "євро"),
    "₴": ("гривня", "гривні", "гривень", "гривні"),
    "рр": ("роки", "роки", "років", "року"),
    "р": ("рік", "роки", "років", "року"),
}
_UK_FEM_UNITS = {"грн", "тис", "год", "хв", "сек", "₴"}

_ORD_ENDINGS = {  # nominative masculine ending -> (gen m/n, dat/loc m/n, nom f, gen f, loc f, nom n, nom pl)
    "ий": ("ого", "ому", "а", "ої", "ій", "е", "і"),
    "ій": ("ього", "ьому", "я", "ьої", "ій", "є", "і"),
}


def _plural(n, forms):
    """Forms = (one, few, many); 11-14 take "many"."""
    n = abs(int(n))
    if n % 10 == 1 and n % 100 != 11:
        return forms[0]
    if 2 <= n % 10 <= 4 and not 12 <= n % 100 <= 14:
        return forms[1]
    return forms[2]


def _uk_card(n, case="nominative", feminine=False):
    kw = {}
    if case != "nominative":
        kw["case"] = case
    if feminine:
        kw["gender"] = "feminine"
    return _words(int(n), "uk", **kw)


def _uk_ord(n, form):
    """Ordinal of ``n``: form is one of nom_m, gen_m, loc_m, nom_f, gen_f, loc_f, nom_n."""
    n = _int(n)
    if n is None:
        return None
    words = _words(n, "uk", to="ordinal")
    if form == "nom_m" or not isinstance(words, str):
        return words
    head, _, last = words.rpartition(" ")
    for end, forms in _ORD_ENDINGS.items():
        if last.endswith(end):
            idx = {"gen_m": 0, "loc_m": 1, "nom_f": 2, "gen_f": 3, "loc_f": 4, "nom_n": 5}[form]
            last = last[: -len(end)] + forms[idx]
            break
    return f"{head} {last}".strip()


def _uk_decimal(whole, frac, case="nominative"):
    """3,5 -> три цілих п'ять десятих (1 ціла, 2-4/5+ цілих)."""
    w = _int(whole)
    f = _int(frac)
    if w is None or f is None:
        return None
    whole_words = _uk_card(w, case, feminine=True)
    cil = "ціла" if w % 10 == 1 and w % 100 != 11 else "цілих"
    denom = {1: ("десята", "десятих"), 2: ("сота", "сотих"), 3: ("тисячна", "тисячних")}.get(len(frac))
    if denom is None:
        return f"{whole_words} кома {' '.join(_uk_card(int(d)) for d in frac)}"
    frac_words = _uk_card(f, case, feminine=True)
    dn = denom[0] if f % 10 == 1 and f % 100 != 11 else denom[1]
    if frac == "5" and case == "nominative":
        return f"{whole_words} з половиною" if w else "половина"
    return f"{whole_words} {cil} {frac_words} {dn}"


_UK_NUM = r"(\d+)(?:[,.](\d+))?"


def _uk(text):
    text = _roman_numerals(text, "uk")
    text = _ungroup(text)
    # abbreviations: plain words, or a \0 marker for units that agree with a number
    for pat, rep in _UK_ABBR:
        # an abbreviation that ends a sentence keeps the full stop it shared with it
        text = re.sub(
            r"(?<![\wʼ'’])" + pat + r"(?=\s*$|\s+[A-ZА-ЯІЇЄҐ])",
            rep + ("." if pat.endswith(".") else ""),
            text,
            flags=re.IGNORECASE,
        )
        text = re.sub(r"(?<![\wʼ'’])" + pat + r"(?![\w])", rep, text, flags=re.IGNORECASE)
    text = re.sub(r"(\d)\s*" + _UK_UNIT_ABBR + r"(?![\w])", "\\1 \0\\2", text)
    # time 10:30 -> десята тридцять (after "о" -> о десятій тридцять)
    text = re.sub(
        r"\b(о|об)\s+(\d{1,2}):(\d{2})\b",
        lambda m: f"{m.group(1)} {_uk_ord(m.group(2), 'loc_f')} {_uk_minutes(m.group(3))}",
        text,
    )
    text = re.sub(r"\b(\d{1,2}):(\d{2})\b", lambda m: f"{_uk_ord(m.group(1), 'nom_f')} {_uk_minutes(m.group(2))}", text)
    # years: "у 2026 році", "2026 року", "2026 р.", "2026 рік", "у 1990-х"
    text = re.sub(
        r"(\d{1,4})(?:-?(?:му|ому|ім|ому))?\s+(році)\b", lambda m: f"{_uk_ord(m.group(1), 'loc_m')} році", text
    )
    text = re.sub(
        r"(\d{1,4})(?:-?(?:го|ого))?\s+(року|\0р)(?![\w])", lambda m: f"{_uk_ord(m.group(1), 'gen_m')} року", text
    )
    text = re.sub(r"(\d{4})\s+(рік)\b", lambda m: f"{_uk_ord(m.group(1), 'nom_m')} рік", text)
    text = re.sub(r"(\d{1,4})-(?:х|их)\b", lambda m: _uk_ord(m.group(1), "nom_m")[:-2] + "их", text)
    text = re.sub(r"\b([IVXL]{1,6})\s*столітті\b", lambda m: f"{_uk_ord(_roman(m.group(1)), 'loc_m')} столітті", text)
    text = re.sub(r"\b([IVXL]{1,6})\s*(ст\.|столітт[яі])", lambda m: f"{_roman(m.group(1))} \0ст", text)

    def century(m):
        words = _uk_ord(m.group(1), "nom_n")
        return m.group(0) if words is None else f"{words} століття"

    text = re.sub(r"(\d+)\s*\0ст(?![\w])", century, text)
    # dates: "5 травня" -> п'ятого травня, "1-го" -> першого
    text = re.sub(
        r"(\d{1,2})(?:-?(?:го|ого))?\s+(" + "|".join(_UK_MONTHS_GEN) + r")\b",
        lambda m: f"{_uk_ord(m.group(1), 'gen_m')} {m.group(2)}",
        text,
        flags=re.IGNORECASE,
    )
    # ordinal suffixes: 5-й, 3-я, 2-га, 10-те, 1-го, 7-му
    suffix = {
        "й": "nom_m",
        "ий": "nom_m",
        "я": "nom_f",
        "а": "nom_f",
        "га": "nom_f",
        "та": "nom_f",
        "е": "nom_n",
        "те": "nom_n",
        "го": "gen_m",
        "ого": "gen_m",
        "му": "loc_m",
        "ому": "loc_m",
        "ої": "gen_f",
        "ій": "loc_f",
    }

    def suffixed(m):
        words = _uk_ord(m.group(1), suffix[m.group(2)])
        return m.group(0) if words is None else words

    text = re.sub(r"(\d+)-(" + "|".join(sorted(suffix, key=len, reverse=True)) + r")\b", suffixed, text)
    # currency symbols before the number: $100 -> 100 $
    text = re.sub(
        r"([$€₴])\s?" + _UK_NUM, lambda m: f"{m.group(2)}{',' + m.group(3) if m.group(3) else ''} {m.group(1)}", text
    )

    # a number (optionally after a preposition) followed by a unit that agrees with it
    unit_re = "|".join(re.escape(u) for u in sorted(("%", "$", "€", "₴"), key=len, reverse=True))
    marker_re = "|".join(sorted((k for k in _UK_UNITS if k not in ("%", "$", "€", "₴")), key=len, reverse=True))

    def with_unit(m):
        prep, whole, frac, unit = m.group(1), m.group(2), m.group(3), m.group(4) or m.group(5)
        case = "genitive" if prep and prep.strip().lower() in _UK_GEN else "nominative"
        forms = _UK_UNITS[unit]
        fem = unit in _UK_FEM_UNITS
        n = _int(whole)
        if n is None:
            return m.group(0).replace("\0", "")
        if frac:
            words = _uk_decimal(whole, frac, case)
            if words is None:
                return m.group(0).replace("\0", "")
            return f"{prep or ''}{words} {forms[3]}"
        words = _uk_card(n, case, feminine=fem)
        if case == "genitive":
            noun = forms[3] if n % 10 == 1 and n % 100 != 11 else forms[2]
        else:
            noun = _plural(n, forms[:3])
        return f"{prep or ''}{words} {noun}"

    text = re.sub(
        r"(\b\w+\s+)?" + _UK_NUM + r"\s*(?:(" + unit_re + r")|\0(" + marker_re + r"))(?![\w])", with_unit, text
    )
    text = re.sub(r"\0(" + marker_re + r")(?![\w])", lambda m: _UK_UNITS[m.group(1)][2], text)
    text = text.replace("\0", "")
    text = re.sub(r"(?<!\d)%", " відсотків", text)
    text = re.sub(r"\$", " доларів", text)

    # remaining numbers: decimals, then integers (genitive after a genitive preposition)
    def plain(m):
        prep, whole, frac = m.group(1), m.group(2), m.group(3)
        case = "genitive" if prep and prep.strip().lower() in _UK_GEN else "nominative"
        n = _int(whole)
        if n is None:
            return m.group(0)
        words = _uk_decimal(whole, frac, case) if frac else _uk_card(n, case)
        if words is None:
            return m.group(0)
        return f"{prep or ''}{words}"

    text = re.sub(r"(\b\w+\s+)?" + r"(\d+)(?:,(\d+))?", plain, text)

    def dotted(m):
        words = _uk_decimal(m.group(1), m.group(2))
        return m.group(0) if words is None else words

    text = re.sub(r"(\d+)\.(\d+)", dotted, text)
    text = re.sub(r"\bодна тисяча\b", "тисяча", text)
    text = re.sub(r"\+(?=\w)|(?<=\w)\+", "", text)  # a "+" left over (after the vowel, or next to a digit)
    return _SPACES.sub(" ", text).strip()


_ROMAN_KEYWORDS = {
    "uk": {
        "розділ": "nom_m",
        "том": "nom_m",
        "акт": "nom_m",
        "параграф": "nom_m",
        "випуск": "nom_m",
        "глава": "nom_f",
        "частина": "nom_f",
        "книга": "nom_f",
        "дія": "nom_f",
        "сцена": "nom_f",
        "пісня": "nom_f",
    },
    "en": dict.fromkeys(
        ("chapter", "part", "book", "volume", "vol.", "act", "scene", "section", "canto", "letter"), ""
    ),
    "ru": dict.fromkeys(("глава", "часть", "книга", "том", "действие"), ""),
    "be": dict.fromkeys(("раздзел", "частка", "кніга", "том"), ""),
    "pl": dict.fromkeys(("rozdział", "część", "księga", "tom", "akt"), ""),
    "de": dict.fromkeys(("kapitel", "teil", "buch", "band", "akt"), ""),
    "fr": dict.fromkeys(("chapitre", "partie", "livre", "tome", "acte"), ""),
    "es": dict.fromkeys(("capítulo", "parte", "libro", "tomo", "acto"), ""),
    "it": dict.fromkeys(("capitolo", "parte", "libro", "volume", "atto"), ""),
    "pt": dict.fromkeys(("capítulo", "parte", "livro", "volume", "ato"), ""),
}
_EN_NUMBERED = {
    "war",
    "phase",
    "type",
    "class",
    "grade",
    "level",
    "stage",
    "episode",
    "round",
    "figure",
    "table",
    "appendix",
    "article",
    "item",
    "series",
    "season",
    "mark",
    "model",
    "unit",
    "lesson",
    "exercise",
}
# Cyrillic І, Х, С stand in for I, X, C in many Ukrainian and Russian books.
_ROMAN_LOOKALIKE = str.maketrans("ІХС", "IXC")
_ROMAN = r"[IVXLCDMІХС]+"
_ROMAN_VALID = re.compile(r"M{0,3}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})")


def _roman_value(token):
    r = token.translate(_ROMAN_LOOKALIKE)
    if not r or not _ROMAN_VALID.fullmatch(r):
        return None
    vals = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000}
    return sum(-vals[a] if vals[b] > vals[a] else vals[a] for a, b in zip(r, r[1:] + "I")) if len(r) > 1 else vals[r]


def _roman_numerals(text, lang):
    keywords = _ROMAN_KEYWORDS.get(lang, {})

    def spoken(n, form):
        if lang == "uk":
            return _uk_ord(n, form or "nom_m")
        if lang == "en":
            return _words(n, "en", to="ordinal") if form == "ordinal" else _words(n, "en")
        return str(n)

    def after_keyword(m):
        n = _roman_value(m.group(2))
        return m.group(0) if n is None else f"{m.group(1)} {spoken(n, keywords[m.group(1).lower()])}"

    if keywords:
        names = "|".join(re.escape(k) for k in sorted(keywords, key=len, reverse=True))
        text = re.sub(
            r"(?<![\w])(" + names + r")\s+(" + _ROMAN + r")(?![\w])", after_keyword, text, flags=re.IGNORECASE
        )

    def alone(m):
        n = _roman_value(m.group(2))
        return m.group(0) if n is None else f"{m.group(1)}{spoken(n, '')}{m.group(3)}"

    text = re.sub(r"(?m)^(\s*)(" + _ROMAN + r")(\.?\s*)$", alone, text)

    def regnal(m):
        n = _roman_value(m.group(2))
        if n is None:
            return m.group(0)
        if lang == "en":
            if m.group(1).lower() in _EN_NUMBERED:
                return f"{m.group(1)} {_words(n, 'en').capitalize()}"
            return f"{m.group(1)} the {_words(n, 'en', to='ordinal').capitalize()}"
        return f"{m.group(1)} {_uk_ord(n, 'nom_m')}"

    if lang in ("uk", "en"):
        upper = r"[A-Z][a-z]+" if lang == "en" else r"[А-ЯІЇЄҐ][а-яіїєґʼ'’]+"
        text = re.sub(r"(?<![\w])(" + upper + r")\s+([IVXLC]{2,}|V|X)(?![\w])(?!\s*(?:ст\.|століт|cent))", regnal, text)
    if lang == "uk":

        def lone(m):
            n = _roman_value(m.group(1))
            return m.group(0) if n is None else _uk_ord(n, "nom_m")

        text = re.sub(r"(?<![\w])([IVXLC]{2,}|V|X)(?![\w])(?!\s*(?:ст\.|столітт))", lone, text)
    return text


def _roman(r):
    vals = {"I": 1, "V": 5, "X": 10, "L": 50}
    total = 0
    for a, b in zip(r, r[1:] + " "):
        v = vals[a]
        total += -v if b != " " and vals[b] > v else v
    return str(total)


def _uk_minutes(mm):
    n = int(mm)
    if n == 0:
        return "нуль нуль"
    return ("нуль " if mm.startswith("0") else "") + _uk_card(n, feminine=True)