sisyo 1.7.0 → 1.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/LICENSE +16 -16
  2. package/README.md +177 -166
  3. package/bin/known-hashes.json +8 -1
  4. package/bin/sisyo.js +285 -285
  5. package/package.json +30 -30
  6. package/templates/.claude/rules/agents-and-tests.md +32 -24
  7. package/templates/.claude/rules/docs.md +39 -19
  8. package/templates/.claude/skills/fastapi-best-practices/ASYNC-PATTERNS.md +121 -121
  9. package/templates/.claude/skills/fastapi-best-practices/DATABASE.md +153 -153
  10. package/templates/.claude/skills/fastapi-best-practices/DEPENDENCIES.md +140 -140
  11. package/templates/.claude/skills/fastapi-best-practices/PROJECT-STRUCTURE.md +90 -90
  12. package/templates/.claude/skills/fastapi-best-practices/PYDANTIC-GUIDE.md +155 -155
  13. package/templates/.claude/skills/fastapi-best-practices/SKILL.md +123 -123
  14. package/templates/.claude/skills/g6-style/SKILL.md +125 -125
  15. package/templates/.claude/skills/g6-style/references/checks.md +58 -58
  16. package/templates/.claude/skills/g6-style/references/imagery.md +103 -103
  17. package/templates/.claude/skills/g6-style/references/motion.md +121 -121
  18. package/templates/.claude/skills/g6-style/references/sections.md +263 -263
  19. package/templates/.claude/skills/g6-style/references/tokens.md +197 -197
  20. package/templates/.claude/skills/hindsight/SKILL.md +175 -175
  21. package/templates/.claude/skills/hoang-auth/SKILL.md +188 -0
  22. package/templates/.claude/skills/html-docs/SKILL.md +207 -207
  23. package/templates/.claude/skills/i18n-multilang/SKILL.md +153 -153
  24. package/templates/.claude/skills/i18n-multilang/assets/languages.json +47 -47
  25. package/templates/.claude/skills/i18n-multilang/assets/plural-vectors.json +46 -46
  26. package/templates/.claude/skills/i18n-multilang/assets/project/README.md +17 -17
  27. package/templates/.claude/skills/i18n-multilang/assets/project/gitattributes.txt +6 -6
  28. package/templates/.claude/skills/i18n-multilang/assets/project/gitignore.txt +4 -4
  29. package/templates/.claude/skills/i18n-multilang/assets/project/glossary.json +6 -6
  30. package/templates/.claude/skills/i18n-multilang/assets/project/i18n.config.json +22 -22
  31. package/templates/.claude/skills/i18n-multilang/assets/project/locales/__source__/common.json +10 -10
  32. package/templates/.claude/skills/i18n-multilang/assets/project/notes/common.json +5 -5
  33. package/templates/.claude/skills/i18n-multilang/assets/project/style.md +20 -20
  34. package/templates/.claude/skills/i18n-multilang/references/format.md +100 -100
  35. package/templates/.claude/skills/i18n-multilang/references/languages.md +97 -97
  36. package/templates/.claude/skills/i18n-multilang/references/layout-and-versioning.md +256 -256
  37. package/templates/.claude/skills/i18n-multilang/references/numbers.md +161 -161
  38. package/templates/.claude/skills/i18n-multilang/references/platform-unity.md +142 -142
  39. package/templates/.claude/skills/i18n-multilang/references/platform-web.md +107 -107
  40. package/templates/.claude/skills/i18n-multilang/references/translation.md +143 -143
  41. package/templates/.claude/skills/i18n-multilang/references/voice.md +271 -271
  42. package/templates/.claude/skills/i18n-multilang/scripts/i18n.py +1041 -1041
  43. package/templates/.claude/skills/i18n-multilang/scripts/numwords.py +1013 -1013
  44. package/templates/.claude/skills/i18n-multilang/scripts/voice.py +478 -478
  45. package/templates/.claude/skills/neon-game-ui-ux-skill/COMPONENTS.md +490 -490
  46. package/templates/.claude/skills/neon-game-ui-ux-skill/GAMIFICATION.md +246 -246
  47. package/templates/.claude/skills/neon-game-ui-ux-skill/ICONS.md +249 -249
  48. package/templates/.claude/skills/neon-game-ui-ux-skill/LAYOUT-NAV.md +362 -362
  49. package/templates/.claude/skills/neon-game-ui-ux-skill/MOTION-A11Y.md +168 -168
  50. package/templates/.claude/skills/neon-game-ui-ux-skill/SKILL.md +137 -137
  51. package/templates/.claude/skills/neon-game-ui-ux-skill/TOKENS.md +323 -323
  52. package/templates/.claude/skills/react-page-oriented/SKILL.md +407 -407
  53. package/templates/.claude/skills/react-page-oriented/triggers.md +12 -12
  54. package/templates/.claude/skills/terraform-best-practices/SKILL.md +341 -341
  55. package/templates/.claude/skills/typesafe-jev/SKILL.md +148 -148
  56. package/templates/.claude/skills/vibe-docs/SKILL.md +139 -242
  57. package/templates/SISYO.md +39 -37
  58. package/templates/docs/99_progress/features.md +7 -7
  59. package/templates/docs/99_progress/handoff.md +19 -19
  60. package/templates/docs/99_progress/todo.md +15 -15
  61. package/templates/docs/MAP.md +26 -26
