zaher-m's picture
download
raw
6.97 kB
"""Digits, separators, formatting and parsing for Western, Eastern Arabic and Persian numerals.
Every character is built from its code point. One parser reads numbers in all three systems.
"""
import re
import unicodedata
from dataclasses import dataclass
from decimal import ROUND_HALF_UP, Decimal
SYSTEMS = ("western", "eastern_arabic", "persian")
ZERO = {"western": 0x0030, "eastern_arabic": 0x0660, "persian": 0x06F0}
DIGITS = {s: "".join(chr(z + i) for i in range(10)) for s, z in ZERO.items()}
ARABIC_THOUSANDS = chr(0x066C)
ARABIC_DECIMAL = chr(0x066B)
ARABIC_PERCENT = chr(0x066A)
MINUS_SIGN = chr(0x2212)
THOUSANDS = {"western": ",", "eastern_arabic": ARABIC_THOUSANDS, "persian": ARABIC_THOUSANDS}
DECIMAL = {"western": ".", "eastern_arabic": ARABIC_DECIMAL, "persian": ARABIC_DECIMAL}
THOUSANDS_CHARS = (",", ARABIC_THOUSANDS)
DECIMAL_CHARS = (".", ARABIC_DECIMAL)
# Bidirectional marks and zero-width characters that do not change a number.
INVISIBLE = [0x061C, 0x200B, 0x200C, 0x200D, 0x200E, 0x200F, 0x2060, 0xFEFF, *range(0x202A, 0x202F), *range(0x2066, 0x206A)]
REMOVE_INVISIBLE = {cp: None for cp in INVISIBLE}
TO_WESTERN = str.maketrans({DIGITS[s][i]: str(i) for s in ("eastern_arabic", "persian") for i in range(10)})
_D = "".join(f"{DIGITS[s][0]}-{DIGITS[s][9]}" for s in SYSTEMS)
_S = re.escape("".join(THOUSANDS_CHARS + DECIMAL_CHARS))
_BODY = rf"[{_D}](?:[{_S}]?[{_D}])*"
TOKEN_RE = re.compile(
rf"(?P<open>\()?[ ]?(?P<sign>[-{MINUS_SIGN}])?[ ]?(?P<body>{_BODY})"
rf"(?:[ ]?(?P<close>\)))?(?P<tail>-(?![{_D}]))?(?:[ ]?[%{ARABIC_PERCENT}])?"
)
def normalize(text):
"""NFC, without bidirectional marks and zero-width characters."""
return unicodedata.normalize("NFC", text).translate(REMOVE_INVISIBLE)
def localize(western_text, system):
"""Map ASCII digits, comma and dot in a Western number string to the given system."""
table = {ord(str(i)): DIGITS[system][i] for i in range(10)}
table[ord(",")] = THOUSANDS[system]
table[ord(".")] = DECIMAL[system]
return western_text.translate(table)
def format_amount(value, system, decimals=0, group=False, negative="minus"):
"""Write a value in a numeral system. negative is 'minus' or 'parens'."""
value = Decimal(value)
magnitude = abs(value).quantize(Decimal(1).scaleb(-decimals), rounding=ROUND_HALF_UP)
int_part, _, frac = f"{magnitude:f}".partition(".")
if group:
int_part = f"{int(int_part):,}"
text = localize(int_part + ("." + frac if decimals else ""), system)
if value < 0:
return f"({text})" if negative == "parens" else "-" + text
return text
def digit_system(text):
"""The numeral system of the digits in text, 'mixed', or None if there are no digits."""
found = {s for s in SYSTEMS for c in text if c in DIGITS[s]}
if not found:
return None
return found.pop() if len(found) == 1 else "mixed"
def digits_only(text):
"""All digits of text, mapped to ASCII, in order."""
return "".join(c for c in text.translate(TO_WESTERN) if c in "0123456789")
def read_body(body, swap=False):
"""Value of a digit string with separators, or None if it breaks the grouping rules.
Thousands groups after the first must have exactly 3 digits. With swap=True the
thousands and decimal roles are exchanged, to detect separator confusion.
"""
thousands, decimal = (DECIMAL_CHARS, THOUSANDS_CHARS) if swap else (THOUSANDS_CHARS, DECIMAL_CHARS)
text = body.translate(TO_WESTERN)
marks = [i for i, c in enumerate(text) if c in decimal]
if len(marks) > 1:
return None
int_part, frac = (text[:marks[0]], text[marks[0] + 1:]) if marks else (text, "")
if frac and not (frac.isascii() and frac.isdigit()):
return None
groups = re.split("[" + re.escape("".join(thousands)) + "]", int_part)
if any(not g.isascii() or not g.isdigit() for g in groups):
return None
if len(groups) > 1 and (not 1 <= len(groups[0]) <= 3 or any(len(g) != 3 for g in groups[1:])):
return None
return Decimal("".join(groups) + ("." + frac if frac else ""))
def read_lenient(body):
"""Value of a digit string whose grouping breaks the rules: thousands separators are dropped.
None if it has more than one decimal separator."""
text = body.translate(TO_WESTERN)
if sum(c in DECIMAL_CHARS for c in text) > 1:
return None
kept = "".join("." if c in DECIMAL_CHARS else c for c in text if c not in THOUSANDS_CHARS)
return Decimal(kept)
@dataclass
class NumberToken:
text: str
body: str
value: Decimal | None
negative: bool
system: str
separators: str
well_formed: bool
def find_numbers(text):
tokens = []
for m in TOKEN_RE.finditer(normalize(text)):
body = m.group("body")
negative = bool(m.group("sign") or m.group("tail") or (m.group("open") and m.group("close")))
value = read_body(body)
well_formed = value is not None
if not well_formed:
value = read_lenient(body)
if value is not None and negative:
value = -value
tokens.append(NumberToken(
text=m.group(0).strip(), body=body, value=value, negative=negative, well_formed=well_formed,
system=digit_system(body), separators="".join(c for c in body if c in THOUSANDS_CHARS + DECIMAL_CHARS),
))
return tokens
def answer_token(text):
"""The last number in text that has a value, or None."""
valued = [t for t in find_numbers(text) if t.value is not None]
return valued[-1] if valued else None
LATIN_LABELS = ("A", "B")
ARABIC_LABELS = (chr(0x0623), chr(0x0628))
_ARABIC_LETTERS = f"{chr(0x0620)}-{chr(0x064A)}{chr(0x064B)}-{chr(0x065F)}{chr(0x066E)}-{chr(0x06D3)}{chr(0x0640)}"
_LABEL_RE = re.compile(
rf"(?<![A-Za-z])(?P<latin>[AB])(?![A-Za-z])|(?<![{_ARABIC_LETTERS}])(?P<arabic>[{''.join(ARABIC_LABELS)}])(?![{_ARABIC_LETTERS}])"
)
_LEADING_LABEL_RE = re.compile(rf"^\W*(?P<label>[AB{''.join(ARABIC_LABELS)}])\s*(?:$|[:.)\]\n])")
def label_index(label):
return (LATIN_LABELS.index(label) if label in LATIN_LABELS else ARABIC_LABELS.index(label))
def parse_choice(text, option_values):
"""Index (0 or 1) of the option chosen in a compare reply, or None.
Accepts the labels A and B or the Arabic letters alef with hamza and beh, in either
prompt language. If the labels do not settle it, accepts a reply that contains
exactly one of the two option values.
"""
text = normalize(text).strip()
found = {label_index(m.group("latin") or m.group("arabic")) for m in _LABEL_RE.finditer(text)}
if len(found) == 1:
return found.pop()
lead = _LEADING_LABEL_RE.match(text)
if lead:
return label_index(lead.group("label"))
values = {t.value for t in find_numbers(text) if t.value is not None}
hits = [i for i, v in enumerate(option_values) if Decimal(v) in values]
return hits[0] if len(hits) == 1 else None

Xet Storage Details

Size:
6.97 kB
·
Xet hash:
39da718b26e05034b85677902c71837caaab52eb77b0a8b307365ead0cc64e59

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.