"""Script aware tokenisation and digit normalisation of a natural language sentence. This module knows nothing about the languages: it splits a sentence into runs of *words* and runs of *mathematics*, and it puts every digit in the shape the math language uses. The mapping from a word to a role is the lexicon, in ``lexicon/.json`` and :mod:`lgstratum.lexicon`. Three normalisations happen here, and all three are testable on their own: * digit scripts: Arabic-Indic, Extended Arabic-Indic and Devanagari digits become ASCII digits, and compatibility normalisation turns the full width forms a Chinese keyboard produces into their ASCII counterparts; * separators that differ per language: the Arabic decimal sign, the Arabic and Devanagari commas, the CJK full stop and question mark, and the bidi control characters disappear or take their ASCII counterpart; * context for ``.`` and ``,``: a dot is part of a number only between digits, a comma is part of the mathematics only between two closed operands, which is what separates an Italian sentence comma from the comma of a matrix literal. """ import re import unicodedata from typing import List, Tuple # --------------------------------------------------------------------------- # Digits and separators # --------------------------------------------------------------------------- def _digits(start: int) -> dict: return {chr(start + i): str(i) for i in range(10)} DIGIT_MAP: dict = {} DIGIT_MAP.update(_digits(0x0660)) # Arabic-Indic DIGIT_MAP.update(_digits(0x06F0)) # Extended Arabic-Indic (Persian/Urdu) DIGIT_MAP.update(_digits(0x0966)) # Devanagari DIGIT_MAP.update(_digits(0x09E6)) # Bengali SEPARATOR_MAP: dict = { "\u060c": " ", # Arabic comma "\u061b": " ", # Arabic semicolon "\u061f": " ", # Arabic question mark "\u066b": ".", # Arabic decimal sign "\u066c": "", # Arabic thousands separator "\u066d": " ", # Arabic date separator "\u0964": " ", # Devanagari danda "\u0965": " ", # Devanagari double danda "\u3001": " ", # ideographic comma "\u3002": " ", # ideographic full stop "\uff1f": " ", # full width question mark "\uff01": " ", # full width exclamation mark "\u201e": " ", "\u201f": " ", "\u2018": " ", "\u2019": "'", # the apostrophe of an elision is kept, and the elision is split apart "\u201c": " ", "\u201d": " ", # The Italian copula would otherwise fold to the connective "e" (and), so it is not a word. "\u00e8": " ", "\u2013": "-", "\u2014": "-", "\u2212": "-", # minus sign "\u00d7": "*", # multiplication sign "\u00b7": "*", # middle dot "\u00f7": "/", # division sign "\u2265": ">=", "\u2264": "<=", "\u2260": "!=", } INVISIBLE = ( "\u200b\u200c\u200d\u200e\u200f\u061c\u202a\u202b\u202c\u202d\u202e\u2066\u2067\u2068\u2069\ufeff" ) # The symbols of the math language, square brackets included: a matrix literal is the reason # they are here, and they must be read as mathematics and not dropped as stray punctuation. MATH_CHARS = set("0123456789+-*/^()[]<>=!|,:.") CLOSED_CHARS = set("0123456789)]") OPENING_CHARS = set("0123456789[(") # The relation and operator symbols the math language accepts. Nothing else is mathematics. OPERATORS = ("=>", "<=>", "<=", ">=", "!=", "+", "-", "*", "/", "^", "=", "<", ">", "|") def normalize(text: str) -> str: """Return the sentence in a canonical shape: ASCII digits, ASCII separators, one space.""" text = unicodedata.normalize("NFKC", text) for ch in INVISIBLE: text = text.replace(ch, "") text = text.translate({ord(k): v for k, v in DIGIT_MAP.items()}) text = text.translate({ord(k): v for k, v in SEPARATOR_MAP.items()}) return re.sub(r"\s+", " ", text).strip() def script_of(text: str) -> str: """The dominant non Latin script of a sentence: cjk, arabic, devanagari, latin or none.""" counts = {"cjk": 0, "arabic": 0, "devanagari": 0, "latin": 0} for ch in text: if not ch.isalpha(): continue name = unicodedata.name(ch, "") if name.startswith("CJK") or name.startswith("IDEOGRAPHIC"): counts["cjk"] += 1 elif name.startswith("ARABIC"): counts["arabic"] += 1 elif name.startswith("DEVANAGARI"): counts["devanagari"] += 1 elif name.startswith("LATIN"): counts["latin"] += 1 best = max(counts, key=lambda k: counts[k]) return best if counts[best] else "none" def _is_math_char(ch: str, text: str, index: int) -> bool: if ch in MATH_CHARS: if ch == ".": return _neighbour(text, index, -1).isdigit() and _neighbour(text, index, 1).isdigit() if ch == ",": return _neighbour(text, index, -1) in CLOSED_CHARS and _neighbour(text, index, 1) in OPENING_CHARS return True return False def _neighbour(text: str, index: int, step: int) -> str: j = index + step while 0 <= j < len(text) and text[j] == " ": j += step return text[j] if 0 <= j < len(text) else "" _MARKS = ("Mn", "Mc", "Me") def _word_char(ch: str) -> bool: """A character of a word: a letter of any script, an apostrophe, or a combining mark. The combining marks matter: the vowel signs of Devanagari and the Arabic diacritics are not letters, and dropping them would break a word into pieces that no lexicon entry matches. """ return ch.isalpha() or ch in "_'" or unicodedata.category(ch) in _MARKS def pieces(run: str) -> List[str]: """Split a word run at every apostrophe: an Italian elision is two words to the lexicon. ``l'integrale`` is the article ``l`` and the noun ``integrale``, and only the second of the two is a phrase of the lexicon. The lexicon patterns are written with the elision joined, and compiled through this same function, so data and matching agree. """ return [piece for piece in run.split("'") if piece] def is_cjk(run: str) -> bool: """Whether a run is written in Chinese characters.""" return any(unicodedata.name(ch, "").startswith(("CJK", "IDEOGRAPHIC")) for ch in run) def word_pieces(run: str) -> List[str]: """The atoms a word run offers the lexicon: characters for Chinese, pieces elsewhere. Chinese is written without spaces, so the only reliable unit is the character, and a multi character term of the lexicon is then a sequence of atoms -- which is how the lexicon file writes it too, one space separated token per character group. """ if is_cjk(run): return list(run) return pieces(run) def atomize(text: str) -> List[Tuple[str, str]]: """A normalized sentence as atoms: ``("m", run)`` mathematics, ``("w", word)`` word atoms. Both readers start here. It is one of the two things they share -- the other is the lexicon -- and it is the counterpart of the shared token spec that the two formalizers of the math topology share: sharing the atomiser buys agreement about *what the words are*, while the two readers still disagree, productively, about what the sentence means. """ out: List[Tuple[str, str]] = [] for kind, run in tokens(text): if kind == "m": out.append(("m", run)) else: for piece in word_pieces(run): out.append(("w", piece)) return out def tokens(text: str) -> List[Tuple[str, str]]: """Split a normalized sentence into ``("m", run)`` mathematics and ``("w", run)`` words. Letters of every script open a word run, digits and the symbols of the math language open a mathematics run. An ASCII letter run is returned as a word: :mod:`lgstratum.read_a` and :mod:`lgstratum.read_b` decide between a variable and a function word through the lexicon. """ text = normalize(text) out: List[Tuple[str, str]] = [] index = 0 while index < len(text): ch = text[index] if ch.isspace(): index += 1 continue if _word_char(ch): start = index while index < len(text) and _word_char(text[index]): index += 1 out.append(("w", text[start:index])) continue if _is_math_char(ch, text, index): start = index while index < len(text) and _is_math_char(text[index], text, index): index += 1 run = text[start:index].strip() if run: out.append(("m", run)) continue index += 1 return out def numeric_literals(text: str) -> List[str]: """Every numeric literal of a sentence, in the order it appears, digits normalised.""" found: List[str] = [] for _kind, run in tokens(text): for match in re.finditer(r"\d+(?:\.\d+)?", run): found.append(match.group(0)) return found def fold(word: str) -> str: """Casefold a Latin word and drop its accents, so that one lexicon entry covers both cases. Non Latin scripts are returned unchanged: casefolding and accent folding do not apply to Chinese, Devanagari or Arabic, and the lexicon entries are written in the form the keyboard produces. """ if not any("a" <= ch.lower() <= "z" for ch in word): return word decomposed = unicodedata.normalize("NFD", word) stripped = "".join(ch for ch in decomposed if not unicodedata.combining(ch)) return stripped.lower()