@@ -1,1013 +1,1013 @@
1
- #!/usr/bin/env python3
2
- # -*- coding: utf-8 -*-
3
- """numwords.py - numbers as spoken words for the 10 voice languages (stdlib only, Python 3.8+).
4
-
5
- Why: a TTS model that is handed digits guesses the reading ("1234" came out as "một, hai trăm ba mươi bốn"; "1 234"
6
- and "1.234" are worse). So the text sent to the voice never holds a digit: this tool writes every number out, and the
7
- same tables check what a recogniser heard afterwards.
8
-
9
- python numwords.py spell 1234 --lang vi một nghìn hai trăm ba mươi bốn
10
- python numwords.py spell 105 --all the reading in every voice language
11
- python numwords.py speak --lang vi "Bạn có 1234 sao" JSON: speak text, the numbers found, the open issues
12
- python numwords.py heard --lang vi --numbers 1234 "bạn có một nghìn hai trăm ba mươi bốn sao"
13
- python numwords.py selftest
14
-
15
- Languages: en ja es pt-BR ko zh-Hans de fr vi id. Range: 0 <= n < 10**12. Rules and pitfalls: references/numbers.md.
16
- """
17
- import argparse
18
- import json
19
- import re
20
- import sys
21
- import unicodedata
22
-
23
- LANGS = ('en', 'ja', 'es', 'pt-BR', 'ko', 'zh-Hans', 'de', 'fr', 'vi', 'id')
24
- MAX = 10 ** 12
25
-
26
-
27
- def _groups3(n):
28
- """1234567 -> [567, 234, 1] (low group first)."""
29
- g = []
30
- while n:
31
- g.append(n % 1000)
32
- n //= 1000
33
- return g
34
-
35
-
36
- # ---------------------------------------------------------------- vi
37
- _VI = ['không', 'một', 'hai', 'ba', 'bốn', 'năm', 'sáu', 'bảy', 'tám', 'chín']
38
-
39
-
40
- def _vi3(n, pad, linh, four):
41
- """0 < n < 1000. pad: a bigger group stands before this one, so the hundreds are always said (không trăm)."""
42
- h, t, u = n // 100, n // 10 % 10, n % 10
43
- w = []
44
- if h or pad:
45
- w += [_VI[h], 'trăm']
46
- if t == 0:
47
- if u:
48
- if w:
49
- w.append(linh)
50
- w.append(_VI[u])
51
- elif t == 1:
52
- w.append('mười')
53
- if u:
54
- w.append('lăm' if u == 5 else _VI[u])
55
- else:
56
- w += [_VI[t], 'mươi']
57
- if u == 1:
58
- w.append('mốt')
59
- elif u == 4:
60
- w.append(four)
61
- elif u == 5:
62
- w.append('lăm')
63
- elif u:
64
- w.append(_VI[u])
65
- return w
66
-
67
-
68
- def vi(n, linh='linh', four='bốn', thousand='nghìn'):
69
- """105 một trăm linh năm (linh='lẻ' for the Southern word); 1234 một nghìn hai trăm ba mươi bốn (four='tư': ba mươi tư)."""
70
- if n == 0:
71
- return 'không'
72
- unit = ['', thousand, 'triệu', 'tỷ']
73
- g = _groups3(n)
74
- w = []
75
- for i in range(len(g) - 1, -1, -1):
76
- if g[i]:
77
- w += _vi3(g[i], bool(w), linh, four)
78
- if unit[i]:
79
- w.append(unit[i])
80
- return ' '.join(w)
81
-
82
-
83
- # ---------------------------------------------------------------- en
84
- _EN1 = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve',
85
- 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen']
86
- _EN10 = ['', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety']
87
-
88
-
89
- def _en3(n, and_):
90
- h, r = divmod(n, 100)
91
- w = []
92
- if h:
93
- w += [_EN1[h], 'hundred']
94
- if r:
95
- if h and and_:
96
- w.append('and')
97
- w.append(_EN1[r] if r < 20 else _EN10[r // 10] + ('-' + _EN1[r % 10] if r % 10 else ''))
98
- return w
99
-
100
-
101
- def en(n, and_=False):
102
- """US reading by default (one hundred five); and_=True: one hundred and five, one thousand and five."""
103
- if n == 0:
104
- return 'zero'
105
- unit = ['', 'thousand', 'million', 'billion']
106
- g = _groups3(n)
107
- w = []
108
- for i in range(len(g) - 1, -1, -1):
109
- if g[i]:
110
- if and_ and i == 0 and w and g[i] < 100:
111
- w.append('and')
112
- w += _en3(g[i], and_)
113
- if unit[i]:
114
- w.append(unit[i])
115
- return ' '.join(w)
116
-
117
-
118
- # ---------------------------------------------------------------- ja (hiragana; kanji as a second form)
119
- _JA1 = ['', 'いち', 'に', 'さん', 'よん', 'ご', 'ろく', 'なな', 'はち', 'きゅう']
120
- _JA100 = ['', 'ひゃく', 'にひゃく', 'さんびゃく', 'よんひゃく', 'ごひゃく', 'ろっぴゃく', 'ななひゃく', 'はっぴゃく', 'きゅうひゃく']
121
- _JA1000 = ['', 'せん', 'にせん', 'さんぜん', 'よんせん', 'ごせん', 'ろくせん', 'ななせん', 'はっせん', 'きゅうせん']
122
- _KANJI = '〇一二三四五六七八九'
123
-
124
-
125
- def _ja4(n):
126
- th, h, t, u = n // 1000, n // 100 % 10, n // 10 % 10, n % 10
127
- s = _JA1000[th] + _JA100[h]
128
- if t:
129
- s += ('' if t == 1 else _JA1[t]) + 'じゅう'
130
- return s + _JA1[u]
131
-
132
-
133
- def _kanji4(n):
134
- s = ''
135
- for d, unit in ((n // 1000, '千'), (n // 100 % 10, '百'), (n // 10 % 10, '十')):
136
- if d:
137
- s += ('' if d == 1 else _KANJI[d]) + unit
138
- u = n % 10
139
- return s + (_KANJI[u] if u else '')
140
-
141
-
142
- def ja(n, zero='ゼロ', script='kana'):
143
- """せんにひゃくさんじゅうよん; よん / なな / きゅう; さんびゃく ろっぴゃく はっぴゃく さんぜん はっせん; いっせんまん."""
144
- if script == 'kanji':
145
- if n == 0:
146
- return '零'
147
- oku, man, rest = n // 10 ** 8, n // 10 ** 4 % 10 ** 4, n % 10 ** 4
148
- s = ''
149
- if oku:
150
- s += ('一千' if oku == 1000 else _kanji4(oku)) + '億'
151
- if man:
152
- s += ('一千' if man == 1000 else _kanji4(man)) + '万'
153
- return s + _kanji4(rest)
154
- if n == 0:
155
- return zero
156
- oku, man, rest = n // 10 ** 8, n // 10 ** 4 % 10 ** 4, n % 10 ** 4
157
- s = ''
158
- if oku:
159
- s += ('いっせん' if oku == 1000 else _ja4(oku)) + 'おく'
160
- if man:
161
- s += ('いっせん' if man == 1000 else _ja4(man)) + 'まん'
162
- return s + _ja4(rest)
163
-
164
-
165
- # ---------------------------------------------------------------- ko (Sino-Korean)
166
- _KO1 = ['', '일', '이', '삼', '사', '오', '육', '칠', '팔', '구']
167
-
168
-
169
- def _ko4(n):
170
- s = ''
171
- for d, unit in ((n // 1000, '천'), (n // 100 % 10, '백'), (n // 10 % 10, '십')):
172
- if d:
173
- s += ('' if d == 1 else _KO1[d]) + unit
174
- return s + _KO1[n % 10]
175
-
176
-
177
- def ko(n):
178
- """천이백삼십사; 만 (not 일만), 일억; a space between the 만 groups. Counting things (세 개, 다섯 명) is NOT this."""
179
- if n == 0:
180
- return '영'
181
- eok, man, rest = n // 10 ** 8, n // 10 ** 4 % 10 ** 4, n % 10 ** 4
182
- parts = []
183
- if eok:
184
- parts.append(_ko4(eok) + '억')
185
- if man:
186
- parts.append(('' if man == 1 else _ko4(man)) + '만')
187
- if rest:
188
- parts.append(_ko4(rest))
189
- return ' '.join(parts)
190
-
191
-
192
- # ---------------------------------------------------------------- zh-Hans
193
- _ZH = '零一二三四五六七八九'
194
-
195
-
196
- def _zh4(n, lead):
197
- """0 < n < 10000. lead: nothing was said before, so 10..19 is 十X (not 一十X)."""
198
- s = ''
199
- zero = False
200
- for i, (d, unit) in enumerate(((n // 1000, '千'), (n // 100 % 10, '百'), (n // 10 % 10, '十'), (n % 10, ''))):
201
- if d == 0:
202
- zero = bool(s)
203
- continue
204
- if zero:
205
- s += '零'
206
- zero = False
207
- if i == 2 and d == 1 and not s and lead:
208
- s += '十'
209
- elif i == 0 and d == 2:
210
- s += '两千'
211
- else:
212
- s += _ZH[d] + unit
213
- return s
214
-
215
-
216
- def zh(n, liang=True):
217
- """一千二百三十四; 一百零五; 一百一十; 两千 / 两万 (liang=False keeps 二 everywhere)."""
218
- if n == 0:
219
- return '零'
220
- yi, wan, rest = n // 10 ** 8, n // 10 ** 4 % 10 ** 4, n % 10 ** 4
221
- s = ''
222
- if yi:
223
- s += ('两' if yi == 2 else _zh4(yi, True)) + '亿'
224
- if wan:
225
- if s and wan < 1000:
226
- s += '零'
227
- s += ('两' if wan == 2 and not s else _zh4(wan, not s)) + '万'
228
- if rest:
229
- if s and (rest < 1000 or wan == 0):
230
- s += '零'
231
- s += _zh4(rest, not s)
232
- return s if liang else s.replace('两', '二')
233
-
234
-
235
- # ---------------------------------------------------------------- es
236
- _ES1 = ['cero', 'uno', 'dos', 'tres', 'cuatro', 'cinco', 'seis', 'siete', 'ocho', 'nueve', 'diez', 'once', 'doce',
237
- 'trece', 'catorce', 'quince', 'dieciséis', 'diecisiete', 'dieciocho', 'diecinueve', 'veinte', 'veintiuno',
238
- 'veintidós', 'veintitrés', 'veinticuatro', 'veinticinco', 'veintiséis', 'veintisiete', 'veintiocho',
239
- 'veintinueve']
240
- _ES10 = ['', '', '', 'treinta', 'cuarenta', 'cincuenta', 'sesenta', 'setenta', 'ochenta', 'noventa']
241
- _ES100 = ['', 'ciento', 'doscientos', 'trescientos', 'cuatrocientos', 'quinientos', 'seiscientos', 'setecientos',
242
- 'ochocientos', 'novecientos']
243
-
244
-
245
- def _es3(n, apocope):
246
- """0 < n < 1000. apocope: before mil / millones (veintiún mil, ciento un mil)."""
247
- if n == 100:
248
- return ['cien']
249
- h, r = divmod(n, 100)
250
- w = []
251
- if h:
252
- w.append(_ES100[h])
253
- if r:
254
- if r < 30:
255
- w.append('un' if apocope and r == 1 else 'veintiún' if apocope and r == 21 else _ES1[r])
256
- else:
257
- t, u = divmod(r, 10)
258
- w.append(_ES10[t])
259
- if u:
260
- w += ['y', 'un' if apocope and u == 1 else _ES1[u]]
261
- return w
262
-
263
-
264
- def _es6(n, apocope):
265
- th, r = divmod(n, 1000)
266
- w = []
267
- if th:
268
- if th > 1:
269
- w += _es3(th, True)
270
- w.append('mil')
271
- if r:
272
- w += _es3(r, apocope)
273
- return w
274
-
275
-
276
- def es(n):
277
- """mil doscientos treinta y cuatro; ciento cinco; cien; veintiún mil; un millón; mil millones (10**9)."""
278
- if n == 0:
279
- return 'cero'
280
- m, r = divmod(n, 10 ** 6)
281
- w = []
282
- if m:
283
- w += ['un', 'millón'] if m == 1 else _es6(m, True) + ['millones']
284
- if r:
285
- w += _es6(r, False)
286
- return ' '.join(w)
287
-
288
-
289
- # ---------------------------------------------------------------- pt-BR
290
- _PT1 = ['zero', 'um', 'dois', 'três', 'quatro', 'cinco', 'seis', 'sete', 'oito', 'nove', 'dez', 'onze', 'doze',
291
- 'treze', 'quatorze', 'quinze', 'dezesseis', 'dezessete', 'dezoito', 'dezenove']
292
- _PT10 = ['', '', 'vinte', 'trinta', 'quarenta', 'cinquenta', 'sessenta', 'setenta', 'oitenta', 'noventa']
293
- _PT100 = ['', 'cento', 'duzentos', 'trezentos', 'quatrocentos', 'quinhentos', 'seiscentos', 'setecentos',
294
- 'oitocentos', 'novecentos']
295
-
296
-
297
- def _pt3(n):
298
- if n == 100:
299
- return 'cem'
300
- h, r = divmod(n, 100)
301
- parts = []
302
- if h:
303
- parts.append(_PT100[h])
304
- if r:
305
- if r < 20:
306
- parts.append(_PT1[r])
307
- else:
308
- parts.append(_PT10[r // 10])
309
- if r % 10:
310
- parts.append(_PT1[r % 10])
311
- return ' e '.join(parts)
312
-
313
-
314
- def pt(n):
315
- """mil duzentos e trinta e quatro; cento e cinco; mil e cem; um milhão e duzentos mil; um bilhão (10**9)."""
316
- if n == 0:
317
- return 'zero'
318
- g = _groups3(n) + [0, 0, 0]
319
- chunks = []
320
- if g[3]:
321
- chunks.append((g[3], 'um bilhão' if g[3] == 1 else _pt3(g[3]) + ' bilhões'))
322
- if g[2]:
323
- chunks.append((g[2], 'um milhão' if g[2] == 1 else _pt3(g[2]) + ' milhões'))
324
- if g[1]:
325
- chunks.append((g[1], 'mil' if g[1] == 1 else _pt3(g[1]) + ' mil'))
326
- if g[0]:
327
- chunks.append((g[0], _pt3(g[0])))
328
- s = chunks[0][1]
329
- for i, (value, text) in enumerate(chunks[1:], 1):
330
- last = i == len(chunks) - 1
331
- s += (' e ' if last and (value < 100 or value % 100 == 0) else ' ') + text
332
- return s
333
-
334
-
335
- # ---------------------------------------------------------------- de
336
- _DE1 = ['null', 'ein', 'zwei', 'drei', 'vier', 'fünf', 'sechs', 'sieben', 'acht', 'neun', 'zehn', 'elf', 'zwölf',
337
- 'dreizehn', 'vierzehn', 'fünfzehn', 'sechzehn', 'siebzehn', 'achtzehn', 'neunzehn']
338
- _DE10 = ['', '', 'zwanzig', 'dreißig', 'vierzig', 'fünfzig', 'sechzig', 'siebzig', 'achtzig', 'neunzig']
339
-
340
-
341
- def _de3(n, final):
342
- """0 < n < 1000. final: the number ends here, so a last 1 is "eins"."""
343
- h, r = divmod(n, 100)
344
- s = _DE1[h] + 'hundert' if h else ''
345
- if r == 1:
346
- s += 'eins' if final else 'ein'
347
- elif r < 20:
348
- s += _DE1[r] if r else ''
349
- else:
350
- s += (_DE1[r % 10] + 'und' if r % 10 else '') + _DE10[r // 10]
351
- return s
352
-
353
-
354
- def de(n):
355
- """eintausendzweihundertvierunddreißig; einhundertfünf; eine Million; eine Milliarde (10**9)."""
356
- if n == 0:
357
- return 'null'
358
- g = _groups3(n) + [0, 0, 0]
359
- parts = []
360
- if g[3]:
361
- parts.append('eine Milliarde' if g[3] == 1 else _de3(g[3], True) + ' Milliarden')
362
- if g[2]:
363
- parts.append('eine Million' if g[2] == 1 else _de3(g[2], True) + ' Millionen')
364
- low = (_de3(g[1], False) + 'tausend' if g[1] else '') + (_de3(g[0], True) if g[0] else '')
365
- if low:
366
- parts.append(low)
367
- return ' '.join(parts)
368
-
369
-
370
- # ---------------------------------------------------------------- fr (France)
371
- _FR1 = ['zéro', 'un', 'deux', 'trois', 'quatre', 'cinq', 'six', 'sept', 'huit', 'neuf', 'dix', 'onze', 'douze',
372
- 'treize', 'quatorze', 'quinze', 'seize', 'dix-sept', 'dix-huit', 'dix-neuf']
373
- _FR10 = ['', '', 'vingt', 'trente', 'quarante', 'cinquante', 'soixante']
374
-
375
-
376
- def _fr2(n, final):
377
- if n < 20:
378
- return _FR1[n]
379
- if n < 70:
380
- t, u = divmod(n, 10)
381
- return _FR10[t] + ('' if u == 0 else ' et un' if u == 1 else '-' + _FR1[u])
382
- if n < 80:
383
- return 'soixante et onze' if n == 71 else 'soixante-' + _FR1[n - 60]
384
- if n == 80:
385
- return 'quatre-vingts' if final else 'quatre-vingt'
386
- return 'quatre-vingt-' + _FR1[n - 80]
387
-
388
-
389
- def _fr3(n, final):
390
- """0 < n < 1000. final: nothing but million(s) / milliard(s) follows, so vingts and cents keep their s."""
391
- h, r = divmod(n, 100)
392
- w = []
393
- if h:
394
- w.append('cent' if h == 1 else _FR1[h] + (' cents' if r == 0 and final else ' cent'))
395
- if r:
396
- w.append(_fr2(r, final))
397
- return ' '.join(w)
398
-
399
-
400
- def fr(n):
401
- """mille deux cent trente-quatre; cent cinq; quatre-vingts; quatre-vingt-onze; deux cents; un milliard (10**9)."""
402
- if n == 0:
403
- return 'zéro'
404
- g = _groups3(n) + [0, 0, 0]
405
- w = []
406
- if g[3]:
407
- w.append(_fr3(g[3], True) + (' milliard' if g[3] == 1 else ' milliards'))
408
- if g[2]:
409
- w.append(_fr3(g[2], True) + (' million' if g[2] == 1 else ' millions'))
410
- if g[1]:
411
- w.append('mille' if g[1] == 1 else _fr3(g[1], False) + ' mille')
412
- if g[0]:
413
- w.append(_fr3(g[0], True))
414
- return ' '.join(w)
415
-
416
-
417
- # ---------------------------------------------------------------- id
418
- _ID1 = ['nol', 'satu', 'dua', 'tiga', 'empat', 'lima', 'enam', 'tujuh', 'delapan', 'sembilan']
419
-
420
-
421
- def _id3(n):
422
- h, t, u = n // 100, n // 10 % 10, n % 10
423
- w = []
424
- if h:
425
- w.append('seratus' if h == 1 else _ID1[h] + ' ratus')
426
- if t == 1:
427
- w.append('sepuluh' if u == 0 else 'sebelas' if u == 1 else _ID1[u] + ' belas')
428
- else:
429
- if t:
430
- w.append(_ID1[t] + ' puluh')
431
- if u:
432
- w.append(_ID1[u])
433
- return ' '.join(w)
434
-
435
-
436
- def id_(n):
437
- """seribu dua ratus tiga puluh empat; seratus lima; sebelas; satu juta; satu miliar (10**9)."""
438
- if n == 0:
439
- return 'nol'
440
- g = _groups3(n) + [0, 0, 0]
441
- w = []
442
- if g[3]:
443
- w.append(_id3(g[3]) + ' miliar')
444
- if g[2]:
445
- w.append(_id3(g[2]) + ' juta')
446
- if g[1]:
447
- w.append('seribu' if g[1] == 1 else _id3(g[1]) + ' ribu')
448
- if g[0]:
449
- w.append(_id3(g[0]))
450
- return ' '.join(w)
451
-
452
-
453
- # ---------------------------------------------------------------- common API
454
- _SPELL = {'vi': vi, 'en': en, 'ja': ja, 'ko': ko, 'zh-Hans': zh, 'es': es, 'pt-BR': pt, 'de': de, 'fr': fr, 'id': id_}
455
- # style options a project may set (i18n.config.json -> voice.numberStyle.<lang>)
456
- STYLE_KEYS = {'vi': ('linh', 'four', 'thousand'), 'en': ('and_',), 'ja': ('zero',), 'zh-Hans': ('liang',)}
457
- _POINT = {'vi': 'phẩy', 'en': 'point', 'ja': 'てん', 'ko': '점', 'zh-Hans': '点', 'es': 'coma', 'pt-BR': 'vírgula',
458
- 'de': 'Komma', 'fr': 'virgule', 'id': 'koma'}
459
- _MINUS = {'vi': 'âm', 'en': 'minus', 'ja': 'マイナス', 'ko': '마이너스', 'zh-Hans': '负', 'es': 'menos', 'pt-BR': 'menos',
460
- 'de': 'minus', 'fr': 'moins', 'id': 'minus'}
461
- _DIGIT0 = {'ja': 'ゼロ', 'ko': '공'} # the word for 0 when digits are read one by one
462
- _NOSPACE = ('ja', 'zh-Hans') # words are written without spaces
463
- _DECIMAL_MARK = {'en': '.', 'ja': '.', 'ko': '.', 'zh-Hans': '.', 'vi': ',', 'de': ',', 'fr': ',', 'es': ',',
464
- 'pt-BR': ',', 'id': ','}
465
- _GROUP_MARK = {'en': ',', 'ja': ',', 'ko': ',', 'zh-Hans': ',', 'vi': '.', 'de': '.', 'es': '.', 'pt-BR': '.',
466
- 'id': '.', 'fr': ' '}
467
-
468
-
469
- def _check_lang(lang):
470
- if lang not in _SPELL:
471
- raise ValueError('no number rules for %r (voice languages: %s)' % (lang, ' '.join(LANGS)))
472
-
473
-
474
- def spell(n, lang, **style):
475
- """The cardinal number n in words. style: see STYLE_KEYS (unknown keys for the language are ignored)."""
476
- _check_lang(lang)
477
- if not 0 <= n < MAX:
478
- raise ValueError('%d is outside 0..10^12-1: write the reading by hand' % n)
479
- style = {k: v for k, v in style.items() if k in STYLE_KEYS.get(lang, ())}
480
- return _SPELL[lang](n, **style)
481
-
482
-
483
- def spell_digits(digits, lang, **style):
484
- """Digits read one by one (codes, phone numbers, "007"): không không bảy."""
485
- _check_lang(lang)
486
- words = [_DIGIT0.get(lang) or spell(0, lang, **style) if d == '0' else spell(int(d), lang, **style) for d in digits]
487
- return ''.join(words) if lang == 'zh-Hans' else ' '.join(words)
488
-
489
-
490
- def spell_decimal(whole, frac, lang, **style):
491
- """3.14 -> three point one four (the digits after the mark are read one by one)."""
492
- _check_lang(lang)
493
- a = spell(int(whole), lang, **style)
494
- b = spell_digits(frac, lang, **style)
495
- if lang == 'ja':
496
- zero = style.get('zero', 'ゼロ')
497
- if a == zero:
498
- a = 'れい' # 0.5 れいてんご
499
- for end, new in (('いち', 'いっ'), ('はち', 'はっ'), ('じゅう', 'じゅっ')):
500
- if a.endswith(end):
501
- a = a[:-len(end)] + new # いってん, はってん, じゅってん
502
- break
503
- return a + 'てん' + b.replace(' ', '').replace('ゼロ', 'れい')
504
- if lang == 'zh-Hans':
505
- return a + _POINT[lang] + b
506
- return '%s %s %s' % (a, _POINT[lang], b)
507
-
508
-
509
- _JA_GEMINATE = (('いち', 'いっ'), ('ろく', 'ろっ'), ('はち', 'はっ'), ('じゅう', 'じゅっ'), ('じゅう', 'じっ'), ('ひゃく', 'ひゃっ'))
510
- _JA_NATIVE = {1: ['ひと'], 2: ['ふた'], 3: ['みっ'], 4: ['よっ'], 5: ['いつ'], 6: ['むっ'], 7: ['しち'], 8: ['やっ'],
511
- 9: ['ここの'], 10: ['とお']}
512
- _KO_NATIVE1 = ['', '한 하나', '두 둘', '세 셋', '네 넷', '다섯', '여섯', '일곱', '여덟', '아홉']
513
- _KO_NATIVE10 = ['', '열', '스물 스무', '서른', '마흔', '쉰', '예순', '일흔', '여든', '아흔']
514
-
515
-
516
- def _ko_native(n):
517
- """Native Korean numbers 1..99, as said before a counter (세 개, 스무 살, 열두 명)."""
518
- if not 1 <= n <= 99:
519
- return []
520
- t, u = divmod(n, 10)
521
- return [a + b for a in (_KO_NATIVE10[t].split() if t else ['']) for b in (_KO_NATIVE1[u].split() if u else [''])]
522
-
523
-
524
- def forms(n, lang):
525
- """Every accepted way to hear the cardinal n (for the check after synthesis), most usual first, plus the digits.
526
- Includes the readings a number takes before a counter or a feminine noun (ja ひゃっこ / みっつ, ko 세 개, es una,
527
- pt duas, fr une), so a correct clip is not refused."""
528
- _check_lang(lang)
529
- out = []
530
- if lang == 'vi':
531
- for thousand in ('nghìn', 'ngàn'):
532
- for linh in ('linh', 'lẻ'):
533
- for four in ('bốn', 'tư'):
534
- s = vi(n, linh=linh, four=four, thousand=thousand)
535
- out += [s, s.replace('mốt', 'một'), s.replace('tỷ', 'tỉ')]
536
- elif lang == 'en':
537
- out = [en(n), en(n, and_=True)]
538
- elif lang == 'ja':
539
- kana = ja(n)
540
- out = [kana, ja(n, script='kanji')]
541
- for end, new in _JA_GEMINATE:
542
- if kana.endswith(end):
543
- out.append(kana[:-len(end)] + new) # ひゃっこ, いっぽん, じゅっぷん
544
- if kana.endswith('なな'):
545
- out.append(kana[:-2] + 'しち')
546
- if n > 10 and kana.endswith('よん'):
547
- out.append(kana[:-1]) # じゅうよにん
548
- if n > 10 and kana.endswith('きゅう'):
549
- out.append(kana[:-3] + 'く') # じゅうくじ
550
- out += _JA_NATIVE.get(n, [])
551
- if n == 0:
552
- out += ['れい', '零', '〇']
553
- elif lang == 'ko':
554
- out = [ko(n)] + _ko_native(n)
555
- elif lang == 'zh-Hans':
556
- out = [zh(n), zh(n, liang=False)]
557
- elif lang == 'de':
558
- s = de(n)
559
- out = [s, re.sub(r'^ein(hundert|tausend)', r'\1', s)] # hundertfünf, tausendzwei
560
- elif lang == 'es':
561
- s = es(n)
562
- out = [s, s.replace('ientos', 'ientas')]
563
- for t in list(out):
564
- if t.endswith('veintiuno'):
565
- out += [t[:-9] + 'veintiún', t[:-9] + 'veintiuna']
566
- elif t.endswith('uno'):
567
- out += [t[:-1], t[:-1] + 'a'] # un, una
568
- elif lang == 'pt-BR':
569
- s = pt(n)
570
- out = [s, s.replace('quatorze', 'catorze'), s.replace('entos', 'entas')]
571
- for t in list(out):
572
- if t.endswith('um'):
573
- out.append(t + 'a') # uma
574
- elif t.endswith('dois'):
575
- out.append(t[:-4] + 'duas')
576
- elif lang == 'fr':
577
- s = fr(n)
578
- out = [s] + ([s + 'e'] if s.endswith('un') else []) # une, vingt et une
579
- else:
580
- out = [spell(n, lang)]
581
- out.append(str(n))
582
- seen = []
583
- for s in out:
584
- if s not in seen:
585
- seen.append(s)
586
- return seen
587
-
588
-
589
- # ---------------------------------------------------------------- speak: digits in a text -> words, with the open issues
590
- _SPACES = '   ' # no-break, narrow no-break, thin: grouping spaces
591
- _NUMBER = re.compile(
592
- r'(?P<sign>(?<![\w.,])[-−](?=\d))?'
593
- r'(?P<int>\d{1,3}(?:[' + _SPACES + r']\d{3})+(?!\d)' # 1 234 567 with a no-break space
594
- r'|\d{1,3}(?:\.\d{3}){2,}(?!\d)|\d{1,3}(?:,\d{3}){2,}(?!\d)' # 1.234.567 / 1,234,567
595
- r'|\d+)'
596
- r'(?:(?P<mark>[.,])(?P<frac>\d+))?(?![.,]?\d)')
597
- _PLAIN_GROUP = re.compile(r'(?<![\d.,])\d{1,3}(?: \d{3})+(?![\d.,])')
598
- _SYMBOLS = '%‰:/+=×÷*^°#$€£¥₫₩~<>'
599
- _CJK = re.compile(r'[぀-ヿ㐀-鿿가-힯々〆ヵヶ]')
600
- _CJK_RUN = re.compile(r'[぀-ヿ㐀-鿿가-힯々〆ヵヶ]{1,3}')
601
-
602
-
603
- def _letter(ch):
604
- return bool(ch) and ch.isalpha()
605
-
606
-
607
- def speak(text, lang, style=None, lenient=False):
608
- """Returns (speak_text, numbers, issues).
609
-
610
- speak_text: the text with every number written in words. numbers: the numbers the text holds, in order (int for
611
- a cardinal, str for a decimal "3.5" or a digit string "007"). issues: what a person or an agent must settle by
612
- writing the spoken text by hand (the `speak` override of the line): a number whose meaning is unclear ("1.234"),
613
- a number glued to letters or to a counter, a symbol next to a number. lenient=True reads grouped numbers by the
614
- language's convention instead of reporting them; it never invents a reading for symbols or counters.
615
- """
616
- _check_lang(lang)
617
- style = style or {}
618
- text = unicodedata.normalize('NFC', text)
619
- numbers, issues = [], []
620
- join = '' if lang in _NOSPACE else ' '
621
-
622
- def issue(kind, m_text, why):
623
- issues.append({'kind': kind, 'at': m_text, 'why': why})
624
-
625
- if not lenient:
626
- for m in _PLAIN_GROUP.finditer(text):
627
- issue('ambiguous', m.group(), 'digit groups split by a plain space: one number or several?')
628
-
629
- def repl(m):
630
- whole, mark, frac = m.group('int'), m.group('mark'), m.group('frac')
631
- before = text[m.start() - 1] if m.start() else ''
632
- after = text[m.end()] if m.end() < len(text) else ''
633
- token = m.group()
634
- cjk_before, cjk_after = bool(_CJK.match(before)), bool(_CJK.match(after))
635
- if (_letter(before) and not cjk_before) or (_letter(after) and not cjk_after):
636
- issue('glued', (before if _letter(before) else '') + token + (after if _letter(after) else ''),
637
- 'a number glued to letters (A4, 3D, 5kg, 1st): write how it is said')
638
- return token
639
- grouped = re.search(r'[.,' + _SPACES + r']', whole) is not None
640
- digits = re.sub(r'\D', '', whole)
641
- if frac is not None and not grouped and len(frac) == 3 and len(whole) <= 3 and not whole.startswith('0'):
642
- if not lenient:
643
- issue('ambiguous', token, '%s could be %s%s or the decimal %s.%s: write it without the mark (%s%s) or write the spoken text'
644
- % (token, whole, frac, whole, frac, whole, frac))
645
- return token
646
- if mark == _GROUP_MARK[lang]:
647
- digits, frac, mark = whole + frac, None, None
648
- elif frac is not None and mark != _DECIMAL_MARK[lang] and not lenient:
649
- issue('ambiguous', token, 'the decimal mark of %s is %r, not %r' % (lang, _DECIMAL_MARK[lang], mark))
650
- return token
651
- if int(digits) >= MAX:
652
- issue('large', token, 'too large: write the reading by hand')
653
- return token
654
- negative = bool(m.group('sign'))
655
- sign = (_MINUS[lang] + join) if negative else ''
656
- if frac is not None:
657
- value = ('-' if negative else '') + digits + '.' + frac
658
- elif len(digits) > 1 and digits.startswith('0') and not grouped:
659
- value = digits
660
- else:
661
- value = -int(digits) if negative else int(digits)
662
- if (cjk_before or cjk_after) and not (lang == 'zh-Hans' and frac is None) and (lang in ('ja', 'ko') or not lenient):
663
- numbers.append(value)
664
- run = _CJK_RUN.match(text, m.end())
665
- issue('counter', token + (run.group() if run else ''),
666
- 'a number with a counter changes its reading (3つ みっつ, 1本 いっぽん, 3개 세 개): write the spoken text')
667
- return token
668
- for ch, shown in ((before, before + token), (after, token + after)):
669
- if ch and ch in _SYMBOLS:
670
- issue('symbol', shown, 'the symbol %r is left for the voice to guess: write the words' % ch)
671
- numbers.append(value)
672
- tail = '' if frac is not None or not mark else mark # "3." at a sentence end: the mark is punctuation
673
- if frac is not None:
674
- return sign + spell_decimal(digits, frac, lang, **style)
675
- if isinstance(value, str):
676
- return sign + spell_digits(digits, lang, **style) + tail
677
- if lang == 'zh-Hans' and int(digits) == 2 and cjk_after and after not in '十百千万亿月日号点分秒年级楼层':
678
- return sign + '两' + tail # 2个 两个
679
- return sign + spell(int(digits), lang, **style) + tail
680
-
681
- return _NUMBER.sub(repl, text), numbers, issues
682
-
683
-
684
- def numbers_in(text, lang, style=None):
685
- """The numbers a shown text holds, read by the language's own conventions ("1.500" in Vietnamese is 1500).
686
- For a line whose spoken text is written by hand: these are the numbers that spoken text must say."""
687
- return speak(text, lang, style, lenient=True)[1]
688
-
689
-
690
- # ---------------------------------------------------------------- heard: were the numbers said?
691
- _CONNECT = {'and', 'y', 'e', 'et'} # words that join number parts but also join ordinary phrases
692
-
693
-
694
- def canon(text, lang):
695
- """A text reduced to what can be compared: case, punctuation and (for scripts without word spaces) spaces dropped."""
696
- t = unicodedata.normalize('NFKC', text).lower()
697
- if lang in ('ja', 'zh-Hans', 'ko', 'de'):
698
- return re.sub(r'[\W_]+', '', t)
699
- return ' '.join(re.sub(r"[^\w]+", ' ', t).split())
700
-
701
-
702
- def _number_words(lang):
703
- """(structure words, unit words). Structure words only occur inside a number (trăm, nghìn, hundred, mil, vingt);
704
- unit words are the readings of 0..9. Found by spelling a sample of numbers."""
705
- sample = list(range(0, 130)) + [200, 300, 500, 700, 900, 1000, 2000, 10 ** 4, 10 ** 5, 10 ** 6, 2 * 10 ** 6, 10 ** 9]
706
- units = set()
707
- for n in range(0, 10):
708
- for f in forms(n, lang):
709
- units.update(canon(f, lang).split())
710
- words = set()
711
- for n in sample:
712
- for f in forms(n, lang):
713
- words.update(canon(f, lang).split())
714
- return ({w for w in words - units - _CONNECT if not w.isdigit()}, {u for u in units if not u.isdigit()})
715
-
716
-
717
- _WORDS = {}
718
-
719
-
720
- def heard(numbers, transcript, lang):
721
- """Checks that each expected number was said whole and in order in a text (a recogniser's transcript, or a
722
- hand-written spoken text).
723
-
724
- numbers: the list from speak() or numbers_in(). Returns (ok, details). A number counts when one of its accepted
725
- forms (words or digits) stands in the text and, in the languages written with spaces, is not part of a longer
726
- number ("hai trăm ba mươi bốn" inside "một nghìn hai trăm ba mươi bốn", "one hundred" inside "one hundred
727
- five"). This is the floor every project applies after synthesis; a project may add stricter gates on top.
728
- """
729
- _check_lang(lang)
730
- spaced = lang not in ('ja', 'zh-Hans', 'ko', 'de')
731
- if spaced and lang not in _WORDS:
732
- _WORDS[lang] = _number_words(lang)
733
- struct, units = _WORDS.get(lang, (set(), set()))
734
- # a unit right after a structure word continues the number (twenty five), except vi "năm" (also "year": 25 is
735
- # "hai mươi lăm") and "không"
736
- follow = units - {'năm', 'không'} if lang == 'vi' else units
737
-
738
- def part_of_longer(text, start, end, form):
739
- left, right = text[:start].split(), text[end:].split()
740
- last = form.split()[-1]
741
- if left:
742
- if left[-1] in struct or left[-1].isdigit():
743
- return True
744
- if left[-1] in _CONNECT and len(left) > 1 and left[-2] in struct:
745
- return True # two hundred and | thirty-four
746
- if right:
747
- if right[0] in struct or right[0].isdigit():
748
- return True
749
- if last in struct:
750
- if right[0] in follow:
751
- return True # one hundred | five
752
- if right[0] in _CONNECT and len(right) > 1 and (right[1] in struct or right[1] in units or right[1].isdigit()):
753
- return True # one hundred | and five
754
- return False
755
-
756
- raw = unicodedata.normalize('NFKC', transcript)
757
- variants = [canon(raw, lang), canon(re.sub(r'(?<=\d)[,.' + _SPACES + r' ](?=\d{3}(?!\d))', '', raw), lang)]
758
- details, ok = [], True
759
- for text in variants:
760
- details, ok, pos = [], True, 0
761
- for num in numbers:
762
- if isinstance(num, int):
763
- cand = forms(abs(num), lang)
764
- elif '.' in num:
765
- whole, frac = num.lstrip('-').split('.')
766
- cand = [spell_decimal(whole, frac, lang), whole + '.' + frac, whole + ',' + frac, whole + frac]
767
- else:
768
- cand = [spell_digits(num, lang), num]
769
- found = None
770
- for f in cand:
771
- c = canon(f, lang)
772
- if not c:
773
- continue
774
- if spaced:
775
- for m in re.finditer(r'(?<![\w])' + re.escape(c) + r'(?![\w])', text[pos:]):
776
- if part_of_longer(text, pos + m.start(), pos + m.end(), c):
777
- continue
778
- found = (pos + m.start(), pos + m.end(), f)
779
- break
780
- else:
781
- i = text.find(c, pos)
782
- while i >= 0 and c.isdigit() and ((i and text[i - 1].isdigit()) or text[i + len(c):i + len(c) + 1].isdigit()):
783
- i = text.find(c, i + 1)
784
- if i >= 0:
785
- found = (i, i + len(c), f)
786
- if found:
787
- break
788
- if found:
789
- pos = found[1]
790
- details.append({'number': num, 'heard': found[2]})
791
- else:
792
- ok = False
793
- details.append({'number': num, 'heard': None, 'expected': cand[0]})
794
- if ok:
795
- break
796
- return ok, details
797
-
798
-
799
- # ---------------------------------------------------------------- self-test
800
- _EXPECT = {
801
- 'vi': {0: 'không', 5: 'năm', 10: 'mười', 11: 'mười một', 14: 'mười bốn', 15: 'mười lăm', 20: 'hai mươi',
802
- 21: 'hai mươi mốt', 24: 'hai mươi bốn', 25: 'hai mươi lăm', 55: 'năm mươi lăm', 100: 'một trăm',
803
- 101: 'một trăm linh một', 105: 'một trăm linh năm', 110: 'một trăm mười', 115: 'một trăm mười lăm',
804
- 121: 'một trăm hai mươi mốt', 1000: 'một nghìn', 1005: 'một nghìn không trăm linh năm',
805
- 1050: 'một nghìn không trăm năm mươi', 1234: 'một nghìn hai trăm ba mươi bốn', 10000: 'mười nghìn',
806
- 15000: 'mười lăm nghìn', 100000: 'một trăm nghìn', 1000000: 'một triệu',
807
- 1000001: 'một triệu không trăm linh một', 2500000: 'hai triệu năm trăm nghìn', 10 ** 9: 'một tỷ'},
808
- 'en': {0: 'zero', 13: 'thirteen', 21: 'twenty-one', 100: 'one hundred', 105: 'one hundred five',
809
- 110: 'one hundred ten', 1000: 'one thousand', 1005: 'one thousand five',
810
- 1234: 'one thousand two hundred thirty-four', 10000: 'ten thousand', 100000: 'one hundred thousand',
811
- 1000000: 'one million',
812
- 1234567: 'one million two hundred thirty-four thousand five hundred sixty-seven', 10 ** 9: 'one billion'},
813
- 'ja': {0: 'ゼロ', 4: 'よん', 7: 'なな', 9: 'きゅう', 10: 'じゅう', 14: 'じゅうよん', 20: 'にじゅう', 100: 'ひゃく',
814
- 105: 'ひゃくご', 300: 'さんびゃく', 600: 'ろっぴゃく', 800: 'はっぴゃく', 1000: 'せん',
815
- 1234: 'せんにひゃくさんじゅうよん', 3000: 'さんぜん', 8000: 'はっせん', 10000: 'いちまん',
816
- 12345: 'いちまんにせんさんびゃくよんじゅうご', 100000: 'じゅうまん', 1000000: 'ひゃくまん',
817
- 10000000: 'いっせんまん', 10 ** 8: 'いちおく'},
818
- 'es': {0: 'cero', 16: 'dieciséis', 21: 'veintiuno', 22: 'veintidós', 30: 'treinta', 31: 'treinta y uno',
819
- 100: 'cien', 101: 'ciento uno', 105: 'ciento cinco', 500: 'quinientos', 700: 'setecientos',
820
- 900: 'novecientos', 1000: 'mil', 1001: 'mil uno', 1234: 'mil doscientos treinta y cuatro', 2000: 'dos mil',
821
- 21000: 'veintiún mil', 100000: 'cien mil', 101000: 'ciento un mil', 1000000: 'un millón',
822
- 2000000: 'dos millones', 10 ** 9: 'mil millones'},
823
- 'pt-BR': {0: 'zero', 14: 'quatorze', 16: 'dezesseis', 19: 'dezenove', 21: 'vinte e um', 100: 'cem',
824
- 101: 'cento e um', 105: 'cento e cinco', 200: 'duzentos', 1000: 'mil', 1001: 'mil e um',
825
- 1100: 'mil e cem', 1200: 'mil e duzentos', 1234: 'mil duzentos e trinta e quatro', 2000: 'dois mil',
826
- 2500: 'dois mil e quinhentos', 10000: 'dez mil', 100000: 'cem mil', 1000000: 'um milhão',
827
- 1200000: 'um milhão e duzentos mil', 1250000: 'um milhão duzentos e cinquenta mil',
828
- 2000000: 'dois milhões', 10 ** 9: 'um bilhão'},
829
- 'ko': {0: '영', 1: '일', 10: '십', 11: '십일', 16: '십육', 20: '이십', 100: '백', 105: '백오', 110: '백십',
830
- 1000: '천', 1234: '천이백삼십사', 10000: '만', 12345: '만 이천삼백사십오', 100000: '십만', 110000: '십일만',
831
- 1000000: '백만', 10 ** 8: '일억'},
832
- 'zh-Hans': {0: '零', 2: '二', 10: '十', 11: '十一', 20: '二十', 100: '一百', 101: '一百零一', 105: '一百零五',
833
- 110: '一百一十', 111: '一百一十一', 200: '二百', 1000: '一千', 1001: '一千零一', 1010: '一千零一十',
834
- 1100: '一千一百', 1234: '一千二百三十四', 2000: '两千', 10000: '一万', 10005: '一万零五',
835
- 12000: '一万两千', 20000: '两万', 100000: '十万', 1000000: '一百万', 10 ** 8: '一亿'},
836
- 'de': {0: 'null', 1: 'eins', 11: 'elf', 16: 'sechzehn', 17: 'siebzehn', 21: 'einundzwanzig', 30: 'dreißig',
837
- 100: 'einhundert', 101: 'einhunderteins', 105: 'einhundertfünf', 1000: 'eintausend',
838
- 1001: 'eintausendeins', 1234: 'eintausendzweihundertvierunddreißig', 10000: 'zehntausend',
839
- 100000: 'einhunderttausend', 1000000: 'eine Million', 2000000: 'zwei Millionen',
840
- 1234567: 'eine Million zweihundertvierunddreißigtausendfünfhundertsiebenundsechzig',
841
- 10 ** 9: 'eine Milliarde'},
842
- 'fr': {0: 'zéro', 16: 'seize', 17: 'dix-sept', 21: 'vingt et un', 22: 'vingt-deux', 70: 'soixante-dix',
843
- 71: 'soixante et onze', 80: 'quatre-vingts', 81: 'quatre-vingt-un', 90: 'quatre-vingt-dix',
844
- 91: 'quatre-vingt-onze', 99: 'quatre-vingt-dix-neuf', 100: 'cent', 101: 'cent un', 105: 'cent cinq',
845
- 200: 'deux cents', 201: 'deux cent un', 1000: 'mille', 1234: 'mille deux cent trente-quatre',
846
- 2000: 'deux mille', 80000: 'quatre-vingt mille', 200000: 'deux cent mille', 1000000: 'un million',
847
- 2000000: 'deux millions', 10 ** 9: 'un milliard'},
848
- 'id': {0: 'nol', 10: 'sepuluh', 11: 'sebelas', 12: 'dua belas', 20: 'dua puluh', 21: 'dua puluh satu',
849
- 100: 'seratus', 105: 'seratus lima', 110: 'seratus sepuluh', 111: 'seratus sebelas', 200: 'dua ratus',
850
- 1000: 'seribu', 1001: 'seribu satu', 1234: 'seribu dua ratus tiga puluh empat', 2000: 'dua ribu',
851
- 10000: 'sepuluh ribu', 11000: 'sebelas ribu', 100000: 'seratus ribu', 1000000: 'satu juta',
852
- 10 ** 9: 'satu miliar'},
853
- }
854
-
855
-
856
- def selftest():
857
- bad = 0
858
-
859
- def expect(label, got, want):
860
- nonlocal bad
861
- if got != want:
862
- bad += 1
863
- print('FAIL %s\n got %r\n want %r' % (label, got, want))
864
-
865
- for lang, table in _EXPECT.items():
866
- for n, want in table.items():
867
- expect('%s %d' % (lang, n), spell(n, lang), want)
868
- seen = {}
869
- for n in list(range(0, 2001)) + [9999, 10000, 10001, 99999, 100000, 123456, 999999, 10 ** 6, 10 ** 9 + 1]:
870
- s = spell(n, lang)
871
- if s in seen:
872
- bad += 1
873
- print('FAIL %s: %d and %d are both %r' % (lang, seen[s], n, s))
874
- seen[s] = n
875
- # the two Vietnamese styles
876
- expect('vi lẻ', spell(105, 'vi', linh='lẻ'), 'một trăm lẻ năm')
877
- expect('vi tư', spell(1234, 'vi', four='tư'), 'một nghìn hai trăm ba mươi tư')
878
- expect('en and', spell(1005, 'en', and_=True), 'one thousand and five')
879
- expect('ja kanji', ja(1234, script='kanji'), '千二百三十四')
880
- expect('digits', spell_digits('007', 'vi'), 'không không bảy')
881
- expect('decimal en', spell_decimal('3', '14', 'en'), 'three point one four')
882
- expect('decimal ja', spell_decimal('1', '5', 'ja'), 'いってんご')
883
- expect('decimal vi', spell_decimal('0', '5', 'vi'), 'không phẩy năm')
884
- # speak
885
- s, nums, iss = speak('Bạn có 1234 sao và 105 xu.', 'vi')
886
- expect('speak vi', (s, nums, iss),
887
- ('Bạn có một nghìn hai trăm ba mươi bốn sao và một trăm linh năm xu.', [1234, 105], []))
888
- s, nums, iss = speak('You have 1,234,567 points.', 'en')
889
- expect('speak en grouped', (s, nums, len(iss)),
890
- ('You have one million two hundred thirty-four thousand five hundred sixty-seven points.', [1234567], 0))
891
- for text, lang, kind in (('Bạn có 1.234 sao', 'vi', 'ambiguous'), ('Bạn có 1 234 sao', 'vi', 'ambiguous'),
892
- ('Giảm 50%', 'vi', 'symbol'), ('りんごを3つ', 'ja', 'counter'), ('사과 3개', 'ko', 'counter'),
893
- ('Level 5kg', 'en', 'glued'), ('12:30 に', 'ja', 'symbol')):
894
- _, _, iss = speak(text, lang)
895
- expect('issue %s %r' % (lang, text), [i['kind'] for i in iss][:1], [kind])
896
- expect('counter keeps its number', speak('りんごを3つ', 'ja')[1], [3])
897
- expect('numbers_in vi', numbers_in('Bạn đã nhận 1.500 sao và 105 xu!', 'vi'), [1500, 105])
898
- expect('numbers_in ja', numbers_in('ほしを 1,500こと コインを 105まい もらったよ!', 'ja'), [1500, 105])
899
- expect('numbers_in en', numbers_in('You got 1,500 stars and 105 coins!', 'en'), [1500, 105])
900
- expect('counter shown', [i['at'] for i in speak('コインを 105まい', 'ja')[2]], ['105まい'])
901
- expect('lenient vi', speak('Bạn có 1.234 sao', 'vi', lenient=True)[:2],
902
- ('Bạn có một nghìn hai trăm ba mươi bốn sao', [1234]))
903
- expect('zh liang', speak('我有2个苹果和12个梨', 'zh-Hans')[0], '我有两个苹果和十二个梨')
904
- expect('minus', speak('Nhiệt độ -5 độ', 'vi')[0], 'Nhiệt độ âm năm độ')
905
- expect('sentence end', speak('Chương 3.', 'vi')[:2], ('Chương ba.', [3]))
906
- # heard
907
- for lang, nums, text, want in (
908
- ('vi', [1234], 'Bạn có một nghìn hai trăm ba mươi bốn sao.', True),
909
- ('vi', [1234], 'bạn có một hai trăm ba mươi bốn sao', False), # "nghìn" swallowed
910
- ('vi', [1234], 'Bạn có 1.234 sao', True),
911
- ('vi', [1234], 'bạn có một ngàn hai trăm ba mươi tư sao', True),
912
- ('vi', [105], 'một trăm lẻ năm', True),
913
- ('vi', [234], 'một nghìn hai trăm ba mươi bốn', False), # part of a longer number
914
- ('vi', [5], 'bạn có năm năm', True),
915
- ('vi', [3, 4], 'ba cộng bốn bằng mấy', True),
916
- ('vi', [3, 4], 'bốn cộng ba bằng mấy', False), # order
917
- ('en', [105], 'you have one hundred and five coins', True),
918
- ('en', [1234], 'You have 1,234 coins.', True),
919
- ('en', [34], 'two hundred thirty-four', False),
920
- ('ja', [1234], '千二百三十四です', True),
921
- ('ja', [1234], 'せんにひゃくさんじゅうよんです', True),
922
- ('ja', [1234], '二百三十四です', False),
923
- ('zh-Hans', [2000], '我有二千个', True),
924
- ('ko', [1234], '천 이백 삼십 사 입니다', True),
925
- ('de', [1234], 'Du hast 1.234 Punkte', True),
926
- ('de', [105], 'du hast hundertfünf punkte', True),
927
- ('fr', [80], 'quatre-vingts points', True),
928
- ('es', [21000], 'veintiún mil puntos', True),
929
- ('pt-BR', [1200], 'mil e duzentos pontos', True),
930
- ('id', [1234], 'seribu dua ratus tiga puluh empat', True),
931
- # a number after "and / y / e / et" is not part of a longer one
932
- ('en', [1500, 105], 'You got one thousand five hundred stars and one hundred five coins!', True),
933
- ('en', [3, 2], 'three apples and two pears', True),
934
- ('en', [100], 'one hundred five', False),
935
- ('en', [100], 'one hundred and five coins', False),
936
- ('en', [34], 'two hundred and thirty-four', False),
937
- ('es', [3, 2], 'tres manzanas y dos peras', True),
938
- ('es', [30], 'treinta y uno', False),
939
- ('es', [200], 'doscientas monedas', True),
940
- ('fr', [3, 2], 'trois pommes et deux poires', True),
941
- ('fr', [4], 'quatre-vingts', False),
942
- ('pt-BR', [3, 2], 'três maçãs e duas peras', True),
943
- ('pt-BR', [20], 'vinte e um', False),
944
- ('id', [100], 'seratus lima', False),
945
- ('vi', [20], 'bạn đã chơi hai mươi năm', True),
946
- ('vi', [105], 'một trăm năm', False),
947
- ('vi', [100], 'một trăm linh năm', False),
948
- # readings before a counter
949
- ('ja', [1500, 105], 'ほしを せんごひゃっこと コインを ひゃくごまい もらったよ!', True),
950
- ('ja', [3], 'りんごを みっつ', True),
951
- ('ja', [1], 'えんぴつを いっぽん', True),
952
- ('ko', [3], '사과 세 개', True),
953
- ('ko', [12], '열두 명이 왔어요', True)):
954
- expect('heard %s %r %r' % (lang, nums, text), heard(nums, text, lang)[0], want)
955
- print('selftest: %s' % ('OK' if not bad else '%d FAILED' % bad))
956
- return 1 if bad else 0
957
-
958
-
959
- def _style_args(pairs):
960
- style = {}
961
- for p in pairs or []:
962
- k, _, v = p.partition('=')
963
- style[k] = {'true': True, 'false': False, '1': True, '0': False}.get(v.lower(), v) if k in ('and_', 'liang') else v
964
- return style
965
-
966
-
967
- def main(argv=None):
968
- for stream in (sys.stdout, sys.stderr):
969
- if hasattr(stream, 'reconfigure'):
970
- stream.reconfigure(encoding='utf-8')
971
- ap = argparse.ArgumentParser(description='Numbers as spoken words for the 10 voice languages.')
972
- sub = ap.add_subparsers(dest='cmd', required=True)
973
- p = sub.add_parser('spell', help='one number in words')
974
- p.add_argument('number', type=int)
975
- p.add_argument('--lang')
976
- p.add_argument('--all', action='store_true', help='every voice language')
977
- p.add_argument('--style', nargs='*', metavar='KEY=VALUE', help='vi: linh=lẻ four=tư thousand=ngàn; en: and_=true; ja: zero=れい')
978
- p = sub.add_parser('speak', help='a text with its numbers in words, as JSON {speak, numbers, issues}')
979
- p.add_argument('text')
980
- p.add_argument('--lang', required=True)
981
- p.add_argument('--lenient', action='store_true')
982
- p.add_argument('--style', nargs='*', metavar='KEY=VALUE')
983
- p = sub.add_parser('heard', help='were these numbers said in this transcript? exit 0 yes, 1 no')
984
- p.add_argument('transcript')
985
- p.add_argument('--lang', required=True)
986
- p.add_argument('--numbers', required=True, help='comma separated, as speak printed them: 1234,105')
987
- sub.add_parser('selftest')
988
- a = ap.parse_args(argv)
989
- if a.cmd == 'selftest':
990
- return selftest()
991
- if a.cmd == 'spell':
992
- style = _style_args(a.style)
993
- if a.all or not a.lang:
994
- for lang in LANGS:
995
- print('%-8s %s' % (lang, spell(a.number, lang, **style)))
996
- else:
997
- print(spell(a.number, a.lang, **style))
998
- return 0
999
- if a.cmd == 'speak':
1000
- text, numbers, issues = speak(a.text, a.lang, _style_args(a.style), a.lenient)
1001
- print(json.dumps({'speak': text, 'numbers': numbers, 'issues': issues}, ensure_ascii=False, indent=2))
1002
- return 2 if issues else 0
1003
- if a.cmd == 'heard':
1004
- nums = [int(x) if re.fullmatch(r'-?\d+', x) and not (len(x) > 1 and x.startswith('0')) else x
1005
- for x in a.numbers.split(',') if x]
1006
- ok, details = heard(nums, a.transcript, a.lang)
1007
- print(json.dumps({'ok': ok, 'numbers': details}, ensure_ascii=False, indent=2))
1008
- return 0 if ok else 1
1009
- return 0
1010
-
1011
-
1012
- if __name__ == '__main__':
1013
- sys.exit(main())
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """numwords.py - numbers as spoken words for the 10 voice languages (stdlib only, Python 3.8+).
4
+
5
+ Why: a TTS model that is handed digits guesses the reading ("1234" came out as "một, hai trăm ba mươi bốn"; "1 234"
6
+ and "1.234" are worse). So the text sent to the voice never holds a digit: this tool writes every number out, and the
7
+ same tables check what a recogniser heard afterwards.
8
+
9
+ python numwords.py spell 1234 --lang vi một nghìn hai trăm ba mươi bốn
10
+ python numwords.py spell 105 --all the reading in every voice language
11
+ python numwords.py speak --lang vi "Bạn có 1234 sao" JSON: speak text, the numbers found, the open issues
12
+ python numwords.py heard --lang vi --numbers 1234 "bạn có một nghìn hai trăm ba mươi bốn sao"
13
+ python numwords.py selftest
14
+
15
+ Languages: en ja es pt-BR ko zh-Hans de fr vi id. Range: 0 <= n < 10**12. Rules and pitfalls: references/numbers.md.
16
+ """
17
+ import argparse
18
+ import json
19
+ import re
20
+ import sys
21
+ import unicodedata
22
+
23
+ LANGS = ('en', 'ja', 'es', 'pt-BR', 'ko', 'zh-Hans', 'de', 'fr', 'vi', 'id')
24
+ MAX = 10 ** 12
25
+
26
+
27
+ def _groups3(n):
28
+ """1234567 -> [567, 234, 1] (low group first)."""
29
+ g = []
30
+ while n:
31
+ g.append(n % 1000)
32
+ n //= 1000
33
+ return g
34
+
35
+
36
+ # ---------------------------------------------------------------- vi
37
+ _VI = ['không', 'một', 'hai', 'ba', 'bốn', 'năm', 'sáu', 'bảy', 'tám', 'chín']
38
+
39
+
40
+ def _vi3(n, pad, linh, four):
41
+ """0 < n < 1000. pad: a bigger group stands before this one, so the hundreds are always said (không trăm)."""
42
+ h, t, u = n // 100, n // 10 % 10, n % 10
43
+ w = []
44
+ if h or pad:
45
+ w += [_VI[h], 'trăm']
46
+ if t == 0:
47
+ if u:
48
+ if w:
49
+ w.append(linh)
50
+ w.append(_VI[u])
51
+ elif t == 1:
52
+ w.append('mười')
53
+ if u:
54
+ w.append('lăm' if u == 5 else _VI[u])
55
+ else:
56
+ w += [_VI[t], 'mươi']
57
+ if u == 1:
58
+ w.append('mốt')
59
+ elif u == 4:
60
+ w.append(four)
61
+ elif u == 5:
62
+ w.append('lăm')
63
+ elif u:
64
+ w.append(_VI[u])
65
+ return w
66
+
67
+
68
+ def vi(n, linh='linh', four='bốn', thousand='nghìn'):
69
+ """105 một trăm linh năm (linh='lẻ' for the Southern word); 1234 một nghìn hai trăm ba mươi bốn (four='tư': ba mươi tư)."""
70
+ if n == 0:
71
+ return 'không'
72
+ unit = ['', thousand, 'triệu', 'tỷ']
73
+ g = _groups3(n)
74
+ w = []
75
+ for i in range(len(g) - 1, -1, -1):
76
+ if g[i]:
77
+ w += _vi3(g[i], bool(w), linh, four)
78
+ if unit[i]:
79
+ w.append(unit[i])
80
+ return ' '.join(w)
81
+
82
+
83
+ # ---------------------------------------------------------------- en
84
+ _EN1 = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve',
85
+ 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen']
86
+ _EN10 = ['', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety']
87
+
88
+
89
+ def _en3(n, and_):
90
+ h, r = divmod(n, 100)
91
+ w = []
92
+ if h:
93
+ w += [_EN1[h], 'hundred']
94
+ if r:
95
+ if h and and_:
96
+ w.append('and')
97
+ w.append(_EN1[r] if r < 20 else _EN10[r // 10] + ('-' + _EN1[r % 10] if r % 10 else ''))
98
+ return w
99
+
100
+
101
+ def en(n, and_=False):
102
+ """US reading by default (one hundred five); and_=True: one hundred and five, one thousand and five."""
103
+ if n == 0:
104
+ return 'zero'
105
+ unit = ['', 'thousand', 'million', 'billion']
106
+ g = _groups3(n)
107
+ w = []
108
+ for i in range(len(g) - 1, -1, -1):
109
+ if g[i]:
110
+ if and_ and i == 0 and w and g[i] < 100:
111
+ w.append('and')
112
+ w += _en3(g[i], and_)
113
+ if unit[i]:
114
+ w.append(unit[i])
115
+ return ' '.join(w)
116
+
117
+
118
+ # ---------------------------------------------------------------- ja (hiragana; kanji as a second form)
119
+ _JA1 = ['', 'いち', 'に', 'さん', 'よん', 'ご', 'ろく', 'なな', 'はち', 'きゅう']
120
+ _JA100 = ['', 'ひゃく', 'にひゃく', 'さんびゃく', 'よんひゃく', 'ごひゃく', 'ろっぴゃく', 'ななひゃく', 'はっぴゃく', 'きゅうひゃく']
121
+ _JA1000 = ['', 'せん', 'にせん', 'さんぜん', 'よんせん', 'ごせん', 'ろくせん', 'ななせん', 'はっせん', 'きゅうせん']
122
+ _KANJI = '〇一二三四五六七八九'
123
+
124
+
125
+ def _ja4(n):
126
+ th, h, t, u = n // 1000, n // 100 % 10, n // 10 % 10, n % 10
127
+ s = _JA1000[th] + _JA100[h]
128
+ if t:
129
+ s += ('' if t == 1 else _JA1[t]) + 'じゅう'
130
+ return s + _JA1[u]
131
+
132
+
133
+ def _kanji4(n):
134
+ s = ''
135
+ for d, unit in ((n // 1000, '千'), (n // 100 % 10, '百'), (n // 10 % 10, '十')):
136
+ if d:
137
+ s += ('' if d == 1 else _KANJI[d]) + unit
138
+ u = n % 10
139
+ return s + (_KANJI[u] if u else '')
140
+
141
+
142
+ def ja(n, zero='ゼロ', script='kana'):
143
+ """せんにひゃくさんじゅうよん; よん / なな / きゅう; さんびゃく ろっぴゃく はっぴゃく さんぜん はっせん; いっせんまん."""
144
+ if script == 'kanji':
145
+ if n == 0:
146
+ return '零'
147
+ oku, man, rest = n // 10 ** 8, n // 10 ** 4 % 10 ** 4, n % 10 ** 4
148
+ s = ''
149
+ if oku:
150
+ s += ('一千' if oku == 1000 else _kanji4(oku)) + '億'
151
+ if man:
152
+ s += ('一千' if man == 1000 else _kanji4(man)) + '万'
153
+ return s + _kanji4(rest)
154
+ if n == 0:
155
+ return zero
156
+ oku, man, rest = n // 10 ** 8, n // 10 ** 4 % 10 ** 4, n % 10 ** 4
157
+ s = ''
158
+ if oku:
159
+ s += ('いっせん' if oku == 1000 else _ja4(oku)) + 'おく'
160
+ if man:
161
+ s += ('いっせん' if man == 1000 else _ja4(man)) + 'まん'
162
+ return s + _ja4(rest)
163
+
164
+
165
+ # ---------------------------------------------------------------- ko (Sino-Korean)
166
+ _KO1 = ['', '일', '이', '삼', '사', '오', '육', '칠', '팔', '구']
167
+
168
+
169
+ def _ko4(n):
170
+ s = ''
171
+ for d, unit in ((n // 1000, '천'), (n // 100 % 10, '백'), (n // 10 % 10, '십')):
172
+ if d:
173
+ s += ('' if d == 1 else _KO1[d]) + unit
174
+ return s + _KO1[n % 10]
175
+
176
+
177
+ def ko(n):
178
+ """천이백삼십사; 만 (not 일만), 일억; a space between the 만 groups. Counting things (세 개, 다섯 명) is NOT this."""
179
+ if n == 0:
180
+ return '영'
181
+ eok, man, rest = n // 10 ** 8, n // 10 ** 4 % 10 ** 4, n % 10 ** 4
182
+ parts = []
183
+ if eok:
184
+ parts.append(_ko4(eok) + '억')
185
+ if man:
186
+ parts.append(('' if man == 1 else _ko4(man)) + '만')
187
+ if rest:
188
+ parts.append(_ko4(rest))
189
+ return ' '.join(parts)
190
+
191
+
192
+ # ---------------------------------------------------------------- zh-Hans
193
+ _ZH = '零一二三四五六七八九'
194
+
195
+
196
+ def _zh4(n, lead):
197
+ """0 < n < 10000. lead: nothing was said before, so 10..19 is 十X (not 一十X)."""
198
+ s = ''
199
+ zero = False
200
+ for i, (d, unit) in enumerate(((n // 1000, '千'), (n // 100 % 10, '百'), (n // 10 % 10, '十'), (n % 10, ''))):
201
+ if d == 0:
202
+ zero = bool(s)
203
+ continue
204
+ if zero:
205
+ s += '零'
206
+ zero = False
207
+ if i == 2 and d == 1 and not s and lead:
208
+ s += '十'
209
+ elif i == 0 and d == 2:
210
+ s += '两千'
211
+ else:
212
+ s += _ZH[d] + unit
213
+ return s
214
+
215
+
216
+ def zh(n, liang=True):
217
+ """一千二百三十四; 一百零五; 一百一十; 两千 / 两万 (liang=False keeps 二 everywhere)."""
218
+ if n == 0:
219
+ return '零'
220
+ yi, wan, rest = n // 10 ** 8, n // 10 ** 4 % 10 ** 4, n % 10 ** 4
221
+ s = ''
222
+ if yi:
223
+ s += ('两' if yi == 2 else _zh4(yi, True)) + '亿'
224
+ if wan:
225
+ if s and wan < 1000:
226
+ s += '零'
227
+ s += ('两' if wan == 2 and not s else _zh4(wan, not s)) + '万'
228
+ if rest:
229
+ if s and (rest < 1000 or wan == 0):
230
+ s += '零'
231
+ s += _zh4(rest, not s)
232
+ return s if liang else s.replace('两', '二')
233
+
234
+
235
+ # ---------------------------------------------------------------- es
236
+ _ES1 = ['cero', 'uno', 'dos', 'tres', 'cuatro', 'cinco', 'seis', 'siete', 'ocho', 'nueve', 'diez', 'once', 'doce',
237
+ 'trece', 'catorce', 'quince', 'dieciséis', 'diecisiete', 'dieciocho', 'diecinueve', 'veinte', 'veintiuno',
238
+ 'veintidós', 'veintitrés', 'veinticuatro', 'veinticinco', 'veintiséis', 'veintisiete', 'veintiocho',
239
+ 'veintinueve']
240
+ _ES10 = ['', '', '', 'treinta', 'cuarenta', 'cincuenta', 'sesenta', 'setenta', 'ochenta', 'noventa']
241
+ _ES100 = ['', 'ciento', 'doscientos', 'trescientos', 'cuatrocientos', 'quinientos', 'seiscientos', 'setecientos',
242
+ 'ochocientos', 'novecientos']
243
+
244
+
245
+ def _es3(n, apocope):
246
+ """0 < n < 1000. apocope: before mil / millones (veintiún mil, ciento un mil)."""
247
+ if n == 100:
248
+ return ['cien']
249
+ h, r = divmod(n, 100)
250
+ w = []
251
+ if h:
252
+ w.append(_ES100[h])
253
+ if r:
254
+ if r < 30:
255
+ w.append('un' if apocope and r == 1 else 'veintiún' if apocope and r == 21 else _ES1[r])
256
+ else:
257
+ t, u = divmod(r, 10)
258
+ w.append(_ES10[t])
259
+ if u:
260
+ w += ['y', 'un' if apocope and u == 1 else _ES1[u]]
261
+ return w
262
+
263
+
264
+ def _es6(n, apocope):
265
+ th, r = divmod(n, 1000)
266
+ w = []
267
+ if th:
268
+ if th > 1:
269
+ w += _es3(th, True)
270
+ w.append('mil')
271
+ if r:
272
+ w += _es3(r, apocope)
273
+ return w
274
+
275
+
276
+ def es(n):
277
+ """mil doscientos treinta y cuatro; ciento cinco; cien; veintiún mil; un millón; mil millones (10**9)."""
278
+ if n == 0:
279
+ return 'cero'
280
+ m, r = divmod(n, 10 ** 6)
281
+ w = []
282
+ if m:
283
+ w += ['un', 'millón'] if m == 1 else _es6(m, True) + ['millones']
284
+ if r:
285
+ w += _es6(r, False)
286
+ return ' '.join(w)
287
+
288
+
289
+ # ---------------------------------------------------------------- pt-BR
290
+ _PT1 = ['zero', 'um', 'dois', 'três', 'quatro', 'cinco', 'seis', 'sete', 'oito', 'nove', 'dez', 'onze', 'doze',
291
+ 'treze', 'quatorze', 'quinze', 'dezesseis', 'dezessete', 'dezoito', 'dezenove']
292
+ _PT10 = ['', '', 'vinte', 'trinta', 'quarenta', 'cinquenta', 'sessenta', 'setenta', 'oitenta', 'noventa']
293
+ _PT100 = ['', 'cento', 'duzentos', 'trezentos', 'quatrocentos', 'quinhentos', 'seiscentos', 'setecentos',
294
+ 'oitocentos', 'novecentos']
295
+
296
+
297
+ def _pt3(n):
298
+ if n == 100:
299
+ return 'cem'
300
+ h, r = divmod(n, 100)
301
+ parts = []
302
+ if h:
303
+ parts.append(_PT100[h])
304
+ if r:
305
+ if r < 20:
306
+ parts.append(_PT1[r])
307
+ else:
308
+ parts.append(_PT10[r // 10])
309
+ if r % 10:
310
+ parts.append(_PT1[r % 10])
311
+ return ' e '.join(parts)
312
+
313
+
314
+ def pt(n):
315
+ """mil duzentos e trinta e quatro; cento e cinco; mil e cem; um milhão e duzentos mil; um bilhão (10**9)."""
316
+ if n == 0:
317
+ return 'zero'
318
+ g = _groups3(n) + [0, 0, 0]
319
+ chunks = []
320
+ if g[3]:
321
+ chunks.append((g[3], 'um bilhão' if g[3] == 1 else _pt3(g[3]) + ' bilhões'))
322
+ if g[2]:
323
+ chunks.append((g[2], 'um milhão' if g[2] == 1 else _pt3(g[2]) + ' milhões'))
324
+ if g[1]:
325
+ chunks.append((g[1], 'mil' if g[1] == 1 else _pt3(g[1]) + ' mil'))
326
+ if g[0]:
327
+ chunks.append((g[0], _pt3(g[0])))
328
+ s = chunks[0][1]
329
+ for i, (value, text) in enumerate(chunks[1:], 1):
330
+ last = i == len(chunks) - 1
331
+ s += (' e ' if last and (value < 100 or value % 100 == 0) else ' ') + text
332
+ return s
333
+
334
+
335
+ # ---------------------------------------------------------------- de
336
+ _DE1 = ['null', 'ein', 'zwei', 'drei', 'vier', 'fünf', 'sechs', 'sieben', 'acht', 'neun', 'zehn', 'elf', 'zwölf',
337
+ 'dreizehn', 'vierzehn', 'fünfzehn', 'sechzehn', 'siebzehn', 'achtzehn', 'neunzehn']
338
+ _DE10 = ['', '', 'zwanzig', 'dreißig', 'vierzig', 'fünfzig', 'sechzig', 'siebzig', 'achtzig', 'neunzig']
339
+
340
+
341
+ def _de3(n, final):
342
+ """0 < n < 1000. final: the number ends here, so a last 1 is "eins"."""
343
+ h, r = divmod(n, 100)
344
+ s = _DE1[h] + 'hundert' if h else ''
345
+ if r == 1:
346
+ s += 'eins' if final else 'ein'
347
+ elif r < 20:
348
+ s += _DE1[r] if r else ''
349
+ else:
350
+ s += (_DE1[r % 10] + 'und' if r % 10 else '') + _DE10[r // 10]
351
+ return s
352
+
353
+
354
+ def de(n):
355
+ """eintausendzweihundertvierunddreißig; einhundertfünf; eine Million; eine Milliarde (10**9)."""
356
+ if n == 0:
357
+ return 'null'
358
+ g = _groups3(n) + [0, 0, 0]
359
+ parts = []
360
+ if g[3]:
361
+ parts.append('eine Milliarde' if g[3] == 1 else _de3(g[3], True) + ' Milliarden')
362
+ if g[2]:
363
+ parts.append('eine Million' if g[2] == 1 else _de3(g[2], True) + ' Millionen')
364
+ low = (_de3(g[1], False) + 'tausend' if g[1] else '') + (_de3(g[0], True) if g[0] else '')
365
+ if low:
366
+ parts.append(low)
367
+ return ' '.join(parts)
368
+
369
+
370
+ # ---------------------------------------------------------------- fr (France)
371
+ _FR1 = ['zéro', 'un', 'deux', 'trois', 'quatre', 'cinq', 'six', 'sept', 'huit', 'neuf', 'dix', 'onze', 'douze',
372
+ 'treize', 'quatorze', 'quinze', 'seize', 'dix-sept', 'dix-huit', 'dix-neuf']
373
+ _FR10 = ['', '', 'vingt', 'trente', 'quarante', 'cinquante', 'soixante']
374
+
375
+
376
+ def _fr2(n, final):
377
+ if n < 20:
378
+ return _FR1[n]
379
+ if n < 70:
380
+ t, u = divmod(n, 10)
381
+ return _FR10[t] + ('' if u == 0 else ' et un' if u == 1 else '-' + _FR1[u])
382
+ if n < 80:
383
+ return 'soixante et onze' if n == 71 else 'soixante-' + _FR1[n - 60]
384
+ if n == 80:
385
+ return 'quatre-vingts' if final else 'quatre-vingt'
386
+ return 'quatre-vingt-' + _FR1[n - 80]
387
+
388
+
389
+ def _fr3(n, final):
390
+ """0 < n < 1000. final: nothing but million(s) / milliard(s) follows, so vingts and cents keep their s."""
391
+ h, r = divmod(n, 100)
392
+ w = []
393
+ if h:
394
+ w.append('cent' if h == 1 else _FR1[h] + (' cents' if r == 0 and final else ' cent'))
395
+ if r:
396
+ w.append(_fr2(r, final))
397
+ return ' '.join(w)
398
+
399
+
400
+ def fr(n):
401
+ """mille deux cent trente-quatre; cent cinq; quatre-vingts; quatre-vingt-onze; deux cents; un milliard (10**9)."""
402
+ if n == 0:
403
+ return 'zéro'
404
+ g = _groups3(n) + [0, 0, 0]
405
+ w = []
406
+ if g[3]:
407
+ w.append(_fr3(g[3], True) + (' milliard' if g[3] == 1 else ' milliards'))
408
+ if g[2]:
409
+ w.append(_fr3(g[2], True) + (' million' if g[2] == 1 else ' millions'))
410
+ if g[1]:
411
+ w.append('mille' if g[1] == 1 else _fr3(g[1], False) + ' mille')
412
+ if g[0]:
413
+ w.append(_fr3(g[0], True))
414
+ return ' '.join(w)
415
+
416
+
417
+ # ---------------------------------------------------------------- id
418
+ _ID1 = ['nol', 'satu', 'dua', 'tiga', 'empat', 'lima', 'enam', 'tujuh', 'delapan', 'sembilan']
419
+
420
+
421
+ def _id3(n):
422
+ h, t, u = n // 100, n // 10 % 10, n % 10
423
+ w = []
424
+ if h:
425
+ w.append('seratus' if h == 1 else _ID1[h] + ' ratus')
426
+ if t == 1:
427
+ w.append('sepuluh' if u == 0 else 'sebelas' if u == 1 else _ID1[u] + ' belas')
428
+ else:
429
+ if t:
430
+ w.append(_ID1[t] + ' puluh')
431
+ if u:
432
+ w.append(_ID1[u])
433
+ return ' '.join(w)
434
+
435
+
436
+ def id_(n):
437
+ """seribu dua ratus tiga puluh empat; seratus lima; sebelas; satu juta; satu miliar (10**9)."""
438
+ if n == 0:
439
+ return 'nol'
440
+ g = _groups3(n) + [0, 0, 0]
441
+ w = []
442
+ if g[3]:
443
+ w.append(_id3(g[3]) + ' miliar')
444
+ if g[2]:
445
+ w.append(_id3(g[2]) + ' juta')
446
+ if g[1]:
447
+ w.append('seribu' if g[1] == 1 else _id3(g[1]) + ' ribu')
448
+ if g[0]:
449
+ w.append(_id3(g[0]))
450
+ return ' '.join(w)
451
+
452
+
453
+ # ---------------------------------------------------------------- common API
454
+ _SPELL = {'vi': vi, 'en': en, 'ja': ja, 'ko': ko, 'zh-Hans': zh, 'es': es, 'pt-BR': pt, 'de': de, 'fr': fr, 'id': id_}
455
+ # style options a project may set (i18n.config.json -> voice.numberStyle.<lang>)
456
+ STYLE_KEYS = {'vi': ('linh', 'four', 'thousand'), 'en': ('and_',), 'ja': ('zero',), 'zh-Hans': ('liang',)}
457
+ _POINT = {'vi': 'phẩy', 'en': 'point', 'ja': 'てん', 'ko': '점', 'zh-Hans': '点', 'es': 'coma', 'pt-BR': 'vírgula',
458
+ 'de': 'Komma', 'fr': 'virgule', 'id': 'koma'}
459
+ _MINUS = {'vi': 'âm', 'en': 'minus', 'ja': 'マイナス', 'ko': '마이너스', 'zh-Hans': '负', 'es': 'menos', 'pt-BR': 'menos',
460
+ 'de': 'minus', 'fr': 'moins', 'id': 'minus'}
461
+ _DIGIT0 = {'ja': 'ゼロ', 'ko': '공'} # the word for 0 when digits are read one by one
462
+ _NOSPACE = ('ja', 'zh-Hans') # words are written without spaces
463
+ _DECIMAL_MARK = {'en': '.', 'ja': '.', 'ko': '.', 'zh-Hans': '.', 'vi': ',', 'de': ',', 'fr': ',', 'es': ',',
464
+ 'pt-BR': ',', 'id': ','}
465
+ _GROUP_MARK = {'en': ',', 'ja': ',', 'ko': ',', 'zh-Hans': ',', 'vi': '.', 'de': '.', 'es': '.', 'pt-BR': '.',
466
+ 'id': '.', 'fr': ' '}
467
+
468
+
469
+ def _check_lang(lang):
470
+ if lang not in _SPELL:
471
+ raise ValueError('no number rules for %r (voice languages: %s)' % (lang, ' '.join(LANGS)))
472
+
473
+
474
+ def spell(n, lang, **style):
475
+ """The cardinal number n in words. style: see STYLE_KEYS (unknown keys for the language are ignored)."""
476
+ _check_lang(lang)
477
+ if not 0 <= n < MAX:
478
+ raise ValueError('%d is outside 0..10^12-1: write the reading by hand' % n)
479
+ style = {k: v for k, v in style.items() if k in STYLE_KEYS.get(lang, ())}
480
+ return _SPELL[lang](n, **style)
481
+
482
+
483
+ def spell_digits(digits, lang, **style):
484
+ """Digits read one by one (codes, phone numbers, "007"): không không bảy."""
485
+ _check_lang(lang)
486
+ words = [_DIGIT0.get(lang) or spell(0, lang, **style) if d == '0' else spell(int(d), lang, **style) for d in digits]
487
+ return ''.join(words) if lang == 'zh-Hans' else ' '.join(words)
488
+
489
+
490
+ def spell_decimal(whole, frac, lang, **style):
491
+ """3.14 -> three point one four (the digits after the mark are read one by one)."""
492
+ _check_lang(lang)
493
+ a = spell(int(whole), lang, **style)
494
+ b = spell_digits(frac, lang, **style)
495
+ if lang == 'ja':
496
+ zero = style.get('zero', 'ゼロ')
497
+ if a == zero:
498
+ a = 'れい' # 0.5 れいてんご
499
+ for end, new in (('いち', 'いっ'), ('はち', 'はっ'), ('じゅう', 'じゅっ')):
500
+ if a.endswith(end):
501
+ a = a[:-len(end)] + new # いってん, はってん, じゅってん
502
+ break
503
+ return a + 'てん' + b.replace(' ', '').replace('ゼロ', 'れい')
504
+ if lang == 'zh-Hans':
505
+ return a + _POINT[lang] + b
506
+ return '%s %s %s' % (a, _POINT[lang], b)
507
+
508
+
509
+ _JA_GEMINATE = (('いち', 'いっ'), ('ろく', 'ろっ'), ('はち', 'はっ'), ('じゅう', 'じゅっ'), ('じゅう', 'じっ'), ('ひゃく', 'ひゃっ'))
510
+ _JA_NATIVE = {1: ['ひと'], 2: ['ふた'], 3: ['みっ'], 4: ['よっ'], 5: ['いつ'], 6: ['むっ'], 7: ['しち'], 8: ['やっ'],
511
+ 9: ['ここの'], 10: ['とお']}
512
+ _KO_NATIVE1 = ['', '한 하나', '두 둘', '세 셋', '네 넷', '다섯', '여섯', '일곱', '여덟', '아홉']
513
+ _KO_NATIVE10 = ['', '열', '스물 스무', '서른', '마흔', '쉰', '예순', '일흔', '여든', '아흔']
514
+
515
+
516
+ def _ko_native(n):
517
+ """Native Korean numbers 1..99, as said before a counter (세 개, 스무 살, 열두 명)."""
518
+ if not 1 <= n <= 99:
519
+ return []
520
+ t, u = divmod(n, 10)
521
+ return [a + b for a in (_KO_NATIVE10[t].split() if t else ['']) for b in (_KO_NATIVE1[u].split() if u else [''])]
522
+
523
+
524
+ def forms(n, lang):
525
+ """Every accepted way to hear the cardinal n (for the check after synthesis), most usual first, plus the digits.
526
+ Includes the readings a number takes before a counter or a feminine noun (ja ひゃっこ / みっつ, ko 세 개, es una,
527
+ pt duas, fr une), so a correct clip is not refused."""
528
+ _check_lang(lang)
529
+ out = []
530
+ if lang == 'vi':
531
+ for thousand in ('nghìn', 'ngàn'):
532
+ for linh in ('linh', 'lẻ'):
533
+ for four in ('bốn', 'tư'):
534
+ s = vi(n, linh=linh, four=four, thousand=thousand)
535
+ out += [s, s.replace('mốt', 'một'), s.replace('tỷ', 'tỉ')]
536
+ elif lang == 'en':
537
+ out = [en(n), en(n, and_=True)]
538
+ elif lang == 'ja':
539
+ kana = ja(n)
540
+ out = [kana, ja(n, script='kanji')]
541
+ for end, new in _JA_GEMINATE:
542
+ if kana.endswith(end):
543
+ out.append(kana[:-len(end)] + new) # ひゃっこ, いっぽん, じゅっぷん
544
+ if kana.endswith('なな'):
545
+ out.append(kana[:-2] + 'しち')
546
+ if n > 10 and kana.endswith('よん'):
547
+ out.append(kana[:-1]) # じゅうよにん
548
+ if n > 10 and kana.endswith('きゅう'):
549
+ out.append(kana[:-3] + 'く') # じゅうくじ
550
+ out += _JA_NATIVE.get(n, [])
551
+ if n == 0:
552
+ out += ['れい', '零', '〇']
553
+ elif lang == 'ko':
554
+ out = [ko(n)] + _ko_native(n)
555
+ elif lang == 'zh-Hans':
556
+ out = [zh(n), zh(n, liang=False)]
557
+ elif lang == 'de':
558
+ s = de(n)
559
+ out = [s, re.sub(r'^ein(hundert|tausend)', r'\1', s)] # hundertfünf, tausendzwei
560
+ elif lang == 'es':
561
+ s = es(n)
562
+ out = [s, s.replace('ientos', 'ientas')]
563
+ for t in list(out):
564
+ if t.endswith('veintiuno'):
565
+ out += [t[:-9] + 'veintiún', t[:-9] + 'veintiuna']
566
+ elif t.endswith('uno'):
567
+ out += [t[:-1], t[:-1] + 'a'] # un, una
568
+ elif lang == 'pt-BR':
569
+ s = pt(n)
570
+ out = [s, s.replace('quatorze', 'catorze'), s.replace('entos', 'entas')]
571
+ for t in list(out):
572
+ if t.endswith('um'):
573
+ out.append(t + 'a') # uma
574
+ elif t.endswith('dois'):
575
+ out.append(t[:-4] + 'duas')
576
+ elif lang == 'fr':
577
+ s = fr(n)
578
+ out = [s] + ([s + 'e'] if s.endswith('un') else []) # une, vingt et une
579
+ else:
580
+ out = [spell(n, lang)]
581
+ out.append(str(n))
582
+ seen = []
583
+ for s in out:
584
+ if s not in seen:
585
+ seen.append(s)
586
+ return seen
587
+
588
+
589
+ # ---------------------------------------------------------------- speak: digits in a text -> words, with the open issues
590
+ _SPACES = '   ' # no-break, narrow no-break, thin: grouping spaces
591
+ _NUMBER = re.compile(
592
+ r'(?P<sign>(?<![\w.,])[-−](?=\d))?'
593
+ r'(?P<int>\d{1,3}(?:[' + _SPACES + r']\d{3})+(?!\d)' # 1 234 567 with a no-break space
594
+ r'|\d{1,3}(?:\.\d{3}){2,}(?!\d)|\d{1,3}(?:,\d{3}){2,}(?!\d)' # 1.234.567 / 1,234,567
595
+ r'|\d+)'
596
+ r'(?:(?P<mark>[.,])(?P<frac>\d+))?(?![.,]?\d)')
597
+ _PLAIN_GROUP = re.compile(r'(?<![\d.,])\d{1,3}(?: \d{3})+(?![\d.,])')
598
+ _SYMBOLS = '%‰:/+=×÷*^°#$€£¥₫₩~<>'
599
+ _CJK = re.compile(r'[぀-ヿ㐀-鿿가-힯々〆ヵヶ]')
600
+ _CJK_RUN = re.compile(r'[぀-ヿ㐀-鿿가-힯々〆ヵヶ]{1,3}')
601
+
602
+
603
+ def _letter(ch):
604
+ return bool(ch) and ch.isalpha()
605
+
606
+
607
+ def speak(text, lang, style=None, lenient=False):
608
+ """Returns (speak_text, numbers, issues).
609
+
610
+ speak_text: the text with every number written in words. numbers: the numbers the text holds, in order (int for
611
+ a cardinal, str for a decimal "3.5" or a digit string "007"). issues: what a person or an agent must settle by
612
+ writing the spoken text by hand (the `speak` override of the line): a number whose meaning is unclear ("1.234"),
613
+ a number glued to letters or to a counter, a symbol next to a number. lenient=True reads grouped numbers by the
614
+ language's convention instead of reporting them; it never invents a reading for symbols or counters.
615
+ """
616
+ _check_lang(lang)
617
+ style = style or {}
618
+ text = unicodedata.normalize('NFC', text)
619
+ numbers, issues = [], []
620
+ join = '' if lang in _NOSPACE else ' '
621
+
622
+ def issue(kind, m_text, why):
623
+ issues.append({'kind': kind, 'at': m_text, 'why': why})
624
+
625
+ if not lenient:
626
+ for m in _PLAIN_GROUP.finditer(text):
627
+ issue('ambiguous', m.group(), 'digit groups split by a plain space: one number or several?')
628
+
629
+ def repl(m):
630
+ whole, mark, frac = m.group('int'), m.group('mark'), m.group('frac')
631
+ before = text[m.start() - 1] if m.start() else ''
632
+ after = text[m.end()] if m.end() < len(text) else ''
633
+ token = m.group()
634
+ cjk_before, cjk_after = bool(_CJK.match(before)), bool(_CJK.match(after))
635
+ if (_letter(before) and not cjk_before) or (_letter(after) and not cjk_after):
636
+ issue('glued', (before if _letter(before) else '') + token + (after if _letter(after) else ''),
637
+ 'a number glued to letters (A4, 3D, 5kg, 1st): write how it is said')
638
+ return token
639
+ grouped = re.search(r'[.,' + _SPACES + r']', whole) is not None
640
+ digits = re.sub(r'\D', '', whole)
641
+ if frac is not None and not grouped and len(frac) == 3 and len(whole) <= 3 and not whole.startswith('0'):
642
+ if not lenient:
643
+ issue('ambiguous', token, '%s could be %s%s or the decimal %s.%s: write it without the mark (%s%s) or write the spoken text'
644
+ % (token, whole, frac, whole, frac, whole, frac))
645
+ return token
646
+ if mark == _GROUP_MARK[lang]:
647
+ digits, frac, mark = whole + frac, None, None
648
+ elif frac is not None and mark != _DECIMAL_MARK[lang] and not lenient:
649
+ issue('ambiguous', token, 'the decimal mark of %s is %r, not %r' % (lang, _DECIMAL_MARK[lang], mark))
650
+ return token
651
+ if int(digits) >= MAX:
652
+ issue('large', token, 'too large: write the reading by hand')
653
+ return token
654
+ negative = bool(m.group('sign'))
655
+ sign = (_MINUS[lang] + join) if negative else ''
656
+ if frac is not None:
657
+ value = ('-' if negative else '') + digits + '.' + frac
658
+ elif len(digits) > 1 and digits.startswith('0') and not grouped:
659
+ value = digits
660
+ else:
661
+ value = -int(digits) if negative else int(digits)
662
+ if (cjk_before or cjk_after) and not (lang == 'zh-Hans' and frac is None) and (lang in ('ja', 'ko') or not lenient):
663
+ numbers.append(value)
664
+ run = _CJK_RUN.match(text, m.end())
665
+ issue('counter', token + (run.group() if run else ''),
666
+ 'a number with a counter changes its reading (3つ みっつ, 1本 いっぽん, 3개 세 개): write the spoken text')
667
+ return token
668
+ for ch, shown in ((before, before + token), (after, token + after)):
669
+ if ch and ch in _SYMBOLS:
670
+ issue('symbol', shown, 'the symbol %r is left for the voice to guess: write the words' % ch)
671
+ numbers.append(value)
672
+ tail = '' if frac is not None or not mark else mark # "3." at a sentence end: the mark is punctuation
673
+ if frac is not None:
674
+ return sign + spell_decimal(digits, frac, lang, **style)
675
+ if isinstance(value, str):
676
+ return sign + spell_digits(digits, lang, **style) + tail
677
+ if lang == 'zh-Hans' and int(digits) == 2 and cjk_after and after not in '十百千万亿月日号点分秒年级楼层':
678
+ return sign + '两' + tail # 2个 两个
679
+ return sign + spell(int(digits), lang, **style) + tail
680
+
681
+ return _NUMBER.sub(repl, text), numbers, issues
682
+
683
+
684
+ def numbers_in(text, lang, style=None):
685
+ """The numbers a shown text holds, read by the language's own conventions ("1.500" in Vietnamese is 1500).
686
+ For a line whose spoken text is written by hand: these are the numbers that spoken text must say."""
687
+ return speak(text, lang, style, lenient=True)[1]
688
+
689
+
690
+ # ---------------------------------------------------------------- heard: were the numbers said?
691
+ _CONNECT = {'and', 'y', 'e', 'et'} # words that join number parts but also join ordinary phrases
692
+
693
+
694
+ def canon(text, lang):
695
+ """A text reduced to what can be compared: case, punctuation and (for scripts without word spaces) spaces dropped."""
696
+ t = unicodedata.normalize('NFKC', text).lower()
697
+ if lang in ('ja', 'zh-Hans', 'ko', 'de'):
698
+ return re.sub(r'[\W_]+', '', t)
699
+ return ' '.join(re.sub(r"[^\w]+", ' ', t).split())
700
+
701
+
702
+ def _number_words(lang):
703
+ """(structure words, unit words). Structure words only occur inside a number (trăm, nghìn, hundred, mil, vingt);
704
+ unit words are the readings of 0..9. Found by spelling a sample of numbers."""
705
+ sample = list(range(0, 130)) + [200, 300, 500, 700, 900, 1000, 2000, 10 ** 4, 10 ** 5, 10 ** 6, 2 * 10 ** 6, 10 ** 9]
706
+ units = set()
707
+ for n in range(0, 10):
708
+ for f in forms(n, lang):
709
+ units.update(canon(f, lang).split())
710
+ words = set()
711
+ for n in sample:
712
+ for f in forms(n, lang):
713
+ words.update(canon(f, lang).split())
714
+ return ({w for w in words - units - _CONNECT if not w.isdigit()}, {u for u in units if not u.isdigit()})
715
+
716
+
717
+ _WORDS = {}
718
+
719
+
720
+ def heard(numbers, transcript, lang):
721
+ """Checks that each expected number was said whole and in order in a text (a recogniser's transcript, or a
722
+ hand-written spoken text).
723
+
724
+ numbers: the list from speak() or numbers_in(). Returns (ok, details). A number counts when one of its accepted
725
+ forms (words or digits) stands in the text and, in the languages written with spaces, is not part of a longer
726
+ number ("hai trăm ba mươi bốn" inside "một nghìn hai trăm ba mươi bốn", "one hundred" inside "one hundred
727
+ five"). This is the floor every project applies after synthesis; a project may add stricter gates on top.
728
+ """
729
+ _check_lang(lang)
730
+ spaced = lang not in ('ja', 'zh-Hans', 'ko', 'de')
731
+ if spaced and lang not in _WORDS:
732
+ _WORDS[lang] = _number_words(lang)
733
+ struct, units = _WORDS.get(lang, (set(), set()))
734
+ # a unit right after a structure word continues the number (twenty five), except vi "năm" (also "year": 25 is
735
+ # "hai mươi lăm") and "không"
736
+ follow = units - {'năm', 'không'} if lang == 'vi' else units
737
+
738
+ def part_of_longer(text, start, end, form):
739
+ left, right = text[:start].split(), text[end:].split()
740
+ last = form.split()[-1]
741
+ if left:
742
+ if left[-1] in struct or left[-1].isdigit():
743
+ return True
744
+ if left[-1] in _CONNECT and len(left) > 1 and left[-2] in struct:
745
+ return True # two hundred and | thirty-four
746
+ if right:
747
+ if right[0] in struct or right[0].isdigit():
748
+ return True
749
+ if last in struct:
750
+ if right[0] in follow:
751
+ return True # one hundred | five
752
+ if right[0] in _CONNECT and len(right) > 1 and (right[1] in struct or right[1] in units or right[1].isdigit()):
753
+ return True # one hundred | and five
754
+ return False
755
+
756
+ raw = unicodedata.normalize('NFKC', transcript)
757
+ variants = [canon(raw, lang), canon(re.sub(r'(?<=\d)[,.' + _SPACES + r' ](?=\d{3}(?!\d))', '', raw), lang)]
758
+ details, ok = [], True
759
+ for text in variants:
760
+ details, ok, pos = [], True, 0
761
+ for num in numbers:
762
+ if isinstance(num, int):
763
+ cand = forms(abs(num), lang)
764
+ elif '.' in num:
765
+ whole, frac = num.lstrip('-').split('.')
766
+ cand = [spell_decimal(whole, frac, lang), whole + '.' + frac, whole + ',' + frac, whole + frac]
767
+ else:
768
+ cand = [spell_digits(num, lang), num]
769
+ found = None
770
+ for f in cand:
771
+ c = canon(f, lang)
772
+ if not c:
773
+ continue
774
+ if spaced:
775
+ for m in re.finditer(r'(?<![\w])' + re.escape(c) + r'(?![\w])', text[pos:]):
776
+ if part_of_longer(text, pos + m.start(), pos + m.end(), c):
777
+ continue
778
+ found = (pos + m.start(), pos + m.end(), f)
779
+ break
780
+ else:
781
+ i = text.find(c, pos)
782
+ while i >= 0 and c.isdigit() and ((i and text[i - 1].isdigit()) or text[i + len(c):i + len(c) + 1].isdigit()):
783
+ i = text.find(c, i + 1)
784
+ if i >= 0:
785
+ found = (i, i + len(c), f)
786
+ if found:
787
+ break
788
+ if found:
789
+ pos = found[1]
790
+ details.append({'number': num, 'heard': found[2]})
791
+ else:
792
+ ok = False
793
+ details.append({'number': num, 'heard': None, 'expected': cand[0]})
794
+ if ok:
795
+ break
796
+ return ok, details
797
+
798
+
799
+ # ---------------------------------------------------------------- self-test
800
+ _EXPECT = {
801
+ 'vi': {0: 'không', 5: 'năm', 10: 'mười', 11: 'mười một', 14: 'mười bốn', 15: 'mười lăm', 20: 'hai mươi',
802
+ 21: 'hai mươi mốt', 24: 'hai mươi bốn', 25: 'hai mươi lăm', 55: 'năm mươi lăm', 100: 'một trăm',
803
+ 101: 'một trăm linh một', 105: 'một trăm linh năm', 110: 'một trăm mười', 115: 'một trăm mười lăm',
804
+ 121: 'một trăm hai mươi mốt', 1000: 'một nghìn', 1005: 'một nghìn không trăm linh năm',
805
+ 1050: 'một nghìn không trăm năm mươi', 1234: 'một nghìn hai trăm ba mươi bốn', 10000: 'mười nghìn',
806
+ 15000: 'mười lăm nghìn', 100000: 'một trăm nghìn', 1000000: 'một triệu',
807
+ 1000001: 'một triệu không trăm linh một', 2500000: 'hai triệu năm trăm nghìn', 10 ** 9: 'một tỷ'},
808
+ 'en': {0: 'zero', 13: 'thirteen', 21: 'twenty-one', 100: 'one hundred', 105: 'one hundred five',
809
+ 110: 'one hundred ten', 1000: 'one thousand', 1005: 'one thousand five',
810
+ 1234: 'one thousand two hundred thirty-four', 10000: 'ten thousand', 100000: 'one hundred thousand',
811
+ 1000000: 'one million',
812
+ 1234567: 'one million two hundred thirty-four thousand five hundred sixty-seven', 10 ** 9: 'one billion'},
813
+ 'ja': {0: 'ゼロ', 4: 'よん', 7: 'なな', 9: 'きゅう', 10: 'じゅう', 14: 'じゅうよん', 20: 'にじゅう', 100: 'ひゃく',
814
+ 105: 'ひゃくご', 300: 'さんびゃく', 600: 'ろっぴゃく', 800: 'はっぴゃく', 1000: 'せん',
815
+ 1234: 'せんにひゃくさんじゅうよん', 3000: 'さんぜん', 8000: 'はっせん', 10000: 'いちまん',
816
+ 12345: 'いちまんにせんさんびゃくよんじゅうご', 100000: 'じゅうまん', 1000000: 'ひゃくまん',
817
+ 10000000: 'いっせんまん', 10 ** 8: 'いちおく'},
818
+ 'es': {0: 'cero', 16: 'dieciséis', 21: 'veintiuno', 22: 'veintidós', 30: 'treinta', 31: 'treinta y uno',
819
+ 100: 'cien', 101: 'ciento uno', 105: 'ciento cinco', 500: 'quinientos', 700: 'setecientos',
820
+ 900: 'novecientos', 1000: 'mil', 1001: 'mil uno', 1234: 'mil doscientos treinta y cuatro', 2000: 'dos mil',
821
+ 21000: 'veintiún mil', 100000: 'cien mil', 101000: 'ciento un mil', 1000000: 'un millón',
822
+ 2000000: 'dos millones', 10 ** 9: 'mil millones'},
823
+ 'pt-BR': {0: 'zero', 14: 'quatorze', 16: 'dezesseis', 19: 'dezenove', 21: 'vinte e um', 100: 'cem',
824
+ 101: 'cento e um', 105: 'cento e cinco', 200: 'duzentos', 1000: 'mil', 1001: 'mil e um',
825
+ 1100: 'mil e cem', 1200: 'mil e duzentos', 1234: 'mil duzentos e trinta e quatro', 2000: 'dois mil',
826
+ 2500: 'dois mil e quinhentos', 10000: 'dez mil', 100000: 'cem mil', 1000000: 'um milhão',
827
+ 1200000: 'um milhão e duzentos mil', 1250000: 'um milhão duzentos e cinquenta mil',
828
+ 2000000: 'dois milhões', 10 ** 9: 'um bilhão'},
829
+ 'ko': {0: '영', 1: '일', 10: '십', 11: '십일', 16: '십육', 20: '이십', 100: '백', 105: '백오', 110: '백십',
830
+ 1000: '천', 1234: '천이백삼십사', 10000: '만', 12345: '만 이천삼백사십오', 100000: '십만', 110000: '십일만',
831
+ 1000000: '백만', 10 ** 8: '일억'},
832
+ 'zh-Hans': {0: '零', 2: '二', 10: '十', 11: '十一', 20: '二十', 100: '一百', 101: '一百零一', 105: '一百零五',
833
+ 110: '一百一十', 111: '一百一十一', 200: '二百', 1000: '一千', 1001: '一千零一', 1010: '一千零一十',
834
+ 1100: '一千一百', 1234: '一千二百三十四', 2000: '两千', 10000: '一万', 10005: '一万零五',
835
+ 12000: '一万两千', 20000: '两万', 100000: '十万', 1000000: '一百万', 10 ** 8: '一亿'},
836
+ 'de': {0: 'null', 1: 'eins', 11: 'elf', 16: 'sechzehn', 17: 'siebzehn', 21: 'einundzwanzig', 30: 'dreißig',
837
+ 100: 'einhundert', 101: 'einhunderteins', 105: 'einhundertfünf', 1000: 'eintausend',
838
+ 1001: 'eintausendeins', 1234: 'eintausendzweihundertvierunddreißig', 10000: 'zehntausend',
839
+ 100000: 'einhunderttausend', 1000000: 'eine Million', 2000000: 'zwei Millionen',
840
+ 1234567: 'eine Million zweihundertvierunddreißigtausendfünfhundertsiebenundsechzig',
841
+ 10 ** 9: 'eine Milliarde'},
842
+ 'fr': {0: 'zéro', 16: 'seize', 17: 'dix-sept', 21: 'vingt et un', 22: 'vingt-deux', 70: 'soixante-dix',
843
+ 71: 'soixante et onze', 80: 'quatre-vingts', 81: 'quatre-vingt-un', 90: 'quatre-vingt-dix',
844
+ 91: 'quatre-vingt-onze', 99: 'quatre-vingt-dix-neuf', 100: 'cent', 101: 'cent un', 105: 'cent cinq',
845
+ 200: 'deux cents', 201: 'deux cent un', 1000: 'mille', 1234: 'mille deux cent trente-quatre',
846
+ 2000: 'deux mille', 80000: 'quatre-vingt mille', 200000: 'deux cent mille', 1000000: 'un million',
847
+ 2000000: 'deux millions', 10 ** 9: 'un milliard'},
848
+ 'id': {0: 'nol', 10: 'sepuluh', 11: 'sebelas', 12: 'dua belas', 20: 'dua puluh', 21: 'dua puluh satu',
849
+ 100: 'seratus', 105: 'seratus lima', 110: 'seratus sepuluh', 111: 'seratus sebelas', 200: 'dua ratus',
850
+ 1000: 'seribu', 1001: 'seribu satu', 1234: 'seribu dua ratus tiga puluh empat', 2000: 'dua ribu',
851
+ 10000: 'sepuluh ribu', 11000: 'sebelas ribu', 100000: 'seratus ribu', 1000000: 'satu juta',
852
+ 10 ** 9: 'satu miliar'},
853
+ }
854
+
855
+
856
+ def selftest():
857
+ bad = 0
858
+
859
+ def expect(label, got, want):
860
+ nonlocal bad
861
+ if got != want:
862
+ bad += 1
863
+ print('FAIL %s\n got %r\n want %r' % (label, got, want))
864
+
865
+ for lang, table in _EXPECT.items():
866
+ for n, want in table.items():
867
+ expect('%s %d' % (lang, n), spell(n, lang), want)
868
+ seen = {}
869
+ for n in list(range(0, 2001)) + [9999, 10000, 10001, 99999, 100000, 123456, 999999, 10 ** 6, 10 ** 9 + 1]:
870
+ s = spell(n, lang)
871
+ if s in seen:
872
+ bad += 1
873
+ print('FAIL %s: %d and %d are both %r' % (lang, seen[s], n, s))
874
+ seen[s] = n
875
+ # the two Vietnamese styles
876
+ expect('vi lẻ', spell(105, 'vi', linh='lẻ'), 'một trăm lẻ năm')
877
+ expect('vi tư', spell(1234, 'vi', four='tư'), 'một nghìn hai trăm ba mươi tư')
878
+ expect('en and', spell(1005, 'en', and_=True), 'one thousand and five')
879
+ expect('ja kanji', ja(1234, script='kanji'), '千二百三十四')
880
+ expect('digits', spell_digits('007', 'vi'), 'không không bảy')
881
+ expect('decimal en', spell_decimal('3', '14', 'en'), 'three point one four')
882
+ expect('decimal ja', spell_decimal('1', '5', 'ja'), 'いってんご')
883
+ expect('decimal vi', spell_decimal('0', '5', 'vi'), 'không phẩy năm')
884
+ # speak
885
+ s, nums, iss = speak('Bạn có 1234 sao và 105 xu.', 'vi')
886
+ expect('speak vi', (s, nums, iss),
887
+ ('Bạn có một nghìn hai trăm ba mươi bốn sao và một trăm linh năm xu.', [1234, 105], []))
888
+ s, nums, iss = speak('You have 1,234,567 points.', 'en')
889
+ expect('speak en grouped', (s, nums, len(iss)),
890
+ ('You have one million two hundred thirty-four thousand five hundred sixty-seven points.', [1234567], 0))
891
+ for text, lang, kind in (('Bạn có 1.234 sao', 'vi', 'ambiguous'), ('Bạn có 1 234 sao', 'vi', 'ambiguous'),
892
+ ('Giảm 50%', 'vi', 'symbol'), ('りんごを3つ', 'ja', 'counter'), ('사과 3개', 'ko', 'counter'),
893
+ ('Level 5kg', 'en', 'glued'), ('12:30 に', 'ja', 'symbol')):
894
+ _, _, iss = speak(text, lang)
895
+ expect('issue %s %r' % (lang, text), [i['kind'] for i in iss][:1], [kind])
896
+ expect('counter keeps its number', speak('りんごを3つ', 'ja')[1], [3])
897
+ expect('numbers_in vi', numbers_in('Bạn đã nhận 1.500 sao và 105 xu!', 'vi'), [1500, 105])
898
+ expect('numbers_in ja', numbers_in('ほしを 1,500こと コインを 105まい もらったよ!', 'ja'), [1500, 105])
899
+ expect('numbers_in en', numbers_in('You got 1,500 stars and 105 coins!', 'en'), [1500, 105])
900
+ expect('counter shown', [i['at'] for i in speak('コインを 105まい', 'ja')[2]], ['105まい'])
901
+ expect('lenient vi', speak('Bạn có 1.234 sao', 'vi', lenient=True)[:2],
902
+ ('Bạn có một nghìn hai trăm ba mươi bốn sao', [1234]))
903
+ expect('zh liang', speak('我有2个苹果和12个梨', 'zh-Hans')[0], '我有两个苹果和十二个梨')
904
+ expect('minus', speak('Nhiệt độ -5 độ', 'vi')[0], 'Nhiệt độ âm năm độ')
905
+ expect('sentence end', speak('Chương 3.', 'vi')[:2], ('Chương ba.', [3]))
906
+ # heard
907
+ for lang, nums, text, want in (
908
+ ('vi', [1234], 'Bạn có một nghìn hai trăm ba mươi bốn sao.', True),
909
+ ('vi', [1234], 'bạn có một hai trăm ba mươi bốn sao', False), # "nghìn" swallowed
910
+ ('vi', [1234], 'Bạn có 1.234 sao', True),
911
+ ('vi', [1234], 'bạn có một ngàn hai trăm ba mươi tư sao', True),
912
+ ('vi', [105], 'một trăm lẻ năm', True),
913
+ ('vi', [234], 'một nghìn hai trăm ba mươi bốn', False), # part of a longer number
914
+ ('vi', [5], 'bạn có năm năm', True),
915
+ ('vi', [3, 4], 'ba cộng bốn bằng mấy', True),
916
+ ('vi', [3, 4], 'bốn cộng ba bằng mấy', False), # order
917
+ ('en', [105], 'you have one hundred and five coins', True),
918
+ ('en', [1234], 'You have 1,234 coins.', True),
919
+ ('en', [34], 'two hundred thirty-four', False),
920
+ ('ja', [1234], '千二百三十四です', True),
921
+ ('ja', [1234], 'せんにひゃくさんじゅうよんです', True),
922
+ ('ja', [1234], '二百三十四です', False),
923
+ ('zh-Hans', [2000], '我有二千个', True),
924
+ ('ko', [1234], '천 이백 삼십 사 입니다', True),
925
+ ('de', [1234], 'Du hast 1.234 Punkte', True),
926
+ ('de', [105], 'du hast hundertfünf punkte', True),
927
+ ('fr', [80], 'quatre-vingts points', True),
928
+ ('es', [21000], 'veintiún mil puntos', True),
929
+ ('pt-BR', [1200], 'mil e duzentos pontos', True),
930
+ ('id', [1234], 'seribu dua ratus tiga puluh empat', True),
931
+ # a number after "and / y / e / et" is not part of a longer one
932
+ ('en', [1500, 105], 'You got one thousand five hundred stars and one hundred five coins!', True),
933
+ ('en', [3, 2], 'three apples and two pears', True),
934
+ ('en', [100], 'one hundred five', False),
935
+ ('en', [100], 'one hundred and five coins', False),
936
+ ('en', [34], 'two hundred and thirty-four', False),
937
+ ('es', [3, 2], 'tres manzanas y dos peras', True),
938
+ ('es', [30], 'treinta y uno', False),
939
+ ('es', [200], 'doscientas monedas', True),
940
+ ('fr', [3, 2], 'trois pommes et deux poires', True),
941
+ ('fr', [4], 'quatre-vingts', False),
942
+ ('pt-BR', [3, 2], 'três maçãs e duas peras', True),
943
+ ('pt-BR', [20], 'vinte e um', False),
944
+ ('id', [100], 'seratus lima', False),
945
+ ('vi', [20], 'bạn đã chơi hai mươi năm', True),
946
+ ('vi', [105], 'một trăm năm', False),
947
+ ('vi', [100], 'một trăm linh năm', False),
948
+ # readings before a counter
949
+ ('ja', [1500, 105], 'ほしを せんごひゃっこと コインを ひゃくごまい もらったよ!', True),
950
+ ('ja', [3], 'りんごを みっつ', True),
951
+ ('ja', [1], 'えんぴつを いっぽん', True),
952
+ ('ko', [3], '사과 세 개', True),
953
+ ('ko', [12], '열두 명이 왔어요', True)):
954
+ expect('heard %s %r %r' % (lang, nums, text), heard(nums, text, lang)[0], want)
955
+ print('selftest: %s' % ('OK' if not bad else '%d FAILED' % bad))
956
+ return 1 if bad else 0
957
+
958
+
959
+ def _style_args(pairs):
960
+ style = {}
961
+ for p in pairs or []:
962
+ k, _, v = p.partition('=')
963
+ style[k] = {'true': True, 'false': False, '1': True, '0': False}.get(v.lower(), v) if k in ('and_', 'liang') else v
964
+ return style
965
+
966
+
967
+ def main(argv=None):
968
+ for stream in (sys.stdout, sys.stderr):
969
+ if hasattr(stream, 'reconfigure'):
970
+ stream.reconfigure(encoding='utf-8')
971
+ ap = argparse.ArgumentParser(description='Numbers as spoken words for the 10 voice languages.')
972
+ sub = ap.add_subparsers(dest='cmd', required=True)
973
+ p = sub.add_parser('spell', help='one number in words')
974
+ p.add_argument('number', type=int)
975
+ p.add_argument('--lang')
976
+ p.add_argument('--all', action='store_true', help='every voice language')
977
+ p.add_argument('--style', nargs='*', metavar='KEY=VALUE', help='vi: linh=lẻ four=tư thousand=ngàn; en: and_=true; ja: zero=れい')
978
+ p = sub.add_parser('speak', help='a text with its numbers in words, as JSON {speak, numbers, issues}')
979
+ p.add_argument('text')
980
+ p.add_argument('--lang', required=True)
981
+ p.add_argument('--lenient', action='store_true')
982
+ p.add_argument('--style', nargs='*', metavar='KEY=VALUE')
983
+ p = sub.add_parser('heard', help='were these numbers said in this transcript? exit 0 yes, 1 no')
984
+ p.add_argument('transcript')
985
+ p.add_argument('--lang', required=True)
986
+ p.add_argument('--numbers', required=True, help='comma separated, as speak printed them: 1234,105')
987
+ sub.add_parser('selftest')
988
+ a = ap.parse_args(argv)
989
+ if a.cmd == 'selftest':
990
+ return selftest()
991
+ if a.cmd == 'spell':
992
+ style = _style_args(a.style)
993
+ if a.all or not a.lang:
994
+ for lang in LANGS:
995
+ print('%-8s %s' % (lang, spell(a.number, lang, **style)))
996
+ else:
997
+ print(spell(a.number, a.lang, **style))
998
+ return 0
999
+ if a.cmd == 'speak':
1000
+ text, numbers, issues = speak(a.text, a.lang, _style_args(a.style), a.lenient)
1001
+ print(json.dumps({'speak': text, 'numbers': numbers, 'issues': issues}, ensure_ascii=False, indent=2))
1002
+ return 2 if issues else 0
1003
+ if a.cmd == 'heard':
1004
+ nums = [int(x) if re.fullmatch(r'-?\d+', x) and not (len(x) > 1 and x.startswith('0')) else x
1005
+ for x in a.numbers.split(',') if x]
1006
+ ok, details = heard(nums, a.transcript, a.lang)
1007
+ print(json.dumps({'ok': ok, 'numbers': details}, ensure_ascii=False, indent=2))
1008
+ return 0 if ok else 1
1009
+ return 0
1010
+
1011
+
1012
+ if __name__ == '__main__':
1013
+ sys.exit(main())