Download code/src/lua_nova_v1/text/normalizer.py from oProfM/LuaNovaV1: direct link, hf CLI and curl.
- Browser
- Download file 12.4 kB
-
https://huggingface.co/oProfM/LuaNovaV1/resolve/main/code/src/lua_nova_v1/text/normalizer.py
- Command line
-
hf download hf://oProfM/LuaNovaV1/code/src/lua_nova_v1/text/normalizer.py
-
curl -L -o normalizer.py https://huggingface.co/oProfM/LuaNovaV1/resolve/main/code/src/lua_nova_v1/text/normalizer.py
12.4 kB
| """Normalizador de texto PT-BR (números, moedas, horários, datas, ordinais e abreviações). | |
| Converte expressões numéricas e abreviações comuns do português brasileiro para | |
| texto por extenso antes da fonemização com eSpeak, preservando a pontuação e a | |
| estrutura de frases. Sem dependências externas. | |
| """ | |
| from __future__ import annotations | |
| import re | |
| import unicodedata | |
| _UNITS_M = [ | |
| "zero", "um", "dois", "três", "quatro", "cinco", "seis", "sete", "oito", | |
| "nove", "dez", "onze", "doze", "treze", "quatorze", "quinze", "dezesseis", | |
| "dezessete", "dezoito", "dezenove", | |
| ] | |
| _UNITS_F = [ | |
| "zero", "uma", "duas", "três", "quatro", "cinco", "seis", "sete", "oito", | |
| "nove", "dez", "onze", "doze", "treze", "quatorze", "quinze", "dezesseis", | |
| "dezessete", "dezoito", "dezenove", | |
| ] | |
| _TENS = [ | |
| "", "dez", "vinte", "trinta", "quarenta", "cinquenta", "sessenta", | |
| "setenta", "oitenta", "noventa", | |
| ] | |
| _HUNDREDS_M = [ | |
| "", "cento", "duzentos", "trezentos", "quatrocentos", "quinhentos", | |
| "seiscentos", "setecentos", "oitocentos", "novecentos", | |
| ] | |
| _HUNDREDS_F = [ | |
| "", "cento", "duzentas", "trezentas", "quatrocentas", "quinhentas", | |
| "seiscentas", "setecentas", "oitocentas", "novecentas", | |
| ] | |
| _ORD_UNITS = [ | |
| "", "primeir", "segund", "terceir", "quart", "quint", | |
| "sext", "sétim", "oitav", "non", | |
| ] | |
| _ORD_TENS = [ | |
| "", "décim", "vigésim", "trigésim", "quadragésim", "quinquagésim", | |
| "sexagésim", "septuagésim", "octogésim", "nonagésim", | |
| ] | |
| _ORD_HUNDREDS = [ | |
| "", "centésim", "ducentésim", "trecentésim", "quadringentésim", | |
| "quingentésim", "sexcentésim", "septingentésim", "octingentésim", | |
| "nongentésim", | |
| ] | |
| _MONTHS = { | |
| 1: "janeiro", 2: "fevereiro", 3: "março", 4: "abril", | |
| 5: "maio", 6: "junho", 7: "julho", 8: "agosto", | |
| 9: "setembro", 10: "outubro", 11: "novembro", 12: "dezembro", | |
| } | |
| def _under_1000(n: int, feminine: bool = False) -> str: | |
| if n == 0: | |
| return "zero" | |
| if n == 100: | |
| return "cem" | |
| units = _UNITS_F if feminine else _UNITS_M | |
| hundreds_tbl = _HUNDREDS_F if feminine else _HUNDREDS_M | |
| parts = [] | |
| hundreds, rest = divmod(n, 100) | |
| if hundreds: | |
| parts.append(hundreds_tbl[hundreds]) | |
| if rest: | |
| if rest < 20: | |
| parts.append(units[rest]) | |
| else: | |
| ten, unit = divmod(rest, 10) | |
| parts.append(f"{_TENS[ten]} e {units[unit]}" if unit else _TENS[ten]) | |
| return " e ".join(parts) | |
| def int_to_ptbr(n: int, feminine: bool = False) -> str: | |
| """Converte inteiro (-999_999_999..999_999_999) para extenso em PT-BR.""" | |
| if n < 0: | |
| return f"menos {int_to_ptbr(-n, feminine=feminine)}" | |
| if n < 1000: | |
| return _under_1000(n, feminine=feminine) | |
| if n < 1_000_000: | |
| thousands, rest = divmod(n, 1000) | |
| t_word = "mil" if thousands == 1 else f"{_under_1000(thousands, feminine=feminine)} mil" | |
| if rest == 0: | |
| return t_word | |
| joiner = " e " if (rest < 100 or rest % 100 == 0) else " " | |
| return t_word + joiner + _under_1000(rest, feminine=feminine) | |
| if n < 1_000_000_000: | |
| millions, rest = divmod(n, 1_000_000) | |
| m_word = "um milhão" if millions == 1 else f"{_under_1000(millions, feminine=False)} milhões" | |
| if rest == 0: | |
| return m_word | |
| if rest < 1000 and (rest < 100 or rest % 100 == 0): | |
| return f"{m_word} e {_under_1000(rest, feminine=feminine)}" | |
| return f"{m_word} {int_to_ptbr(rest, feminine=feminine)}" | |
| return " ".join(_UNITS_M[int(ch)] for ch in str(n)) | |
| def ordinal_to_ptbr(n: int, feminine: bool = False) -> str: | |
| """Converte ordinal (1..999) para extenso em PT-BR.""" | |
| if n < 1 or n > 999: | |
| return int_to_ptbr(n, feminine=feminine) | |
| suf = "a" if feminine else "o" | |
| h, rem = divmod(n, 100) | |
| t, u = divmod(rem, 10) | |
| parts = [] | |
| if h: | |
| parts.append(_ORD_HUNDREDS[h] + suf) | |
| if t: | |
| parts.append(_ORD_TENS[t] + suf) | |
| if u: | |
| parts.append(_ORD_UNITS[u] + suf) | |
| return " ".join(parts) | |
| def decimal_to_ptbr(int_str: str, frac_str: str, feminine: bool = False) -> str: | |
| whole = int_to_ptbr(int(int_str.replace(".", "")), feminine=feminine) | |
| if frac_str.startswith("0") and len(frac_str) > 1: | |
| frac = " ".join(_UNITS_M[int(d)] for d in frac_str) | |
| else: | |
| frac = int_to_ptbr(int(frac_str)) | |
| return f"{whole} vírgula {frac}" | |
| _CURRENCY_RE = re.compile( | |
| r"R\$\s*(\d{1,3}(?:\.\d{3})+|\d+)(?:,(\d{1,2}))?(?![\d,])" | |
| ) | |
| _PERCENT_RE = re.compile( | |
| r"(\d{1,3}(?:\.\d{3})+|\d+)(?:,(\d+))?\s*%" | |
| ) | |
| _DATE_RE = re.compile( | |
| r"\b([0-3]?\d)/([01]?\d)(?:/(\d{2,4}))?\b" | |
| ) | |
| _TIME_H_RE = re.compile( | |
| r"\b([01]?\d|2[0-3])\s*h(?:(\d{2}))?(?:min)?\b", re.IGNORECASE | |
| ) | |
| _TIME_COLON_RE = re.compile( | |
| r"\b([01]?\d|2[0-3]):([0-5]\d)\b" | |
| ) | |
| _ORDINAL_RE = re.compile( | |
| r"\b(\d{1,3})\s*([º°ª])\b" | |
| ) | |
| _TEMP_RE = re.compile( | |
| r"(-?\d+)(?:,(\d+))?\s*°\s*C\b" | |
| ) | |
| _UNIT_RE = re.compile( | |
| r"\b(\d{1,3}(?:\.\d{3})+|\d+)(?:,(\d+))?\s*(kHz|Hz|km|kg|cm|mm|mL|ml|GB|MB|KB)\b" | |
| ) | |
| _THOUSANDS_RE = re.compile( | |
| r"\b(\d{1,3}(?:\.\d{3})+)(?:,(\d+))?\b" | |
| ) | |
| _DECIMAL_RE = re.compile( | |
| r"\b(\d+),(\d+)\b" | |
| ) | |
| _INT_RE = re.compile( | |
| r"\b(\d+)\b" | |
| ) | |
| _ABBREV_RULES = [ | |
| (re.compile(r"\bDra\.", re.IGNORECASE), "doutora"), | |
| (re.compile(r"\bDr\.", re.IGNORECASE), "doutor"), | |
| (re.compile(r"\bSrta\.", re.IGNORECASE), "senhorita"), | |
| (re.compile(r"\bSra\.", re.IGNORECASE), "senhora"), | |
| (re.compile(r"\bSr\.", re.IGNORECASE), "senhor"), | |
| (re.compile(r"\bProfa\.", re.IGNORECASE), "professora"), | |
| (re.compile(r"\bProf\.", re.IGNORECASE), "professor"), | |
| (re.compile(r"\betc\.", re.IGNORECASE), "etcétera"), | |
| ] | |
| _ACRONYM_MAP = { | |
| "CPU": "cê pê u", | |
| "GPU": "gê pê u", | |
| "API": "a pê i", | |
| "URL": "u érre éle", | |
| "ONNX": "ônics", | |
| "JSON": "jeizon", | |
| "PDF": "pê dê éfe", | |
| "TTS": "tê tê ésse", | |
| "IA": "i a", | |
| "RAM": "rã", | |
| "SSD": "ésse ésse dê", | |
| "USB": "u ésse bê", | |
| "SQL": "ésse quê éle", | |
| "HTTP": "agá tê tê pê", | |
| "HTTPS": "agá tê tê pê ésse", | |
| "HTML": "agá tê eme éle", | |
| "RGB": "érre gê bê", | |
| "CPF": "cê pê éfe", | |
| "CNPJ": "cê ene pê jóta", | |
| "CEP": "cépi", | |
| "RG": "érre gê", | |
| "IBGE": "i bê gê é", | |
| "LLM": "éle éle eme", | |
| "GPT": "gê pê tê", | |
| "CSV": "cê ésse vê", | |
| "CLI": "cê éle i", | |
| "WAV": "uávi", | |
| "PIX": "pics", | |
| } | |
| _ACRONYM_RE = re.compile( | |
| r"(?<![A-Za-zÀ-ÿ])(?:" | |
| + "|".join(re.escape(k) for k in sorted(_ACRONYM_MAP, key=len, reverse=True)) | |
| + r")(?![A-Za-zÀ-ÿ])" | |
| ) | |
| _LOANWORD_RULES = [ | |
| (re.compile(r"(?<![A-Za-zÀ-ÿ])wi-?fi(?![A-Za-zÀ-ÿ])", re.IGNORECASE), "uái-fái"), | |
| (re.compile(r"(?<![A-Za-zÀ-ÿ])bluetooth(?![A-Za-zÀ-ÿ])", re.IGNORECASE), "blutuf"), | |
| (re.compile(r"(?<![A-Za-zÀ-ÿ])python(?![A-Za-zÀ-ÿ])", re.IGNORECASE), "páiton"), | |
| (re.compile(r"(?<![A-Za-zÀ-ÿ])youtube(?![A-Za-zÀ-ÿ])", re.IGNORECASE), "iutúbi"), | |
| (re.compile(r"(?<![A-Za-zÀ-ÿ])whatsapp(?![A-Za-zÀ-ÿ])", re.IGNORECASE), "uátsápi"), | |
| (re.compile(r"(?<![A-Za-zÀ-ÿ])windows(?![A-Za-zÀ-ÿ])", re.IGNORECASE), "uíndous"), | |
| ] | |
| _SEDE_RE = re.compile( | |
| r"\b(a|na|da|pela|essa|esta|sua|nossa|nova)\s+(sede)\s+" | |
| r"(da|do|de|dos|das|central|principal|própria|nova|antiga|nacional|regional|local|social|administrativa)\b", | |
| re.IGNORECASE, | |
| ) | |
| _VERB_OPEN_O_RE = re.compile( | |
| r"\b(não|sempre|nunca|já|ainda|também|hoje|amanhã|quando|se|só)\s+(almoço|começo)\b", | |
| re.IGNORECASE, | |
| ) | |
| _HOMOGRAPH_RULES = [ | |
| (_SEDE_RE, lambda m: f"{m.group(1)} {'Séde' if m.group(2)[0].isupper() else 'séde'} {m.group(3)}"), | |
| ( | |
| _VERB_OPEN_O_RE, | |
| lambda m: f"{m.group(1)} {'Almóço' if m.group(2) == 'Almoço' else 'almóço' if m.group(2).lower() == 'almoço' else 'Coméço' if m.group(2)[0].isupper() else 'coméço'}", | |
| ), | |
| ] | |
| _UNIT_NAMES = { | |
| "kHz": ("quilohertz", "quilohertz", False), | |
| "Hz": ("hertz", "hertz", False), | |
| "km": ("quilômetro", "quilômetros", False), | |
| "kg": ("quilo", "quilos", False), | |
| "cm": ("centímetro", "centímetros", False), | |
| "mm": ("milímetro", "milímetros", False), | |
| "mL": ("mililitro", "mililitros", False), | |
| "ml": ("mililitro", "mililitros", False), | |
| "GB": ("gigabyte", "gigabytes", False), | |
| "MB": ("megabyte", "megabytes", False), | |
| "KB": ("quilobyte", "quilobytes", False), | |
| } | |
| def _rep_currency(m: re.Match) -> str: | |
| reais = int(m.group(1).replace(".", "")) | |
| cents_raw = m.group(2) | |
| cents = int(cents_raw.ljust(2, "0")) if cents_raw else 0 | |
| parts = [] | |
| if reais > 0 or cents == 0: | |
| unit = "real" if reais == 1 else "reais" | |
| parts.append(f"{int_to_ptbr(reais)} {unit}") | |
| if cents > 0: | |
| c_unit = "centavo" if cents == 1 else "centavos" | |
| parts.append(f"{int_to_ptbr(cents)} {c_unit}") | |
| return " e ".join(parts) | |
| def _rep_percent(m: re.Match) -> str: | |
| if m.group(2): | |
| return f"{decimal_to_ptbr(m.group(1), m.group(2))} por cento" | |
| return f"{int_to_ptbr(int(m.group(1).replace('.', '')))} por cento" | |
| def _rep_date(m: re.Match) -> str: | |
| day, month = int(m.group(1)), int(m.group(2)) | |
| if not (1 <= day <= 31 and 1 <= month <= 12): | |
| return m.group(0) | |
| day_word = "primeiro" if day == 1 else int_to_ptbr(day) | |
| out = f"{day_word} de {_MONTHS[month]}" | |
| if m.group(3): | |
| year = int(m.group(3)) | |
| if len(m.group(3)) == 2: | |
| year += 2000 if year < 50 else 1900 | |
| out += f" de {int_to_ptbr(year)}" | |
| return out | |
| def _format_time(hour: int, minute: int) -> str: | |
| h_word = int_to_ptbr(hour, feminine=True) | |
| h_unit = "hora" if hour == 1 else "horas" | |
| if minute == 0: | |
| return f"{h_word} {h_unit}" | |
| m_unit = "minuto" if minute == 1 else "minutos" | |
| return f"{h_word} {h_unit} e {int_to_ptbr(minute)} {m_unit}" | |
| def _rep_time_h(m: re.Match) -> str: | |
| hour = int(m.group(1)) | |
| minute = int(m.group(2)) if m.group(2) else 0 | |
| return _format_time(hour, minute) | |
| def _rep_time_colon(m: re.Match) -> str: | |
| return _format_time(int(m.group(1)), int(m.group(2))) | |
| def _rep_ordinal(m: re.Match) -> str: | |
| return ordinal_to_ptbr(int(m.group(1)), feminine=(m.group(2) == "ª")) | |
| def _rep_temp(m: re.Match) -> str: | |
| val_str = m.group(1) | |
| neg = val_str.startswith("-") | |
| num = abs(int(val_str)) | |
| prefix = "menos " if neg else "" | |
| if m.group(2): | |
| return f"{prefix}{decimal_to_ptbr(str(num), m.group(2))} graus Celsius" | |
| unit = "grau Celsius" if num == 1 else "graus Celsius" | |
| return f"{prefix}{int_to_ptbr(num)} {unit}" | |
| def _rep_unit(m: re.Match) -> str: | |
| sing, plur, fem = _UNIT_NAMES[m.group(3)] | |
| if m.group(2): | |
| return f"{decimal_to_ptbr(m.group(1), m.group(2), feminine=fem)} {plur}" | |
| val = int(m.group(1).replace(".", "")) | |
| return f"{int_to_ptbr(val, feminine=fem)} {sing if val == 1 else plur}" | |
| def normalize_ptbr_text(text: str) -> str: | |
| """Expande moedas, porcentagens, datas, horários, ordinais, números e abreviações PT-BR.""" | |
| s = unicodedata.normalize("NFC", text) | |
| s = _CURRENCY_RE.sub(_rep_currency, s) | |
| s = _TEMP_RE.sub(_rep_temp, s) | |
| s = _PERCENT_RE.sub(_rep_percent, s) | |
| s = _DATE_RE.sub(_rep_date, s) | |
| s = _TIME_COLON_RE.sub(_rep_time_colon, s) | |
| s = _TIME_H_RE.sub(_rep_time_h, s) | |
| s = _ORDINAL_RE.sub(_rep_ordinal, s) | |
| s = _UNIT_RE.sub(_rep_unit, s) | |
| s = _THOUSANDS_RE.sub( | |
| lambda m: decimal_to_ptbr(m.group(1), m.group(2)) if m.group(2) else int_to_ptbr(int(m.group(1).replace(".", ""))), | |
| s, | |
| ) | |
| s = _DECIMAL_RE.sub(lambda m: decimal_to_ptbr(m.group(1), m.group(2)), s) | |
| s = _INT_RE.sub(lambda m: int_to_ptbr(int(m.group(1))), s) | |
| for pattern, repl in _ABBREV_RULES: | |
| s = pattern.sub(repl, s) | |
| for pattern, repl in _LOANWORD_RULES: | |
| s = pattern.sub(repl, s) | |
| s = _ACRONYM_RE.sub(lambda m: _ACRONYM_MAP[m.group(0)], s) | |
| for pattern, repl in _HOMOGRAPH_RULES: | |
| s = pattern.sub(repl, s) | |
| return re.sub(r"[ \t]{2,}", " ", s).strip() | |