sr-zero 0.9.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- sr_zero-0.9.0.dist-info/METADATA +148 -0
- sr_zero-0.9.0.dist-info/RECORD +36 -0
- sr_zero-0.9.0.dist-info/WHEEL +5 -0
- sr_zero-0.9.0.dist-info/entry_points.txt +3 -0
- sr_zero-0.9.0.dist-info/licenses/DATA_SOURCES.md +322 -0
- sr_zero-0.9.0.dist-info/licenses/LICENSE +202 -0
- sr_zero-0.9.0.dist-info/licenses/NOTICE +10 -0
- sr_zero-0.9.0.dist-info/top_level.txt +1 -0
- system_zero/__init__.py +8 -0
- system_zero/__main__.py +5 -0
- system_zero/cli.py +175 -0
- system_zero/console.py +162 -0
- system_zero/cues.py +90 -0
- system_zero/decision_index.py +52 -0
- system_zero/evidence.py +42 -0
- system_zero/marks.py +27 -0
- system_zero/model.py +489 -0
- system_zero/modules/__init__.py +5 -0
- system_zero/modules/match.py +141 -0
- system_zero/modules/music.py +85 -0
- system_zero/modules/puzzles.py +489 -0
- system_zero/modules/run.py +668 -0
- system_zero/modules/scenes.py +345 -0
- system_zero/modules/tools.py +400 -0
- system_zero/modules/verse.py +105 -0
- system_zero/request.py +34 -0
- system_zero/rules/__init__.py +9 -0
- system_zero/rules/cues.py +15014 -0
- system_zero/rules/frames.py +150337 -0
- system_zero/rules/modules.py +54 -0
- system_zero/rules/option_sets.py +865 -0
- system_zero/rules/options.py +123346 -0
- system_zero/scopes.py +38 -0
- system_zero/server.py +169 -0
- system_zero/systemone.py +771 -0
- system_zero/text.py +308 -0
system_zero/text.py
ADDED
|
@@ -0,0 +1,308 @@
|
|
|
1
|
+
"""How System Zero reads a request. The learner and the runtime both use this file, so a rule means the same
|
|
2
|
+
thing when it is learned and when it fires."""
|
|
3
|
+
import json
|
|
4
|
+
import re
|
|
5
|
+
|
|
6
|
+
from .marks import MARKS
|
|
7
|
+
|
|
8
|
+
# Matched on text whose underscores are spaces: letters and digits of any script, with their combining marks. Text in
|
|
9
|
+
# ASCII alone has no marks and no spaceless script, so it is read by the plain pattern, word for word the same.
|
|
10
|
+
_WORD = re.compile("[\\w" + MARKS + "]+")
|
|
11
|
+
_ASCII_WORD = re.compile(r"[^\W_]+")
|
|
12
|
+
# Scripts written without spaces between words: Japanese kana, Chinese characters, Thai, Lao, Myanmar, Khmer and the
|
|
13
|
+
# Tai scripts. A run of them is read as pairs of neighbouring characters, each with its combining marks.
|
|
14
|
+
_SPACELESS_CHARS = ("\u0e00-\u0eff\u1000-\u109f\u1780-\u17ff\u1950-\u19ff\u1a20-\u1aaf\u3040-\u30ff\u31f0-\u31ff"
|
|
15
|
+
"\u3400-\u4dbf\u4e00-\u9fff\ua9e0-\ua9ff\uaa60-\uaadf\uf900-\ufaff\uff66-\uff9f")
|
|
16
|
+
_SPACELESS = re.compile(f"[{_SPACELESS_CHARS}]")
|
|
17
|
+
_SPACELESS_RUN = re.compile(f"((?:[{_SPACELESS_CHARS}][{MARKS}]*)+)")
|
|
18
|
+
_CLUSTER = re.compile(f".[{MARKS}]*", re.S)
|
|
19
|
+
_HAN = re.compile(r"[\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff]")
|
|
20
|
+
_DIGITS = re.compile(r"\d+")
|
|
21
|
+
_SENTENCE_END = re.compile(r"(?<=[.?!:;])\s|\n|(?<=[\u3002\uff01\uff1a\uff1b\uff1f])")
|
|
22
|
+
|
|
23
|
+
STATE_WORDS = 400
|
|
24
|
+
INSTRUCTION_WORDS = 120
|
|
25
|
+
TEMPLATE_WORDS = 12
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def flatten(value):
|
|
29
|
+
"""A state, instruction or option description as one string."""
|
|
30
|
+
if value is None:
|
|
31
|
+
return ""
|
|
32
|
+
if isinstance(value, str):
|
|
33
|
+
return value
|
|
34
|
+
return json.dumps(value, ensure_ascii=False, separators=(", ", ": "))
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def values(value):
|
|
38
|
+
"""The text of a state: an object's or a list's values, never its keys."""
|
|
39
|
+
if isinstance(value, dict):
|
|
40
|
+
return "\n".join(values(v) for v in value.values())
|
|
41
|
+
if isinstance(value, list):
|
|
42
|
+
return "\n".join(values(v) for v in value)
|
|
43
|
+
return "" if value is None else str(value)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _pieces(token):
|
|
47
|
+
"""A word as it is read: a run of a script written without spaces becomes the pairs of its neighbouring
|
|
48
|
+
characters (one character alone stays itself), and the rest of the word stays whole."""
|
|
49
|
+
out = []
|
|
50
|
+
for i, part in enumerate(_SPACELESS_RUN.split(token)):
|
|
51
|
+
if not part:
|
|
52
|
+
continue
|
|
53
|
+
if i % 2 == 0:
|
|
54
|
+
out.append(part)
|
|
55
|
+
continue
|
|
56
|
+
chars = _CLUSTER.findall(part) if len(part) > 1 else [part]
|
|
57
|
+
if len(chars) == 1:
|
|
58
|
+
out.append(part)
|
|
59
|
+
else:
|
|
60
|
+
out.extend(chars[j] + chars[j + 1] for j in range(len(chars) - 1))
|
|
61
|
+
return out
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _scan(tokens, limit, han=None):
|
|
65
|
+
"""(words, tokens used) of a token list, up to limit words. `han` (a list) collects the Chinese characters of the
|
|
66
|
+
words read."""
|
|
67
|
+
out = []
|
|
68
|
+
for used, token in enumerate(tokens, 1):
|
|
69
|
+
if not token.isascii() and _SPACELESS.search(token):
|
|
70
|
+
out.extend(_pieces(token))
|
|
71
|
+
if han is not None:
|
|
72
|
+
han.extend(_HAN.findall(token))
|
|
73
|
+
else:
|
|
74
|
+
out.append(token)
|
|
75
|
+
if limit and len(out) >= limit:
|
|
76
|
+
return out[:limit], used
|
|
77
|
+
return out, len(tokens)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _read(text, limit, han=None):
|
|
81
|
+
if text.isascii():
|
|
82
|
+
head = text[: limit * 24] if limit and len(text) > limit * 24 else text
|
|
83
|
+
tokens = _ASCII_WORD.findall(head.lower())
|
|
84
|
+
if head is not text and len(tokens) < limit:
|
|
85
|
+
tokens = _ASCII_WORD.findall(text.lower())
|
|
86
|
+
return tokens[:limit] if limit else tokens
|
|
87
|
+
if limit and len(text) > limit * 24:
|
|
88
|
+
tokens = _WORD.findall(text[: limit * 24].lower().replace("_", " "))
|
|
89
|
+
found = [] if han is not None else None
|
|
90
|
+
out, used = _scan(tokens, limit, found)
|
|
91
|
+
if len(out) >= limit and used < len(tokens):
|
|
92
|
+
if han is not None:
|
|
93
|
+
han.extend(found)
|
|
94
|
+
return out
|
|
95
|
+
return _scan(_WORD.findall(text.lower().replace("_", " ")), limit, han)[0]
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def words(text, limit=None):
|
|
99
|
+
"""Lower-case words in any script, with their combining marks. Runs of scripts written without spaces (Chinese,
|
|
100
|
+
Japanese, Thai, Khmer, ...) become pairs of neighbouring characters."""
|
|
101
|
+
return _read(text, limit)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def written_words(text):
|
|
105
|
+
"""The words of a text as written (case kept), read as words() reads them: what names are split from."""
|
|
106
|
+
if text.isascii():
|
|
107
|
+
return _ASCII_WORD.findall(text)
|
|
108
|
+
out = []
|
|
109
|
+
for token in _WORD.findall(text.replace("_", " ")):
|
|
110
|
+
if not token.isascii() and _SPACELESS.search(token):
|
|
111
|
+
out.extend(_pieces(token))
|
|
112
|
+
else:
|
|
113
|
+
out.append(token)
|
|
114
|
+
return out
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def count(text):
|
|
118
|
+
"""How many words a text holds (no lower-casing, no character pairs): what usage counts."""
|
|
119
|
+
if text.isascii():
|
|
120
|
+
return len(_ASCII_WORD.findall(text))
|
|
121
|
+
return len(_WORD.findall(text.replace("_", " ")))
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def cues(text, prefix, limit):
|
|
125
|
+
"""The words and word pairs a rule can test for, each once, as '<prefix>word' or '<prefix>word word'. Chinese
|
|
126
|
+
characters count one by one as well, so a rule can read a character that is a word by itself."""
|
|
127
|
+
han = [] if not text.isascii() else None
|
|
128
|
+
read = _read(text, limit, han)
|
|
129
|
+
found = dict.fromkeys(prefix + t for t in read)
|
|
130
|
+
for a, b in zip(read, read[1:]):
|
|
131
|
+
found[prefix + a + " " + b] = None
|
|
132
|
+
if han:
|
|
133
|
+
for c in han:
|
|
134
|
+
found[prefix + c] = None
|
|
135
|
+
return found
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def question_parts(instructions):
|
|
139
|
+
"""(the question: the first sentence of the instructions, the rest: what it is about, such as the user's message
|
|
140
|
+
after "Classify the intent of this request:")."""
|
|
141
|
+
body = flatten(instructions).strip()
|
|
142
|
+
parts = _SENTENCE_END.split(body, maxsplit=1)
|
|
143
|
+
return parts[0], (parts[1].strip() if len(parts) == 2 else "")
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def label_cues(state_cues, instructions):
|
|
147
|
+
"""The cues a question with a known option set is read by: words and word pairs of what it is about (the state,
|
|
148
|
+
and the instructions after their first sentence) as 's', and of the question itself as 'q'."""
|
|
149
|
+
question, about = question_parts(instructions)
|
|
150
|
+
found = dict(state_cues)
|
|
151
|
+
if about:
|
|
152
|
+
found.update(cues(about, "s ", INSTRUCTION_WORDS))
|
|
153
|
+
found.update(cues(question, "q ", INSTRUCTION_WORDS))
|
|
154
|
+
return found
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
_STOP = frozenset("""a an the of to in on at by for from with and or is are was were be it this that as its which
|
|
158
|
+
who what how does do did not no""".split())
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def _content(text):
|
|
162
|
+
return {w for w in words(text) if w not in _STOP}
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _cover(probe, rest):
|
|
166
|
+
"""How much of the probe's words the rest contains, in six steps: 0, 1-24, 25-49, 50-74, 75-99, 100 (%)."""
|
|
167
|
+
if not probe:
|
|
168
|
+
return None
|
|
169
|
+
share = len(probe & rest) / len(probe)
|
|
170
|
+
return "0" if share == 0 else "100" if share == 1 else str(25 * min(3, int(share * 4))) + "+"
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def _fields(value, prefix="", depth=0):
|
|
174
|
+
"""(name, text) of the text fields of a JSON state, one level deep."""
|
|
175
|
+
out = []
|
|
176
|
+
if isinstance(value, dict) and depth < 2:
|
|
177
|
+
for key, item in value.items():
|
|
178
|
+
name = prefix + str(key)
|
|
179
|
+
if isinstance(item, str):
|
|
180
|
+
out.append((name, item))
|
|
181
|
+
elif isinstance(item, dict):
|
|
182
|
+
out.extend(_fields(item, name + ".", depth + 1))
|
|
183
|
+
return out
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
_TOKEN = re.compile(r"[^\W\d_][\w'\-]*|\d[\d,.]*\d|\d")
|
|
187
|
+
_POSSESSIVE = re.compile(r"['\u2019]s$")
|
|
188
|
+
_NEGATION = frozenset("not no never none nobody nothing neither nor without cannot n't".split())
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def _grounding(name, probe, rest_words):
|
|
192
|
+
"""How a claim is grounded in its evidence, beyond shared words: how many of its names (capitalised words after
|
|
193
|
+
its first) and numbers the evidence lacks, and whether it is negated."""
|
|
194
|
+
tokens = [_POSSESSIVE.sub("", t) for t in _TOKEN.findall(probe)]
|
|
195
|
+
names = {t.lower() for t in tokens[1:] if t[0].isupper() and t.lower() not in _STOP}
|
|
196
|
+
numbers = {t.replace(",", "") for t in tokens if t[0].isdigit()}
|
|
197
|
+
out = []
|
|
198
|
+
if names:
|
|
199
|
+
missing = sum(1 for n in names if n not in rest_words)
|
|
200
|
+
out.append(f"r {name} names missing {min(missing, 2)}{'+' if missing >= 2 else ''}")
|
|
201
|
+
if numbers:
|
|
202
|
+
missing = sum(1 for n in numbers if n not in rest_words)
|
|
203
|
+
out.append(f"r {name} numbers missing {'1+' if missing else '0'}")
|
|
204
|
+
if any(t.lower() in _NEGATION or t.lower().endswith("n't") for t in tokens):
|
|
205
|
+
out.append(f"r {name} negated")
|
|
206
|
+
return out
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def state_relations(data, state_text):
|
|
210
|
+
"""The relation of a JSON state's parts: its shortest text field (a search query, a claim, a response) against
|
|
211
|
+
the rest of the state. 'r search_query cover 100' means every word of the query is in the rest; 'r claim names
|
|
212
|
+
missing 2+' that two or more of the claim's names are not in it."""
|
|
213
|
+
fields = [(n, t) for n, t in _fields(data) if 2 <= len(t.split()) <= STATE_WORDS]
|
|
214
|
+
if len(fields) >= 1 and isinstance(data, dict):
|
|
215
|
+
name, probe = min(fields, key=lambda f: (len(f[1]), f[0]))
|
|
216
|
+
rest = state_text.replace(probe, " ", 1)
|
|
217
|
+
cover = _cover(_content(probe), _content(rest))
|
|
218
|
+
if cover is not None:
|
|
219
|
+
rest_words = {w.replace(",", "") for w in words(rest)}
|
|
220
|
+
return [f"r {name} cover {cover}"] + _grounding(name, probe, rest_words)
|
|
221
|
+
return []
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def relations(data, state_text, instructions, cache=None):
|
|
225
|
+
"""Features about how the parts of a request relate: the state's (state_relations), and the instructions
|
|
226
|
+
beyond their first sentence (a statement to judge, a candidate) checked against the state the same way.
|
|
227
|
+
`cache` (a dict kept for one request) keeps what depends on the state alone."""
|
|
228
|
+
cache = {} if cache is None else cache
|
|
229
|
+
if "state" not in cache:
|
|
230
|
+
cache["state"] = state_relations(data, state_text)
|
|
231
|
+
out = list(cache["state"])
|
|
232
|
+
body = flatten(instructions)
|
|
233
|
+
parts = _SENTENCE_END.split(body.strip(), maxsplit=1)
|
|
234
|
+
if len(parts) == 2:
|
|
235
|
+
probe = _content(parts[1])
|
|
236
|
+
if len(probe) >= 3:
|
|
237
|
+
if "content" not in cache:
|
|
238
|
+
cache["content"] = _content(state_text)
|
|
239
|
+
cache["words"] = {w.replace(",", "") for w in words(state_text)}
|
|
240
|
+
out.append(f"r question cover {_cover(probe, cache['content'])}")
|
|
241
|
+
out.extend(_grounding("question", parts[1], cache["words"]))
|
|
242
|
+
return out
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def template(instructions):
|
|
246
|
+
"""The frame of a question: the first sentence of its instructions, numbers masked, at most 12 words."""
|
|
247
|
+
text = flatten(instructions).strip()
|
|
248
|
+
first = _SENTENCE_END.split(text, maxsplit=1)[0] if text else ""
|
|
249
|
+
return " ".join(_DIGITS.sub("#", w) for w in words(first, TEMPLATE_WORDS))
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def full_question(instructions):
|
|
253
|
+
"""The whole question as words (at most INSTRUCTION_WORDS, numbers kept): what a sub-frame is keyed by, so the 17
|
|
254
|
+
fixed hypotheses asked of every contract, or each category and sentiment pair asked of every review, get
|
|
255
|
+
decision lists of their own. None when it says no more than the template."""
|
|
256
|
+
whole = " ".join(words(flatten(instructions), INSTRUCTION_WORDS))
|
|
257
|
+
return whole if whole and whole != template(instructions) else None
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def norm(text):
|
|
261
|
+
"""An option description as the runtime compares it: lower case, single spaces."""
|
|
262
|
+
return " ".join(flatten(text).lower().split())
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def options(question):
|
|
266
|
+
"""[(key, description)] of a choice or noul question, in the order given."""
|
|
267
|
+
if question.get("type") == "noul":
|
|
268
|
+
crit = question.get("criteria") or {}
|
|
269
|
+
return [("true", norm(crit.get("true", ""))), ("false", norm(crit.get("false", "")))]
|
|
270
|
+
crit = question.get("criteria") or {}
|
|
271
|
+
if isinstance(crit, list):
|
|
272
|
+
return [(str(i), norm(v)) for i, v in enumerate(crit)]
|
|
273
|
+
return [(str(k), norm(v)) for k, v in crit.items()]
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
_LABEL_TRIM = " _'\"`.:;,!?()[]{}"
|
|
277
|
+
_EXPLAINED = re.compile(r"^([^:]{1,40}):\s+(\S+(?:\s+\S+){2,})$")
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def _name(text, key):
|
|
281
|
+
return " ".join(text.lower().replace("_", " ").split()).strip(_LABEL_TRIM) or key.lower()
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def _label(name):
|
|
285
|
+
"""A name without its explanation: 'out of scope: none of the listed intents' is 'out of scope' (a label of at
|
|
286
|
+
most four words, a colon, then three words or more)."""
|
|
287
|
+
m = _EXPLAINED.match(name) if ":" in name else None
|
|
288
|
+
return m.group(1).strip(_LABEL_TRIM) if m and len(m.group(1).split()) <= 4 else name
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
def names(question):
|
|
292
|
+
"""What each option means, in order: its label, read from its description, or its key when it has none, so that
|
|
293
|
+
renderings of one label set are one set: 'A: yes', 'option_000: yes', 'Yes' and 'yes' are the same answer, as are
|
|
294
|
+
'card_arrival' and 'card arrival', and 'out of scope' and 'out of scope: none of the listed intents'. A label
|
|
295
|
+
keeps its explanation when dropping it would make two options alike; keys when two options share a name."""
|
|
296
|
+
opts = options(question)
|
|
297
|
+
full = [_name(d or k, k) for k, d in opts]
|
|
298
|
+
short = [_label(n) for n in full]
|
|
299
|
+
if len(set(short)) == len(short):
|
|
300
|
+
return short
|
|
301
|
+
return full if len(set(full)) == len(full) else [k for k, _ in opts]
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
def signature(question):
|
|
305
|
+
"""The option set of a question, independent of order and of how its options are keyed: what makes two
|
|
306
|
+
questions the same kind of decision."""
|
|
307
|
+
kind = question.get("type", "choice")
|
|
308
|
+
return kind + "|" + "|".join(sorted(names(question)))
|