|
16 | 16 | # MA 02110-1301 USA |
17 | 17 | """num2words2 — a thin Python binder over the Rust conversion core. |
18 | 18 |
|
19 | | -Every conversion is served by the compiled `_rust` extension: this module |
20 | | -normalises the language code, maps the public keyword arguments onto the |
21 | | -core's entry points, and applies the two string-level post-processing steps |
22 | | -(`style=`, `cents=`) that are presentation, not conversion. There is no |
23 | | -pure-Python conversion fallback — the core is authoritative, and an input it |
24 | | -declines raises rather than silently diverging. |
| 19 | +Every conversion, and every piece of presentation logic that used to live |
| 20 | +here (language-code resolution, the ``style=`` post-processing, the ``cents=`` |
| 21 | +mode mapping and the whole type dispatch), is now served by the compiled |
| 22 | +``_rust`` extension. This module is a pass-through: it re-exports the public |
| 23 | +entry points and the exception types, nothing more. |
25 | 24 | """ |
26 | 25 | from __future__ import unicode_literals |
27 | 26 |
|
28 | | -import decimal |
29 | | - |
30 | | -from .grouping import group_digits # noqa: E402 |
| 27 | +from . import _rust as _RUST |
| 28 | +from .grouping import group_digits # noqa: F401 (re-exported) |
31 | 29 |
|
32 | 30 | # Version information |
33 | 31 | try: |
|
37 | 35 | __version__ = "unknown" |
38 | 36 | __version_tuple__ = (0, 0, 0, "unknown", 0) |
39 | 37 |
|
40 | | - |
41 | | -# The compiled core is mandatory: this package is a binder over it. |
42 | | -from . import _rust as _RUST # noqa: E402 |
43 | | - |
44 | | -_RUST_LANGS = frozenset(_RUST.supported_langs()) |
45 | | -_RUST_TYPES = frozenset(["cardinal", "ordinal", "ordinal_num", "year"]) |
46 | | -# The core's "declined" signal (see rust/num2words2-py/src/lib.rs). It is |
47 | | -# distinct from NotImplementedError so a genuine NotImplementedError raise |
48 | | -# propagates natively; here, with no Python conversion path behind it, a |
49 | | -# decline is surfaced as NotImplementedError to the caller. |
50 | | -_RUST_FALLBACK = _RUST.RustFallback |
51 | | - |
52 | | -# bn raises NumberTooLargeError past its MAX_NUMBER. The class used to live in |
53 | | -# lang_BN.py; the pure binder defines it in the core and re-exports it here so |
54 | | -# `from num2words2 import NumberTooLargeError` (and `except`) keep working. |
| 38 | +# Exception types defined in the compiled core and re-exported so |
| 39 | +# ``from num2words2 import NumberTooLargeError`` (and ``except`` on it) keep |
| 40 | +# working. RustFallback is the core's "declined" signal, kept importable for |
| 41 | +# the same reason. |
| 42 | +RustFallback = _RUST.RustFallback |
55 | 43 | NumberTooLargeError = _RUST.NumberTooLargeError |
56 | 44 |
|
57 | 45 |
|
|
72 | 60 | CONVERTER_TYPES = CONVERTES_TYPES # Alias for compatibility |
73 | 61 |
|
74 | 62 |
|
75 | | -def maxval(lang="en"): |
76 | | - """Return the maximum integer ``num2words(..., lang=lang)`` can convert. |
77 | | -
|
78 | | - Issue #582 ports savoirfairelinux/num2words#582. |
79 | | - """ |
80 | | - return _RUST.maxval(lang) |
81 | | - |
82 | | - |
83 | | -def _normalize_lang(lang): |
84 | | - """Resolve a caller's language code to a core key, mirroring the historic |
85 | | - dispatcher: exact match, then hyphen->underscore, then ``xx_YY`` casing, |
86 | | - then the bare two-letter prefix. Raises NotImplementedError if none match. |
87 | | - """ |
88 | | - if lang in _RUST_LANGS: |
89 | | - return lang |
90 | | - nl = lang.replace("-", "_") |
91 | | - if nl in _RUST_LANGS: |
92 | | - return nl |
93 | | - parts = nl.split("_") |
94 | | - if len(parts) >= 2: |
95 | | - candidate = "%s_%s" % (parts[0].lower(), parts[1].upper()) |
96 | | - if candidate in _RUST_LANGS: |
97 | | - return candidate |
98 | | - if parts[0] in _RUST_LANGS: |
99 | | - return parts[0] |
100 | | - if nl[:2] in _RUST_LANGS: |
101 | | - return nl[:2] |
102 | | - raise NotImplementedError() |
103 | | - |
104 | | - |
105 | | -def _rust_kw_items(kwargs): |
106 | | - """kwargs -> [(k, v)] for the core boundary, or None when a value has a |
107 | | - type the boundary cannot carry (then the call is out of the core's |
108 | | - envelope and must raise).""" |
109 | | - items = [] |
110 | | - for k, v in kwargs.items(): |
111 | | - if v is None or isinstance(v, (bool, int, str)): |
112 | | - items.append((k, v)) |
113 | | - elif isinstance(v, (list, tuple)) and all( |
114 | | - isinstance(x, str) for x in v): |
115 | | - items.append((k, list(v))) |
116 | | - else: |
117 | | - return None |
118 | | - return items |
119 | | - |
120 | | - |
121 | | -def _apply_style(result, style, to, lang): |
122 | | - """`style=` presentation post-processing (issues #535, #562). Operates on |
123 | | - the rendered string, so it is conversion-independent.""" |
124 | | - if style == "terse" and to == "ordinal" and isinstance(result, str): |
125 | | - for prefix in ("one ", "un ", "uno "): |
126 | | - if result.startswith(prefix) and len(result) > len(prefix): |
127 | | - result = result[len(prefix):] |
128 | | - break |
129 | | - if style == "us" and lang.startswith("en") and isinstance(result, str): |
130 | | - result = result.replace(" and ", " ") |
131 | | - return result |
132 | | - |
133 | | - |
134 | | -def _normalize_cents(kwargs): |
135 | | - """`cents='omit'|'verbose'|'terse'` -> the legacy bool the core expects |
136 | | - (issue #554). Returns (cents_bool, drop_cents) where drop_cents means the |
137 | | - float value should be truncated to an int so no cents segment appears.""" |
138 | | - cents_kw = kwargs.get("cents", True) |
139 | | - if cents_kw == "omit": |
140 | | - return True, True |
141 | | - if cents_kw == "verbose": |
142 | | - return True, False |
143 | | - if cents_kw == "terse": |
144 | | - return False, False |
145 | | - return cents_kw, False |
146 | | - |
147 | | - |
148 | 63 | def num2words(number, ordinal=False, lang="en", to="cardinal", **kwargs): |
149 | | - # Captured before any normalisation: the core keys off the *arrival* type |
150 | | - # (a plain int vs a float/Decimal vs a str), not a post-parse value. |
151 | | - _plain_int = type(number) is int |
152 | | - _plain_num = isinstance(number, (float, decimal.Decimal)) |
153 | | - |
154 | | - lang = _normalize_lang(lang) |
155 | | - _style = kwargs.get("style") |
156 | | - |
157 | | - # ---- string input: the core's from_string owns the whole pipeline |
158 | | - # (fraction strings, str_to_number incl. the ES "1ro" / pt_BR "ponto" |
159 | | - # handshakes, mixed text -> sentence, then the mode dispatch). |
160 | | - if isinstance(number, str): |
161 | | - _to_final = "ordinal" if ordinal else to |
162 | | - if _to_final not in CONVERTES_TYPES: |
163 | | - raise NotImplementedError() |
164 | | - _cents, _ = _normalize_cents(kwargs) |
165 | | - _extras = {k: v for k, v in kwargs.items() |
166 | | - if k not in ("currency", "cents", "separator", |
167 | | - "adjective", "style", "precision")} |
168 | | - _items = _rust_kw_items(_extras) |
169 | | - if _cents not in (True, False) or _items is None: |
170 | | - raise NotImplementedError() |
171 | | - try: |
172 | | - _kind, _out = _RUST.from_string( |
173 | | - lang, number, _to_final, kwargs.get("currency"), _cents, |
174 | | - kwargs.get("separator"), kwargs.get("adjective"), _items) |
175 | | - except _RUST_FALLBACK: |
176 | | - raise NotImplementedError() |
177 | | - if _kind != 0: |
178 | | - raise NotImplementedError() |
179 | | - return _apply_style(_out, _style, _to_final, lang) |
180 | | - |
181 | | - # backwards compatible |
182 | | - if ordinal: |
183 | | - to = "ordinal" |
184 | | - if to not in CONVERTES_TYPES: |
185 | | - raise NotImplementedError() |
186 | | - |
187 | | - _precision = kwargs.get("precision") |
188 | | - _extras = {k: v for k, v in kwargs.items() |
189 | | - if k not in ("style", "precision")} |
190 | | - |
191 | | - # ---- integer modes with a plain int |
192 | | - if _plain_int and to in _RUST_TYPES: |
193 | | - _items = _rust_kw_items(_extras) |
194 | | - if _items is not None: |
195 | | - try: |
196 | | - if _items: |
197 | | - result = getattr(_RUST, "to_%s_kw" % to)( |
198 | | - lang, number, _items) |
199 | | - else: |
200 | | - result = getattr(_RUST, "to_%s" % to)(lang, number) |
201 | | - except _RUST_FALLBACK: |
202 | | - raise NotImplementedError() |
203 | | - return _apply_style(result, _style, to, lang) |
204 | | - |
205 | | - # ---- float / Decimal, all four integer modes |
206 | | - if _plain_num and to in _RUST_TYPES: |
207 | | - try: |
208 | | - _finite = float(number) == float(number) and float( |
209 | | - number) not in (float("inf"), float("-inf")) |
210 | | - except (OverflowError, ValueError): |
211 | | - _finite = False |
212 | | - _fitems = {k: v for k, v in _extras.items() |
213 | | - if k not in ("currency", "cents", "separator", "adjective")} |
214 | | - _items = _rust_kw_items(_fitems) |
215 | | - if _finite and _items is not None: |
216 | | - _prec = abs(decimal.Decimal(str(number)).as_tuple().exponent) |
217 | | - _dec = str(number) if isinstance(number, decimal.Decimal) else "" |
218 | | - try: |
219 | | - result = _RUST.to_float( |
220 | | - lang, to, float(number), _prec, _dec, str(number), |
221 | | - _precision, _items) |
222 | | - except _RUST_FALLBACK: |
223 | | - raise NotImplementedError() |
224 | | - return _apply_style(result, _style, to, lang) |
225 | | - |
226 | | - # ---- currency |
227 | | - if to == "currency" and isinstance(number, (int, float, decimal.Decimal)): |
228 | | - _cents, _drop = _normalize_cents(kwargs) |
229 | | - if _drop and isinstance(number, float): |
230 | | - number = int(number) # int path drops cents naturally |
231 | | - if _cents in (True, False): |
232 | | - _citems = {k: v for k, v in _extras.items() |
233 | | - if k not in ("currency", "cents", "separator", |
234 | | - "adjective")} |
235 | | - _items = _rust_kw_items(_citems) |
236 | | - if _items is not None: |
237 | | - _args = ( |
238 | | - lang, str(number), type(number) is int, |
239 | | - isinstance(number, float) or "." in str(number), |
240 | | - isinstance(number, float), |
241 | | - kwargs.get("currency"), _cents, |
242 | | - kwargs.get("separator"), kwargs.get("adjective"), |
243 | | - ) |
244 | | - try: |
245 | | - if _items: |
246 | | - return _RUST.to_currency_kw(*_args, _items) |
247 | | - return _RUST.to_currency(*_args) |
248 | | - except _RUST_FALLBACK: |
249 | | - raise NotImplementedError() |
250 | | - |
251 | | - if to == "cheque" and isinstance(number, (int, float, decimal.Decimal)): |
252 | | - try: |
253 | | - return _RUST.to_cheque(lang, str(number), kwargs.get("currency")) |
254 | | - except _RUST_FALLBACK: |
255 | | - raise NotImplementedError() |
256 | | - |
257 | | - # to='fraction' with a non-string number: the historic dispatcher fed the |
258 | | - # value straight to converter.to_fraction(value). A single positional (the |
259 | | - # tuple ``(1, 2)``) raised TypeError where the method exists, or |
260 | | - # AttributeError where it does not (bn/dv/id have no to_fraction). Probe |
261 | | - # the core to tell them apart; genuine "n/d" fractions arrive as strings |
262 | | - # and are served by from_string above. |
263 | | - if to == "fraction": |
264 | | - try: |
265 | | - _RUST.to_fraction(lang, 1, 1) |
266 | | - except AttributeError: |
267 | | - raise |
268 | | - except Exception: # noqa: BLE001 - probing for the method's existence |
269 | | - pass |
270 | | - raise TypeError( |
271 | | - "to_fraction() missing 1 required positional argument: " |
272 | | - "'denominator'") |
273 | | - |
274 | | - raise NotImplementedError() |
| 64 | + return _RUST.num2words(number, ordinal, lang, to, **kwargs) |
275 | 65 |
|
276 | 66 |
|
277 | 67 | def num2words_sentence(sentence, lang="en", to="cardinal", **kwargs): |
278 | | - """Convert every number in a sentence to words. |
| 68 | + return _RUST.num2words_sentence(sentence, lang, to, **kwargs) |
279 | 69 |
|
280 | | - `lang=None` auto-detects (lingua-rs in the full build). Handles ordinals, |
281 | | - currency, dates, temperatures and plain numbers, splicing each conversion |
282 | | - back in place. |
283 | 70 |
|
284 | | - >>> num2words_sentence("I bought 6 apples") |
285 | | - 'I bought six apples' |
286 | | - >>> num2words_sentence("The 1st place winner got $100") |
287 | | - 'The first place winner got one hundred dollars, zero cents' |
288 | | - """ |
289 | | - if lang is None: |
290 | | - return _RUST.sentence_auto(sentence, to) |
291 | | - # The core's sentence converter does its own lang validation (and the |
292 | | - # same two-letter-prefix fallback), raising NotImplementedError for an |
293 | | - # unsupported language exactly as the historic dispatcher did. |
294 | | - return _RUST.sentence(sentence, lang, to) |
| 71 | +def maxval(lang="en"): |
| 72 | + return _RUST.maxval(lang) |
295 | 73 |
|
296 | 74 |
|
297 | 75 | # Aliases for num2words_sentence |
|
0 commit comments