File size: 9,961 Bytes
3a0a69b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
"""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 physics language uses. The mapping from
a word to a role is the lexicon, in ``lexicon/<lang>.json`` and :mod:`lgphysstratum.lexicon`.

Three normalisations happen here, and all three are testable on their own:

* digit scripts: Arabic-Indic, Extended Arabic-Indic, Devanagari and Bengali 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 the comma of a unit
  expression from the comma that ends a clause in a sentence.
"""

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, the Italian way of writing a unit product
    "\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 physics language, square brackets included: the resistor list of a circuit
# problem is the reason they are here, and they must be read as mathematics and not dropped as
# stray punctuation. The semicolon is deliberately absent: inside a natural language sentence it
# separates clauses, and the circuit form is reachable through the direct mode, which reads the
# sentence as written.
MATH_CHARS = set("0123456789+-*/^()[]<>=!|,:.")
CLOSED_CHARS = set("0123456789)]")
OPENING_CHARS = set("0123456789[(")

# The relation and operator symbols the physics 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'unita`` is the article ``l`` and the noun ``unita``, 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 readers of the physics
    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 physics language open
    a mathematics run. An ASCII letter run is returned as a word: :mod:`lgphysstratum.read_a` and
    :mod:`lgphysstratum.read_b` decide between a token of the physics language 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. The units and quantities of the physics language are written with their ASCII
    spelling, which is why folding is safe for them too.
    """
    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()