spelledout 0.2.2__py3-none-any.whl

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.
spelledout/__init__.py ADDED
@@ -0,0 +1,27 @@
1
+ """spelledout - numbers and money amounts written out in words, with the
2
+ grammar right, and read back from words.
3
+
4
+ >>> import spelledout
5
+ >>> spelledout.words(1250)
6
+ 'one thousand two hundred fifty'
7
+ >>> spelledout.money("1250.50", "USD")
8
+ 'one thousand two hundred fifty dollars and fifty cents'
9
+ >>> spelledout.ordinal(21)
10
+ 'twenty-first'
11
+ >>> spelledout.parse("one thousand two hundred and fifty")
12
+ 1250
13
+ >>> spelledout.check("1250.50", "one thousand two hundred fifty dollars and fifty cents", "USD").ok
14
+ True
15
+ """
16
+
17
+ from .api import currencies, languages, money, ordinal, words
18
+ from .currency import Currency
19
+ from .errors import AmbiguousAmountError, ParseError, SpelledOutError
20
+ from .parsing import CheckResult, Money, check, parse, parse_money
21
+
22
+ __version__ = "0.2.2"
23
+ __all__ = [
24
+ "words", "ordinal", "money", "languages", "currencies",
25
+ "parse", "parse_money", "check", "Money", "CheckResult",
26
+ "Currency", "SpelledOutError", "ParseError", "AmbiguousAmountError", "__version__",
27
+ ]
spelledout/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ raise SystemExit(main())
@@ -0,0 +1,391 @@
1
+ """Arabic words to numbers.
2
+
3
+ Words are compared after normalisation: short vowels, tanween, shadda and
4
+ tatweel are removed, أ إ آ ٱ become ا, a final ة becomes ه and ى becomes ي.
5
+ So ثلاثة, ثلاثه and ثَلاثَة are the same word, and so are إحدى and احدي.
6
+
7
+ The grammar is strict about what changes the value and tolerant about what
8
+ does not:
9
+
10
+ * parts go from the largest to the smallest and are joined with و (attached
11
+ or written apart); the و is required;
12
+ * inside 21-99 the unit comes first: خمسة وعشرون;
13
+ * gender and case are not checked: ثلاثة / ثلاث, عشرون / عشرين,
14
+ مئتان / مئتين / مئتا, ألفان / ألفين all read the same;
15
+ * a scale word (ألف, مليون ...) may be counted by a number in any of its
16
+ forms (ثلاثة آلاف, أحد عشر ألفاً), but its dual takes no number.
17
+
18
+ Anything else raises :class:`spelledout.errors.ParseError`.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import re
24
+ import unicodedata
25
+
26
+ from ._parse_base import Phrase, Token, fail
27
+ from .errors import ParseError
28
+ from .lang import ar as _ar
29
+
30
+ _MARKS = re.compile("[ً-ٰٟـ]") # harakat, tanween, dagger alif, tatweel
31
+ _LETTERS = {ord(a): "ا" for a in "أإآٱ"}
32
+ _LETTERS.update({ord("ى"): "ي", ord("ی"): "ي", ord("ک"): "ك"})
33
+ FATHATAN = "ً"
34
+ WA = "و"
35
+ _WAHID = "واحد"
36
+
37
+
38
+ def normalize(word):
39
+ # compose first: in NFD ئ is ي + a combining hamza, and stripping the marks
40
+ # would leave ي (مئتان would become ميتان)
41
+ word = _MARKS.sub("", unicodedata.normalize("NFC", word)).translate(_LETTERS)
42
+ if word.endswith("ة"):
43
+ word = word[:-1] + "ه"
44
+ return word
45
+
46
+
47
+ def _table(pairs):
48
+ return {normalize(w): v for w, v in pairs}
49
+
50
+
51
+ # 1-10 standing alone, both genders and both cases
52
+ ALONE = _table([
53
+ ("واحد", 1), ("واحدة", 1), ("اثنان", 2), ("اثنين", 2), ("اثنتان", 2), ("اثنتين", 2),
54
+ ("ثلاثة", 3), ("ثلاث", 3), ("أربعة", 4), ("أربع", 4), ("خمسة", 5), ("خمس", 5),
55
+ ("ستة", 6), ("ست", 6), ("سبعة", 7), ("سبع", 7), ("ثمانية", 8), ("ثمان", 8),
56
+ ("ثماني", 8), ("ثمانيا", 8), ("تسعة", 9), ("تسع", 9), ("عشرة", 10), ("عشر", 10),
57
+ ])
58
+ # colloquial forms (see the README for the complete list)
59
+ COLLOQUIAL_ONES = _table([("اتنين", 2), ("تلاتة", 3), ("تلات", 3), ("تمانية", 8)])
60
+ ALONE.update(COLLOQUIAL_ONES)
61
+ _UNITS_1_9 = {w: v for w, v in ALONE.items() if v < 10}
62
+ # the unit of 11-19: أحد عشر, اثنا عشر, ثلاثة عشر
63
+ TEEN_UNIT = dict({w: v for w, v in _UNITS_1_9.items() if v >= 3},
64
+ **_table([("أحد", 1), ("إحدى", 1), ("اثنا", 2), ("اثني", 2), ("اثنتا", 2),
65
+ ("اثنتي", 2)]))
66
+ # the unit of 21-99: واحد وعشرون, إحدى وعشرون
67
+ BEFORE_TENS = dict(_UNITS_1_9, **_table([("أحد", 1), ("إحدى", 1)]))
68
+ TEN_WORD = frozenset(_table([("عشر", 10), ("عشرة", 10)]))
69
+ _TENS_STEMS = ["عشر", "ثلاث", "أربع", "خمس", "ست", "سبع", "ثمان", "تسع"]
70
+ TENS = _table([(stem + ending, 10 * k) for k, stem in enumerate(_TENS_STEMS, 2)
71
+ for ending in ("ون", "ين")])
72
+ COLLOQUIAL_TENS = _table([("تلاتين", 30), ("تمانين", 80)])
73
+ TENS.update(COLLOQUIAL_TENS)
74
+
75
+ COLLOQUIAL_HUNDREDS = _table([
76
+ ("مية", 100), ("ميتين", 200), ("تلتمية", 300), ("تلاتمية", 300), ("ربعمية", 400),
77
+ ("أربعمية", 400), ("خمسمية", 500), ("ستمية", 600), ("سبعمية", 700), ("تمنمية", 800),
78
+ ("تمانمية", 800), ("تسعمية", 900),
79
+ ])
80
+ H100 = frozenset(_table([("مئة", 100), ("مائة", 100), ("مية", 100)]))
81
+ H200 = frozenset(_table([(stem + ending, 200) for stem in ("مئت", "مائت")
82
+ for ending in ("ان", "ين", "ا", "ي")] + [("ميتين", 200)]))
83
+ # ثلاث مئة (two words): the short form of the unit
84
+ H_STEM = _table([("ثلاث", 3), ("أربع", 4), ("خمس", 5), ("ست", 6), ("سبع", 7), ("ثمان", 8),
85
+ ("ثماني", 8), ("تسع", 9)])
86
+ COMPOUND = _table([(stem + hundred, 100 * k)
87
+ for stem, k in [("ثلاث", 3), ("أربع", 4), ("خمس", 5), ("ست", 6), ("سبع", 7),
88
+ ("ثمان", 8), ("تسع", 9)]
89
+ for hundred in ("مئة", "مائة")])
90
+ COMPOUND.update({w: v for w, v in COLLOQUIAL_HUNDREDS.items() if v >= 300})
91
+
92
+
93
+ def _scale(value, singular, dual_stem, plural, alt=()):
94
+ rows = [(singular, (value, "sg")), (singular + "ا", (value, "acc")),
95
+ (dual_stem + "ان", (value, "dual")), (dual_stem + "ين", (value, "dual")),
96
+ (dual_stem + "ي", (value, "dual")), (plural, (value, "pl"))]
97
+ return rows + [(w, (value, "pl")) for w in alt]
98
+
99
+
100
+ # kind: sg, acc (ألفاً, or the dual ألفا before a noun), dual, pl
101
+ SCALES = _table(
102
+ _scale(10 ** 3, "ألف", "ألف", "آلاف")
103
+ + _scale(10 ** 6, "مليون", "مليون", "ملايين")
104
+ + _scale(10 ** 9, "مليار", "مليار", "مليارات")
105
+ + _scale(10 ** 9, "بليون", "بليون", "بلايين")
106
+ + _scale(10 ** 12, "تريليون", "تريليون", "تريليونات")
107
+ + _scale(10 ** 12, "ترليون", "ترليون", "ترليونات"))
108
+
109
+ ZERO = frozenset({"صفر"})
110
+ NEGATIVE = frozenset({"سالب", "ناقص"})
111
+ POINT = frozenset({normalize("فاصلة")})
112
+ DIGITS = dict(_UNITS_1_9, **{"صفر": 0})
113
+ BARE_POINT = False
114
+ ONE_AFTER_NOUN = frozenset(_table([("واحد", 1), ("واحدة", 1)]))
115
+
116
+ _NUMBER_WORDS = (set(ALONE) | set(TEEN_UNIT) | set(BEFORE_TENS) | set(TENS) | H100 | H200
117
+ | set(H_STEM) | set(COMPOUND) | set(SCALES) | ZERO | NEGATIVE | POINT | {WA})
118
+
119
+ # ---- currency nouns --------------------------------------------------------
120
+
121
+ _UNIT_ALIASES = [ # (word, unit id, kind)
122
+ ("شيقل", "shekel", "sg"), ("شيقلاً", "shekel", "sg"), ("شيقلان", "shekel", "du"),
123
+ ("شيقلين", "shekel", "du"), ("شواقل", "shekel", "pl"), ("ملاليم", "millime", "pl"),
124
+ ]
125
+
126
+
127
+ def _build_units():
128
+ ids, kinds = {}, {}
129
+ rows = []
130
+ for uid, (sg, du, du_obl, pl, acc, _gender) in _ar.LANG.units.items():
131
+ rows += [(sg, uid, "sg"), (acc, uid, "sg"), (pl, uid, "sg" if du is None else "pl")]
132
+ if du is not None:
133
+ rows += [(du, uid, "du"), (du_obl, uid, "du")]
134
+ for word, uid, kind in rows + _UNIT_ALIASES:
135
+ w = normalize(word)
136
+ ids.setdefault(w, set()).add(uid)
137
+ if kinds.get(w) != "sg":
138
+ kinds[w] = kind
139
+ return {w: (frozenset(ids[w]), kinds[w]) for w in ids}
140
+
141
+
142
+ UNITS = _build_units() # normalised noun -> (unit ids, sg | du | pl)
143
+
144
+ _NISBAS = {
145
+ "أمريكي": "USD", "أميركي": "USD", "إسترليني": "GBP", "بريطاني": "GBP", "ياباني": "JPY",
146
+ "سويسري": "CHF", "كندي": "CAD", "أسترالي": "AUD", "نيوزيلندي": "NZD", "سنغافوري": "SGD",
147
+ "صيني": "CNY", "هندي": "INR", "باكستاني": "PKR", "تركي": "TRY", "روسي": "RUB",
148
+ "برازيلي": "BRL", "مكسيكي": "MXN", "إسرائيلي": "ILS", "سعودي": "SAR", "إماراتي": "AED",
149
+ "قطري": "QAR", "كويتي": "KWD", "بحريني": "BHD", "عماني": "OMR", "أردني": "JOD",
150
+ "عراقي": "IQD", "مصري": "EGP", "سوداني": "SDG", "سوري": "SYP", "لبناني": "LBP",
151
+ "يمني": "YER", "ليبي": "LYD", "تونسي": "TND", "جزائري": "DZD", "مغربي": "MAD",
152
+ "موريتاني": "MRU", "صومالي": "SOS", "جيبوتي": "DJF", "قمري": "KMF",
153
+ }
154
+ # كويتي, كويتية, كويتياً, كويتيان, كويتيين, كويتيتان, كويتيتين
155
+ QUALIFIERS = {normalize(base + ending): code for base, code in _NISBAS.items()
156
+ for ending in ("", "ة", "ا", "ان", "ين", "تان", "تين")}
157
+
158
+ _FRAME = {"فقط", "لا", "غير"}
159
+ _VOCAB = _NUMBER_WORDS | set(UNITS) | set(QUALIFIERS) | _FRAME
160
+
161
+ _CHUNK = re.compile(r"\S+")
162
+ _PIECE = re.compile(r"[^,،;؛]+")
163
+ _EDGE = ".:!?؟()[]{}\"'«»“”*"
164
+
165
+
166
+ def tokenize(text):
167
+ toks = []
168
+ for index, m in enumerate(_CHUNK.finditer(text)):
169
+ for p in _PIECE.finditer(m.group()):
170
+ piece = p.group()
171
+ raw = piece.strip(_EDGE)
172
+ if not raw:
173
+ continue
174
+ pos = m.start() + p.start() + (len(piece) - len(piece.lstrip(_EDGE)))
175
+ norm = normalize(raw)
176
+ tanween = FATHATAN in raw
177
+ # وأحد عشر: with its hamza the word is و + أحد, not واحد (composed
178
+ # first, so the hamza of NFD text is kept)
179
+ hamza = _MARKS.sub("", unicodedata.normalize("NFC", raw))[:2] in ("وأ", "وإ")
180
+ if (norm.startswith(WA) and len(norm) > 1 and norm[1:] in _VOCAB
181
+ and (hamza or norm not in _VOCAB)):
182
+ toks.append(Token(raw[0], WA, pos, index)) # an attached و
183
+ toks.append(Token(raw[1:], norm[1:], pos + 1, index, tanween))
184
+ else:
185
+ toks.append(Token(raw, norm, pos, index, tanween))
186
+ # the same without the hamza: "مئة واحد عشر" can only be مئة و أحد عشر
187
+ for i in range(len(toks) - 1, 0, -1):
188
+ t = toks[i]
189
+ if (t.norm == _WAHID and toks[i - 1].norm != WA and i + 1 < len(toks)
190
+ and toks[i + 1].norm in TEN_WORD):
191
+ toks[i:i + 1] = [Token(t.raw[0], WA, t.pos, t.index),
192
+ Token(t.raw[1:], t.norm[1:], t.pos + 1, t.index)]
193
+ return toks
194
+
195
+
196
+ def strip_frame(toks):
197
+ """Drop the cheque formula: فقط at either end, لا غير at the end."""
198
+ if toks and toks[0].norm == "فقط":
199
+ toks = toks[1:]
200
+ if len(toks) >= 2 and toks[-2].norm == "لا" and toks[-1].norm == "غير":
201
+ toks = toks[:-2]
202
+ if toks and toks[-1].norm == "فقط":
203
+ toks = toks[:-1]
204
+ return toks
205
+
206
+
207
+ def is_number_word(norm):
208
+ return norm in _NUMBER_WORDS
209
+
210
+
211
+ def unexpected(toks, j, want="a number word"):
212
+ t = toks[j]
213
+ if j > 0 and (t.norm in _NUMBER_WORDS or t.norm in UNITS):
214
+ fail(f"this word cannot follow {toks[j - 1].raw!r}", t)
215
+ fail(f"this is not {want}", t)
216
+
217
+
218
+ # ---- whole numbers ---------------------------------------------------------
219
+
220
+ def _starts_sub100(tok):
221
+ w = tok.norm
222
+ return w in ALONE or w in TEEN_UNIT or w in BEFORE_TENS or w in TENS
223
+
224
+
225
+ def _starts(tok):
226
+ w = tok.norm
227
+ return (_starts_sub100(tok) or w in H100 or w in H200 or w in COMPOUND or w in H_STEM
228
+ or w in SCALES)
229
+
230
+
231
+ def _sub100(toks, i):
232
+ n = len(toks)
233
+ w = toks[i].norm
234
+ if w in TENS:
235
+ return TENS[w], i + 1
236
+ nxt = toks[i + 1].norm if i + 1 < n else None
237
+ if nxt in TEN_WORD and w in TEEN_UNIT:
238
+ return 10 + TEEN_UNIT[w], i + 2
239
+ if nxt == WA and w in BEFORE_TENS and i + 2 < n and toks[i + 2].norm in TENS:
240
+ return BEFORE_TENS[w] + TENS[toks[i + 2].norm], i + 3
241
+ if w in ALONE:
242
+ return ALONE[w], i + 1
243
+ if w in TEEN_UNIT or w in BEFORE_TENS:
244
+ fail("this form is only used inside 11-19 or 21-99", toks[i])
245
+ unexpected(toks, i)
246
+
247
+
248
+ def _sub1000(toks, i):
249
+ n = len(toks)
250
+ w = toks[i].norm
251
+ hundreds, j = 0, i
252
+ if w in H_STEM and i + 1 < n and toks[i + 1].norm in H100:
253
+ hundreds, j = H_STEM[w] * 100, i + 2
254
+ elif w in H100:
255
+ hundreds, j = 100, i + 1
256
+ elif w in H200:
257
+ hundreds, j = 200, i + 1
258
+ elif w in COMPOUND:
259
+ hundreds, j = COMPOUND[w], i + 1
260
+ if not hundreds:
261
+ return _sub100(toks, i)
262
+ if j + 1 < n and toks[j].norm == WA and _starts_sub100(toks[j + 1]):
263
+ rest, k = _sub100(toks, j + 1)
264
+ return hundreds + rest, k
265
+ return hundreds, j
266
+
267
+
268
+ def integer(toks, i, nouns=frozenset()):
269
+ """Read the longest whole number that starts at ``toks[i]``.
270
+ Returns ``(value, next index)``. ``nouns`` are the words that may follow
271
+ a number as the thing counted (currency nouns); they decide whether an
272
+ unvowelled ألفا is the dual before its noun."""
273
+ n = len(toks)
274
+ if toks[i].norm in ZERO:
275
+ return 0, i + 1
276
+ if not _starts(toks[i]):
277
+ unexpected(toks, i)
278
+ total, last, last_count, repeated = 0, None, 0, False
279
+ while True:
280
+ tok = toks[i]
281
+ if tok.norm in SCALES: # ألف, ألفان: no number before it
282
+ value, kind = SCALES[tok.norm]
283
+ if kind == "sg":
284
+ count = 1
285
+ elif kind == "dual":
286
+ count = 2
287
+ elif kind == "pl":
288
+ fail("a plural scale word needs a number before it", tok)
289
+ elif tok.tanween:
290
+ count = 1 # ألفاً
291
+ elif i + 1 < n and toks[i + 1].norm in nouns:
292
+ count = 2 # ألفا دينار
293
+ else:
294
+ fail("ambiguous without a number before it: write ألفان / ألفين for two "
295
+ "or ألف for one", tok)
296
+ j = i + 1
297
+ else:
298
+ count, j = _sub1000(toks, i)
299
+ if not (j < n and toks[j].norm in SCALES):
300
+ return total + count, j
301
+ tok = toks[j]
302
+ value, kind = SCALES[tok.norm]
303
+ if kind == "dual":
304
+ fail("the dual of a scale word takes no number before it", tok)
305
+ j += 1
306
+ if last is not None:
307
+ # مئة ألف وألف: the same scale twice, round hundreds then 1-99
308
+ again = (value == last and not repeated and last_count >= 100
309
+ and last_count % 100 == 0 and count < 100)
310
+ if value > last or (value == last and not again):
311
+ fail("scale words must go from the largest to the smallest", tok)
312
+ repeated = value == last
313
+ total += count * value
314
+ last, last_count, i = value, count, j
315
+ if i + 1 < n and toks[i].norm == WA and _starts(toks[i + 1]):
316
+ i += 1
317
+ continue
318
+ return total, i
319
+
320
+
321
+ # ---- money -----------------------------------------------------------------
322
+
323
+ def main_ids(cur):
324
+ return {_ar.LANG.unit_ids(cur)[0]}
325
+
326
+
327
+ def sub_id(cur):
328
+ return _ar.LANG.unit_ids(cur)[1]
329
+
330
+
331
+ def has_units(toks):
332
+ return any(t.norm in UNITS and t.norm not in _NUMBER_WORDS or t.norm in QUALIFIERS
333
+ for t in toks)
334
+
335
+
336
+ def _qualifier(toks, j):
337
+ if j < len(toks) and toks[j].norm in QUALIFIERS:
338
+ return frozenset({QUALIFIERS[toks[j].norm]}), j + 1
339
+ return None, j
340
+
341
+
342
+ def _counted(toks, i):
343
+ """One counted noun starting at ``toks[i]``: ثلاثة دنانير, دينار واحد,
344
+ ديناران. Returns ``(Phrase, next index)``."""
345
+ n = len(toks)
346
+ tok = toks[i]
347
+ error = None
348
+ if _starts(tok) or tok.norm in ZERO:
349
+ try:
350
+ count, j = integer(toks, i, frozenset(UNITS))
351
+ if j >= n:
352
+ fail("a currency unit is expected after the number, but the text stops")
353
+ if toks[j].norm not in UNITS:
354
+ unexpected(toks, j, "a currency unit")
355
+ ids, kind = UNITS[toks[j].norm]
356
+ if kind == "du" and count != 2:
357
+ fail("the dual of a currency noun takes no number before it", toks[j])
358
+ allowed, k = _qualifier(toks, j + 1)
359
+ return Phrase(count, toks[j], ids, allowed), k
360
+ except ParseError as exc:
361
+ error = exc
362
+ if tok.norm in UNITS: # دينار واحد, ديناران
363
+ ids, kind = UNITS[tok.norm]
364
+ if kind == "pl":
365
+ fail("a plural currency noun needs a number before it", tok)
366
+ allowed, j = _qualifier(toks, i + 1)
367
+ if kind == "sg" and j < n and toks[j].norm in ONE_AFTER_NOUN:
368
+ j += 1
369
+ if allowed is None:
370
+ allowed, j = _qualifier(toks, j)
371
+ return Phrase(1 if kind == "sg" else 2, tok, ids, allowed), j
372
+ if error is not None:
373
+ raise error
374
+ fail("this is not a number word or a currency unit", tok)
375
+
376
+
377
+ def phrases(toks):
378
+ """Split an amount into counted currency nouns joined with و."""
379
+ n = len(toks)
380
+ out = []
381
+ i = 0
382
+ while i < n:
383
+ if out:
384
+ if toks[i].norm != WA:
385
+ fail("'و' is expected between the parts of an amount, before this word", toks[i])
386
+ i += 1
387
+ if i >= n:
388
+ fail("the text stops after 'و'")
389
+ phrase, i = _counted(toks, i)
390
+ out.append(phrase)
391
+ return out
@@ -0,0 +1,35 @@
1
+ """Shared pieces of the words-to-number parsers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+
7
+ from .errors import ParseError
8
+
9
+
10
+ @dataclass(frozen=True)
11
+ class Token:
12
+ raw: str # the word as written
13
+ norm: str # normalised form used for look-ups
14
+ pos: int # zero-based character offset in the text
15
+ index: int # zero-based number of the white-space separated word
16
+ tanween: bool = False # Arabic: the word carries a fathatan (ألفاً)
17
+
18
+
19
+ @dataclass
20
+ class Phrase:
21
+ """A counted currency noun: "five hundred fils", "ديناران"."""
22
+ count: int
23
+ unit: Token
24
+ ids: frozenset # unit ids the noun can stand for
25
+ allowed: frozenset | None # ISO codes allowed by a qualifier ("Kuwaiti"), or None
26
+ frac: tuple | None = None # (numerator, denominator) of "and 50/100"
27
+ merged: bool = False # a repeated noun was folded in (مئة دينار ودينار واحد)
28
+
29
+
30
+ def fail(why, tok=None):
31
+ """Raise a ParseError, naming the word and where it stands."""
32
+ if tok is None:
33
+ raise ParseError(why)
34
+ raise ParseError(f"{why}: {tok.raw!r} (word {tok.index + 1}, character offset {tok.pos})",
35
+ word=tok.raw, position=tok.pos, index=tok.index)