### Install text2num with uv Source: https://github.com/allo-media/text2num/blob/master/docs/quickstart.rst Install the text2num package in your project using uv. ```default uv add text2num ``` -------------------------------- ### Output of find_numbers example Source: https://github.com/allo-media/text2num/blob/master/docs/quickstart.rst Expected output when executing the token example. ```default found number 20 (20.0) at range [3, 4] in the stream found number 9 (9.0) at range [4, 5] in the stream found number 34 (34.0) at range [6, 8] in the stream ``` -------------------------------- ### Install text2num with pip Source: https://github.com/allo-media/text2num/blob/master/docs/quickstart.rst Install the text2num package in your virtual environment using pip. ```default pip install text2num ``` -------------------------------- ### Install text2num with pip or uv Source: https://github.com/allo-media/text2num/blob/master/README.md Install the text2num package using pip or, for uv projects, uv add. ```bash pip install text2num # or, if using an `uv` project: uv add text2num ``` -------------------------------- ### Parse and convert German text to numbers Source: https://github.com/allo-media/text2num/blob/master/README.md Examples of converting German number words to integers using text2num. ```python >>> from text_to_num import text2num >>> text2num("einundfünfzigmillionenfünfhundertachtundsiebzigtausenddreihundertzwei", "de") 51578302 >>> text2num("ein und achtzig", "de") 81 ``` -------------------------------- ### Parse and convert Portuguese text to numbers Source: https://github.com/allo-media/text2num/blob/master/README.md Examples of converting Portuguese number words to integers using text2num. ```python >>> from text_to_num import text2num >>> text2num("trinta e dois", "pt") 32 >>> text2num("mil novecentos e seis", "pt") 1906 >>> text2num("vinte e quatro milhões duzentos mil quarenta e sete", "pt") 24200047 ``` -------------------------------- ### Find and transcribe numbers with alpha2digit (French) Source: https://github.com/allo-media/text2num/blob/master/docs/quickstart.rst Convert number words to digits in French, handling ordinals, decimals, and series. ```python >>> sentence = ( ... "Huit cent quarante-deux pommes, vingt-cinq chiens, mille trois chevaux, " ... "douze mille six cent quatre-vingt-dix-huit clous.\n" ... "Quatre-vingt-quinze vaut nonante-cinq. On tolère l'absence de tirets avant les unités : " ... "soixante seize vaut septante six.\n" ... "Nombres en série : douze, quinze, zéro zéro quatre, vingt, cinquante-deux, cent trois, cinquante deux, " ... "trente et un.\n" ... "Ordinaux: cinquième troisième vingt et unième centième mille deux cent trentième.\n" ... "Décimaux: douze virgule quatre-vingt dix-neuf, cent vingt virgule zéro cinq ; " ... "mais soixante zéro deux." ... ) >>> print(alpha2digit(sentence, "fr")) 842 pommes, 25 chiens, 1003 chevaux, 12698 clous. 95 vaut 95. On tolère l'absence de tirets avant les unités : 76 vaut 76. Nombres en série : 12, 15, 004, 20, 52, 103, 52, 31. Ordinaux: 5ème 3ème 21ème 100ème 1230ème. Décimaux: 12,99, 120,05 ; mais 60 02. >>> print(alpha2digit("on distingue aussi l'article (un chat) du nombre: un deux trois.", "fr")) on distingue aussi l'article (un chat) du nombre: 1 2 3. ``` -------------------------------- ### Find and transcribe numbers with alpha2digit (English) Source: https://github.com/allo-media/text2num/blob/master/docs/quickstart.rst Convert number words in text to digits, including ordinals, for English. ```python >>> from text_to_num import alpha2digit >>> text = "On May twenty-third, I bought twenty-five cows, twelve chickens and one hundred twenty five point five kg of potatoes." >>> alpha2digit(text, "en") 'On May 23rd, I bought 25 cows, 12 chickens and 125.5 kg of potatoes.' >>> alpha2digit("I finished the race in the twelfth position!", "en") 'I finished the race in the 12th position!' ``` -------------------------------- ### Parse and convert English text to numbers Source: https://github.com/allo-media/text2num/blob/master/README.md Examples of converting English number words to integers using text2num. ```python >>> from text_to_num import text2num >>> text2num("fifty-one million five hundred seventy-eight thousand three hundred two", "en") 51578302 >>> text2num("eighty-one", "en") 81 ``` -------------------------------- ### Parse and convert integers with text2num Source: https://github.com/allo-media/text2num/blob/master/docs/quickstart.rst Convert number words to integers in English, Spanish, and French. Raises ValueError for invalid input. ```python >>> from text_to_num import text2num >>> text2num("fifty-one million five hundred seventy-eight thousand three hundred two", "en") 51578302 >>> text2num("eighty-one", "en") 81 >>> text2num("ochenta y uno", "es") 81 >>> text2num("nueve mil novecientos noventa y nueve", "es") 9999 >>> text2num('quatre-vingt-quinze', "fr") 95 >>> text2num("cinquante et un million cinq cent soixante dix-huit mille trois cent deux", "fr") 51578302 >>> text2num('thousand thousand and two hundreds', 'en') Traceback (most recent call last): ... ValueError: invalid literal for text2num: 'thousand thousand and two hundreds' ``` -------------------------------- ### Parse and convert Spanish text to numbers Source: https://github.com/allo-media/text2num/blob/master/README.md Examples of converting Spanish number words to integers using text2num. ```python >>> from text_to_num import text2num >>> text2num("ochenta y uno", "es") 81 >>> text2num("nueve mil novecientos noventa y nueve", "es") 9999 >>> text2num("cincuenta y tres millones doscientos cuarenta y tres mil setecientos veinticuatro", "es") 53243724 ``` -------------------------------- ### Working with tokens: find_numbers Source: https://github.com/allo-media/text2num/blob/master/docs/quickstart.rst Define a custom Token subclass and use find_numbers to locate numbers in an ASR token stream. ```python from text_to_num import (Token, find_numbers) class DecodedWord(Token): def __init__(self, text, start, end): self._text = text self.start = start self.end = end def text(self): return self._text def nt_separated(self, previous): # we consider a voice gap of more that 100 ms as significant return self.start - previous.end > 100 # Let's simulate ASR output stream = [ DecodedWord("We", 0, 100), DecodedWord("have", 100, 200), DecodedWord("respectively", 200, 400), DecodedWord("twenty", 400, 500), DecodedWord("nine", 610, 700), DecodedWord("and", 700, 800), DecodedWord("thirty", 800, 900), DecodedWord("four", 950, 1000), DecodedWord("dollars", 1010, 1410) ] occurences = find_numbers(stream, "en") for num in occurences: print(f"found number {num.text} ({num.value}) at range [{num.start}, {num.end}] in the stream") ``` -------------------------------- ### Find and transcribe numbers with alpha2digit (Spanish) Source: https://github.com/allo-media/text2num/blob/master/docs/quickstart.rst Convert number words to digits in Spanish, supporting both 'coma' and 'punto' as decimal separators. ```python >>> text = "Compramos veinticinco vacas, doce gallinas y ciento veinticinco coma cuarenta kg de patatas." >>> alpha2digit(text, "es") 'Compramos 25 vacas, 12 gallinas y 125,40 kg de patatas.' >>> text = "Compramos veinticinco vacas, doce gallinas y ciento veinticinco punto cuarenta kg de patatas." >>> alpha2digit(text, "es") 'Compramos 25 vacas, 12 gallinas y 125.40 kg de patatas.' ``` -------------------------------- ### Portuguese alpha2digit example Source: https://github.com/allo-media/text2num/blob/master/README.md Converts Portuguese number words (including ordinals) to digits using alpha2digit with language 'pt'. ```python >>> from text_to_num import alpha2digit >>> text = "Comprámos vinte e cinco vacas, doze galinhas e cento e vinte e cinco vírgula quarenta kg de batatas." >>> alpha2digit(text, "pt") 'Comprámos 25 vacas, 12 galinhas e 125,40 kg de batatas.' ``` ```python >>> text = "Ordinais: quinto, terceiro, vigésima, vigésimo primeiro, centésimo quarto" >>> alpha2digit(text, "pt") 'Ordinais: 5º, 3º, 20ª, 21º, 104º' ``` -------------------------------- ### Iterate over numbers in ASR token stream Source: https://github.com/allo-media/text2num Example from README showing how to iterate over numbers found by find_numbers in a token stream, printing start, end, value, text, and is_ordinal. ```python from text_to_num import Token, find_numbers class DecodedWord(Token): def __init__(self, text, start, end): self._text = text self.start = start self.end = end def text(self): return self._text def nt_separated(self, previous): return self.start - previous.end > 100 stream = [ DecodedWord("twenty", 400, 500), DecodedWord("nine", 610, 700), DecodedWord("thirty", 800, 900), DecodedWord("four", 950, 1000), ] for num in find_numbers(stream, "en"): print(num.start, num.end, num.value, num.text, num.is_ordinal) # 0 1 20.0 20 False # 1 2 9.0 9 False # 2 4 34.0 34 False ``` -------------------------------- ### English alpha2digit example Source: https://github.com/allo-media/text2num/blob/master/README.md Converts English number words (including ordinals and decimals) to digits using alpha2digit with language 'en'. ```python >>> from text_to_num import alpha2digit >>> text = "On May twenty-third, I bought twenty-five cows, twelve chickens and one hundred twenty five point four zero kg of potatoes." >>> alpha2digit(text, "en") 'On May 23rd, I bought 25 cows, 12 chickens and 125.40 kg of potatoes.' ``` ```python >>> alpha2digit("I finished the race in the twelfth position!", "en") 'I finished the race in the 12th position!' ``` -------------------------------- ### Both failure modes from README/docs Source: https://github.com/allo-media/text2num Shows the traceback output for two invalid literal examples in French and English. The ValueError message includes the original text. ```python >>> text2num('mille mille deux cents', "fr") Traceback (most recent call last): ... ValueError: invalid literal for text2num: 'mille mille deux cents' >>> text2num('thousand thousand and two hundreds', 'en') Traceback (most recent call last): ... ValueError: invalid literal for text2num: 'thousand thousand and two hundreds' ``` -------------------------------- ### Parse and convert French text to numbers Source: https://github.com/allo-media/text2num/blob/master/README.md Examples of converting French number words to integers using text2num. Includes a case that raises ValueError for invalid input. ```python >>> from text_to_num import text2num >>> text2num('quatre-vingt-quinze', "fr") 95 >>> text2num('nonante-cinq', "fr") 95 >>> text2num('mille neuf cent quatre-vingt dix-neuf', "fr") 1999 >>> text2num('dix-neuf cent quatre-vingt dix-neuf', "fr") 1999 >>> text2num("cinquante et un million cinq cent soixante dix-huit mille trois cent deux", "fr") 51578302 >>> text2num('mille mille deux cents', "fr") Traceback (most recent call last): ... ValueError: invalid literal for text2num: 'mille mille deux cents' ``` -------------------------------- ### Spanish alpha2digit example Source: https://github.com/allo-media/text2num/blob/master/README.md Converts Spanish number words (including ordinals and decimals) to digits using alpha2digit with language 'es'. Shows handling of comma and point decimal separators, and threshold=0 for ordinals. ```python >>> from text_to_num import alpha2digit >>> text = "Compramos veinticinco vacas, doce gallinas y ciento veinticinco coma cuarenta kg de patatas." >>> alpha2digit(text, "es") 'Compramos 25 vacas, 12 gallinas y 125,40 kg de patatas.' ``` ```python >>> text = "Compramos veinticinco vacas, doce gallinas y ciento veinticinco punto cuarenta kg de patatas." >>> alpha2digit(text, "es") 'Compramos 25 vacas, 12 gallinas y 125.40 kg de patatas.' ``` ```python >>> text = "Ella ha quedado tercera" >>> alpha2digit(text, "es", threshold=0) 'Ella ha quedado 3ª' ``` -------------------------------- ### French alpha2digit example Source: https://github.com/allo-media/text2num/blob/master/README.md Converts French number words (including ordinals, decimals, and series) to digits using alpha2digit with language 'fr'. Demonstrates handling of missing hyphens and ordinal suffixes. ```python >>> from text_to_num import alpha2digit >>> sentence = ( ... "Huit cent quarante-deux pommes, vingt-cinq chiens, mille trois chevaux, " ... "douze mille six cent quatre-vingt-dix-huit clous.\n" ... "Quatre-vingt-quinze vaut nonante-cinq. On tolère l'absence de tirets avant les unités : " ... "soixante seize vaut septante six.\n" ... "Nombres en série : douze, quinze, zéro zéro quatre, vingt, cinquante-deux, cent trois, cinquante deux, " ... "trente et un.\n" ... "Ordinaux: cinquième troisième vingt et unième centième mille deux cent trentième.\n" ... "Décimaux: douze virgule quatre-vingt dix-neuf, cent vingt virgule zéro cinq ; " ... "mais soixante zéro deux." ... ) >>> print(alpha2digit(sentence, "fr")) 842 pommes, 25 chiens, 1003 chevaux, 12698 clous. 95 vaut 95. On tolère l'absence de tirets avant les unités : 76 vaut 76. Nombres en série : 12, 15, 004, 20, 52, 103, 52, 31. Ordinaux: 5ème 3ème 21ème 100ème 1230ème. Décimaux: 12,99, 120,05 ; mais 60 02. ``` ```python >>> sentence = "Cinquième premier deuxième troisième vingt et unième centième mille deux cent trentième." >>> print(alpha2digit(sentence, "fr")) 5ème 1er 2ème 3ème 21ème 100ème 1230ème. ``` -------------------------------- ### Consume Occurence fields programmatically Source: https://github.com/allo-media/text2num Example showing how to sum values, collect digit texts, extract token spans, and filter ordinals from find_numbers results. ```python from text_to_num import find_numbers # ... tokenize some text into Token instances (see find_numbers.md) ... numbers = find_numbers(tokens, "fr") total = sum(o.value for o in numbers) # float values digit_texts = [o.text for o in numbers] # digit strings spans = [(o.start, o.end) for o in numbers] # token spans in the input list ordinals = [o for o in numbers if o.is_ordinal] ``` -------------------------------- ### German alpha2digit example Source: https://github.com/allo-media/text2num/blob/master/README.md Converts German number words (including ordinals, phone numbers, and decimals) to digits using alpha2digit with language 'de'. Shows threshold=0 behavior for small numbers. ```python >>> from text_to_num import alpha2digit >>> text = "Ich habe fünfundzwanzig Kühe, zwölf Hühner und einhundertfünfundzwanzig kg Kartoffeln gekauft." >>> alpha2digit(text, "de") 'Ich habe 25 Kühe, 12 Hühner und 125 kg Kartoffeln gekauft.' ``` ```python >>> text = "Die Telefonnummer lautet dreiunddreißig neun sechzig null sechs zwölf einundzwanzig." >>> alpha2digit(text, "de") 'Die Telefonnummer lautet 33 9 60 06 12 21.' ``` ```python >>> text = "Der zweiundzwanzigste Januar zweitausendzweiundzwanzig." >>> alpha2digit(text, "de") 'Der 22. Januar 2022.' ``` ```python >>> text = "Es ist ein Buch mit dreitausend Seiten aber nicht das erste." >>> alpha2digit(text, "de", threshold=0) 'Es ist 1 Buch mit 3000 Seiten aber nicht das 1..' ``` ```python >>> text = "Pi ist drei Komma eins vier und so weiter, aber nicht drei Komma vierzehn :-p" >>> alpha2digit(text, "de", threshold=0) 'Pi ist 3,14 und so weiter, aber nicht 3 Komma 14 :-p' ``` -------------------------------- ### Catch errors in consumer code Source: https://github.com/allo-media/text2num All documented, deliberate errors are ValueError subclasses of Exception. This example shows how to catch errors from text2num and alpha2digit, including re-raising unsupported language errors as LookupError. ```python from text_to_num import alpha2digit, find_numbers, text2num from text_to_num import Token # base for token classes def safe_text2num(text: str, lang: str) -> int | None: try: return text2num(text, lang) except ValueError: return None def safe_transcribe(text: str, lang: str) -> str: try: return alpha2digit(text, lang) except ValueError as exc: # only "unsupported language ..." raise LookupError(f"no interpreter for {lang!r}") from exc ``` -------------------------------- ### Getter implementations for Occurence properties Source: https://github.com/allo-media/text2num Rust getter implementations for the read-only properties start, end, value, text, and is_ordinal. ```rust #[getter] pub fn start(&self) -> usize { self.occurence.start } #[getter] pub fn end(&self) -> usize { self.occurence.end } #[getter] pub fn value(&self) -> f64 { self.occurence.value } #[getter] pub fn text(&self) -> &str { self.occurence.text.as_str() } #[getter] pub fn is_ordinal(&self) -> bool { self.occurence.is_ordinal } ``` -------------------------------- ### Minimal Token subclass implementing only text() Source: https://github.com/allo-media/text2num Subclass Token and implement only text(); nt_separated() and not_a_number_part() defaults are inherited. find_numbers() returns occurrences with value, start, and end. ```python from text_to_num import Token, find_numbers class SimpleWord(Token): def __init__(self, text): self.content = text def text(self): return self.content occurences = find_numbers([SimpleWord(w) for w in "twenty five cows".split()], "en") [(o.value, o.start, o.end) for o in occurences] # [(25.0, 0, 2)] ``` -------------------------------- ### ASR token with timing-aware separation (nt_separated) Source: https://github.com/allo-media/text2num Override nt_separated() to treat a voice gap of more than 100 ms as a number separator. The example uses DecodedWord with start/end timestamps and prints found numbers with their text, value, and span. ```python from text_to_num import Token, find_numbers class DecodedWord(Token): def __init__(self, text, start, end): self._text = text self.start = start self.end = end def text(self): return self._text def nt_separated(self, previous): # we consider a voice gap of more than 100 ms as significant return self.start - previous.end > 100 stream = [ DecodedWord("twenty", 400, 500), DecodedWord("nine", 610, 700), # gap = 110 ms -> separated DecodedWord("thirty", 800, 900), DecodedWord("four", 950, 1000), # gap = 50 ms -> same number ] for num in find_numbers(stream, "en"): print(f"found {num.text} ({num.value}) at [{num.start}, {num.end}]") # found 20 (20.0) at [0, 1] # found 9 (9.0) at [1, 2] # found 34 (34.0) at [2, 4] ``` -------------------------------- ### Using not_a_number_part to exclude tokens from number grouping Source: https://github.com/allo-media/text2num Override not_a_number_part() to mark a token as not a number part, keeping it out of number-group detection. The example uses a Word class with a skip flag; the exact grouping effect is determined by the external text2num crate. ```python from text_to_num import Token, find_numbers class Word(Token): def __init__(self, text, skip=False): self._text = text self._skip = skip def text(self): return self._text def not_a_number_part(self): return self._skip stream = [Word("fifty"), Word("five", skip=True), Word("cows")] print([(o.text, o.start, o.end) for o in find_numbers(stream, "en")]) ``` -------------------------------- ### Import Token protocol Source: https://github.com/allo-media/text2num Import the Token protocol from the text_to_num package. ```python from text_to_num import Token ``` -------------------------------- ### Python signature for text2num Source: https://github.com/allo-media/text2num The Python-exposed signature of text2num. ```python text2num(text: str, lang: str) -> int ``` -------------------------------- ### Quick symbol table import and signatures Source: https://github.com/allo-media/text2num Import the main public API of the text2num package and view the signatures of text2num(), alpha2digit(), find_numbers(), and the Occurence/Token types. Note that text2num raises ValueError on invalid text or language, and alpha2digit is punctuation-aware with a default threshold of 3.0. ```python from text_to_num import text2num, alpha2digit, find_numbers, Occurence, Token text2num(text: str, lang: str) -> int # ValueError on invalid text / language alpha2digit(text: str, lang: str, threshold: float = 3.0) -> str # punctuation-aware rewrite find_numbers(input: list[Token], lang: str, threshold: float = 3.0) -> list[Occurence] # Occurence: .start: int, .end: int, .value: float, .text: str, .is_ordinal: bool (read-only) # Token: subclass and implement .text() -> str; optional nt_separated()/not_a_number_part() hooks ``` -------------------------------- ### Import text2num Source: https://github.com/allo-media/text2num Import the text2num function from the text_to_num package. ```python from text_to_num import text2num ``` -------------------------------- ### find_numbers(input, lang, threshold=3.0) Source: https://github.com/allo-media/text2num Finds numbers and their positions in a stream of tokens (for example Speech-to-Text word timestamps) and returns one Occurence per number found. An occurrence can span multiple consecutive tokens. ```APIDOC ## find_numbers(input, lang, threshold=3.0) ### Description Finds numbers and their positions in a stream of tokens (for example Speech-to-Text word timestamps) and returns one `Occurence` per number found. An occurrence can span multiple consecutive tokens. ### Signature ```python find_numbers(input: list[Token], lang: str, threshold: float = 3.0) -> list[Occurence] ``` ### Parameters - `input` (list[Token]) - Required - Sequence of tokens to scan. Each element must be a Python object exposing the `Token` protocol methods — see [Token.md](Token.md). - `lang` (str) - Required - Language code. Supported languages per README: Danish, Dutch, English, French, German, Italian, Portuguese (Brazilian and European), Spanish. - `threshold` (float) - Optional, default `3.0` - Same semantics as `alpha2digit`: isolated numbers (integers/ordinals not belonging to a number group) are converted/returned only if their value is above the threshold. Forwarded unchanged to the Rust crate's `find_numbers_iter` (`src/lib.rs:140-141`). ### Return Value `list[Occurence]` — one instance per number found, in token order. Each `Occurence` exposes: - `start` (int) — offset of the first token of the occurrence, - `end` (int) — offset one past the last token of the occurrence (end-exclusive), - `value` (float) — the numeric value, - `text` (str) — the digit representation, e.g. `"125"`, - `is_ordinal` (bool) — whether the number is an ordinal. See [Occurence.md](Occurence.md) for the full property documentation. ``` -------------------------------- ### Token.text() Source: https://github.com/allo-media/text2num Returns the text content of the token. This is the only mandatory method for objects conforming to the Token protocol. ```APIDOC ## text() ### Description Returns the text content of the token. This is the only mandatory method for objects conforming to the Token protocol. ### Method `text(self) -> str` ### Parameters None ### Returns - **str** - The text content of the token. ### Example ```python token.text() ``` ``` -------------------------------- ### Import Token and Occurence from text_to_num Source: https://github.com/allo-media/text2num Both named types are importable from the top-level package. ```python from text_to_num import Token, Occurence ``` -------------------------------- ### Error handling for invalid text and unsupported language Source: https://github.com/allo-media/text2num Demonstrates ValueError handling for a text with two number groups and an unknown language code. The output shows the error messages. ```python from text_to_num import text2num for text, lang in [ ("mille mille deux cents", "fr"), # two "mille" groups → invalid ("cinquante-deux", "xx"), # unknown language code ]: try: value = text2num(text, lang) except ValueError as exc: print(f"failed: {exc}") # failed: invalid literal for text2num: 'mille mille deux cents' # failed: unsupported language xx ``` -------------------------------- ### Cardinals, ordinals and decimals in one sentence (English) Source: https://github.com/allo-media/text2num Converts cardinals, ordinals, and decimals in a single English sentence. ```python >>> text = "On May twenty-third, I bought twenty-five cows, twelve chickens and one hundred twenty five point four zero kg of potatoes." >>> alpha2digit(text, "en") 'On May 23rd, I bought 25 cows, 12 chickens and 125.40 kg of potatoes.' ``` ```python >>> alpha2digit("I finished the race in the twelfth position!", "en") 'I finished the race in the 12th position!' ``` -------------------------------- ### Rust source signature for text2num Source: https://github.com/allo-media/text2num The Rust function definition with the pyo3 attribute renaming it to text2num. ```rust #[pyfunction] #[pyo3(name = "text2num")] fn text_to_num(text: &str, lang: &str) -> PyResult ``` -------------------------------- ### Error handling for unsupported language Source: https://github.com/allo-media/text2num Raises ValueError with message 'unsupported language klingon' when an invalid language code is passed. ```python from text_to_num import alpha2digit try: out = alpha2digit("twenty-five cows", "klingon") except ValueError as exc: print(exc) # unsupported language klingon ``` -------------------------------- ### Import alpha2digit from text_to_num Source: https://github.com/allo-media/text2num Import the alpha2digit function from the text_to_num package before using it. ```python from text_to_num import alpha2digit ``` -------------------------------- ### Token protocol definition Source: https://github.com/allo-media/text2num Defines the Token protocol with abstract text() method and optional hooks nt_separated and not_a_number_part, both defaulting to False. ```python class Token(Protocol): """Protocol for natural language tokens suitable for ``find_numbers```. The only mandatory method is ``self.text()``. """ @abstractmethod def text(self) -> str: """Return the text content of the token.""" ... def nt_separated(self, previous: "Token") -> bool: """... return true if `self` and `previous` are unrelated. Default implementation return ``False``. """ return False def not_a_number_part(self) -> bool: """Despite its form, we have evidence that this token is not a number part. Default implementation return ``False``. """ return False ``` -------------------------------- ### Punctuation-aware behavior in French Source: https://github.com/allo-media/text2num Handles comma groups and decimals in French, preserving punctuation. ```python >>> sentence = ( ... "Nombres en série : douze, quinze, zéro zéro quatre, vingt, cinquante-deux, cent trois, cinquante deux, " ... "trente et un.\n" ... "Ordinaux: cinquième troisième vingt et unième centième mille deux cent trentième.\n" ... "Décimaux: douze virgule quatre-vingt dix-neuf, cent vingt virgule zéro cinq." ... ) >>> print(alpha2digit(sentence, "fr")) Nombres en série : 12, 15, 004, 20, 52, 103, 52, 31. Ordinaux: 5ème 3ème 21ème 100ème 1230ème. Décimaux: 12,99, 120,05. ``` -------------------------------- ### Import Occurence class Source: https://github.com/allo-media/text2num Import the Occurence class from the text_to_num module. ```python from text_to_num import Occurence ``` -------------------------------- ### Spelled-out decimal fails Source: https://github.com/allo-media/text2num Shows that text2num raises ValueError for a spelled-out decimal because it only supports integers. ```python >>> text2num("douze virgule quatre-vingt-dix-neuf", "fr") Traceback (most recent call last): ... ValueError: invalid literal for text2num: 'douze virgule quatre-vingt-dix-neuf' ``` -------------------------------- ### Token.not_a_number_part() Source: https://github.com/allo-media/text2num Indicates whether there is evidence that this token, despite its form, is not a number part. The default implementation returns False. ```APIDOC ## not_a_number_part() ### Description Indicates whether there is evidence that this token, despite its form, is not a number part. The default implementation returns False. ### Method `not_a_number_part(self) -> bool` ### Parameters None ### Returns - **bool** - True if the token is not a number part, False otherwise. ### Example ```python token.not_a_number_part() ``` ``` -------------------------------- ### Multiple languages in one application Source: https://github.com/allo-media/text2num Shows how to use text2num with different language codes. The function parse_invoice_amount returns the integer value for the given amount and locale. ```python from text_to_num import text2num def parse_invoice_amount(amount_in_words: str, locale: str) -> int: return text2num(amount_in_words, locale) parse_invoice_amount("quatre-vingt-quinze", "fr") # 95 parse_invoice_amount("ochenta y uno", "es") # 81 parse_invoice_amount("trinta e dois", "pt") # 32 parse_invoice_amount("ein und achtzig", "de") # 81 ``` -------------------------------- ### Token Protocol Source: https://github.com/allo-media/text2num A structural protocol for natural language tokens that can be passed to find_numbers. It requires implementing the text() method and provides optional hooks for token separation and number-part detection. ```APIDOC ## Token Protocol ### Description A structural protocol for natural language tokens that can be passed to `find_numbers`. It requires implementing the `text()` method and provides optional hooks for token separation and number-part detection. ### Members - `text()` (() -> str) - Required - Text content of the token. - `nt_separated(previous)` ((Token) -> bool) - Optional (default `False`) - True if `self` and `previous` are unrelated (e.g. separated by a voice pause in ASR output). - `not_a_number_part()` (() -> bool) - Optional (default `False`) - Evidence that the token is not a number part despite its form. ### Usage Subclass `Token` and implement `text()`; the two boolean hooks are inherited with default `False` implementations. ``` -------------------------------- ### Python signature of alpha2digit Source: https://github.com/allo-media/text2num The Python-facing signature of alpha2digit, exposed with a default threshold of 3.0. ```python alpha2digit(text: str, lang: str, threshold: float = 3.0) -> str ``` -------------------------------- ### text2num Function Source: https://github.com/allo-media/text2num Converts a text string to an integer. It takes a text and a language code. ```APIDOC ## text2num Function ### Description Converts a text string to an integer. It takes a text and a language code. ### Signature `text2num(text: str, lang: str) -> int` ### Parameters - `text` (str) - Required - Input text. - `lang` (str) - Required - Language code (validated at runtime by the `text2num` crate). ``` -------------------------------- ### Language-specific decimal separators (Spanish) Source: https://github.com/allo-media/text2num Uses comma or point as decimal separator depending on the input wording. ```python >>> alpha2digit("Compramos veinticinco vacas, doce gallinas y ciento veinticinco coma cuarenta kg de patatas.", "es") 'Compramos 25 vacas, 12 gallinas y 125,40 kg de patatas.' ``` ```python >>> alpha2digit("Compramos veinticinco vacas, doce gallinas y ciento veinticinco punto cuarenta kg de patatas.", "es") 'Compramos 25 vacas, 12 gallinas y 125.40 kg de patatas.' ``` -------------------------------- ### Import public symbols from text2num Source: https://github.com/allo-media/text2num Import all public API symbols from the top-level package. The package version is 3.1.0 and requires Python ≥ 3.8. ```python from text_to_num import text2num, alpha2digit, find_numbers, Occurence, Token ``` -------------------------------- ### Import find_numbers from text_to_num Source: https://github.com/allo-media/text2num Import the find_numbers function from the text_to_num package. ```python from text_to_num import find_numbers ``` -------------------------------- ### find_numbers(input, lang, threshold) Source: https://github.com/allo-media/text2num Finds numbers in text and returns them. Raises ValueError for unsupported language or panic on protocol issues. ```APIDOC ## find_numbers(input, lang, threshold) ### Description Finds numbers in text and returns them. Raises ValueError for unsupported language or panic on protocol issues. ### Parameters - **input** (str) - Required - The input text. - **lang** (str) - Required - The language code. - **threshold** (int) - Optional - Threshold for detection. ### Errors - `ValueError: unsupported language` - Raised when `lang` is unknown. - Panic / PanicException (Rust `panic!`) - Raised when token `text()` does not return `str` or missing protocol methods on duck-typed tokens. ``` -------------------------------- ### Find numbers in token stream with custom Token subclass Source: https://github.com/allo-media/text2num/blob/master/README.md Defines a DecodedWord subclass of Token with start/end timestamps and a custom nt_separated method that treats a voice gap of more than 100 ms as significant. Simulates ASR output and uses find_numbers(stream, "en") to locate numbers, printing their text, value, and range. ```python from text_to_num import (Token, find_numbers) class DecodedWord(Token): def __init__(self, text, start, end): self._text = text self.start = start self.end = end def text(self): return self._text def nt_separated(self, previous): # we consider a voice gap of more that 100 ms as significant return self.start - previous.end > 100 # Let's simulate ASR output stream = [ DecodedWord("We", 0, 100), DecodedWord("have", 100, 200), DecodedWord("respectively", 200, 400), DecodedWord("twenty", 400, 500), DecodedWord("nine", 610, 700), DecodedWord("and", 700, 800), DecodedWord("thirty", 800, 900), DecodedWord("four", 950, 1000), DecodedWord("dollars", 1010, 1410) ] occurences = find_numbers(stream, "en") for num in occurences: print(f"found number {num.text} ({num.value}) at range [{num.start}, {num.end}] in the stream") ``` ```text found number 20 (20.0) at range [3, 4] in the stream found number 9 (9.0) at range [4, 5] in the stream found number 34 (34.0) at range [6, 8] in the stream ``` -------------------------------- ### Rust source signature of alpha2digit Source: https://github.com/allo-media/text2num The exact Rust signature of the alpha2digit function as defined in src/lib.rs:17-19. It is a pyfunction with a pyo3 signature accepting text, lang, and threshold (default 3.0). ```rust #[pyfunction] #[pyo3(signature = (text, lang, threshold=3.0))] fn alpha2digit(text: &str, lang: &str, threshold: f64) -> PyResult ``` -------------------------------- ### Token protocol Source: https://github.com/allo-media/text2num Input contract for find_numbers(). Subclass and implement the text() method; optional hooks nt_separated() and not_a_number_part() are available. ```APIDOC ## Token protocol ### Description Input contract for find_numbers(). Subclass and implement the text() method; optional hooks nt_separated() and not_a_number_part() are available. ### Methods - **text()** -> str - Required - Returns the token's text. - **nt_separated()** - Optional - Hook for handling number-token separation. - **not_a_number_part()** - Optional - Hook for identifying non-number parts. ``` -------------------------------- ### Token Protocol definition Source: https://github.com/allo-media/text2num Defines the Token protocol with mandatory text() method and optional nt_separated() and not_a_number_part() methods. Default implementations return False. ```python class Token(Protocol): """Protocol for natural language tokens suitable for ``find_numbers```. The only mandatory method is ``self.text()``. """ @abstractmethod def text(self) -> str: """Return the text content of the token.""" ... def nt_separated(self, previous: "Token") -> bool: """In some token streams (e.g. ASR output), there is no punctuation tokens to separate words that must be undestood separately, but the tokens themselves may embed additional information to convey that distinction (e.g. timing information that can reveal voice pauses). This method should return true if `self` and `previous` are unrelated. Default implementation return ``False``. """ return False def not_a_number_part(self) -> bool: """Despite its form, we have evidence that this token is not a number part. Default implementation return ``False``. """ return False ``` -------------------------------- ### find_numbers(input: list[Token], lang: str, threshold: float = 3.0) -> list[Occurence] Source: https://github.com/allo-media/text2num Detects numbers in a token stream and returns a list of occurrences. The input tokens must implement the Token protocol. ```APIDOC ## find_numbers(input: list[Token], lang: str, threshold: float = 3.0) -> list[Occurence] ### Description Detects numbers in a token stream and returns a list of occurrences. The input tokens must implement the Token protocol. ### Parameters - **input** (list[Token]) - Required - List of tokens to analyze. - **lang** (str) - Required - The language code (e.g., 'en', 'fr'). - **threshold** (float) - Optional - Detection threshold (default: 3.0). ### Returns - **list[Occurence]** - List of detected number occurrences. ``` -------------------------------- ### Catching ValueError for unsupported language Source: https://github.com/allo-media/text2num Use this to catch the ValueError raised when an unsupported language code is passed to text2num. The error message is 'unsupported language {lang}' with the caller's lang string verbatim. ```python from text_to_num import text2num try: text2num("cinquante-deux", "xx") except ValueError as exc: assert str(exc) == "unsupported language xx" ``` -------------------------------- ### Panic: non-str token text in find_numbers Source: https://github.com/allo-media/text2num A Rust panic that occurs when a token's text() method returns a non-str value. This is not a catchable exception and should not be relied upon as an application-level error path. ```APIDOC ## Panic: non-str token text in find_numbers ### Description A Rust panic that occurs when a token's text() method returns a non-str value. This is not a catchable exception and should not be relied upon as an application-level error path. ### Raised by - `find_numbers(input, lang, threshold)` ### Condition A token's `text()` method returns a value whose type is not `str`. ### Panic Message `Expected a str for the get_results() method signature, got {type}` (the panic message text is taken verbatim from the source; note it mentions `get_results()` although the check is on `text()`). ### Catchability This is a Rust `panic!` inside a `#[pyfunction]`. Whether it surfaces as a Python-raised `PanicException`, aborts, or is otherwise handled is determined by PyO3's panic policy at runtime — it should not be relied upon as an application-level error path. The normal contract is: every token passes `text()` returning `str` (guaranteed when subclassing `Token`). ``` -------------------------------- ### Default threshold behavior with isolated numbers Source: https://github.com/allo-media/text2num With default threshold=3.0, isolated small cardinals/ordinals are left as words, but groups are converted. ```python >>> alpha2digit("on distingue aussi l'article (un chat) du nombre: un deux trois.", "fr") 'on distingue aussi l'article (un chat) du nombre: 1 2 3.' ``` -------------------------------- ### Rust source signature of find_numbers Source: https://github.com/allo-media/text2num The exact Rust source signature for find_numbers, defined in src/lib.rs:130-139. It takes a PyList, a language string, and an optional threshold (default 3.0), returning a list of NumOccurence. ```rust #[pyfunction] #[pyo3(signature = (input, lang, threshold=3.0))] pub fn find_numbers( input: &Bound<'_, PyList>, lang: &str, threshold: f64, ) -> PyResult> ``` -------------------------------- ### Python signature of find_numbers Source: https://github.com/allo-media/text2num The Python-exposed signature for find_numbers, showing parameter types and default threshold. ```python find_numbers(input: list[Token], lang: str, threshold: float = 3.0) -> list[Occurence] ```