brenorb commited on
Commit
79bb292
·
verified ·
1 Parent(s): 0ea879d

Model: v1 weights, ONNX, config and front end

Browse files
Files changed (4) hide show
  1. config.json +2 -2
  2. onnx/model.onnx +2 -2
  3. text.py +2396 -164
  4. tiny-broca.pt +2 -2
config.json CHANGED
@@ -36,7 +36,7 @@
36
  "energy_scale": 2.0,
37
  "pitch_reference_hz": 200.0
38
  },
39
- "step": 118000,
40
  "sample_rate": 24000,
41
  "hop": 256,
42
  "voices": [
@@ -46,7 +46,7 @@
46
  "phonemizer": {
47
  "name": "pt",
48
  "version": 1,
49
- "fingerprint": "87e0dcc95e144113252a020e1d39b61678cbfc29923f6e4a443dc2ff39b69a41"
50
  },
51
  "stress": {
52
  "none": 0,
 
36
  "energy_scale": 2.0,
37
  "pitch_reference_hz": 200.0
38
  },
39
+ "step": 148000,
40
  "sample_rate": 24000,
41
  "hop": 256,
42
  "voices": [
 
46
  "phonemizer": {
47
  "name": "pt",
48
  "version": 1,
49
+ "fingerprint": "21ea45190f89d73191f1e9861b5dd3bea5910023dd523d9c295c5353830222df"
50
  },
51
  "stress": {
52
  "none": 0,
onnx/model.onnx CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:2e3b7a57884047b933eb35782d9456afd3e04311009828b775c94f28270dd616
3
- size 21372510
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:78d2652121cd8b815f78d22e775a13e677cbfe5c9a2484fef7c37ea8cd3e108a
3
+ size 21377373
text.py CHANGED
@@ -2,7 +2,7 @@
2
 
3
  The token alphabet is the Portuguese written form itself: lowercase letters
4
  (including the accented ones that are distinct graphemes), punctuation, and
5
- the usual special tokens. Two decisions, documented against the English
6
  original:
7
 
8
  * **Characters, not phonemes.** The original front end mapped text to eSpeak
@@ -12,12 +12,24 @@ original:
12
  dictionary is available. Portuguese graphemes map to phones through a small,
13
  regular set of context rules, so a character-level front end whose encoder
14
  learns the context is the standard, fully permissive design.
15
- * **The number reader lives in the normaliser.** Digits, dates, money and
16
- identifiers are spelled in Brazilian conventions (dot thousands separator,
17
- comma decimal) before tokenisation, so "R$ 1.234,56" and "15/11/2026" reach
18
- the model as ordinary words. This is the feature the model is known for
19
- (reading numbers, dates and money from context) and it is language-specific
20
- either way.
 
 
 
 
 
 
 
 
 
 
 
 
21
 
22
  The forced aligner (``tiny_broca.align``) is a Portuguese character-level CTC
23
  recogniser, so every written letter is a label it can emit; punctuation is
@@ -31,8 +43,8 @@ import re
31
  import unicodedata
32
  from dataclasses import dataclass
33
 
34
- FRONTEND_VERSION = 1
35
- NORMALIZER_VERSION = 1
36
  SEPARATOR = "_"
37
  FRONTENDS = ("pt",)
38
  FRONTEND_VARIABLE = "TINY_BROCA_FRONTEND"
@@ -64,10 +76,12 @@ LETTER_SET = frozenset(LETTERS)
64
  STRESS_STRESSED = 1
65
 
66
  _QUOTE_TRANSLATION = str.maketrans({
67
- "\u2018": "'", "\u2019": "'", "\u201a": "'", "\u201b": "'", "`": "'",
68
- "\u201c": '"', "\u201d": '"', "\u201e": '"', "\u201f": '"',
69
- "\u00ab": '"', "\u00bb": '"',
70
- "\u2013": "\u2014", "\u2015": "\u2014",
 
 
71
  })
72
  _WORD_CHARS = LETTER_SET | {"'"} # apostrophes stay inside words (d'água)
73
 
@@ -112,12 +126,14 @@ _TENS = ("", "dez", "vinte", "trinta", "quarenta", "cinquenta", "sessenta",
112
  "setenta", "oitenta", "noventa")
113
  _HUNDREDS = ("", "cento", "duzentos", "trezentos", "quatrocentos", "quinhentos",
114
  "seiscentos", "setecentos", "oitocentos", "novecentos")
115
- _ORDINALS = ("primeiro", "segundo", "terceiro", "quarto", "quinto", "sexto",
116
- "sétimo", "oitavo", "nono", "décimo", "undécimo", "duodécimo", "trezeno")
117
  _MONTHS = ("janeiro", "fevereiro", "março", "abril", "maio", "junho", "julho",
118
  "agosto", "setembro", "outubro", "novembro", "dezembro")
119
- _SCALE = ((10 ** 9, "bilhão", "bilhões"), (10 ** 6, "milhão", "milhões"),
120
- (10 ** 3, "mil", "mil"))
 
 
 
 
121
 
122
 
123
  def _below_thousand(n):
@@ -141,155 +157,2285 @@ def _below_thousand(n):
141
  return " ".join(p for p in parts if p)
142
 
143
 
144
- def number_words(n):
145
- """Spell an integer 0..10**12 in Brazilian Portuguese (masculine form)."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
146
  n = int(abs(n))
147
  if n == 0:
148
  return "zero"
149
  if n < 1000:
150
- return _below_thousand(n)
151
- if n % 1000 == 0 and n < 10 ** 6:
152
  head = _below_thousand(n // 1000)
153
- return "mil" if head == "um" else head + " mil"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
154
  parts = []
155
- for scale, singular, plural in _SCALE:
156
- if n >= scale:
157
- count, n = divmod(n, scale)
158
- # Portuguese says "mil", never "um mil".
159
- head = "" if (count == 1 and scale == 10 ** 3) else (
160
- _UNITS[count] if count == 1 else number_words(count))
161
- parts.append((head + " " if head else "") +
162
- (singular if count == 1 else plural))
163
- # "e" joins the scales when the rest has no tens part:
164
- # "quatro mil e noventa", "mil e quinhentos", "mil e cinco", but
165
- # "mil cento e cinquenta". The larger scales take "e" for any rest
166
- # ("um milhão e quinhentos mil").
167
- if n and (scale > 10 ** 3 or n < 100 or n % 100 == 0):
168
- parts.append("e")
169
- if n:
170
- parts.append(_below_thousand(n) if n < 1000 else number_words(n))
171
- return " ".join(parts)
172
 
173
 
174
- def ordinal_words(n):
175
- if n < len(_ORDINALS):
176
- return _ORDINALS[n - 1]
177
- decade, unit = divmod(n, 10)
178
- if decade < 20:
179
- base = number_words(decade).rstrip("s") if decade > 1 else ""
180
- return (base + " " if base else "") + number_words(unit).replace("um", "um") + "ésimo" if unit else _ORDINALS[9] if decade == 1 else number_words(n) + "ésimo"
181
- return number_words(n) + "ésimo"
182
 
183
 
184
- def digits_words(text):
185
- return " ".join(_UNITS[int(c)] if int(c) < 10 else "dez" for c in text if c.isdigit())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
186
 
187
 
188
  # ---------------------------------------------------------------------------
189
- # Text normalisation: digits and symbols -> words
190
  # ---------------------------------------------------------------------------
191
 
192
- _MONEY = re.compile(r"\b[rR]\$\s?(\d{1,3}(?:\.\d{3})*|\d+)(?!\d)(?:,(\d{1,2}))?")
193
- _DATE = re.compile(r"\b(\d{1,2})/(\d{1,2})/(\d{2}|\d{4})\b")
194
- _TIME = re.compile(r"\b(\d{1,2}):(\d{2})\b")
195
- _CLOCK = re.compile(r"\b(\d{1,2})h(\d{2})\b")
196
- _PERCENT = re.compile(r"\b(\d+(?:[.,]\d+)?)\s?%")
197
- _DEGREE = re.compile(r"\b(\d+(?:[.,]\d+)?)\s?°")
198
- _PHONE = re.compile(r"\(\d{2}\)\s?\d{5}-\d{4}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
199
  _GROUPS = re.compile(r"\b\d{1,3}(?:[.-]\d{1,3}){2,}\b") # CPF, CNPJ-like, CEP
200
- _DECIMAL = re.compile(r"\b(\d{1,3}(?:\.\d{3})*|\d+)[,](\d{1,3})\b")
201
- _INTEGER = re.compile(r"\b(\d{1,3}(?:\.\d{3})+|\d{1,5})\b")
202
- _YEAR = re.compile(r"\b(1[0-9]{3}|20\d{2})\b")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
203
 
204
 
205
  def _money(m):
206
- integer = m.group(1).replace(".", "")
207
- cents = m.group(2)
208
- words = number_words(int(integer)) + " real" if int(integer) == 1 else number_words(int(integer)) + " reais"
209
- if cents and int(cents):
210
- words += " e " + number_words(int(cents)) + (" centavo" if int(cents) == 1 else " centavos")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
211
  return words
212
 
213
 
214
- def _date(m):
215
  day, month, year = int(m.group(1)), int(m.group(2)), m.group(3)
216
- year = "20" + year if len(year) == 2 else year
217
- if 1 <= month <= 12:
218
- return f"{number_words(day)} de {_MONTHS[month - 1]} de {number_words(int(year))}"
219
- return m.group(0) # not a date: leave the digits (the integer rule reads them)
 
220
 
221
 
222
- def _time(m):
223
- hour, minute = int(m.group(1)), int(m.group(2))
224
- if not 0 <= hour <= 23 or minute > 59:
225
  return m.group(0)
226
- if hour == 12 and minute == 0:
227
- return "meio dia"
228
- if hour == 0:
229
- return "meia noite" if minute == 0 else f"zero hora e {number_words(minute)}"
230
- if minute == 0:
231
- return f"{number_words(hour)}{' hora' if hour == 1 else ' horas'}"
232
- if minute == 30:
233
- return f"{number_words(hour)} e meia"
234
- return f"{number_words(hour)} horas e {number_words(minute)}"
235
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
236
 
237
- def _clock(m):
238
- hour, minute = int(m.group(1)), int(m.group(2))
239
- if not 0 <= hour <= 23 or minute > 59:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
240
  return m.group(0)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
241
  if minute == 0:
242
- return f"{number_words(hour)}{' hora' if hour == 1 else ' horas'}"
243
  if minute == 30:
244
- return f"{number_words(hour)} e meia"
245
- return f"{number_words(hour)} e {number_words(minute)}"
 
 
246
 
247
 
248
- def _decimal(m):
249
- integer = int(m.group(1).replace(".", ""))
250
- frac = m.group(2)
251
- if int(frac) == 0:
252
- return number_words(integer) # "150,00" -> "cento e cinquenta"
253
- if len(frac) > 1 and frac[0] == "0":
254
- frac_words = digits_words(frac) # "3,05" -> "zero cinco"
255
- else:
256
- frac_words = number_words(int(frac)) # "3,14" -> "quatorze"
257
- return f"{number_words(integer)} vírgula {frac_words}"
258
 
259
 
260
- def _groups(m):
261
- return ", ".join(digits_words(g) for g in re.split(r"[.-]", m.group(0)))
 
 
 
 
262
 
263
 
264
- def normalize_text(text):
265
- """NFKC + casefold + quote/dash unification + spelling out digits.
 
 
 
 
 
266
 
267
- Digits follow Brazilian conventions: "1.234" is a thousand and "3,14" a
268
- decimal; money uses reais and centavos; dates read day-month-year; times
269
- read in hours and minutes; document identifiers (three-digit groups) read
270
- digit by digit.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
271
  """
272
  if not isinstance(text, str):
273
  raise TypeError("text must be a string")
 
 
 
274
  text = unicodedata.normalize("NFKC", text).translate(_QUOTE_TRANSLATION)
275
- text = text.replace("ª", " a").replace("º", " o").replace("×", " vezes ")
 
 
276
  # Two hyphens and three dots are the ASCII forms of the inventory symbols;
277
  # without this "..." would become three pause tokens.
278
  text = text.replace("--", "—").replace("...", "…")
279
- text = text.lower()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
280
  text = _MONEY.sub(_money, text)
281
- text = _DATE.sub(_date, text)
282
- text = _TIME.sub(_time, text)
283
- text = _CLOCK.sub(_clock, text)
284
- text = _PERCENT.sub(lambda m: number_words(int(re.sub(r"[^0-9]", "", m.group(1)))) + " por cento", text)
285
- text = _DEGREE.sub(lambda m: number_words(int(re.sub(r"[^0-9]", "", m.group(1)))) + " graus", text)
286
- text = _PHONE.sub(lambda m: " ".join(digits_words(g) for g in re.findall(r"\d+", m.group(0))), text)
287
- text = _GROUPS.sub(_groups, text)
288
- text = _DECIMAL.sub(_decimal, text)
289
- text = _YEAR.sub(lambda m: number_words(int(m.group(1))), text)
290
- text = _INTEGER.sub(lambda m: number_words(int(m.group(1).replace(".", ""))), text)
291
- text = re.sub(r"\s+", " ", text).strip()
292
- return text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
293
 
294
 
295
  # For comparing a transcription against its text: numbers are spoken by the
@@ -318,53 +2464,129 @@ def wer_normalize(text):
318
  return " ".join(words).strip()
319
 
320
 
321
- _ACCENTED = frozenset(("á", "â", "é", "ê", "í", "ó", "ô", "õ", "ú", "ã", "õ"))
 
 
 
 
 
 
 
 
322
 
323
 
324
- def _syllable_starts(word):
325
- """Start indices of the syllables of a word (one per vowel nucleus).
 
326
 
327
- A consonant run between two vowels splits so the consonants go with the
328
- following syllable, the Brazilian convention for single consonants; this
329
- is an approximation, which is fine for a prosody feature.
330
- """
331
- vowel = lambda c: c in VOWELS
332
- starts = [0]
333
- i, n = 0, len(word)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
334
  while i < n:
335
- if vowel(word[i]) and i + 1 < n and not vowel(word[i + 1]):
336
- j = i + 1
337
- while j < n and not vowel(word[j]):
338
- j += 1
339
- if j < n and vowel(word[j]): # a consonant run between two vowels
340
- run = j - i - 1
341
- starts.append(i + 1 if run == 1 else min(i + 2, j))
342
- i += 1
343
- return starts
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
344
 
345
 
346
  def _stressed_range(word):
347
- """(start, end) of the stressed syllable in a word.
348
 
349
- An explicit accent (á â é ê í ó ô õ ú ã) wins; otherwise a word ending in
350
- a vowel is stressed on its penultimate syllable, a word ending in L, N, R
351
- or X on its last syllable, other endings on the penultimate.
352
  """
353
- for i, c in enumerate(word):
354
- if c in _ACCENTED:
355
- starts = _syllable_starts(word)
356
- start = max((s for s in starts if s <= i), default=0)
357
- index = starts.index(start)
358
- end = starts[index + 1] if index + 1 < len(starts) else len(word)
359
- return start, end
360
- starts = _syllable_starts(word)
361
- if word[-1] in ("l", "n", "r", "x"):
362
- start = starts[-1]
363
- else:
364
- start = starts[-2] if len(starts) >= 2 else starts[0]
365
- index = starts.index(start)
366
- end = starts[index + 1] if index + 1 < len(starts) else len(word)
367
- return start, end
368
 
369
 
370
  @dataclass(frozen=True)
@@ -383,8 +2605,8 @@ def tokenize(text):
383
 
384
  Returns a :class:`Phonemized` whose symbols are letters, punctuation and
385
  word spaces, with a stress feature per token (1 on the letters of the
386
- stressed syllable of each word, 0 elsewhere) and the list of characters
387
- that fell outside the inventory.
388
  """
389
  symbols = [BOS]
390
  stress = [0]
@@ -395,10 +2617,17 @@ def tokenize(text):
395
  if not word:
396
  return
397
  text_ = "".join(word)
398
- start, end = _stressed_range(text_)
 
 
 
 
 
 
 
399
  for i, c in enumerate(word):
400
  symbols.append(c)
401
- stress.append(STRESS_STRESSED if start <= i < end else 0)
402
  word.clear()
403
 
404
  for c in text:
@@ -422,13 +2651,16 @@ def tokenize(text):
422
  symbols.append(EOS)
423
  stress.append(0)
424
  return Phonemized(tuple(symbols), tuple(SYMBOL_TO_ID[s] for s in symbols),
425
- tuple(stress), tuple(unknown))
426
 
427
 
428
  def phonemize(text):
429
  if not isinstance(text, str) or not text.strip():
430
  raise ValueError("empty text")
431
- return tokenize(normalize_text(text))
 
 
 
432
 
433
 
434
  def is_phone(token_ids):
 
2
 
3
  The token alphabet is the Portuguese written form itself: lowercase letters
4
  (including the accented ones that are distinct graphemes), punctuation, and
5
+ the usual special tokens. Three decisions, documented against the English
6
  original:
7
 
8
  * **Characters, not phonemes.** The original front end mapped text to eSpeak
 
12
  dictionary is available. Portuguese graphemes map to phones through a small,
13
  regular set of context rules, so a character-level front end whose encoder
14
  learns the context is the standard, fully permissive design.
15
+ * **The normaliser reads what a person reads aloud.** Digits, dates, times,
16
+ money, symbols, units, ordinals, acronyms, abbreviations, roman numerals,
17
+ URLs and common English loanwords become ordinary Portuguese words before
18
+ tokenisation ("R$ 1.234,56", "14/03", "4 > 3", "2ª", "CPF", "online"), with
19
+ Brazilian conventions (dot thousands separator, comma decimal, "duas horas",
20
+ "primeiro de maio"). English loanwords are respelled the way Brazilians say
21
+ them ("online" -> "onlaine", "shampoo" -> "xampu"), so the letter model never
22
+ has to learn English spelling.
23
+ * **Stress from syllables.** The stress feature marks the stressed syllable
24
+ found by a Portuguese syllabifier: an accent wins, else the oxytone endings
25
+ (-r, -l, -z, -x, -i, -u, -im, -um, -is, -us, ...) stress the last syllable
26
+ and everything else the penultimate; hiatus and diphthongs are split the
27
+ Portuguese way (ra-iz, re-ais, sa-í-da, mui-to). Unstressed function words
28
+ (de, que, se, o, a, ...) carry no stress.
29
+
30
+ Version 2 of the front end (tiny-broca v1) changed the normaliser and the
31
+ stress feature; the symbol inventory is unchanged, so version-1 checkpoints
32
+ load and fine-tune on version-2 tokens.
33
 
34
  The forced aligner (``tiny_broca.align``) is a Portuguese character-level CTC
35
  recogniser, so every written letter is a label it can emit; punctuation is
 
43
  import unicodedata
44
  from dataclasses import dataclass
45
 
46
+ FRONTEND_VERSION = 2
47
+ NORMALIZER_VERSION = 2
48
  SEPARATOR = "_"
49
  FRONTENDS = ("pt",)
50
  FRONTEND_VARIABLE = "TINY_BROCA_FRONTEND"
 
76
  STRESS_STRESSED = 1
77
 
78
  _QUOTE_TRANSLATION = str.maketrans({
79
+ "‘": "'", "’": "'", "‚": "'", "‛": "'", "`": "'", "´": "'",
80
+ "“": '"', "”": '"', "„": '"', "‟": '"',
81
+ "«": '"', "»": '"',
82
+ "–": "—", "―": "—", "‒": "—",
83
+ "‐": "-", "‑": "-", "­": "",
84
+ "−": "−",
85
  })
86
  _WORD_CHARS = LETTER_SET | {"'"} # apostrophes stay inside words (d'água)
87
 
 
126
  "setenta", "oitenta", "noventa")
127
  _HUNDREDS = ("", "cento", "duzentos", "trezentos", "quatrocentos", "quinhentos",
128
  "seiscentos", "setecentos", "oitocentos", "novecentos")
 
 
129
  _MONTHS = ("janeiro", "fevereiro", "março", "abril", "maio", "junho", "julho",
130
  "agosto", "setembro", "outubro", "novembro", "dezembro")
131
+ _SCALE = ((10 ** 12, "trilhão", "trilhões"), (10 ** 9, "bilhão", "bilhões"),
132
+ (10 ** 6, "milhão", "milhões"), (10 ** 3, "mil", "mil"))
133
+ _SCALE_WORDS = frozenset(("milhão", "milhões", "bilhão", "bilhões", "trilhão", "trilhões"))
134
+ _FEMININE_NUMBERS = {"um": "uma", "dois": "duas", "duzentos": "duzentas", "trezentos": "trezentas",
135
+ "quatrocentos": "quatrocentas", "quinhentos": "quinhentas", "seiscentos": "seiscentas",
136
+ "setecentos": "setecentas", "oitocentos": "oitocentas", "novecentos": "novecentas"}
137
 
138
 
139
  def _below_thousand(n):
 
157
  return " ".join(p for p in parts if p)
158
 
159
 
160
+ def _feminine(words):
161
+ """Feminine agreement of a spelled number ("duzentas e uma"). The scale
162
+ nouns milhão/bilhão are masculine, so only what follows the last of them
163
+ agrees: "dois milhões e duzentas mil pessoas"."""
164
+ parts = words.split(" ")
165
+ last = max((i for i, w in enumerate(parts) if w in _SCALE_WORDS), default=-1)
166
+ return " ".join(parts[:last + 1] + [_FEMININE_NUMBERS.get(w, w) for w in parts[last + 1:]])
167
+
168
+
169
+ def _single_round_group(n):
170
+ while n and n % 1000 == 0:
171
+ n //= 1000
172
+ return n < 100 or (n < 1000 and n % 100 == 0)
173
+
174
+
175
+ def number_words(n, feminine=False):
176
+ """Spell an integer 0..10**15 in Brazilian Portuguese."""
177
  n = int(abs(n))
178
  if n == 0:
179
  return "zero"
180
  if n < 1000:
181
+ words = _below_thousand(n)
182
+ elif n % 1000 == 0 and n < 10 ** 6:
183
  head = _below_thousand(n // 1000)
184
+ words = "mil" if head == "um" else head + " mil"
185
+ else:
186
+ parts = []
187
+ for scale, singular, plural in _SCALE:
188
+ if n >= scale:
189
+ count, n = divmod(n, scale)
190
+ # Portuguese says "mil", never "um mil".
191
+ head = "" if (count == 1 and scale == 10 ** 3) else (
192
+ _UNITS[count] if count == 1 else number_words(count))
193
+ parts.append((head + " " if head else "") +
194
+ (singular if count == 1 else plural))
195
+ # "e" joins a scale to what follows only when that is a single
196
+ # group below a hundred or a round hundred: "quatro mil e noventa",
197
+ # "mil e quinhentos", "um milhão e quinhentos mil", but "mil cento
198
+ # e cinquenta", "um milhão duzentos e trinta e quatro mil".
199
+ if n and _single_round_group(n):
200
+ parts.append("e")
201
+ if n:
202
+ parts.append(_below_thousand(n) if n < 1000 else number_words(n))
203
+ words = " ".join(parts)
204
+ return _feminine(words) if feminine else words
205
+
206
+
207
+ _ORD_UNITS = ("", "primeiro", "segundo", "terceiro", "quarto", "quinto", "sexto",
208
+ "sétimo", "oitavo", "nono")
209
+ _ORD_TENS = ("", "décimo", "vigésimo", "trigésimo", "quadragésimo", "quinquagésimo",
210
+ "sexagésimo", "septuagésimo", "octogésimo", "nonagésimo")
211
+ _ORD_HUNDREDS = ("", "centésimo", "ducentésimo", "trecentésimo", "quadringentésimo",
212
+ "quingentésimo", "sexcentésimo", "septingentésimo", "octingentésimo",
213
+ "noningentésimo")
214
+ _ORDINAL_WORDS = frozenset(_ORD_UNITS + _ORD_TENS + _ORD_HUNDREDS + ("milésimo",)) - {""}
215
+
216
+
217
+ def ordinal_words(n, feminine=False):
218
+ """Spell an ordinal: 1 -> "primeiro", 21 -> "vigésimo primeiro", 2 (f) -> "segunda"."""
219
+ n = int(n)
220
+ if n <= 0:
221
+ return number_words(n)
222
  parts = []
223
+ if n >= 1000:
224
+ thousands, n = divmod(n, 1000)
225
+ parts.append(("" if thousands == 1 else number_words(thousands) + " ") + "milésimo")
226
+ hundreds, rest = divmod(n, 100)
227
+ tens, unit = divmod(rest, 10)
228
+ for table, index in ((_ORD_HUNDREDS, hundreds), (_ORD_TENS, tens), (_ORD_UNITS, unit)):
229
+ if index:
230
+ parts.append(table[index])
231
+ words = " ".join(parts).split(" ")
232
+ if feminine:
233
+ words = [w[:-1] + "a" if w in _ORDINAL_WORDS else w for w in words]
234
+ return " ".join(words)
 
 
 
 
 
235
 
236
 
237
+ def digits_words(text):
238
+ return " ".join(_UNITS[int(c)] for c in text if c.isdigit())
 
 
 
 
 
 
239
 
240
 
241
+ def decimal_words(integer, fraction, feminine=False):
242
+ """'3', '14' -> "três vírgula quatorze"; '3', '05' -> "três vírgula zero cinco"."""
243
+ whole = number_words(int(integer.replace(".", "")), feminine)
244
+ if not fraction or not fraction.strip("0"):
245
+ return whole # "150,00" -> "cento e cinquenta"
246
+ if len(fraction) > 3 or (fraction[0] == "0" and len(fraction) > 1):
247
+ frac = digits_words(fraction) # "3,05" -> "zero cinco"
248
+ else:
249
+ frac = number_words(int(fraction)) # "3,14" -> "quatorze"
250
+ return f"{whole} vírgula {frac}"
251
+
252
+
253
+ # ---------------------------------------------------------------------------
254
+ # Lexicons
255
+ # ---------------------------------------------------------------------------
256
+
257
+ # English loanwords and brands as Brazilians say them, respelled in ordinary
258
+ # Portuguese spelling (accents mark the stress where the default rules would
259
+ # put it elsewhere). Keys are matched case-insensitively as whole words; a
260
+ # plural "-s" on the key carries over to the respelling ("sites" -> "saites").
261
+ _LOANWORDS_TSV = """
262
+ online onlaine
263
+ tiny táini
264
+ offline oflaine
265
+ bitcoin bitecóin
266
+ blockchain bloquitchêin
267
+ shampoo xampu
268
+ tradeoff treidófe
269
+ trade-off treidófe
270
+ show xou
271
+ mouse mause
272
+ delivery delíveri
273
+ feedback fidibéque
274
+ email imêil
275
+ e-mail imêil
276
+ site saite
277
+ website uebsaite
278
+ web uébe
279
+ app épe
280
+ wifi uaifai
281
+ wi-fi uaifai
282
+ iphone aifone
283
+ ipad aipéde
284
+ youtube iutúbe
285
+ youtuber iutúber
286
+ whatsapp uotsápe
287
+ instagram instagrã
288
+ facebook feicebúque
289
+ twitter tuíter
290
+ tiktok tiquitóque
291
+ google gúgou
292
+ gmail gemêil
293
+ hotmail rótmeil
294
+ outlook autlúque
295
+ yahoo iarrú
296
+ uber úber
297
+ netflix nétiflix
298
+ spotify ispótifai
299
+ amazon ámazon
300
+ microsoft maicrossófte
301
+ apple épou
302
+ samsung sânsungue
303
+ software sóftuer
304
+ hardware rárduer
305
+ download daunlôude
306
+ upload aplôude
307
+ login lóguin
308
+ logout logáute
309
+ link linque
310
+ streaming istrímin
311
+ stream istrime
312
+ streamer istrímer
313
+ startup startápe
314
+ marketing márquetin
315
+ home office rôme ófice
316
+ design dizáine
317
+ designer dizáiner
318
+ notebook nôutibuque
319
+ laptop léptope
320
+ smartphone ismartifone
321
+ smartwatch ismartuótche
322
+ tablet táblete
323
+ podcast pódcaste
324
+ playlist pleilíste
325
+ deadline dédilaine
326
+ freelancer frilâncer
327
+ freela frila
328
+ fast food fést fúde
329
+ shopping xópin
330
+ outdoor autidór
331
+ layout leiáute
332
+ hacker réquer
333
+ crush crãxe
334
+ spoiler ispóiler
335
+ like láique
336
+ story istóri
337
+ stories istóris
338
+ live láive
339
+ game gueime
340
+ gamer guêimer
341
+ videogame videogueime
342
+ nerd nérde
343
+ geek guíque
344
+ rock róque
345
+ pop pópe
346
+ jazz djéz
347
+ blues blus
348
+ funk fanque
349
+ rap répe
350
+ rapper réper
351
+ hip hop ripe rópe
352
+ hip-hop ripe rópe
353
+ selfie sélfie
354
+ hashtag rexitégue
355
+ post pôste
356
+ fake feique
357
+ fake news feique niús
358
+ news niús
359
+ check-in xequín
360
+ checkin xequín
361
+ check-out xecáute
362
+ checkout xecáute
363
+ know-how nourráu
364
+ happy hour répi áuer
365
+ black friday bléque fráidei
366
+ halloween ralouín
367
+ bluetooth blutúfe
368
+ pen drive pen dráive
369
+ pendrive pendráive
370
+ backup becápe
371
+ bug bágue
372
+ debug dibágue
373
+ deploy diplói
374
+ framework freimuórque
375
+ frontend frontiénde
376
+ front-end frontiénde
377
+ backend bequiénde
378
+ back-end bequiénde
379
+ coworking couórquin
380
+ coach coutche
381
+ coaching coutchin
382
+ mindset maindséte
383
+ insight insáite
384
+ networking netuórquin
385
+ brainstorm breinstórme
386
+ briefing brífin
387
+ budget bádjete
388
+ business bíznes
389
+ branding bréndin
390
+ e-commerce icomérce
391
+ ecommerce icomérce
392
+ outlet áutlete
393
+ off ófe
394
+ fitness fítines
395
+ crossfit crósfite
396
+ personal trainer pérsonal trêiner
397
+ trainer trêiner
398
+ skincare isquinquér
399
+ look lúque
400
+ outfit áutfite
401
+ jeans djins
402
+ short xórte
403
+ shorts xórtes
404
+ cropped crópede
405
+ blazer blêizer
406
+ hot dog róte dógue
407
+ cheeseburger xisbúrguer
408
+ milkshake milquexeique
409
+ brownie bráuni
410
+ cupcake cápqueique
411
+ cookie cúqui
412
+ bacon bêicon
413
+ ketchup quétchupe
414
+ drink drinque
415
+ self-service sélfe sérvice
416
+ pet shop péte xópe
417
+ petshop petexópe
418
+ pet péte
419
+ playground pleigráunde
420
+ camping câmpin
421
+ trailer trêiler
422
+ okay oquêi
423
+ ok oquêi
424
+ bye bai
425
+ sorry sóri
426
+ wow uau
427
+ cool cul
428
+ top tópe
429
+ vibe váibe
430
+ match métche
431
+ ranking rânquin
432
+ level lével
433
+ upgrade apigreide
434
+ update apdeite
435
+ reset risséte
436
+ chat xéte
437
+ chatbot xetebóte
438
+ bot bóte
439
+ spam ispãme
440
+ influencer influêncer
441
+ blogger blóguer
442
+ blog blógue
443
+ internet internéte
444
+ touch tátche
445
+ zoom zum
446
+ meet mite
447
+ call cól
448
+ meeting mítin
449
+ follow-up folouápe
450
+ job djóbe
451
+ trainee treiní
452
+ fintech fintéque
453
+ ethereum etérium
454
+ crypto crípto
455
+ token tôquen
456
+ wallet uólete
457
+ trader trêider
458
+ trade treide
459
+ trading trêidin
460
+ big data bigue dêita
461
+ machine learning maxíne lérnin
462
+ cloud cláude
463
+ gadget gádjete
464
+ headset redséte
465
+ headphone redfone
466
+ player plêier
467
+ playstation pleistêixon
468
+ xbox équisbóx
469
+ windows uíndous
470
+ linux línux
471
+ android andróide
472
+ ios ai ó ésse
473
+ macbook mequibúque
474
+ chrome crôume
475
+ firefox fairefóx
476
+ chatgpt xéte gê pê tê
477
+ openai oupen ei ai
478
+ linkedin línquedin
479
+ telegram telegrã
480
+ pinterest pínterest
481
+ reddit rédite
482
+ twitch tuítche
483
+ discord discórde
484
+ kindle quíndou
485
+ wikipedia uiquipédia
486
+ waze uêize
487
+ airbnb érbienbi
488
+ ifood aifúde
489
+ nubank nubanque
490
+ picpay piquepêi
491
+ shopee xopí
492
+ shein xiín
493
+ aliexpress aliesprés
494
+ burger king búrguer quim
495
+ mcdonald's mequidônalds
496
+ mcdonalds mequidônalds
497
+ starbucks istarbáques
498
+ subway sábuei
499
+ nike náique
500
+ disney dísnei
501
+ marvel márvel
502
+ star wars istar uórs
503
+ harry potter rári póter
504
+ new york niu iórque
505
+ los angeles lós ândjeles
506
+ washington uóxinton
507
+ hollywood rólivude
508
+ wall street uól istríte
509
+ big brother bigue bróder
510
+ masterchef máster xéfe
511
+ reality show riáliti xou
512
+ stand-up istendápe
513
+ talk show tóque xou
514
+ fair play fér plêi
515
+ stress istrésse
516
+ lobby lóbi
517
+ merchandising merxandáizin
518
+ showroom xourrum
519
+ spray ispréi
520
+ jet ski djéte isqui
521
+ skate isqueite
522
+ playoff pleiófe
523
+ round ráunde
524
+ cover câver
525
+ hit rite
526
+ single síngou
527
+ remix rimíx
528
+ playback pleibéque
529
+ cosplay cosplêi
530
+ emoji emôji
531
+ print prínte
532
+ bullying búlin
533
+ stalker istólquer
534
+ hater rêiter
535
+ k-pop queipópe
536
+ kpop queipópe
537
+ code côude
538
+ feed fíde
539
+ freezer frízer
540
+ cashback quéxibéque
541
+ call center cól cênter
542
+ webcam uebicã
543
+ drive dráive
544
+ smart ismarte
545
+ e-book ibúque
546
+ ebook ibúque
547
+ chip xípe
548
+ nugget nâguete
549
+ brunch brãnche
550
+ muffin mâfin
551
+ pancake penqueique
552
+ waffle uófou
553
+ donut dônut
554
+ cheesecake xisqueique
555
+ food truck fúde trâque
556
+ drive-thru dráive tru
557
+ petrobras petrobrás
558
+ eletrobras eletrobrás
559
+ detran detrã
560
+ procon procôm
561
+ enem enêm
562
+ selic selíque
563
+ samu sâmu
564
+ unicamp unicâmpi
565
+ unesp unéspi
566
+ fuvest fuvéste
567
+ sebrae sebráe
568
+ senac senáque
569
+ anatel anatél
570
+ aneel aneél
571
+ embratel embratél
572
+ bovespa bovéspa
573
+ infraero infraéro
574
+ covid côvide
575
+ on-line onlaine
576
+ kubernetes cubernétis
577
+ docker dóquer
578
+ overfitting overfítin
579
+ underfitting anderfítin
580
+ database dêitabeice
581
+ dataset dêitasséte
582
+ data center dêita cênter
583
+ data science dêita sáience
584
+ data lake dêita lêique
585
+ deep learning dípe lérnin
586
+ fine-tuning fáine túnin
587
+ fine tuning fáine túnin
588
+ pipeline paipláine
589
+ python páiton
590
+ javascript javascrípte
591
+ typescript taipiscrípte
592
+ github guíte râbe
593
+ gitlab guíte lébe
594
+ git guíte
595
+ commit comíte
596
+ merge mérgi
597
+ pull request pul riquéste
598
+ branch bréntche
599
+ dev déve
600
+ devops devópis
601
+ full stack ful istéque
602
+ fullstack ful istéque
603
+ full-stack ful istéque
604
+ script iscrípte
605
+ prompt prômpite
606
+ plugin plúguin
607
+ widget uídjete
608
+ driver dráiver
609
+ firmware fírmuer
610
+ malware máluer
611
+ spyware ispáiuer
612
+ ransomware rânsomuer
613
+ phishing fíxin
614
+ firewall fáieruól
615
+ proxy próquici
616
+ server sérver
617
+ host rôste
618
+ hosting rôstin
619
+ cache quéxe
620
+ cluster clâster
621
+ container contêiner
622
+ endpoint endipóinte
623
+ payload peilôude
624
+ query quéri
625
+ runtime rantáime
626
+ stack istéque
627
+ thread tréde
628
+ array arrêi
629
+ string istríngue
630
+ loop lúpe
631
+ bit bíte
632
+ byte báite
633
+ kilobyte quilobáite
634
+ megabyte megabáite
635
+ gigabyte gigabáite
636
+ terabyte terabáite
637
+ megabit megabíte
638
+ gigabit gigabíte
639
+ pixel píquicel
640
+ transformer transfórmer
641
+ embedding embédin
642
+ benchmark bêntchimarque
643
+ dashboard déxibórde
644
+ scrum iscrâm
645
+ sprint isprínte
646
+ kanban cânban
647
+ roadmap rôudemépe
648
+ backlog béquelógue
649
+ workflow uórqueflou
650
+ onboarding onbórdin
651
+ feature fítcher
652
+ release rilíce
653
+ rollback rólbéque
654
+ patch pétche
655
+ password pássuorde
656
+ username iúzerneime
657
+ browser bráuzer
658
+ touchscreen tátchiscrín
659
+ router ráuter
660
+ vlog vlógue
661
+ unboxing anbóquicin
662
+ review riviú
663
+ gameplay gueimeplêi
664
+ lag légue
665
+ ping píngue
666
+ noob núbe
667
+ skin isquín
668
+ steam istím
669
+ desktop déskitópe
670
+ wireless uáierles
671
+ power bank páuer bénque
672
+ screenshot iscrínxóte
673
+ scanner iscâner
674
+ inbox ínbox
675
+ downgrade dáungreide
676
+ restart ristárte
677
+ setup setápe
678
+ crash créxe
679
+ zap zápe
680
+ joystick djóistique
681
+ arcade arquêide
682
+ mousepad máusepéde
683
+ display displêi
684
+ blu-ray blu rêi
685
+ bluray blu rêi
686
+ flash fléxe
687
+ log lógue
688
+ kernel kérnel
689
+ unicode iunicôude
690
+ assembly assémbli
691
+ debian débian
692
+ saas sás
693
+ mint mínte
694
+ signal síguinal
695
+ copilot copáilote
696
+ gemini djémini
697
+ claude clôde
698
+ anthropic antrópique
699
+ deepseek dípe síque
700
+ midjourney mídi djârni
701
+ nvidia envídia
702
+ powerpoint páuer póinte
703
+ office ófice
704
+ word uórde
705
+ photoshop fotoxópe
706
+ teams tíns
707
+ slack isléque
708
+ notion nôuxon
709
+ skype iscáipe
710
+ tinder tínder
711
+ snapchat isnépixéte
712
+ spacex ispêicex
713
+ oracle óracou
714
+ adobe adôbi
715
+ paypal peipáu
716
+ stripe istráipe
717
+ rappi rápi
718
+ booking búquin
719
+ tripadvisor tripadváizor
720
+ prime video práime vídeo
721
+ deezer dízer
722
+ soundcloud sáunde cláude
723
+ walmart uólmarte
724
+ ikea iquéia
725
+ reebok ribóque
726
+ gucci gútchi
727
+ louis vuitton luí vitôn
728
+ rolex rólex
729
+ porsche pórche
730
+ audi áudi
731
+ volkswagen volquisváguen
732
+ ford fórde
733
+ chevrolet chevrolé
734
+ honda rônda
735
+ toyota toióta
736
+ hyundai riundái
737
+ nissan níssan
738
+ jeep djípe
739
+ renault renô
740
+ peugeot pejô
741
+ citroën citroén
742
+ citroen citroén
743
+ mitsubishi mitsubíxi
744
+ lamborghini lamborguíni
745
+ fiat fiáte
746
+ pepsi pépsi
747
+ heineken ráineken
748
+ budweiser budváizer
749
+ nutella nutéla
750
+ oreo ório
751
+ pizza hut pítsa râte
752
+ domino's dóminos
753
+ outback autibéque
754
+ bob's bóbis
755
+ sony sôni
756
+ philips fílips
757
+ dell déu
758
+ acer êicer
759
+ xiaomi xiaomí
760
+ huawei ruauêi
761
+ nokia nóquia
762
+ fortnite fórtenaite
763
+ minecraft máinecrafte
764
+ roblox róblox
765
+ valorant válorante
766
+ free fire fri fáier
767
+ league of legends líg ofe légendes
768
+ counter-strike cáunter istráique
769
+ counter strike cáunter istráique
770
+ mastercard máster cárde
771
+ american express américan esprés
772
+ vimeo vímeo
773
+ bing bíngue
774
+ yandex iândex
775
+ trump trâmpi
776
+ biden báiden
777
+ elon ílon
778
+ musk mâsque
779
+ bill gates bíu gueites
780
+ steve jobs istívi djóbis
781
+ zuckerberg zúquerbergue
782
+ shakespeare xéquispir
783
+ beatles bítous
784
+ michael máicou
785
+ jackson djéquisson
786
+ john djón
787
+ james djêimes
788
+ george djórdji
789
+ justin djâstin
790
+ bieber bíber
791
+ kevin quévin
792
+ kelly quéli
793
+ william uílian
794
+ willian uílian
795
+ wesley uésli
796
+ wilson uílson
797
+ wagner vágner
798
+ chris crís
799
+ donald dônald
800
+ tony tôni
801
+ henry rênri
802
+ peter píter
803
+ robert róberte
804
+ oliver óliver
805
+ taylor swift têilor suífte
806
+ beyoncé bionsê
807
+ beyonce bionsê
808
+ madonna madôna
809
+ rihanna riána
810
+ lady gaga lêidi gága
811
+ drake drêique
812
+ eminem êminem
813
+ buffett bâfete
814
+ parkinson párquinson
815
+ eiffel êifel
816
+ seattle siátou
817
+ tennessee tenessí
818
+ las vegas lás végas
819
+ vegas végas
820
+ miami maiâmi
821
+ boston bóston
822
+ texas téquissas
823
+ manhattan manréten
824
+ brooklyn brúclin
825
+ silicon valley sílicon váli
826
+ times square táimis iscuér
827
+ taiwan taiuã
828
+ york iórque
829
+ stablecoin istêibou cóin
830
+ altcoin áute cóin
831
+ dogecoin dógui cóin
832
+ staking istêiquin
833
+ day trade dêi treide
834
+ day trader dêi trêider
835
+ swing trade suíngue treide
836
+ hedge rédji
837
+ hedge fund rédji fânde
838
+ spread ispréde
839
+ stop loss istópe lós
840
+ private equity práivete écuiti
841
+ venture capital vêntcher cápital
842
+ valuation valuêixon
843
+ equity écuiti
844
+ cash quéxe
845
+ cash flow quéxe flôu
846
+ payback peibéque
847
+ breakeven breiquíven
848
+ funding fândin
849
+ compliance complâience
850
+ rating rêitin
851
+ holding rôldin
852
+ leasing lízin
853
+ franchising frenxáizin
854
+ factoring fáctorin
855
+ dumping dâmpin
856
+ lockdown loquedáun
857
+ headhunter réde rânter
858
+ board bórde
859
+ stakeholder isteiquirrôlder
860
+ performance perfórmance
861
+ telemarketing telemárquetin
862
+ marketplace márquetepleice
863
+ dropshipping dropxípin
864
+ lead líde
865
+ target tárguete
866
+ pitch pítche
867
+ burnout bârnáute
868
+ commodity comóditi
869
+ commodities comóditis
870
+ outsourcing autsórcin
871
+ offshore ofxór
872
+ overbooking ôuverbúquin
873
+ cyber monday sáiber mândei
874
+ voucher váucher
875
+ manager mânadjer
876
+ yuan iuã
877
+ impeachment impítchimente
878
+ bike báique
879
+ e-bike ibáique
880
+ surf sârfe
881
+ windsurf uínde sârfe
882
+ kitesurf cáite sârfe
883
+ wakeboard uêique bórde
884
+ snowboard isnôu bórde
885
+ snowboarder isnôu bórder
886
+ snowboarding isnôu bórdin
887
+ trekking trékin
888
+ rafting ráftin
889
+ parkour parcúr
890
+ jiu-jitsu jiujítsu
891
+ jiu jitsu jiujítsu
892
+ pit stop píte istópe
893
+ pole position pôu posíxon
894
+ rugby rúgbi
895
+ golf gólfe
896
+ frisbee frísbi
897
+ paintball pêintból
898
+ sport ispórte
899
+ spinning ispínin
900
+ personal pérsonal
901
+ fit fíte
902
+ whey uêi
903
+ whey protein uêi prôutin
904
+ low carb lôu cárbe
905
+ vegan végan
906
+ peeling pílin
907
+ piercing pírcin
908
+ tattoo tatu
909
+ yoga ióga
910
+ spa ispá
911
+ legging léguin
912
+ blush blâxe
913
+ gloss glós
914
+ primer práimer
915
+ oversized ôuversáized
916
+ fashion féxon
917
+ plus size plâs sáize
918
+ plus plâs
919
+ make mêique
920
+ air fryer ér fráier
921
+ airfryer ér fráier
922
+ closet clósete
923
+ loft lófte
924
+ flat fléte
925
+ duplex dúplex
926
+ triplex tríplex
927
+ hall ról
928
+ home theater rôme tíater
929
+ home care rôme quér
930
+ deck déque
931
+ resort rizórte
932
+ hostel rôstel
933
+ tour túr
934
+ city tour síti túr
935
+ city síti
936
+ jet lag djéte légue
937
+ free shop fri xópe
938
+ duty free diúti fri
939
+ jet-ski djéte isqui
940
+ cooler cúler
941
+ blackout blecáute
942
+ laser lêizer
943
+ scooter iscúter
944
+ pickup picápe
945
+ pick-up picápe
946
+ hatch rétchi
947
+ diesel dísel
948
+ airbag érbégue
949
+ motorhome motor rôme
950
+ motocross motocrós
951
+ minivan minivã
952
+ test drive tést dráive
953
+ check-up xecápe
954
+ checkup xecápe
955
+ stand istênde
956
+ stand-by istendibái
957
+ standby istendibái
958
+ shop xópe
959
+ barber shop bárber xópe
960
+ store istór
961
+ play plêi
962
+ stop istópe
963
+ pop-up popápe
964
+ popup popápe
965
+ motoboy motobói
966
+ office boy ófice bói
967
+ cowboy caubói
968
+ playboy pleibói
969
+ boy bói
970
+ baby bêibi
971
+ baby shower bêibi xáuer
972
+ teen tín
973
+ kids quídis
974
+ miss mís
975
+ love lâve
976
+ gay guêi
977
+ sexy séqui
978
+ drag dréque
979
+ drag queen dréque quín
980
+ nude núde
981
+ free fri
982
+ full ful
983
+ full time ful táime
984
+ part-time párti táime
985
+ timing táimin
986
+ boss bós
987
+ light láite
988
+ lite láite
989
+ diet dáiete
990
+ premium prêmium
991
+ vintage víntidji
992
+ dealer díler
993
+ barman bármen
994
+ bartender bartênder
995
+ close clôuse
996
+ kit quíte
997
+ status istátus
998
+ banner bâner
999
+ boom bum
1000
+ tag tégue
1001
+ the dâ
1002
+ voice vóice
1003
+ music miúzique
1004
+ street istríte
1005
+ studio istúdio
1006
+ graffiti grafíti
1007
+ hipster rípster
1008
+ indie índi
1009
+ junior júnior
1010
+ matrix mêitrix
1011
+ maps mépes
1012
+ walkman uóquimen
1013
+ pub pâbe
1014
+ cheerleader tchirlíder
1015
+ black bléque
1016
+ power páuer
1017
+ green card grín cárde
1018
+ big tech bigue téque
1019
+ tech téque
1020
+ center cênter
1021
+ shopping center xópin cênter
1022
+ self service sélfe sérvice
1023
+ fast-food fést fúde
1024
+ milk-shake milquexeique
1025
+ hot-dog róte dógue
1026
+ ferry férri
1027
+ remake rimêique
1028
+ reboot ribúte
1029
+ sitcom sítcon
1030
+ blockbuster blóquebâster
1031
+ best-seller bést séler
1032
+ best seller bést séler
1033
+ heavy metal révi métau
1034
+ punk pânque
1035
+ reggae régue
1036
+ soul sôu
1037
+ gospel góspel
1038
+ trap trépe
1039
+ folk fóuque
1040
+ country cântri
1041
+ backstage béquistêidji
1042
+ fandom féndom
1043
+ hype ráipe
1044
+ cringe crínji
1045
+ flop flópe
1046
+ shippar xipár
1047
+ stalkear istolquiár
1048
+ hackear requiár
1049
+ hackeou requiôu
1050
+ hackeado requiádo
1051
+ hackeada requiáda
1052
+ hackearam requiáram
1053
+ hackeando requiândo
1054
+ hacking réquin
1055
+ tweet tuíte
1056
+ retweet rituíte
1057
+ reels ríus
1058
+ trend trénde
1059
+ trending tréndin
1060
+ gif guífe
1061
+ mood múde
1062
+ random rândom
1063
+ bad béde
1064
+ chill tchíl
1065
+ feat fíte
1066
+ beat bíte
1067
+ groove grúve
1068
+ swing suíngue
1069
+ chef xéfe
1070
+ buffet bufê
1071
+ gourmet gurmê
1072
+ reveillon reveiôn
1073
+ réveillon reveiôn
1074
+ champagne xampânhe
1075
+ chantilly xantilí
1076
+ croissant croassã
1077
+ fondue fondí
1078
+ petit gateau petí gatô
1079
+ mousse músse
1080
+ bouquet buquê
1081
+ boutique butíque
1082
+ lingerie lanjerrí
1083
+ necessaire necessér
1084
+ nécessaire necessér
1085
+ déjà vu dejavú
1086
+ deja vu dejavú
1087
+ ballet balé
1088
+ cappuccino capuchíno
1089
+ espresso esprésso
1090
+ macchiato maquiáto
1091
+ latte láte
1092
+ smoothie ismúdi
1093
+ whisky uísque
1094
+ whiskey uísque
1095
+ gin djím
1096
+ chopp xópe
1097
+ cheddar xédar
1098
+ sushi súxi
1099
+ sashimi saxími
1100
+ temaki temáqui
1101
+ yakisoba iaquissóba
1102
+ ramen râmen
1103
+ kebab quebábe
1104
+ nachos nátchos
1105
+ pickles píquous
1106
+ snack isnéque
1107
+ shoyu xôiu
1108
+ wasabi uassábi
1109
+ gyoza guiôza
1110
+ poke pôque
1111
+ bowl bôul
1112
+ cream cheese crím xís
1113
+ catchup quétchupe
1114
+ barbecue barbequiú
1115
+ roast beef rôste bífe
1116
+ wrap répe
1117
+ bagel bêiguel
1118
+ panini paníni
1119
+ risotto rizóto
1120
+ spaghetti espaguéte
1121
+ gnocchi nhóqui
1122
+ bruschetta brusquéta
1123
+ tiramisu tiramissú
1124
+ prosecco proséco
1125
+ mozzarella mussaréla
1126
+ curry cúrri
1127
+ hamburguer hambúrguer
1128
+ funghi fúngui
1129
+ coaches coutches
1130
+ matches métches
1131
+ crushes crãxes
1132
+ flashes fléxes
1133
+ crashes créxes
1134
+ patches pétches
1135
+ pitches pítches
1136
+ branches bréntches
1137
+ brunches brãnches
1138
+ hatches rétchis
1139
+ smartwatches ismartuótches
1140
+ remixes rimíxes
1141
+ inboxes ínboxes
1142
+ xboxes équisbóxes
1143
+ businesses bíznesses
1144
+ bosses bósses
1145
+ misses mísses
1146
+ touches tátches
1147
+ sets sétes
1148
+ set point séte póinte
1149
+ o primeiro set o primeiro séte
1150
+ no primeiro set no primeiro séte
1151
+ do primeiro set do primeiro séte
1152
+ num date num deite
1153
+ meu date meu deite
1154
+ nesse date nesse deite
1155
+ no date no deite
1156
+ do date do deite
1157
+ no primeiro date no primeiro deite
1158
+ meu primeiro date meu primeiro deite
1159
+ nosso primeiro date nosso primeiro deite
1160
+ super nice super náice
1161
+ tão nice tão náice
1162
+ memória ram memória râmi
1163
+ home do site rôme do saite
1164
+ home page rôme pêidje
1165
+ homepage rômepêidje
1166
+ amazon prime ámazon práime
1167
+ no segundo set no segundo séte
1168
+ no terceiro set no terceiro séte
1169
+ no quarto set no quarto séte
1170
+ no quinto set no quinto séte
1171
+ no último set no último séte
1172
+ é bem nice é bem náice
1173
+ marcou um date marcou um deite
1174
+ marquei um date marquei um deite
1175
+ marcamos um date marcamos um deite
1176
+ marcar um date marcar um deite
1177
+ tive um date tive um deite
1178
+ teve um date teve um deite
1179
+ o primeiro date foi o primeiro deite foi
1180
+ trade- off treidófe
1181
+ trade- ófe treidófe
1182
+ trade - ófe treidófe
1183
+ amazon prime video ámazon práime vídeo
1184
+ amazon prime pelo ámazon prime pelo
1185
+ amazon prime pela ámazon prime pela
1186
+ amazon prime por ámazon prime por
1187
+ prime time práime táime
1188
+ georges jórjes
1189
+ james rodríguez rámes rodrígues
1190
+ james rodriguez rámes rodrígues
1191
+ post mortem póste mórtem
1192
+ non plus ultra non plús últra
1193
+ blushes blâxes
1194
+ stresses istrésses
1195
+ twitches tuítches
1196
+ rolexes rólexes
1197
+ duplexes dúplexes
1198
+ triplexes tríplexes
1199
+ statuses istátus
1200
+ glosses glósses
1201
+ stop losses istópe lósses
1202
+ queries quéris
1203
+ proxies próquicis
1204
+ lobbies lóbis
1205
+ whiskies uísques
1206
+ deliveries delíveris
1207
+ barmen bármen
1208
+ hobby róbi
1209
+ hobbies róbis
1210
+ """
1211
+
1212
+ # Acronyms, matched case-sensitively in upper case (a lower-case "s" plural is
1213
+ # allowed: "ONGs", "CDs"). Unlisted acronyms are spelled letter by letter, or
1214
+ # read as a word when Portuguese can pronounce them (NASA, FIFA).
1215
+ _ACRONYMS_TSV = """
1216
+ CPF cê pê éfe
1217
+ CEP cépe
1218
+ RG érre gê
1219
+ CNH cê ene agá
1220
+ CNPJ cê ene pê jota
1221
+ INSS i ene ésse ésse
1222
+ FGTS éfe gê tê ésse
1223
+ SUS sus
1224
+ PIX pix
1225
+ PIB píbi
1226
+ IBGE i bê gê é
1227
+ ONU ônu
1228
+ ONG ôngue
1229
+ ENEM enêm
1230
+ USP úspi
1231
+ UNICAMP unicâmpi
1232
+ PUC púqui
1233
+ MEC méqui
1234
+ UFRJ u éfe érre jota
1235
+ UFMG u éfe eme gê
1236
+ UNESP unéspi
1237
+ FGV éfe gê vê
1238
+ STF ésse tê éfe
1239
+ STJ ésse tê jota
1240
+ TSE tê ésse é
1241
+ TCU tê cê u
1242
+ PF pê éfe
1243
+ PM pê eme
1244
+ PRF pê érre éfe
1245
+ OAB ó á bê
1246
+ CBF cê bê éfe
1247
+ EUA estados unidos
1248
+ UE união europeia
1249
+ TV tê vê
1250
+ DVD dê vê dê
1251
+ CD cê dê
1252
+ PC pê cê
1253
+ HD agá dê
1254
+ SSD ésse ésse dê
1255
+ USB u ésse bê
1256
+ PDF pê dê éfe
1257
+ GPS gê pê ésse
1258
+ LED léde
1259
+ DNA dê ene á
1260
+ HIV agá i vê
1261
+ AIDS áidis
1262
+ COVID côvide
1263
+ UTI u tê i
1264
+ SAMU sâmu
1265
+ SESC sésque
1266
+ SENAI senai
1267
+ SENAC senáque
1268
+ SEBRAE sebráe
1269
+ IPVA i pê vê á
1270
+ IPTU i pê tê u
1271
+ IR i érre
1272
+ IOF i ó éfe
1273
+ ICMS i cê eme ésse
1274
+ MEI mei
1275
+ CLT cê éle tê
1276
+ PJ pê jota
1277
+ RH érre agá
1278
+ TI tê i
1279
+ IA i á
1280
+ CEO ci i ôu
1281
+ API á pê i
1282
+ URL u érre éle
1283
+ HTML agá tê eme éle
1284
+ SQL ésse quê éle
1285
+ RAM râmi
1286
+ CPU cê pê u
1287
+ GPU gê pê u
1288
+ HDMI agá dê eme i
1289
+ QR quê érre
1290
+ SMS ésse eme ésse
1291
+ LGPD éle gê pê dê
1292
+ FAQ éfe á quê
1293
+ VIP vípe
1294
+ OK oquêi
1295
+ RS érre ésse
1296
+ SP ésse pê
1297
+ RJ érre jota
1298
+ MG eme gê
1299
+ DF dê éfe
1300
+ BR bê érre
1301
+ NBA ene bê á
1302
+ UFC u éfe cê
1303
+ MMA eme eme á
1304
+ BMW bê eme dáblio
1305
+ HP agá pê
1306
+ IBM i bê eme
1307
+ LG éle gê
1308
+ MBA eme bê á
1309
+ PHD pê agá dê
1310
+ TCC tê cê cê
1311
+ FUVEST fuvéste
1312
+ OMS ó eme ésse
1313
+ G20 gê vinte
1314
+ MPB eme pê bê
1315
+ FM éfe eme
1316
+ ID i dê
1317
+ OTAN otã
1318
+ UNICEF unicéfe
1319
+ UNESCO unésco
1320
+ ANVISA anvisa
1321
+ ANATEL anatél
1322
+ DETRAN detrã
1323
+ PROCON procôm
1324
+ IBAMA ibama
1325
+ FUNAI funai
1326
+ EMBRAPA embrapa
1327
+ PETROBRAS petrobrás
1328
+ BNDES bê ene dê é ésse
1329
+ BC bê cê
1330
+ IPCA i pê cê á
1331
+ SELIC selíque
1332
+ CDI cê dê i
1333
+ CDB cê dê bê
1334
+ NFT ene éfe tê
1335
+ CPI cê pê i
1336
+ PEC péque
1337
+ DJ didjêi
1338
+ MP3 eme pê três
1339
+ MP4 eme pê quatro
1340
+ OFF ófe
1341
+ """
1342
+
1343
+ _ABBREVIATIONS = (
1344
+ # (pattern, reading); patterns are case-insensitive and end at a word edge.
1345
+ (r"\bsras?\.", lambda m: "senhoras" if m.group(0).lower().startswith("sras") else "senhora"),
1346
+ (r"\bsrs?\.", lambda m: "senhores" if m.group(0).lower().startswith("srs") else "senhor"),
1347
+ (r"\bsrta\.", "senhorita"),
1348
+ (r"\bdras?\.", lambda m: "doutoras" if m.group(0).lower().startswith("dras") else "doutora"),
1349
+ (r"\bdrs?\.", lambda m: "doutores" if m.group(0).lower().startswith("drs") else "doutor"),
1350
+ (r"\bprofa\.", "professora"),
1351
+ (r"\bprof\.", "professor"),
1352
+ (r"\bav\.", "avenida"),
1353
+ (r"\bal\.(?=\s[A-ZÀ-Ú])", "alameda"),
1354
+ (r"\bpça\.", "praça"),
1355
+ (r"\bn[º°]\s?\.?|\bn\.\s?[º°]|\bnúm\.", "número "),
1356
+ (r"\btel\.", "telefone"),
1357
+ (r"\bcel\.", "celular"),
1358
+ (r"\betc\b\.(?=\s*$|\s+[A-ZÀ-Ú])", "etcétera."),
1359
+ (r"\betc\b\.?", "etcétera"),
1360
+ (r"\bséc\.", "século"),
1361
+ (r"(?-i:\bD)\.(?=\s(?-i:[A-ZÀ-Ú]))", "dom"),
1362
+ (r"\bp\.\s?ex\.", "por exemplo"),
1363
+ (r"\bvs\.", "versus"),
1364
+ (r"\baprox\.", "aproximadamente"),
1365
+ (r"\bobs\.", "observação"),
1366
+ (r"\bpágs?\.", lambda m: "páginas" if m.group(0).lower().startswith("págs") else "página"),
1367
+ (r"\bpg\.", "página"),
1368
+ (r"\bcap\.", "capítulo"),
1369
+ (r"\bart\.", "artigo"),
1370
+ (r"\bvol\.", "volume"),
1371
+ (r"\bltda\b\.?", "limitada"),
1372
+ (r"\bcia\.", "companhia"),
1373
+ (r"\bdepto\.", "departamento"),
1374
+ (r"\ba\.\s?c\.", "antes de cristo"),
1375
+ (r"\bd\.\s?c\.", "depois de cristo"),
1376
+ (r"\bsto\.", "santo"),
1377
+ (r"\bsta\.", "santa"),
1378
+ (r"\bexmo\.", "excelentíssimo"),
1379
+ (r"\bexma\.", "excelentíssima"),
1380
+ (r"\bfeat\.", "fíte"),
1381
+ (r"\bc/(?=\s)", "com"),
1382
+ (r"\bs/(?=\s)", "sem"),
1383
+ (r"\bp/(?=\s)", "para"),
1384
+ )
1385
+
1386
+ # Chat abbreviations, matched as whole lower-case words.
1387
+ _SLANG = {
1388
+ "vc": "você", "vcs": "vocês", "tb": "também", "tbm": "também", "pq": "porque",
1389
+ "q": "que", "blz": "beleza", "vlw": "valeu", "obg": "obrigado", "obgd": "obrigado",
1390
+ "msg": "mensagem", "hj": "hoje", "td": "tudo", "tds": "todos", "cmg": "comigo",
1391
+ "ctz": "certeza", "mt": "muito", "mto": "muito", "mts": "muitos", "qdo": "quando",
1392
+ "qnd": "quando", "dps": "depois", "agr": "agora", "fds": "fim de semana",
1393
+ "pfv": "por favor", "pfvr": "por favor", "sdd": "saudade", "sdds": "saudades",
1394
+ "bjs": "beijos", "bj": "beijo", "abs": "abraços", "kd": "cadê", "tmj": "tamo junto",
1395
+ "add": "adicionar", "aff": "afe", "rs": "risos", "rsrs": "risos", "rsrsrs": "risos",
1396
+ }
1397
+
1398
+ _LETTER_NAMES = {
1399
+ "a": "á", "b": "bê", "c": "cê", "d": "dê", "e": "é", "f": "éfe", "g": "gê", "h": "agá",
1400
+ "i": "i", "j": "jota", "k": "cá", "l": "éle", "m": "eme", "n": "ene", "o": "ó", "p": "pê",
1401
+ "q": "quê", "r": "érre", "s": "ésse", "t": "tê", "u": "u", "v": "vê", "w": "dáblio",
1402
+ "x": "xis", "y": "ípsilon", "z": "zê",
1403
+ }
1404
+
1405
+
1406
+ def _read_tsv(source):
1407
+ table = {}
1408
+ for line in source.strip().splitlines():
1409
+ key, value = line.split("\t")
1410
+ table[key] = value
1411
+ return table
1412
+
1413
+
1414
+ LOANWORDS = {k.lower(): v for k, v in _read_tsv(_LOANWORDS_TSV).items()}
1415
+ ACRONYMS = _read_tsv(_ACRONYMS_TSV)
1416
+ _LOANWORD_PARTS = frozenset(word for key in LOANWORDS for word in key.split())
1417
+
1418
+ # Nouns that make a number feminine ("duas horas", "duzentas pessoas"); other
1419
+ # nouns ending in -a are feminine too unless listed in _MASCULINE_A.
1420
+ _FEMININE_NOUNS = frozenset("""
1421
+ vez vezes mulher mulheres mãe mães colher colheres flor flores cor cores noite noites
1422
+ tarde tardes parte partes classe classes fase fases frase frases base bases chave chaves
1423
+ rede redes série séries espécie espécies fonte fontes lei leis mão mãos nuvem nuvens
1424
+ ordem ordens imagem imagens viagem viagens mensagem mensagens garagem garagens
1425
+ passagem passagens vantagem vantagens margem margens origem origens dor dores
1426
+ gente pele peles neve febre sede sedes torre torres ponte pontes morte mortes
1427
+ sorte arte artes face faces fé paz luz luzes voz vozes cruz cruzes vagem
1428
+ libra libras gema gemas bala balas unidade unidades cidade cidades semana semanas
1429
+ árvore árvores foto fotos moto motos questão questões região regiões razão razões semente sementes
1430
+ raiz raízes grade grades tribo tribos parede paredes rede redes neve fome noção
1431
+ """.split())
1432
+ _MASCULINE_A = frozenset("""
1433
+ dia dias problema problemas sistema sistemas tema temas programa programas mapa mapas
1434
+ clima climas idioma idiomas planeta planetas cometa cometas poeta poetas telefonema
1435
+ dilema dilemas esquema esquemas drama dramas diploma diplomas fantasma fantasmas
1436
+ sofá sofás pijama pijamas cinema cinemas grama gramas quilograma quilogramas
1437
+ miligrama miligramas aroma aromas delta alfa beta gama pirata piratas guarda guardas
1438
+ atleta atletas motorista motoristas jornalista jornalistas artista artistas dentista
1439
+ dentistas policial policiais papa papas profeta profetas monarca monarcas diadema
1440
+ teorema teoremas trema emblema emblemas enigma enigmas paradigma paradigmas poema poemas
1441
+ telefonemas coração corações
1442
+ """.split())
1443
+ _FEMININE_ENDINGS = ("ção", "ções", "são", "sões", "dade", "dades", "gem", "gens", "ice", "ices",
1444
+ "eza", "ezas", "ura", "uras", "ância", "âncias", "ência", "ências", "ise", "ises",
1445
+ "tude", "tudes", "triz", "trizes")
1446
+
1447
+
1448
+ def _is_feminine(word):
1449
+ word = word.lower()
1450
+ if word in _FEMININE_NOUNS:
1451
+ return True
1452
+ if word in _MASCULINE_A:
1453
+ return False
1454
+ if word.endswith(_FEMININE_ENDINGS):
1455
+ return True
1456
+ return word.endswith(("a", "as", "ã", "ãs"))
1457
 
1458
 
1459
  # ---------------------------------------------------------------------------
1460
+ # Text normalisation: what is written -> what is said
1461
  # ---------------------------------------------------------------------------
1462
 
1463
+ _NUMBER = r"\d{1,3}(?:\.\d{3})+|\d+"
1464
+ _UPPER = "A-ZÀÁÂÃÇÉÊÍÓÔÕÚÜ"
1465
+ _LOWER = "a-zàáâãçéêíóôõúü"
1466
+
1467
+ _ROMAN = re.compile(r"\b(?=[MDCLXVI])M{0,3}(?:CM|CD|D?C{0,3})(?:XC|XL|L?X{0,3})(?:IX|IV|V?I{0,3})\b")
1468
+ _ROMAN_VALUES = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000}
1469
+ _ROMAN_CARDINAL_CONTEXT = frozenset(("século", "séculos", "capítulo", "capítulos", "volume", "parte",
1470
+ "ato", "livro", "tomo", "fase", "título", "anexo", "nível",
1471
+ "classe", "seção", "bloco", "módulo", "temporada", "edição"))
1472
+ _ROMAN_ARTICLE_CONTEXT = frozenset(("artigo", "inciso", "parágrafo"))
1473
+ _QUEEN_NAMES = frozenset(("isabel", "elizabeth", "elisabete", "maria", "vitória", "catarina", "cristina", "leonor",
1474
+ "beatriz", "joana", "teresa", "carlota", "ana", "margarida"))
1475
+ _REGNAL_NAMES = _QUEEN_NAMES | frozenset("""
1476
+ pedro joão paulo bento pio leão luís luiz henrique carlos elizabeth elisabete isabel fernando
1477
+ felipe filipe afonso manuel manoel jorge eduardo guilherme napoleão ricardo gregório inocêncio
1478
+ clemente urbano alexandre constantino frederico francisco josé maria sisto nicolau bonifácio
1479
+ """.split())
1480
+
1481
+ _MONEY = re.compile(r"(?<![\w$])([-−])?\s?(R\$|US\$|U\$|€|£|\$)\s?([-−])?(" + _NUMBER + r")(?:,(\d{1,2}))?(?![\d.,]\d)"
1482
+ r"(?:\s?(mil|milhão|milhao|milhões|milhoes|mi|bilhão|bilhao|bilhões|bilhoes|bi|tri|trilhão|trilhões)\b)?",
1483
+ re.IGNORECASE)
1484
+ _CURRENCIES = {"r$": ("real", "reais", False), "us$": ("dólar", "dólares", False),
1485
+ "u$": ("dólar", "dólares", False), "$": ("dólar", "dólares", False),
1486
+ "€": ("euro", "euros", False), "£": ("libra", "libras", True)}
1487
+ _DATE_FULL = re.compile(r"\b(\d{1,2})[/.](\d{1,2})[/.](\d{4}|\d{2})\b")
1488
+ _DATE_ISO = re.compile(r"\b(\d{4})-(\d{1,2})-(\d{1,2})\b")
1489
+ _DATE_MONTH_YEAR = re.compile(r"(?<![\d/])(\d{1,2})/(\d{4})\b")
1490
+ _DATE_PARTIAL = re.compile(r"(?<![\d/.,])(\d{1,2})/(\d{1,2})(?![\d/]|,\d)")
1491
+ _FIRST_OF = re.compile(r"\b(?:1|1º|1°)(?=\s+de\s+(?:" + "|".join(_MONTHS) + r")\b)", re.IGNORECASE)
1492
+ _DATE_CONTEXT = frozenset(("dia", "dias", "em", "até", "desde", "no", "entre", "partir", "data", "datas", "vencimento", "prazo"))
1493
+ _TIME_HMS = re.compile(r"\b(\d{1,2}):(\d{2}):(\d{2})\b")
1494
+ _TIME_HM = re.compile(r"\b(\d{1,2}):(\d{2})(?:\s?(?:h|hs|hrs)\b)?")
1495
+ _CLOCK = re.compile(r"\b(\d{1,2})\s?h\s?(\d{2})(?:\s?min)?\b", re.IGNORECASE)
1496
+ _HOURS = re.compile(r"\b(\d{1,2})\s?(?:h|hs|hrs|hr)(?![\w²³])", re.IGNORECASE)
1497
+ _ORDINAL_SIGN = re.compile(r"\b(\d{1,3}(?:\.\d{3})+|\d{1,4})\s?\.?\s?([ºª])(s?)")
1498
+ _NUMBER_SIGN = re.compile(r"\b[nN]\s?\.?\s?[º°]\s?\.?\s?(?=\d)")
1499
+ _ORDINAL_ASCII = re.compile(r"\b(\d{1,3})(o|a|os|as)\b")
1500
+ _ORDINAL_DEGREE = re.compile(r"\b(\d{1,3})\s?°(?=\s+(?:lugar|andar|ano|anos|dia|turno|colocado|colocada|série|período|"
1501
+ r"semestre|bimestre|trimestre|tempo|filho|filha|neto|aniversário|encontro|capítulo|"
1502
+ r"volume|mandato|batalhão|distrito|grau|time|vez|edição|round|jogo|gol)\b)")
1503
+ _PERCENT = re.compile(r"(?<![\w,.])([-−])?(" + _NUMBER + r")(?:,(\d+))?\s?%")
1504
+ _DEGREES = re.compile(r"(?<![\w,.])([-−])?(" + _NUMBER + r")(?:,(\d+))?\s?°\s?([CF])?(?![\w])")
1505
+ _PHONE = re.compile(r"(\+\s?55\s?)?\(\s?(\d{2})\s?\)\s?(9\s?\d{4}|\d{4})[-\s.]?(\d{4})\b|"
1506
+ r"(\+\s?55\s?)?\b(\d{2})\s(9\d{4}|\d{4})-(\d{4})\b")
1507
+ _PHONE_LOCAL = re.compile(r"(?<![\d-])(9?\d{4})-(\d{4})(?![\d-])")
1508
+ _TOLL_FREE = re.compile(r"\b(0[38]00)[\s-]?(\d{3})[\s-]?(\d{4})\b")
1509
+ _COUNTRY_CODE = re.compile(r"(?<![\w])\+(\d{1,3})(?=\s?\(?\d)")
1510
+ _CEP = re.compile(r"\b(\d{5})-(\d{3})\b")
1511
+ _CNPJ = re.compile(r"\b(\d{2})\.(\d{3})\.(\d{3})/(\d{4})-(\d{2})\b")
1512
  _GROUPS = re.compile(r"\b\d{1,3}(?:[.-]\d{1,3}){2,}\b") # CPF, CNPJ-like, CEP
1513
+ _PLATE = re.compile(r"\b([A-Z]{3})-?(\d)([A-Z0-9])(\d{2})\b")
1514
+ _SCORE = re.compile(r"(\b[" + _UPPER + r"][" + _LOWER + r"]+\s+)(\d{1,2})\s?[xX]\s?(\d{1,2})(?=\s+[" + _UPPER + r"])")
1515
+ _COEFFICIENT = re.compile(r"(?<![\w,.])(\d{1,3})([a-zA-Z])(?![\w])")
1516
+ _SPACED_SCORE = re.compile(r"(?<![\w,.])(\d{1,2})\s+[xX]\s+(\d{1,2})(?!\d|,\d|\s*(?:cm|mm|m|metros|km|pol|polegadas)\b)")
1517
+ _TIMES_X = re.compile(r"(?<![\w,.])(\d{1,3})\s?[xX](?![\w\d])(?!\s*\d)")
1518
+ _BY_X = re.compile(r"(?<![\w,.])(\d+)\s?[xX]\s?(\d+)(?!\d|[,.]\d)")
1519
+ _RANGE = re.compile(r"(?<![\d.,/:-])(\d{1,4})\s?[-—]\s?(\d{1,4})(?!\d|[.,/:-]\d)")
1520
+ _NEGATIVE = re.compile(r"(?<![\w\d])[-−](?=\d)")
1521
+ _DECIMAL = re.compile(r"(?<![\w,.])(" + _NUMBER + r"),(\d{1,6})(?!\d)")
1522
+ _DOT_DECIMAL = re.compile(r"(?<![\w.])(\d+)\.(\d{1,2})(?!\d|\.\d)")
1523
+ _INTEGER = re.compile(r"(?<![\w,])(" + _NUMBER + r")(?![\w]|[.,]\d)")
1524
+ _FRACTIONS = {2: ("meio", "meios"), 3: ("terço", "terços"), 4: ("quarto", "quartos"), 5: ("quinto", "quintos"),
1525
+ 6: ("sexto", "sextos"), 7: ("sétimo", "sétimos"), 8: ("oitavo", "oitavos"),
1526
+ 9: ("nono", "nonos"), 10: ("décimo", "décimos"), 100: ("centésimo", "centésimos"),
1527
+ 1000: ("milésimo", "milésimos")}
1528
+
1529
+ _UNITS_TABLE = (
1530
+ # symbol, singular, plural, feminine
1531
+ ("km/h", "quilômetro por hora", "quilômetros por hora", False),
1532
+ ("km/l", "quilômetro por litro", "quilômetros por litro", False),
1533
+ ("cm²", "centímetro quadrado", "centímetros quadrados", False),
1534
+ ("cm2", "centímetro quadrado", "centímetros quadrados", False),
1535
+ ("Mbps", "megabit por segundo", "megabits por segundo", False),
1536
+ ("Gbps", "gigabit por segundo", "gigabits por segundo", False),
1537
+ ("kbps", "quilobit por segundo", "quilobits por segundo", False),
1538
+ ("m/s", "metro por segundo", "metros por segundo", False),
1539
+ ("km²", "quilômetro quadrado", "quilômetros quadrados", False),
1540
+ ("km2", "quilômetro quadrado", "quilômetros quadrados", False),
1541
+ ("m²", "metro quadrado", "metros quadrados", False),
1542
+ ("m2", "metro quadrado", "metros quadrados", False),
1543
+ ("m³", "metro cúbico", "metros cúbicos", False),
1544
+ ("m3", "metro cúbico", "metros cúbicos", False),
1545
+ ("kWh", "quilouóte hora", "quilouótes hora", False),
1546
+ ("mAh", "miliampére hora", "miliampéres hora", False),
1547
+ ("kcal", "quilocaloria", "quilocalorias", True),
1548
+ ("cal", "caloria", "calorias", True),
1549
+ ("km", "quilômetro", "quilômetros", False),
1550
+ ("cm", "centímetro", "centímetros", False),
1551
+ ("mm", "milímetro", "milímetros", False),
1552
+ ("kg", "quilo", "quilos", False),
1553
+ ("mg", "miligrama", "miligramas", False),
1554
+ ("ml", "mililitro", "mililitros", False),
1555
+ ("mL", "mililitro", "mililitros", False),
1556
+ ("ha", "hectare", "hectares", False),
1557
+ ("min", "minuto", "minutos", False),
1558
+ ("seg", "segundo", "segundos", False),
1559
+ ("ms", "milissegundo", "milissegundos", False),
1560
+ ("GB", "gigabaite", "gigabaites", False),
1561
+ ("MB", "megabaite", "megabaites", False),
1562
+ ("KB", "quilobaite", "quilobaites", False),
1563
+ ("kB", "quilobaite", "quilobaites", False),
1564
+ ("TB", "terabaite", "terabaites", False),
1565
+ ("GHz", "gigarrértz", "gigarrértz", False),
1566
+ ("MHz", "megarrértz", "megarrértz", False),
1567
+ ("Hz", "rértz", "rértz", False),
1568
+ ("kW", "quilouóte", "quilouótes", False),
1569
+ ("W", "uóte", "uótes", False),
1570
+ ("V", "volt", "volts", False),
1571
+ ("pol", "polegada", "polegadas", True),
1572
+ ("g", "grama", "gramas", False),
1573
+ ("t", "tonelada", "toneladas", True),
1574
+ ("l", "litro", "litros", False),
1575
+ ("L", "litro", "litros", False),
1576
+ ("m", "metro", "metros", False),
1577
+ ("s", "segundo", "segundos", False),
1578
+ )
1579
+ _UNIT_NAMES = {symbol: (singular, plural, feminine) for symbol, singular, plural, feminine in _UNITS_TABLE}
1580
+ _UNIT = re.compile(r"(?<![\w,.])([-−])?(" + _NUMBER + r")(?:,(\d+))?\s?(" +
1581
+ "|".join(re.escape(u[0]) for u in _UNITS_TABLE) + r")(?![\w²³/])")
1582
+ _TECH_NUMBER = re.compile(r"\b(\d{1,3})([A-KM-UX-Z])\b") # 4G, 3D, 4K, seat 23C (not L, V, W: units)
1583
+ # Single capital letters standing alone (plano B, vitamina C, Raio X); vowels only after a naming word.
1584
+ _LONE_CONSONANT = re.compile(r"(?<![\w'.])([B-DF-HJ-NP-TV-Z])(?![\w'])")
1585
+ _LONE_VOWEL = re.compile(r"\b(plano|vitamina|letra|classe|tipo|grupo|nota|série|opção|item|bloco|setor|ala|portão|"
1586
+ r"fila|turma|seção|categoria|modelo|versão|lado|prédio|torre|sala)\s+([AEIOU])(?![\w'])",
1587
+ re.IGNORECASE)
1588
+ _LETTER_HYPHEN_DIGIT = re.compile(r"(?<=[A-Za-zÀ-ú])-(?=\d)")
1589
+ _LONE_HASH = re.compile(r"(?<!\S)#(?!\S)")
1590
+ _LONE_STAR = re.compile(r"(?<!\d )(?<!\S)\*(?!\S)(?! \d)")
1591
+ _ABOUT = re.compile(r"(?<![\w~])~\s?(?=[\dR$])")
1592
+ _STREET = re.compile(r"(\b(?:[Nn]a|[Aa]|[Dd]a|[Pp]ela|[Àà]|[Dd]e|[Ee]m)\s+|^)R\.(?=\s[A-ZÀ-Ú])")
1593
+ _PER = re.compile(r"\s?/\s?(mês|dia|hora|semana|ano|noite|pessoa|unidade|litro|quilo|kg|aula|mensal)\b")
1594
+ _KM_MARKER = re.compile(r"(?<![\w\d])km\.?\s+(?=\d)", re.IGNORECASE)
1595
+ _CONTEXT_SCORE = re.compile(r"\b(venceu|perdeu|ganhou|empatou|terminou|ficou|placar|por|foi)\s+(\d{1,2})\s?[xX]\s?(\d{1,2})\b"
1596
+ r"(?!\s*(?:cm|mm|m|km|pol|metros?|centímetros?)\b)", re.IGNORECASE)
1597
+ _DIMENSION = re.compile(r"(?<![\w,.])(\d+(?:,\d+)?)\s?[xX×]\s?(\d+(?:,\d+)?)(?:\s?[xX×]\s?(\d+(?:,\d+)?))?"
1598
+ r"(?:\s?(cm|mm|m|km|pol)(?![\w²³/])|(?=\s+(?:metros?|centímetros?|milímetros?|quilômetros?|polegadas?)\b))")
1599
+
1600
+ _EMAIL = re.compile(r"\b[\w.+-]+@[\w-]+(?:\.[\w-]+)+\b")
1601
+ _URL = re.compile(r"\b(?:https?://)?(?:www\.)?[\w-]+(?:\.[\w-]+)*\.(?:com|br|org|net|gov|edu|io|app|dev|info|me|tv|co|ai)"
1602
+ r"(?:\.[a-z]{2})?(?:/[\w./%?=&#-]*)?(?![\w@])", re.IGNORECASE)
1603
+ _HANDLE = re.compile(r"(?<![\w@])@(\w+)")
1604
+ _HASHTAG = re.compile(r"(?<![\w#])#(\w+)")
1605
+ _DOMAIN_WORDS = {"com": "com", "br": "bê érre", "org": "órgue", "net": "néte", "gov": "góve",
1606
+ "edu": "édu", "io": "i ó", "app": "épe", "dev": "déve", "info": "info", "me": "mi",
1607
+ "tv": "tê vê", "co": "cô", "ai": "ei ai", "www": "dáblio dáblio dáblio",
1608
+ "http": "agá tê tê pê", "https": "agá tê tê pê ésse"}
1609
+
1610
+ _LAUGH_K = re.compile(r"\b[kK]{3,}\b")
1611
+ _LAUGH_HA = re.compile(r"\b(?:[hH][aAuUeE]){2,}[hH]?\b")
1612
+
1613
+ _MATH = (
1614
+ (">=", " maior ou igual a "), ("<=", " menor ou igual a "), ("≥", " maior ou igual a "),
1615
+ ("≤", " menor ou igual a "), ("!=", " diferente de "), ("≠", " diferente de "), ("==", " igual a "),
1616
+ ("=", " igual a "), (">", " maior que "), ("<", " menor que "), ("±", " mais ou menos "),
1617
+ ("+", " mais "), ("×", " \u2297 "), ("÷", " dividido por "), ("^", " elevado a "),
1618
+ ("√", " raiz quadrada de "), ("≈", " aproximadamente "), ("∞", " infinito "), ("π", " pi "),
1619
+ ("−", " menos "), ("&", " e "), ("§", " parágrafo "), ("@", " arroba "),
1620
+ )
1621
+ _OPERATOR_CHARS = "<>=+×÷^≥≤≠±−"
1622
+ _OPERAND = r"(?:\d|[a-zA-Z](?![\w']))"
1623
+ _VARIABLE = re.compile(r"(?<![\w'])([a-zA-Z])(?=\s*[!" + re.escape(_OPERATOR_CHARS) + r"]+\s*" + _OPERAND + r")|"
1624
+ r"(?<=[" + re.escape(_OPERATOR_CHARS) + r"])(\s*)([a-zA-Z])(?![\w'])")
1625
+ _SPACED_MINUS = re.compile(r"(?<=[\d\w])\s+-\s+(?=[\d\w])")
1626
+ _SPACED_TIMES = re.compile(r"(?<=\d)\s+[xX]\s+(?=\d)")
1627
+ _STAR = re.compile(r"(?<=\d)\s?\*\s?(?=\d)")
1628
+ _SLASH_DIVIDE = re.compile(r"(?<=\d)\s?/\s?(?=\d)")
1629
+
1630
+ _CONSONANTS_ONLY = re.compile(r"(?<![\w'])[bcdfghjklmnpqrstvwxzBCDFGHJKLMNPQRSTVWXZ]{2,6}(?![\w'])")
1631
+ _KEEP = frozenset(LETTERS) | frozenset(PUNCTUATION) | {" "}
1632
+ _SPACE_BEFORE_PUNCT = re.compile(r"\s+([,.?!;:…)])")
1633
+ _REPEATED_PUNCT = re.compile(r"([?!])[?!]+|([,;:])[,;:]+")
1634
+
1635
+
1636
+ # Words after which a number is a code read digit by digit.
1637
+ _IDENTIFIER_CONTEXT = frozenset(("protocolo", "senha", "código", "pin", "ramal", "matrícula", "final", "agência",
1638
+ "conta", "token", "chassi", "renavam", "lote"))
1639
+ _NOT_NOUNS = frozenset(("a", "o", "as", "os", "e", "ou", "de", "do", "da", "dos", "das", "em", "no", "na",
1640
+ "por", "para", "pra", "com", "que", "se", "à", "às", "ao", "aos", "até", "mais", "menos",
1641
+ "cada", "nada", "agora", "ainda", "fora", "embora", "quase", "apenas", "só", "já", "lá",
1642
+ "cá", "ali", "aqui"))
1643
+
1644
+
1645
+ _NEUTRAL_ADJECTIVES = frozenset(("grande", "grandes", "maior", "maiores", "melhor", "melhores", "pior", "piores",
1646
+ "enorme", "enormes", "simples", "jovem", "jovens", "principal", "principais",
1647
+ "importante", "importantes", "diferente", "diferentes", "excelente", "excelentes",
1648
+ "incrível", "incríveis", "breve", "breves", "leve", "leves", "forte", "fortes",
1649
+ "interessante", "interessantes", "feliz", "felizes", "verde", "verdes"))
1650
+
1651
+
1652
+ def _next_word(text, end):
1653
+ """The noun a number counts: the next word, looking past "de", "mil",
1654
+ the second number of a span ("de 231 a 1037 cidades"), a partitive
1655
+ ("2 em cada 10 brasileiras") and a gender-neutral adjective ("22 grandes
1656
+ cidades")."""
1657
+ m = re.match(r"\s+(?:(?:a|e|ou|até)\s+[\d.,]+\s+)?(?:em\s+cada\s+[\d.,]+\s+)?(?:mil\s+)?(?:de\s+)?"
1658
+ r"([^\W\d_]+)(?:\s+([^\W\d_]+))?", text[end:])
1659
+ if not m:
1660
+ return ""
1661
+ word = m.group(1)
1662
+ if word.lower() in _NEUTRAL_ADJECTIVES and m.group(2):
1663
+ word = m.group(2)
1664
+ if word.lower() in _NOT_NOUNS:
1665
+ return ""
1666
+ return word
1667
+
1668
+
1669
+ def _previous_word(text, start):
1670
+ m = re.search(r"([^\W\d_]+)\W*$", text[:start])
1671
+ return m.group(1).lower() if m else ""
1672
+
1673
+
1674
+ def _count_words(n, feminine, next_word, has_de=False):
1675
+ """A cardinal before a noun: gender agreement, and "de" after exact
1676
+ millions ("um milhão de pessoas") unless the text already has it."""
1677
+ words = number_words(n, feminine)
1678
+ if words.split(" ")[-1] in _SCALE_WORDS and next_word and next_word.lower() not in ("de", "e") and not has_de:
1679
+ words += " de"
1680
+ return words
1681
 
1682
 
1683
  def _money(m):
1684
+ minus = m.group(1) or m.group(3)
1685
+ symbol, integer, cents, scale = m.group(2).lower(), m.group(4), m.group(5), m.group(6)
1686
+ singular, plural, feminine = _CURRENCIES[symbol]
1687
+ value = int(integer.replace(".", ""))
1688
+ if scale:
1689
+ scale = scale.lower().replace("milhao", "milhão").replace("milhoes", "milhões").replace(
1690
+ "bilhao", "bilhão").replace("bilhoes", "bilhões")
1691
+ if scale == "mil":
1692
+ amount = value * 1000 + (int((cents + "00")[:3]) if cents else 0)
1693
+ words = number_words(amount, feminine) + " " + plural
1694
+ else:
1695
+ one = value == 1 and not cents
1696
+ scale = {"tri": "trilhão" if one else "trilhões", "bi": "bilhão" if one else "bilhões",
1697
+ "mi": "milhão" if one else "milhões"}.get(scale, scale)
1698
+ head = decimal_words(integer, cents) if cents else number_words(value)
1699
+ words = f"{head} {scale} de {plural}"
1700
+ else:
1701
+ cents_value = int((cents + "0")[:2]) if cents else 0
1702
+ if value == 0 and cents_value:
1703
+ words = number_words(cents_value) + (" centavo" if cents_value == 1 else " centavos")
1704
+ else:
1705
+ words = number_words(value, feminine)
1706
+ if words.split(" ")[-1] in _SCALE_WORDS:
1707
+ words += " de"
1708
+ words += " " + (singular if value == 1 else plural)
1709
+ if cents_value:
1710
+ words += " e " + number_words(cents_value) + (" centavo" if cents_value == 1 else " centavos")
1711
+ return (" menos " if minus else " ") + words + " "
1712
+
1713
+
1714
+ def _day_words(day):
1715
+ return "primeiro" if day == 1 else number_words(day)
1716
+
1717
+
1718
+ def _date_words(day, month, year=None):
1719
+ words = f"{_day_words(day)} de {_MONTHS[month - 1]}"
1720
+ if year is not None:
1721
+ words += f" de {number_words(year)}"
1722
  return words
1723
 
1724
 
1725
+ def _date_full(m):
1726
  day, month, year = int(m.group(1)), int(m.group(2)), m.group(3)
1727
+ if not (1 <= month <= 12 and 1 <= day <= 31):
1728
+ return m.group(0)
1729
+ if len(year) == 2:
1730
+ year = ("20" if int(year) <= 40 else "19") + year
1731
+ return " " + _date_words(day, month, int(year)) + " "
1732
 
1733
 
1734
+ def _date_iso(m):
1735
+ year, month, day = int(m.group(1)), int(m.group(2)), int(m.group(3))
1736
+ if not (1 <= month <= 12 and 1 <= day <= 31):
1737
  return m.group(0)
1738
+ return " " + _date_words(day, month, year) + " "
1739
+
 
 
 
 
 
 
 
1740
 
1741
+ def _month_year(m):
1742
+ month, year = int(m.group(1)), int(m.group(2))
1743
+ if not 1 <= month <= 12:
1744
+ return m.group(0)
1745
+ return f" {_MONTHS[month - 1]} de {number_words(year)} "
1746
+
1747
+
1748
+ # Month abbreviations, only where something marks them as a date: a slash
1749
+ # (8/dez, set/2026), or a day or year beside them (15 de out., 21 set 2025,
1750
+ # set. de 2026, em ago.). "mar" and "dez" are Portuguese words (the sea, ten),
1751
+ # so without a slash they need a day and a year, or "dia" before the day. "set"
1752
+ # (a game or film set) needs its period after "N de". Jan, Jun and Mai can be
1753
+ # names. The day stays a digit for the date and range rules; the year is read
1754
+ # here so it is never inflected.
1755
+ _MONTH_ABBR = {month[:3]: month for month in _MONTHS}
1756
+ _ANY_MONTH = "|".join(_MONTH_ABBR)
1757
+ _CLEAR_MONTH = "|".join(m for m in _MONTH_ABBR if m not in ("set", "mar", "dez"))
1758
+ _DOTTED_MONTH = "|".join(m for m in _MONTH_ABBR if m not in ("mar", "dez"))
1759
+ _DAY = r"0?[1-9]|[12]\d|3[01]"
1760
+ _DAY_SLASH_MONTH = re.compile(rf"(?<![\w/.,:-])({_DAY})/({_ANY_MONTH})(?:/(\d{{4}}|\d{{2}}))?(?![\w/%-]|[.,]\d)", re.IGNORECASE)
1761
+ _MONTH_SLASH_YEAR = re.compile(rf"(?<![\w/-])({_ANY_MONTH})/(\d{{4}}|\d{{2}})(?![\w/%-]|[.,]\d)", re.IGNORECASE)
1762
+ _DAY_MONTH_YEAR = re.compile(rf"(?<![\w/.,:-])({_DAY}) ({_ANY_MONTH})(\.)?((?<=\.) (?-i:de))? (\d{{4}})(?![\d/-])", re.IGNORECASE)
1763
+ _DAY_DE_MONTH = re.compile(rf"(?<![\w.,:/])({_DAY}|primeiro)\s+de\s+({_ANY_MONTH})\b(?!-)(\.(?=\s|$|[,;:)]))?"
1764
+ r"(?:\s+(?-i:de)\s+(\d{4})(?!\d))?", re.IGNORECASE)
1765
+ _MONTH_DOT_DE_YEAR = re.compile(rf"(?<![\w/-])({_DOTTED_MONTH})\. (?-i:de) (\d{{4}})(?!\d)", re.IGNORECASE)
1766
+ _DAY_MONTH_DOT = re.compile(rf"(?<![\w/.,:-])({_DAY}) ({_CLEAR_MONTH})\.(?=\s|$|[,;:)])", re.IGNORECASE)
1767
+ _SINCE_MONTH = re.compile(rf"\b((?i:em|até|desde))\s+({_CLEAR_MONTH})(\.(?=\s|$|[,;:)]))?(?:(?:\s+de)?\s+(\d{{4}})(?!\d))?(?![\w/-])")
1768
+ _DIA_BEFORE = re.compile(r"(?<!\bem )\bdia\s+$", re.IGNORECASE) # not "hoje em dia"
1769
+
1770
+
1771
+ def _year_words(digits):
1772
+ return number_words(int(digits if len(digits) == 4 else ("20" if int(digits) <= 40 else "19") + digits))
1773
+
1774
+
1775
+ def _month_name(token):
1776
+ return _MONTH_ABBR[token.lower()]
1777
+
1778
+
1779
+ def _maybe_name(token):
1780
+ return token.istitle() and token.lower() in ("jan", "jun", "mai")
1781
+
1782
+
1783
+ def _kept_period(m):
1784
+ """An abbreviation's period stays only where it also ends the sentence."""
1785
+ return "" if re.match(r"\s+[a-zà-ÿ]|[,;:)]", m.string[m.end():]) else "."
1786
+
1787
+
1788
+ def _day_slash_month(m):
1789
+ year = f" de {_year_words(m.group(3))}" if m.group(3) else ""
1790
+ return f" {int(m.group(1))} de {_month_name(m.group(2))}{year} "
1791
+
1792
+
1793
+ def _month_slash_year(m):
1794
+ if m.group(1).lower() == "dez" and len(m.group(2)) == 2 and not 21 <= int(m.group(2)) <= 39:
1795
+ return m.group(0) # "uns dez/15 minutos", "nota dez/10"
1796
+ return f" {_month_name(m.group(1))} de {_year_words(m.group(2))} "
1797
+
1798
+
1799
+ def _day_month_year(m):
1800
+ day, token, dot, de, year = m.groups()
1801
+ if dot and not de and token.lower() in ("set", "mar", "dez") and re.match(r"\s+\w", m.string[m.end():]):
1802
+ return m.group(0) # the period ends a sentence: "ela tirou 3 dez. 2025 foi um ótimo ano"
1803
+ return f" {int(day)} de {_month_name(token)} de {_year_words(year)} "
1804
 
1805
+
1806
+ def _day_de_month(m):
1807
+ day, token, dot, year = m.groups()
1808
+ if not year:
1809
+ if _maybe_name(token) or (token.istitle() and re.match(r"\s+[A-ZÀ-Ý]", m.string[m.end(2):])):
1810
+ return m.group(0) # "a camisa 10 de Jan Oblak"
1811
+ month = token.lower()
1812
+ if (month in ("mar", "dez") or (month == "set" and not dot)) and not _DIA_BEFORE.search(m.string[:m.start()]):
1813
+ return m.group(0) # "5 de rio e 3 de mar", "acertei 8 de dez", "15 de set e 10 de palco"
1814
+ spoken = (day if day.lower() == "primeiro" else str(int(day))) + f" de {_month_name(token)}"
1815
+ if year:
1816
+ return spoken + f" de {_year_words(year)}"
1817
+ return spoken + (_kept_period(m) if dot else "")
1818
+
1819
+
1820
+ def _day_month_dot(m):
1821
+ if _maybe_name(m.group(2)):
1822
  return m.group(0)
1823
+ return f"{int(m.group(1))} de {_month_name(m.group(2))}{_kept_period(m)}"
1824
+
1825
+
1826
+ def _since_month(m):
1827
+ word, token, dot, year = m.groups()
1828
+ if year:
1829
+ return f"{word} {_month_name(token)} de {_year_words(year)}"
1830
+ if not dot:
1831
+ return m.group(0)
1832
+ return f"{word} {_month_name(token)}{_kept_period(m)}"
1833
+
1834
+
1835
+ def _month_abbreviations(text):
1836
+ text = _DAY_SLASH_MONTH.sub(_day_slash_month, text)
1837
+ text = _MONTH_SLASH_YEAR.sub(_month_slash_year, text)
1838
+ text = _DAY_MONTH_YEAR.sub(_day_month_year, text)
1839
+ text = _DAY_DE_MONTH.sub(_day_de_month, text)
1840
+ text = _MONTH_DOT_DE_YEAR.sub(lambda m: f" {_month_name(m.group(1))} de {_year_words(m.group(2))} ", text)
1841
+ text = _DAY_MONTH_DOT.sub(_day_month_dot, text)
1842
+ return _SINCE_MONTH.sub(_since_month, text)
1843
+
1844
+
1845
+ def _fraction_words(numerator, denominator, next_word=""):
1846
+ singular, plural = _FRACTIONS[denominator]
1847
+ if denominator == 2 and numerator == 1:
1848
+ return "meia" if next_word and _is_feminine(next_word) else "meio"
1849
+ return f"{number_words(numerator)} {singular if numerator == 1 else plural}"
1850
+
1851
+
1852
+ _MEASURE_NOUNS = frozenset("""xícara xícaras copo copos colher colheres litro litros quilo quilos kg g grama gramas
1853
+ hora horas dúzia dúzias pizza pizzas parte partes página páginas tablete tabletes lata latas pacote pacotes
1854
+ """.split())
1855
+
1856
+
1857
+ def _partial_date(text):
1858
+ def replace(m):
1859
+ a, b = m.group(1), m.group(2)
1860
+ day, month = int(a), int(b)
1861
+ before = _previous_word(text, m.start())
1862
+ after = text[m.end():]
1863
+ if (day, month) == (24, 7):
1864
+ return " vinte e quatro por sete "
1865
+ word = re.match(r"\s+([^\W\d_]+)", after)
1866
+ word = word.group(1).lower() if word else ""
1867
+ is_date = 1 <= month <= 12 and 1 <= day <= 31
1868
+ span = re.match(r"\s+(?:a|até|e|ao)\s+\d{1,2}/\d{1,2}", after)
1869
+ fraction_like = (month in (2, 3, 4, 8) and day < month and not a.startswith("0") and not b.startswith("0")
1870
+ and before not in _DATE_CONTEXT and not span
1871
+ and (word in ("de", "da", "do", "dos", "das") or word in _MEASURE_NOUNS or not is_date))
1872
+ if fraction_like or not is_date:
1873
+ if month in _FRACTIONS and day < month:
1874
+ return " " + _fraction_words(day, month, _next_word(text, m.end())) + " "
1875
+ return f" {number_words(day)} barra {number_words(month)} "
1876
+ return " " + _date_words(day, month) + " "
1877
+ return _DATE_PARTIAL.sub(replace, text)
1878
+
1879
+
1880
+ def _clock_words(hour, minute, hours_word, duration=False):
1881
+ if not 0 <= hour <= 24 or not 0 <= minute <= 59:
1882
+ return None
1883
+ if duration:
1884
+ head = number_words(hour, feminine=True) + (" hora" if hour == 1 else " horas")
1885
+ if minute == 0:
1886
+ return head
1887
+ return head + (" e meia" if minute == 30 else f" e {number_words(minute)}")
1888
+ if hour in (0, 24):
1889
+ head = "meia noite"
1890
+ elif hour == 12:
1891
+ head = "meio dia"
1892
+ else:
1893
+ head = number_words(hour, feminine=True)
1894
+ named = hour in (0, 12, 24)
1895
  if minute == 0:
1896
+ return head if named else head + (" hora" if hour == 1 else " horas")
1897
  if minute == 30:
1898
+ return head + " e meia"
1899
+ if hours_word and not named:
1900
+ head += " hora" if hour == 1 else " horas"
1901
+ return f"{head} e {number_words(minute)}"
1902
 
1903
 
1904
+ def _unit_count(n, singular, plural, feminine=False):
1905
+ return f"{number_words(n, feminine)} {singular if n == 1 else plural}"
 
 
 
 
 
 
 
 
1906
 
1907
 
1908
+ def _time_hms(m):
1909
+ hours, minutes, seconds = int(m.group(1)), int(m.group(2)), int(m.group(3))
1910
+ if hours > 24 or minutes > 59 or seconds > 59:
1911
+ return m.group(0)
1912
+ return (f" {_unit_count(hours, 'hora', 'horas', True)}, {_unit_count(minutes, 'minuto', 'minutos')} e "
1913
+ f"{_unit_count(seconds, 'segundo', 'segundos')} ")
1914
 
1915
 
1916
+ def _time_hm(m):
1917
+ first, second = int(m.group(1)), int(m.group(2))
1918
+ if first > 24 and second <= 59:
1919
+ # A duration in minutes and seconds ("corri em 25:30").
1920
+ return f" {_unit_count(first, 'minuto', 'minutos')} e {_unit_count(second, 'segundo', 'segundos')} "
1921
+ words = _clock_words(first, second, True)
1922
+ return m.group(0) if words is None else " " + words + " "
1923
 
1924
+
1925
+ _CLOCK_CONTEXT = frozenset(("às", "as", "das", "até", "desde", "pelas", "à", "a", "para", "entre"))
1926
+ # Words before "1h30" that make it a duration ("tem 1h30", "em 2h15"); otherwise it is a time of day.
1927
+ _DURATION_CONTEXT = frozenset(("em", "durante", "por", "dura", "durou", "duram", "leva", "levou", "levam", "tem",
1928
+ "teve", "têm", "há", "faz", "fez", "após", "mais", "menos", "quase", "cerca", "só",
1929
+ "apenas", "uns", "umas", "total"))
1930
+
1931
+
1932
+ def _clocks(text):
1933
+ def replace(m):
1934
+ before = _previous_word(text, m.start())
1935
+ duration = before in _DURATION_CONTEXT or (
1936
+ before not in _CLOCK_CONTEXT
1937
+ and bool(re.match(r"\s+de\s+(?!manhã|tarde|noite|madrugada|\d)", text[m.end():])))
1938
+ words = _clock_words(int(m.group(1)), int(m.group(2)), False, duration=duration)
1939
+ return m.group(0) if words is None else " " + words + " "
1940
+ return _CLOCK.sub(replace, text)
1941
+
1942
+
1943
+ _NAMED_HOURS = ((r"\b(?:(À)|à)s(\s+)(meio dia)", lambda m: ("Ao" if m.group(1) else "ao") + m.group(2) + m.group(3)),
1944
+ (r"\b([Àà])s(\s+)(meia noite)", r"\1\2\3"),
1945
+ (r"\b([Aa])s(\s+)(meio dia)", r"o\2\3"), (r"\b([Aa])s(\s+)(meia noite)", r"\1\2\3"),
1946
+ (r"\b([Dd])as(\s+)(meio dia)", r"\1o\2\3"), (r"\b([Dd])as(\s+)(meia noite)", r"\1a\2\3"),
1947
+ (r"\b([Pp]el)as(\s+)(meio dia)", r"\1o\2\3"), (r"\b([Pp]el)as(\s+)(meia noite)", r"\1a\2\3"))
1948
+
1949
+
1950
+ def _hours(m):
1951
+ hour = int(m.group(1))
1952
+ if hour > 24:
1953
+ return m.group(0)
1954
+ return " " + number_words(hour, feminine=True) + (" hora " if hour == 1 else " horas ")
1955
+
1956
+
1957
+ def _ordinal_sign(m):
1958
+ words = ordinal_words(int(m.group(1).replace(".", "")), feminine=m.group(2) == "ª")
1959
+ if m.group(3):
1960
+ words = " ".join(w + "s" if w[:-1] + "o" in _ORDINAL_WORDS or w in _ORDINAL_WORDS else w for w in words.split(" "))
1961
+ return " " + words + " "
1962
+
1963
+
1964
+ def _ordinal_ascii(m):
1965
+ suffix = m.group(2)
1966
+ words = ordinal_words(int(m.group(1)), feminine=suffix.startswith("a"))
1967
+ if suffix.endswith("s"):
1968
+ words = " ".join(w + "s" if w in _ORDINAL_WORDS or w[:-1] + "o" in _ORDINAL_WORDS else w
1969
+ for w in words.split(" "))
1970
+ return " " + words + " "
1971
+
1972
+
1973
+ def _signed_number(minus, integer, fraction, feminine=False):
1974
+ words = decimal_words(integer, fraction, feminine) if fraction else number_words(int(integer.replace(".", "")), feminine)
1975
+ return ("menos " if minus else "") + words
1976
+
1977
+
1978
+ def _percent(m):
1979
+ return " " + _signed_number(m.group(1), m.group(2), m.group(3)) + " por cento "
1980
+
1981
+
1982
+ def _degrees(m):
1983
+ value = _signed_number(m.group(1), m.group(2), m.group(3))
1984
+ one = m.group(2) == "1" and not m.group(3)
1985
+ scale = " fahrenheit" if m.group(4) == "F" else ""
1986
+ return f" {value} {'grau' if one else 'graus'}{scale} "
1987
+
1988
+
1989
+ def _unit(m):
1990
+ minus, integer, fraction, symbol = m.groups()
1991
+ singular, plural, feminine = _UNIT_NAMES[symbol]
1992
+ one = integer == "1" and not (fraction and fraction.strip("0"))
1993
+ return " " + _signed_number(minus, integer, fraction, feminine) + " " + (singular if one else plural) + " "
1994
+
1995
+
1996
+ def _spell_digits_groups(*groups):
1997
+ return ", ".join(digits_words(g) for g in groups)
1998
+
1999
+
2000
+ def _phone(m):
2001
+ country = m.group(1) or m.group(5)
2002
+ groups = [g for g in (m.groups()[1:4] if m.group(2) else m.groups()[5:8]) if g]
2003
+ area, rest = groups[0], [g.replace(" ", "") for g in groups[1:]]
2004
+ prefix = "mais cinquenta e cinco, " if country else ""
2005
+ return " " + prefix + number_words(int(area)) + ", " + _spell_digits_groups(*rest) + " "
2006
+
2007
+
2008
+ def _phone_local(m):
2009
+ first, second = m.group(1), m.group(2)
2010
+ if len(first) == 4 and 1900 <= int(first) <= 2100 and 1900 <= int(second) <= 2100 and int(second) > int(first):
2011
+ return m.group(0) # a span of years, read by the range rule
2012
+ return " " + _spell_digits_groups(first, second) + " "
2013
+
2014
+
2015
+ def _plate(m):
2016
+ letters = " ".join(_LETTER_NAMES[c.lower()] for c in m.group(1))
2017
+ middle = m.group(3)
2018
+ middle = _LETTER_NAMES[middle.lower()] if middle.isalpha() else _UNITS[int(middle)]
2019
+ return f" {letters}, {_UNITS[int(m.group(2))]} {middle} {digits_words(m.group(4))} "
2020
+
2021
+
2022
+ def _range(m):
2023
+ first, second = int(m.group(1)), int(m.group(2))
2024
+ if second <= first:
2025
+ return m.group(0)
2026
+ return f" {number_words(first)} a {number_words(second)} "
2027
+
2028
+
2029
+ def _roman_value(numeral):
2030
+ total = 0
2031
+ for i, c in enumerate(numeral):
2032
+ value = _ROMAN_VALUES[c]
2033
+ if i + 1 < len(numeral) and _ROMAN_VALUES[numeral[i + 1]] > value:
2034
+ total -= value
2035
+ else:
2036
+ total += value
2037
+ return total
2038
+
2039
+
2040
+ def _roman(text):
2041
+ def replace(m):
2042
+ numeral = m.group(0)
2043
+ value = _roman_value(numeral)
2044
+ if not 0 < value < 4000:
2045
+ return numeral
2046
+ before_text = text[:m.start()]
2047
+ before = re.search(r"([^\W\d_]+)\.?\s+$", before_text)
2048
+ before = before.group(1) if before else ""
2049
+ after = re.match(r"\s+([" + _UPPER + r"][^\W\d_]*)", text[m.end():])
2050
+ if (before.lower() in _ROMAN_CARDINAL_CONTEXT or before.lower() in ("cap", "vol", "sec", "séc")
2051
+ or re.match(r"\s+de\s+(?:" + "|".join(_MONTHS) + r")\b", text[m.end():], re.IGNORECASE)):
2052
+ return number_words(value)
2053
+ if before.lower() in _ROMAN_ARTICLE_CONTEXT or before.lower() == "art":
2054
+ return ordinal_words(value) if value < 10 else number_words(value)
2055
+ if before.lower() in _REGNAL_NAMES and before[:1].isupper() and value <= 30:
2056
+ return ordinal_words(value, feminine=before.lower() in _QUEEN_NAMES) if value <= 10 else number_words(value)
2057
+ if after and (len(numeral) > 1 or before.lower() in ("", "a", "o", "na", "no", "da", "do", "pela", "pelo", "à", "ao")) \
2058
+ and value <= 100:
2059
+ return ordinal_words(value, feminine=_is_feminine(after.group(1)))
2060
+ return numeral
2061
+ return _ROMAN.sub(replace, text)
2062
+
2063
+
2064
+ def _spell_letters(word):
2065
+ return " ".join(_LETTER_NAMES[c] for c in word.lower() if c in _LETTER_NAMES)
2066
+
2067
+
2068
+ _CODAS = frozenset("srlnmxz")
2069
+ _ONSETS = frozenset(("pr", "br", "tr", "dr", "cr", "gr", "fr", "vr", "pl", "bl", "cl", "gl", "fl", "ch", "lh", "nh"))
2070
+
2071
+
2072
+ def _pronounceable(word):
2073
+ """Can an upper-case acronym be read as a Portuguese word (NASA, FIFA)?"""
2074
+ w = word.lower()
2075
+ if len(w) <= 2 or not any(c in "aeiou" for c in w):
2076
+ return False
2077
+ for m in re.finditer(r"[^aeiou]+", w):
2078
+ cluster = m.group(0)
2079
+ if m.start() == 0:
2080
+ ok = len(cluster) == 1 or cluster in _ONSETS
2081
+ elif m.end() == len(w):
2082
+ ok = cluster in _CODAS
2083
+ else:
2084
+ ok = (len(cluster) == 1 or cluster in _ONSETS or (len(cluster) == 2 and cluster[0] in _CODAS)
2085
+ or (len(cluster) == 3 and cluster[0] in _CODAS and cluster[1:] in _ONSETS))
2086
+ if not ok:
2087
+ return False
2088
+ return True
2089
+
2090
+
2091
+ def _acronym_reading(token):
2092
+ if token in ACRONYMS:
2093
+ return ACRONYMS[token]
2094
+ plural = token.endswith("s") and token[:-1] in ACRONYMS
2095
+ if plural:
2096
+ return ACRONYMS[token[:-1]] + "s"
2097
+ core = token[:-1] if token.endswith("s") and token[:-1].isupper() else token
2098
+ suffix = "s" if core != token else ""
2099
+ if any(c.isdigit() for c in core):
2100
+ parts = re.findall(r"[A-Z]+|\d+", core)
2101
+ return " ".join(_spell_letters(p) if p.isalpha() else number_words(int(p)) for p in parts) + suffix
2102
+ if _pronounceable(core) or (len(core) >= 4 and {core.lower(), token.lower()} & _LOANWORD_PARTS):
2103
+ return core.lower() + suffix
2104
+ return _spell_letters(core) + suffix
2105
+
2106
+
2107
+ _ACRONYM = re.compile(r"(?<![\w'])([A-Z][A-Z0-9]{1,9}s?)(?![\w'])")
2108
+
2109
+
2110
+ def _shouted(text):
2111
+ letters = [c for c in text if c.isalpha()]
2112
+ return bool(letters) and sum(c.isupper() for c in letters) / len(letters) > 0.6 and len(text.split()) >= 3
2113
+
2114
+
2115
+ def _acronyms(text, shouted):
2116
+ if shouted:
2117
+ # Shouted text: only listed acronyms are spelled; the rest is ordinary words.
2118
+ return _ACRONYM.sub(lambda m: (" " + ACRONYMS[m.group(1)] + " ") if m.group(1) in ACRONYMS else m.group(1), text)
2119
+
2120
+ def replace(m):
2121
+ token = m.group(1)
2122
+ if token.isdigit() or (token[0].isupper() and token[1:].islower()):
2123
+ return token
2124
+ if token in _UNIT_NAMES and re.search(r"\d\s?$", text[:m.start()]):
2125
+ return token
2126
+ if not any(c.isupper() for c in token[1:]) and not token[1:].isdigit():
2127
+ return token
2128
+ return " " + _acronym_reading(token) + " "
2129
+ return _ACRONYM.sub(replace, text)
2130
+
2131
+
2132
+ def _speak_domain_part(part):
2133
+ part_lower = part.lower()
2134
+ if part_lower in _DOMAIN_WORDS:
2135
+ return _DOMAIN_WORDS[part_lower]
2136
+ if part_lower in LOANWORDS:
2137
+ return LOANWORDS[part_lower]
2138
+ if part.isdigit():
2139
+ return number_words(int(part)) if len(part) <= 4 else digits_words(part)
2140
+ return part_lower
2141
+
2142
+
2143
+ def _speak_address(address, separators):
2144
+ out = []
2145
+ for piece in re.split(r"([./_\-?=&#%])", address):
2146
+ if not piece:
2147
+ continue
2148
+ if piece in separators:
2149
+ out.append(separators[piece])
2150
+ else:
2151
+ out.extend(_speak_domain_part(p) for p in re.findall(r"[^\W\d_]+|\d+", piece))
2152
+ return " ".join(w for w in out if w)
2153
+
2154
+
2155
+ _URL_SEPARATORS = {".": "ponto", "/": "barra", "_": "underline", "-": "hífen", "?": "", "=": "igual",
2156
+ "&": "e", "#": "", "%": "por cento"}
2157
+
2158
+
2159
+ def _email(m):
2160
+ local, domain = m.group(0).split("@", 1)
2161
+ return " " + _speak_address(local, _URL_SEPARATORS) + " arroba " + _speak_address(domain, _URL_SEPARATORS) + " "
2162
+
2163
+
2164
+ def _url(m):
2165
+ address = re.sub(r"^https?://", "", m.group(0), flags=re.IGNORECASE)
2166
+ tail = ""
2167
+ while address and address[-1] in ".,;:!?":
2168
+ tail, address = address[-1] + tail, address[:-1]
2169
+ return " " + _speak_address(address.rstrip("/"), _URL_SEPARATORS) + " " + tail
2170
+
2171
+
2172
+ _LOANWORD_KEYS = sorted(LOANWORDS, key=len, reverse=True)
2173
+ # A loanword is a word of the table, or a word of the table + s. English
2174
+ # plurals in -es are listed in the table: no ending can tell "coaches" from
2175
+ # the Portuguese "felizes", "peixes", "ganaches" or "osmoses".
2176
+ _LOANWORD = re.compile(r"(?<![\w-])(?<!\w')(" + "|".join(re.escape(k).replace(r"\ ", " +") for k in _LOANWORD_KEYS)
2177
+ + r")(s)?(?![\w-])(?!'\w)", re.IGNORECASE)
2178
+
2179
+
2180
+ def _loanword(m):
2181
+ respelled = LOANWORDS[" ".join(m.group(1).lower().split())]
2182
+ if m.group(2):
2183
+ respelled = respelled + ("s" if respelled[-1] in "aeiouáéíóúâêôãõ" or not respelled.endswith("s") else "")
2184
+ return respelled
2185
+
2186
+
2187
+ def _dimension(m):
2188
+ sides = [decimal_words(*v.split(",")) if "," in v else number_words(int(v)) for v in m.groups()[:3] if v]
2189
+ unit = m.group(4)
2190
+ words = " por ".join(sides)
2191
+ return f" {words} {_UNIT_NAMES[unit][1]} " if unit else f" {words} "
2192
+
2193
+
2194
+ _SLANG_RE = re.compile(r"(?<![\w'])(" + "|".join(map(re.escape, sorted(_SLANG, key=len, reverse=True))) + r")(?![\w'])",
2195
+ re.IGNORECASE)
2196
+
2197
+
2198
+ def _slang(m):
2199
+ token = m.group(1)
2200
+ if token in ACRONYMS or (len(token) == 1 and not token.islower()):
2201
+ return token
2202
+ if token.islower() or (token[0].isupper() and token[1:].islower()) or token.lower() in ("vc", "vcs"):
2203
+ reading = _SLANG[token.lower()]
2204
+ return reading[0].upper() + reading[1:] if token[0].isupper() else reading
2205
+ return token
2206
+
2207
+
2208
+ _Y = r"(?:19|20)\d\d"
2209
+ _YEAR = re.compile(_Y) # as a year is written: no thousands dot
2210
+ _YEAR_SPAN = re.compile(rf"\b(?:de|entre)\s+{_Y}\s+(?:a|e)\s+{_Y}(?!\d)", re.IGNORECASE)
2211
+ _OPENS_CLAUSE = r"(?:^\s*|[.!?:;(\"\n]\s*)(?=(?-i:[A-ZÀ-Ý]))" # a closing quote or a list goes on in lower case
2212
+ # What before a number marks a date. After "named" (or "decade", for a number
2213
+ # ending in 0) it is a year whatever follows; after "likely" a round number can
2214
+ # be a count; after the others any plural can.
2215
+ _YEAR_MARK = re.compile(
2216
+ r"(?:(?P<named>\bem\s+pleno|\bem\s+meados\s+de|\b(?:d[ée]cada|n?as\s+d[ée]cadas)\s+de|" + _OPENS_CLAUSE + r"no\s+ano(?:\s+de)?)"
2217
+ r"|(?P<decade>\b(?:nos|dos|aos|pelos)\s+anos)"
2218
+ r"|(?P<likely>" + _OPENS_CLAUSE + r"(?:em|desde|no\s+(?:in[íi]cio|começo|final|fim)\s+de)"
2219
+ r"|(?<![^\W\d_]\sde\s)\b(?:" + "|".join(_MONTHS) + r")\s+de)" # not "a entrega de maio de 1980 cestas"
2220
+ r"|\bem|\bdesde|\bno\s+(?:ano(?:\s+de)?|(?:in[íi]cio|começo|final|fim)\s+de)|\b(?:o|do|ao|pelo)\s+ano\s+de|" + _OPENS_CLAUSE + r"(?:até|após)|\b(?:antes|depois)\s+de"
2221
+ r"|\b(?:censo|eleição|eleições|copa|olimpíadas?|verão|inverno|primavera|outono|natal|carnaval|crise|pandemia"
2222
+ r"|constituição|lei|reforma|edição|temporada|guerra|revolução|golpe)\s+de)"
2223
+ r"\s+(?:" + _Y + r"\s+(?:a|e|ou|até)\s+)?$", re.IGNORECASE)
2224
+ _CLAUSE_START = re.compile(r"(?:^\s*|[.!?:;(\"\n]\s*)$")
2225
+ _PARTITIVE = re.compile(r"\s+(?:de|delas|dessas|destas|daquelas)\b", re.IGNORECASE)
2226
+ # Plural words that start a new phrase after a year; a number never counts them.
2227
+ _AFTER_A_YEAR = frozenset("""elas nas pelas umas numas suas minhas tuas nossas vossas essas estas aquelas nessas nestas
2228
+ naquelas algumas nenhumas todas muitas poucas tantas várias duas mas""".split())
2229
+ # Singular verbs: a count opening a clause would take the plural, so this is a year.
2230
+ _YEAR_VERBS = frozenset("era estava seria tinha havia começa termina acaba marca continua mostra".split())
2231
+
2232
+
2233
+ def _counts_feminine(digits, value, word, text, start, end):
2234
+ """Whether a number agrees with the feminine-looking word after it.
2235
+
2236
+ The next word alone cannot tell a year from a count whose noun came earlier
2237
+ ("Das 2000 vagas, 1500 são..."), so a number from 1900 to 2099 is a year
2238
+ only when something marks it: a word before it ("Em 2023 ela mudou", "Em
2239
+ março de 2020 escolas fecharam"), a range ("De 1930 a 1945 Vargas governou")
2240
+ or a singular verb ("1998 era"). After a mark a plural can still be the noun
2241
+ counted: "chegou em 1934 escolas", "Em 2000 dessas pessoas".
2242
+ """
2243
+ if not word or not _is_feminine(word):
2244
+ return False
2245
+ if not _YEAR.fullmatch(digits):
2246
+ return True
2247
+ lower = word.lower()
2248
+ if lower in _YEAR_VERBS and _CLAUSE_START.search(text, max(0, start - 4), start):
2249
+ return False
2250
+ mark = _YEAR_MARK.search(text, max(0, start - 48), start)
2251
+ span = _YEAR_SPAN.search(text, max(0, start - 24), end + 16)
2252
+ spanned = bool(span) and span.start() < start < span.end()
2253
+ if not (mark or spanned) or _PARTITIVE.match(text, end):
2254
+ return True
2255
+ named = mark and (mark.group("named") or (mark.group("decade") and not value % 10))
2256
+ if not lower.endswith("s") or lower in _AFTER_A_YEAR or named:
2257
+ return False
2258
+ if mark and mark.group("likely"):
2259
+ return not (value % 100 or word.istitle())
2260
+ return not (value % 100 and word.istitle())
2261
+
2262
+
2263
+ def _integers(text):
2264
+ def replace(m):
2265
+ digits = m.group(1)
2266
+ plain = digits.replace(".", "")
2267
+ before = _previous_word(text, m.start())
2268
+ if (len(plain) > 15 or (len(plain) > 1 and plain.startswith("0")) or (len(plain) >= 10 and "." not in digits)
2269
+ or before in _IDENTIFIER_CONTEXT):
2270
+ return " " + digits_words(plain) + " "
2271
+ value = int(plain)
2272
+ next_word = _next_word(text, m.end())
2273
+ following = text[m.end():]
2274
+ time_of_day = bool(re.match(r"\s+(?:e\s+meia\s+)?da\s+(?:manhã|tarde|noite|madrugada)\b", following))
2275
+ feminine = (before in ("à", "às", "das", "pelas") or time_of_day
2276
+ or (before in ("as", "são") and not next_word)
2277
+ or _counts_feminine(digits, value, next_word, text, m.start(), m.end()))
2278
+ if before == "dia" and value == 1:
2279
+ return " primeiro "
2280
+ return " " + _count_words(value, feminine, next_word, bool(re.match(r"\s+de\b", following))) + " "
2281
+ return _INTEGER.sub(replace, text)
2282
+
2283
+
2284
+ def _decimals(text):
2285
+ def replace(m):
2286
+ next_word = _next_word(text, m.end())
2287
+ return " " + decimal_words(m.group(1), m.group(2), bool(next_word) and _is_feminine(next_word)) + " "
2288
+ return _DECIMAL.sub(replace, text)
2289
+
2290
+
2291
+ def _math(text):
2292
+ text = _STAR.sub(" \u2297 ", text)
2293
+ if "=" in text or any(op in text for op in ("<", ">", "≥", "≤", "≠")):
2294
+ text = _SPACED_TIMES.sub(" \u2297 ", text)
2295
+ text = _SPACED_MINUS.sub(" menos ", text)
2296
+ text = _SLASH_DIVIDE.sub(" dividido por ", text)
2297
+ def variable(m):
2298
+ letter = m.group(1) or m.group(3)
2299
+ # "a", "o" and "e" before a word are an article or a conjunction ("> o preço").
2300
+ if m.group(3) and letter in "aoeAOE" and re.match(r"\s+[^\W\d_]{2,}", text[m.end():]):
2301
+ return m.group(0)
2302
+ return " " + _LETTER_NAMES[letter.lower()] + " "
2303
+ text = _VARIABLE.sub(variable, text)
2304
+ for symbol, words in _MATH:
2305
+ text = text.replace(symbol, words)
2306
+ return text
2307
+
2308
+
2309
+ def _cleanup(text):
2310
+ out = []
2311
+ for c in text:
2312
+ if c in _KEEP or c.lower() in LETTER_SET:
2313
+ out.append(c)
2314
+ elif c.isdigit():
2315
+ out.append(" " + _UNITS[int(c)] + " ")
2316
+ elif c.isalpha():
2317
+ base = unicodedata.normalize("NFKD", c)
2318
+ base = "".join(b for b in base if not unicodedata.combining(b))
2319
+ base = {"ß": "ss", "æ": "ae", "œ": "oe", "ø": "o", "ł": "l", "đ": "d", "ı": "i"}.get(base, base)
2320
+ out.append(base if all(b.lower() in LETTER_SET for b in base) else " ")
2321
+ elif c in "[{":
2322
+ out.append("(")
2323
+ elif c in "]}":
2324
+ out.append(")")
2325
+ elif c in "|•·":
2326
+ out.append(",")
2327
+ else:
2328
+ out.append(" ")
2329
+ return "".join(out)
2330
+
2331
+
2332
+ def spoken_form(text):
2333
+ """The words a Brazilian reader would say for ``text``, case preserved.
2334
+
2335
+ This is what the teacher TTS reads when the training audio is generated,
2336
+ so the audio and the student's tokens always agree. ``normalize_text``
2337
+ lower-cases it.
2338
  """
2339
  if not isinstance(text, str):
2340
  raise TypeError("text must be a string")
2341
+ # The number sign and ordinal indicators before NFKC folds º and ª into o and a.
2342
+ text = _NUMBER_SIGN.sub(" número ", text)
2343
+ text = _ORDINAL_SIGN.sub(_ordinal_sign, text)
2344
  text = unicodedata.normalize("NFKC", text).translate(_QUOTE_TRANSLATION)
2345
+ text = text.replace("İ", "I").replace("ı", "i") # re.IGNORECASE folds them to i; .lower() does not
2346
+ text = text.replace("⁄", "/").replace("​", "").replace("️", "").replace("‍", "")
2347
+ text = text.replace("ª", " a").replace("º", " o")
2348
  # Two hyphens and three dots are the ASCII forms of the inventory symbols;
2349
  # without this "..." would become three pause tokens.
2350
  text = text.replace("--", "—").replace("...", "…")
2351
+ text = _PLATE.sub(_plate, text)
2352
+ text = _LETTER_HYPHEN_DIGIT.sub(" ", text)
2353
+ text = _LONE_HASH.sub(" cerquilha ", text)
2354
+ text = _LONE_STAR.sub(" asterisco ", text)
2355
+ text = _ABOUT.sub(" cerca de ", text)
2356
+ text = _STREET.sub(lambda m: m.group(1) + "Rua", text)
2357
+ text = _EMAIL.sub(_email, text)
2358
+ text = _URL.sub(_url, text)
2359
+ text = _HANDLE.sub(lambda m: " arroba " + m.group(1) + " ", text)
2360
+ text = _HASHTAG.sub(lambda m: (" número " + m.group(1) + " ") if m.group(1).isdigit()
2361
+ else " rexitégue " + m.group(1) + " ", text)
2362
+ for pattern, reading in _ABBREVIATIONS:
2363
+ text = re.sub(pattern, (lambda m, r=reading: " " + r(m) + " ") if callable(reading) else " " + reading + " ",
2364
+ text, flags=re.IGNORECASE)
2365
+ text = _LAUGH_K.sub(" cacacá ", text)
2366
+ text = _LAUGH_HA.sub(" rárárá ", text)
2367
+ text = _roman(text)
2368
+ text = _TECH_NUMBER.sub(lambda m: f" {number_words(int(m.group(1)))} {_LETTER_NAMES[m.group(2).lower()]} ", text)
2369
  text = _MONEY.sub(_money, text)
2370
+ shouted = _shouted(text) # before the months below turn capitals into lower-case words
2371
+ text = _month_abbreviations(text)
2372
+ text = _acronyms(text, shouted)
2373
+ text = _CNPJ.sub(lambda m: " " + _spell_digits_groups(*m.groups()) + " ", text)
2374
+ text = _DATE_ISO.sub(_date_iso, text)
2375
+ text = _DATE_FULL.sub(_date_full, text)
2376
+ text = _FIRST_OF.sub(" primeiro", text)
2377
+ text = _DATE_MONTH_YEAR.sub(_month_year, text)
2378
+ text = _TIME_HMS.sub(_time_hms, text)
2379
+ text = _TIME_HM.sub(_time_hm, text)
2380
+ text = _clocks(text)
2381
+ text = _HOURS.sub(_hours, text)
2382
+ for pattern, replacement in _NAMED_HOURS:
2383
+ text = re.sub(pattern, replacement, text)
2384
+ text = _ORDINAL_DEGREE.sub(lambda m: " " + ordinal_words(int(m.group(1))) + " ", text)
2385
+ text = _ORDINAL_ASCII.sub(_ordinal_ascii, text)
2386
+ text = _PERCENT.sub(_percent, text)
2387
+ text = _DEGREES.sub(_degrees, text)
2388
+ text = _DIMENSION.sub(_dimension, text)
2389
+ text = _UNIT.sub(_unit, text)
2390
+ text = _PER.sub(lambda m: " por " + {"kg": "quilo", "mensal": "mês"}.get(m.group(1), m.group(1)), text)
2391
+ text = _KM_MARKER.sub(" quilômetro ", text)
2392
+ text = _TOLL_FREE.sub(lambda m: " " + _spell_digits_groups(*m.groups()) + " ", text)
2393
+ text = _PHONE.sub(_phone, text)
2394
+ text = _CEP.sub(lambda m: " " + _spell_digits_groups(m.group(1), m.group(2)) + " ", text)
2395
+ text = _GROUPS.sub(lambda m: m.group(0) if re.fullmatch(r"\d{1,3}(?:\.\d{3})+", m.group(0))
2396
+ else " " + _spell_digits_groups(*re.split(r"[.-]", m.group(0))) + " ", text)
2397
+ text = _PHONE_LOCAL.sub(_phone_local, text)
2398
+ text = _COUNTRY_CODE.sub(lambda m: " mais " + number_words(int(m.group(1))) + " ", text)
2399
+ text = _SCORE.sub(lambda m: f"{m.group(1)}{number_words(int(m.group(2)))} a {number_words(int(m.group(3)))}", text)
2400
+ text = _CONTEXT_SCORE.sub(lambda m: f"{m.group(1)} {number_words(int(m.group(2)))} a {number_words(int(m.group(3)))}", text)
2401
+ if "=" in text or any(op in text for op in ("<", ">", "≥", "≤", "≠")):
2402
+ text = _COEFFICIENT.sub(lambda m: f" {number_words(int(m.group(1)))} {_LETTER_NAMES[m.group(2).lower()]} ", text)
2403
+ else:
2404
+ text = _SPACED_SCORE.sub(lambda m: f" {number_words(int(m.group(1)))} a {number_words(int(m.group(2)))} ", text)
2405
+ if "=" not in text:
2406
+ text = _BY_X.sub(lambda m: f" {number_words(int(m.group(1)))} por {number_words(int(m.group(2)))} ", text)
2407
+ text = _TIMES_X.sub(lambda m: " " + number_words(int(m.group(1)), feminine=True) + " vezes ", text)
2408
+ text = _partial_date(text)
2409
+ if "=" not in text:
2410
+ text = _RANGE.sub(_range, text)
2411
+ text = _math(text)
2412
+ text = _NEGATIVE.sub(" menos ", text)
2413
+ text = _decimals(text)
2414
+ text = _DOT_DECIMAL.sub(lambda m: f" {number_words(int(m.group(1)))} ponto {digits_words(m.group(2)) if m.group(2).startswith('0') else number_words(int(m.group(2)))} ", text)
2415
+ text = _integers(text)
2416
+ text = text.replace("\u2297", " vezes ")
2417
+ text = _LOANWORD.sub(_loanword, text)
2418
+ text = _SLANG_RE.sub(_slang, text)
2419
+ text = _LONE_VOWEL.sub(lambda m: m.group(1) + " " + _LETTER_NAMES[m.group(2).lower()], text)
2420
+ text = _LONE_CONSONANT.sub(lambda m: " " + _LETTER_NAMES[m.group(1).lower()] + " ", text)
2421
+ text = _CONSONANTS_ONLY.sub(lambda m: " " + _spell_letters(m.group(0)) + " ", text)
2422
+ text = _cleanup(text)
2423
+ text = _REPEATED_PUNCT.sub(lambda m: m.group(1) or m.group(2), text)
2424
+ text = re.sub(r"\s+", " ", text)
2425
+ text = _SPACE_BEFORE_PUNCT.sub(r"\1", text)
2426
+ text = re.sub(r"\(\s+", "(", text).strip()
2427
+ return text[:1].upper() + text[1:]
2428
+
2429
+
2430
+ def normalize_text(text):
2431
+ """What the model reads: the spoken form, lower-cased.
2432
+
2433
+ Digits follow Brazilian conventions: "1.234" is a thousand and "3,14" a
2434
+ decimal; money uses reais and centavos; dates read day-month-year; times
2435
+ read in hours and minutes; document identifiers read digit by digit;
2436
+ symbols, units, ordinals, acronyms and loanwords become words.
2437
+ """
2438
+ return re.sub(r"\s+", " ", spoken_form(text).lower()).strip()
2439
 
2440
 
2441
  # For comparing a transcription against its text: numbers are spoken by the
 
2464
  return " ".join(words).strip()
2465
 
2466
 
2467
+ def spoken_normalize(text):
2468
+ """For scoring a transcription without masking anything: both sides go
2469
+ through the normaliser (so "R$ 3,00" and "três reais" agree), then accents,
2470
+ punctuation and the quatorze/catorze spelling variants are folded."""
2471
+ text = normalize_text(text).replace("catorze", "quatorze")
2472
+ text = unicodedata.normalize("NFKD", text)
2473
+ text = "".join(c for c in text if not unicodedata.combining(c))
2474
+ text = re.sub(r"[^\w\s]", " ", text)
2475
+ return " ".join(text.split())
2476
 
2477
 
2478
+ # ---------------------------------------------------------------------------
2479
+ # Syllables and stress
2480
+ # ---------------------------------------------------------------------------
2481
 
2482
+ _VOWEL_LETTERS = frozenset("aeiouyáàâãéêíóôõúüũ")
2483
+ _WEAK = frozenset("iuy")
2484
+ _ACUTE_CIRCUMFLEX = frozenset("áéíóúâêô")
2485
+ _TILDE = frozenset("ãõũ")
2486
+ _ONSET_CLUSTERS = frozenset(("pr", "br", "tr", "dr", "cr", "gr", "fr", "vr", "pl", "bl", "cl", "gl",
2487
+ "fl", "tl", "kr", "kl", "ch", "lh", "nh", "qu", "gu", "qü", "gü"))
2488
+ _HIATUS_CODA = frozenset("lmnrz")
2489
+ _OXYTONE_ENDINGS = ("r", "l", "z", "x", "i", "u", "y", "im", "um", "om", "is", "us", "ys", "ins",
2490
+ "uns", "ons", "ims")
2491
+ # Words the default rule gets wrong.
2492
+ _OXYTONE_WORDS = frozenset(("porque", "porquê"))
2493
+ # Unstressed function words: articles, contractions, clitic pronouns and
2494
+ # monosyllabic conjunctions and prepositions.
2495
+ CLITICS = frozenset(("o", "a", "os", "as", "e", "de", "do", "da", "dos", "das", "em", "no", "na", "nos",
2496
+ "nas", "ao", "aos", "à", "às", "que", "se", "me", "te", "lhe", "lhes", "por", "pra",
2497
+ "pro", "pras", "pros", "com", "sem", "mas", "ou", "nem", "num", "numa"))
2498
+
2499
+
2500
+ def _letter_kinds(word):
2501
+ """'V' for a letter that can be a syllable nucleus, 'C' otherwise. The u of
2502
+ qu/gu before a vowel is part of the onset (aquilo, água), as is y before a
2503
+ vowel at the start of a word (Yasmin)."""
2504
+ kinds = []
2505
+ n = len(word)
2506
+ for i, c in enumerate(word):
2507
+ if c not in _VOWEL_LETTERS:
2508
+ kinds.append("C")
2509
+ elif c in "uü" and i > 0 and word[i - 1] in "qg" and i + 1 < n and word[i + 1] in _VOWEL_LETTERS:
2510
+ kinds.append("C")
2511
+ elif c == "y" and i == 0 and n > 1 and word[1] in _VOWEL_LETTERS:
2512
+ kinds.append("C")
2513
+ else:
2514
+ kinds.append("V")
2515
+ return kinds
2516
+
2517
+
2518
+ def _falling_diphthong(word, kinds, j):
2519
+ """Does the vowel at ``j`` glide onto the vowel before it?"""
2520
+ first, second = word[j - 1], word[j]
2521
+ if first in _TILDE and second in "eo":
2522
+ return True # mãe, pão, põe
2523
+ if second not in _WEAK or first == second:
2524
+ return False
2525
+ # An unaccented i/u before l, m, n, r, z closing its syllable, or before
2526
+ # nh, is a hiatus: ra-iz, ju-iz, ru-im, ca-ir, ra-i-nha, a-in-da.
2527
+ rest = word[j + 1:]
2528
+ if rest[:2] == "nh":
2529
+ return False
2530
+ if rest[:2] in ("rr", "ss"):
2531
+ return True
2532
+ if rest[:1] in _HIATUS_CODA and (len(rest) == 1 or kinds[j + 2] == "C"):
2533
+ return False
2534
+ return True
2535
+
2536
+
2537
+ def syllables(word):
2538
+ """Letter spans (start, end) of the syllables of a lower-case word."""
2539
+ n = len(word)
2540
+ kinds = _letter_kinds(word)
2541
+ nuclei = []
2542
+ i = 0
2543
  while i < n:
2544
+ if kinds[i] != "V":
2545
+ i += 1
2546
+ continue
2547
+ j = i + 1
2548
+ if j < n and kinds[j] == "V" and _falling_diphthong(word, kinds, j):
2549
+ j += 1
2550
+ nuclei.append((i, j))
2551
+ i = j
2552
+ if not nuclei:
2553
+ return [(0, n)] if n else []
2554
+ starts = [0]
2555
+ for (_, end), (start, _) in zip(nuclei, nuclei[1:]):
2556
+ run = start - end
2557
+ if run <= 1:
2558
+ starts.append(end if run == 0 else start - 1)
2559
+ elif word[start - 2:start] in _ONSET_CLUSTERS:
2560
+ starts.append(start - 2)
2561
+ else:
2562
+ starts.append(start - 1)
2563
+ ends = starts[1:] + [n]
2564
+ return list(zip(starts, ends))
2565
+
2566
+
2567
+ def _syllable_starts(word):
2568
+ """Start indices of the syllables of a word (kept for older callers)."""
2569
+ return [s for s, _ in syllables(word)]
2570
 
2571
 
2572
  def _stressed_range(word):
2573
+ """(start, end) of the stressed syllable of a word.
2574
 
2575
+ An acute or circumflex accent wins, then a tilde; otherwise the oxytone
2576
+ endings stress the last syllable and every other word the penultimate.
 
2577
  """
2578
+ spans = syllables(word)
2579
+ if not spans:
2580
+ return 0, len(word)
2581
+ if word in _OXYTONE_WORDS and len(spans) > 1:
2582
+ return spans[-1]
2583
+ for marks in (_ACUTE_CIRCUMFLEX, _TILDE):
2584
+ for start, end in spans:
2585
+ if any(c in marks for c in word[start:end]):
2586
+ return start, end
2587
+ if len(spans) == 1:
2588
+ return spans[0]
2589
+ return spans[-1] if word.endswith(_OXYTONE_ENDINGS) else spans[-2]
 
 
 
2590
 
2591
 
2592
  @dataclass(frozen=True)
 
2605
 
2606
  Returns a :class:`Phonemized` whose symbols are letters, punctuation and
2607
  word spaces, with a stress feature per token (1 on the letters of the
2608
+ stressed syllable of each word, 0 elsewhere and on unstressed function
2609
+ words) and the list of characters that fell outside the inventory.
2610
  """
2611
  symbols = [BOS]
2612
  stress = [0]
 
2617
  if not word:
2618
  return
2619
  text_ = "".join(word)
2620
+ letters = text_.replace("'", "")
2621
+ if text_ in CLITICS or not letters:
2622
+ start = end = -1
2623
+ else:
2624
+ start, end = _stressed_range(letters)
2625
+ # Map the span on the apostrophe-free word back onto the word.
2626
+ index = [i for i, c in enumerate(word) if c != "'"]
2627
+ start, end = index[start], index[end - 1] + 1
2628
  for i, c in enumerate(word):
2629
  symbols.append(c)
2630
+ stress.append(STRESS_STRESSED if start <= i < end and c != "'" else 0)
2631
  word.clear()
2632
 
2633
  for c in text:
 
2651
  symbols.append(EOS)
2652
  stress.append(0)
2653
  return Phonemized(tuple(symbols), tuple(SYMBOL_TO_ID[s] for s in symbols),
2654
+ tuple(stress), tuple(unknown))
2655
 
2656
 
2657
  def phonemize(text):
2658
  if not isinstance(text, str) or not text.strip():
2659
  raise ValueError("empty text")
2660
+ normalized = normalize_text(text)
2661
+ if not normalized:
2662
+ raise ValueError("nothing to read")
2663
+ return tokenize(normalized)
2664
 
2665
 
2666
  def is_phone(token_ids):
tiny-broca.pt CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:debd760592d8a98450118efdba5503a3f4e0d9606e067f531054e4966052b447
3
- size 18195141
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a65ca52802a1985dc60b2c48d67650fb4a50bd83e9e4b1e807a926969417c17a
3
+ size 18195205