File size: 12,400 Bytes
d4101a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
"""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()