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
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
202
|
+
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
sr-zero (System Zero)
|
|
2
|
+
|
|
3
|
+
The code of this package is licensed under the Apache License, Version 2.0, in LICENSE.
|
|
4
|
+
|
|
5
|
+
The rule tables (system_zero/rules/) are statistics counted from 995,023 training questions: third-party datasets
|
|
6
|
+
with mixed licences, the output of our own generator programs, machine-written text, and labels generated by models.
|
|
7
|
+
374,074 of those questions (37.6%) come from sources that are non-commercial or research-only, share-alike, of
|
|
8
|
+
unknown licence, or written by a model or a machine. The licence of the rule tables is under review; the package
|
|
9
|
+
metadata names it LicenseRef-System-Zero-Rule-Tables. DATA_SOURCES.md, distributed with this package, lists every
|
|
10
|
+
source with its licence, its flag and the attribution it requires. Check it before commercial use.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
system_zero
|
system_zero/__init__.py
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"""System Zero: a decision model with 0 parameters. Every decision is a rule you can read."""
|
|
2
|
+
__version__ = "0.9.0"
|
|
3
|
+
|
|
4
|
+
from . import systemone # noqa: E402
|
|
5
|
+
from .model import SystemZero, decide # noqa: E402
|
|
6
|
+
from .systemone import Problem, Unsupported # noqa: E402
|
|
7
|
+
|
|
8
|
+
__all__ = ["SystemZero", "Problem", "Unsupported", "decide", "systemone", "__version__"]
|
system_zero/__main__.py
ADDED
system_zero/cli.py
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
"""The command line.
|
|
2
|
+
|
|
3
|
+
system-zero "STATE" -q "QUESTION" -o OPTION OPTION ... one decision, with the rule behind it
|
|
4
|
+
system-zero "STATE" -q "QUESTION" --yes-no a yes/no probability
|
|
5
|
+
system-zero "STATE" -q "QUESTION" --levels LOW ... HIGH a score on ordered levels
|
|
6
|
+
system-zero -j request.json {state, questions} in, the answer out (JSON)
|
|
7
|
+
cat requests.jsonl | system-zero -j - one answer per line
|
|
8
|
+
system-zero --serve 8000 the System One API on a local port
|
|
9
|
+
system-zero in a terminal: decide interactively
|
|
10
|
+
"""
|
|
11
|
+
import argparse
|
|
12
|
+
import json
|
|
13
|
+
import sys
|
|
14
|
+
import time
|
|
15
|
+
|
|
16
|
+
from . import __version__
|
|
17
|
+
from .model import SystemZero
|
|
18
|
+
from .systemone import Problem
|
|
19
|
+
|
|
20
|
+
LOGO = r"""
|
|
21
|
+
_____ __ _____
|
|
22
|
+
/ ___/__ _______/ /____ ____ ___ /__ / ___ _________
|
|
23
|
+
\__ \/ / / / ___/ __/ _ \/ __ `__ \ / / / _ \/ ___/ __ \
|
|
24
|
+
___/ / /_/ (__ ) /_/ __/ / / / / / / /__/ __/ / / /_/ /
|
|
25
|
+
/____/\__, /____/\__/\___/_/ /_/ /_/ /____/\___/_/ \____/
|
|
26
|
+
/____/
|
|
27
|
+
""".strip("\n")
|
|
28
|
+
TAGLINE = "A decision model with 0 parameters. Every decision is a rule you can read."
|
|
29
|
+
BAR = 24
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def build(state, question, options, yes_no, levels=None):
|
|
33
|
+
if yes_no:
|
|
34
|
+
q = {"type": "noul", "instructions": question}
|
|
35
|
+
elif levels:
|
|
36
|
+
q = {"type": "score", "instructions": question, "criteria": list(levels)}
|
|
37
|
+
else:
|
|
38
|
+
q = {"type": "choice", "instructions": question, "criteria": {o: o for o in options}}
|
|
39
|
+
return state, {"decision": q}
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def show(response, seconds, out=None):
|
|
43
|
+
"""The answer as bars, then the rule that decided it."""
|
|
44
|
+
out = out or sys.stdout
|
|
45
|
+
for key, answer in response["answers"].items():
|
|
46
|
+
why = answer.get("explanation", {})
|
|
47
|
+
if answer["type"] == "noul":
|
|
48
|
+
probs = {"yes": answer["noul"], "no": 1 - answer["noul"]}
|
|
49
|
+
pick = "yes" if answer["noul"] >= 0.5 else "no"
|
|
50
|
+
elif answer["type"] == "score":
|
|
51
|
+
probs = {answer["legend"][level]: p for level, p in answer["probabilities"].items()}
|
|
52
|
+
pick = max(probs, key=probs.get)
|
|
53
|
+
print(f"score {answer['score']:.2f} of 0-{len(probs) - 1}", file=out)
|
|
54
|
+
else:
|
|
55
|
+
probs = answer["probabilities"]
|
|
56
|
+
pick = answer["choice"]
|
|
57
|
+
width = min(28, max(len(k) for k in probs))
|
|
58
|
+
for option, p in sorted(probs.items(), key=lambda kv: -kv[1]):
|
|
59
|
+
mark = ">" if option == pick else " "
|
|
60
|
+
print(f"{mark} {option[:width]:<{width}} {p:5.2f} {'#' * round(p * BAR)}", file=out)
|
|
61
|
+
rule = why.get("rule", "")
|
|
62
|
+
record = f" ({why['right']:,} of {why['fired']:,} right in training)" if why.get("fired") else ""
|
|
63
|
+
print(f"\nwhy: {rule}{record}", file=out)
|
|
64
|
+
where = f"{why['file']}:{why['line']}" if why.get("line") else why.get("file", "")
|
|
65
|
+
print(f" {where + ' · ' if where else ''}{seconds * 1e6:,.0f} µs · 0 parameters", file=out)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def one(model, state, questions, as_json, out=None):
|
|
69
|
+
out = out or sys.stdout
|
|
70
|
+
started = time.perf_counter()
|
|
71
|
+
response = model.decide(state, questions, explain=True)
|
|
72
|
+
seconds = time.perf_counter() - started
|
|
73
|
+
if as_json:
|
|
74
|
+
print(json.dumps(response, ensure_ascii=False), file=out)
|
|
75
|
+
else:
|
|
76
|
+
show(response, seconds, out)
|
|
77
|
+
return response
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def from_json(model, source, explain):
|
|
81
|
+
"""A file (or '-' for stdin) holding one request, or one request per line."""
|
|
82
|
+
handle = sys.stdin if source == "-" else open(source, encoding="utf-8")
|
|
83
|
+
text = handle.read()
|
|
84
|
+
if source != "-":
|
|
85
|
+
handle.close()
|
|
86
|
+
try:
|
|
87
|
+
requests = [json.loads(text)]
|
|
88
|
+
except ValueError:
|
|
89
|
+
requests = [json.loads(line) for line in text.splitlines() if line.strip()]
|
|
90
|
+
for request in requests:
|
|
91
|
+
try:
|
|
92
|
+
response = model.decide(request.get("state", ""), request["questions"], explain=explain)
|
|
93
|
+
except Problem as problem:
|
|
94
|
+
response = problem.five()[1]
|
|
95
|
+
except (KeyError, TypeError, AttributeError) as error:
|
|
96
|
+
response = {"detail": f"a request is {{state, questions}}: {error}", "code": "invalid_request"}
|
|
97
|
+
print(json.dumps(response, ensure_ascii=False), flush=True)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def interactive(model):
|
|
101
|
+
try:
|
|
102
|
+
import readline # noqa: F401 - line editing for input()
|
|
103
|
+
except ImportError:
|
|
104
|
+
pass
|
|
105
|
+
print(LOGO + "\n")
|
|
106
|
+
print(TAGLINE)
|
|
107
|
+
print("Give a situation, a question and the options (separated by |), or 'yes/no' for a yes/no question.")
|
|
108
|
+
print("Ctrl+D quits.\n")
|
|
109
|
+
while True:
|
|
110
|
+
try:
|
|
111
|
+
state = input("state: ")
|
|
112
|
+
question = input("question: ")
|
|
113
|
+
options = input("options: ")
|
|
114
|
+
except (EOFError, KeyboardInterrupt):
|
|
115
|
+
print()
|
|
116
|
+
return
|
|
117
|
+
yes_no = options.strip().lower() in ("yes/no", "y/n", "")
|
|
118
|
+
opts = [o.strip() for o in options.split("|") if o.strip()]
|
|
119
|
+
if not yes_no and len(opts) < 2:
|
|
120
|
+
print("Give at least two options, separated by |.\n")
|
|
121
|
+
continue
|
|
122
|
+
print()
|
|
123
|
+
one(model, *build(state, question, opts, yes_no), as_json=False)
|
|
124
|
+
print()
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def main(argv=None):
|
|
128
|
+
parser = argparse.ArgumentParser(
|
|
129
|
+
prog="system-zero", description="System Zero: " + TAGLINE,
|
|
130
|
+
epilog="With no arguments in a terminal, System Zero asks for a decision interactively.")
|
|
131
|
+
parser.add_argument("state", nargs="?", help="the situation to decide about (text)")
|
|
132
|
+
parser.add_argument("-q", "--question", default="Which option is right?", help="the question to answer")
|
|
133
|
+
parser.add_argument("-o", "--options", nargs="+", metavar="OPTION", help="the options to choose from")
|
|
134
|
+
parser.add_argument("--yes-no", action="store_true", help="ask a yes/no question: answer with p(yes)")
|
|
135
|
+
parser.add_argument("--levels", nargs="+", metavar="LEVEL", help="ask for a score on these levels, lowest first")
|
|
136
|
+
parser.add_argument("-j", "--json", metavar="FILE", help="read {state, questions} requests from FILE ('-': stdin)")
|
|
137
|
+
parser.add_argument("-e", "--explain", action="store_true", help="with --json: add the rule behind each answer")
|
|
138
|
+
parser.add_argument("--raw", action="store_true", help="print the answer as JSON instead of bars")
|
|
139
|
+
parser.add_argument("--serve", nargs="?", const=8000, type=int, metavar="PORT",
|
|
140
|
+
help="answer POST /v1/systemone on this port (default 8000)")
|
|
141
|
+
parser.add_argument("--host", default="127.0.0.1", help="with --serve: the address to listen on")
|
|
142
|
+
parser.add_argument("--rules", metavar="DIR", help="load rule files from DIR instead of the packaged ones")
|
|
143
|
+
parser.add_argument("--stats", action="store_true", help="print what the model holds and exit")
|
|
144
|
+
parser.add_argument("--version", action="version", version=f"system-zero {__version__}")
|
|
145
|
+
args = parser.parse_args(argv)
|
|
146
|
+
|
|
147
|
+
if args.serve is not None:
|
|
148
|
+
from .server import serve
|
|
149
|
+
serve(args.host, args.serve, model=SystemZero(args.rules))
|
|
150
|
+
return 0
|
|
151
|
+
model = SystemZero(args.rules)
|
|
152
|
+
if args.stats:
|
|
153
|
+
print(json.dumps(dict(model.stats(), parameters=0), indent=1))
|
|
154
|
+
return 0
|
|
155
|
+
if args.json:
|
|
156
|
+
from_json(model, args.json, args.explain)
|
|
157
|
+
return 0
|
|
158
|
+
if args.state is None:
|
|
159
|
+
if sys.stdin.isatty():
|
|
160
|
+
interactive(model)
|
|
161
|
+
return 0
|
|
162
|
+
parser.error("give a STATE, or --json FILE")
|
|
163
|
+
if not args.yes_no and not args.levels and (not args.options or len(args.options) < 2):
|
|
164
|
+
parser.error("give at least two --options, --levels, or --yes-no")
|
|
165
|
+
try:
|
|
166
|
+
one(model, *build(args.state, args.question, args.options or [], args.yes_no, args.levels), as_json=args.raw)
|
|
167
|
+
except Problem as error:
|
|
168
|
+
print(f"system-zero: {error}", file=sys.stderr)
|
|
169
|
+
return 2
|
|
170
|
+
return 0
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
if __name__ == "__main__":
|
|
174
|
+
sys.exit(main())
|
|
175
|
+
|
system_zero/console.py
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
"""The `system-zero` command: `serve` and `ask` in front of the command line of cli.py, and one-line errors.
|
|
2
|
+
|
|
3
|
+
system-zero STATE -q QUESTION -o OPTION OPTION ... one decision, with the rule behind it (also: ask STATE ...)
|
|
4
|
+
system-zero serve [--host HOST] [--port PORT] the System One API over HTTP
|
|
5
|
+
system-zero --help | --version
|
|
6
|
+
|
|
7
|
+
A busy port, a missing file or input that is not JSON is reported in one line, before the rules load where it can
|
|
8
|
+
be, instead of as a traceback.
|
|
9
|
+
"""
|
|
10
|
+
import argparse
|
|
11
|
+
import contextlib
|
|
12
|
+
import errno
|
|
13
|
+
import io
|
|
14
|
+
import json
|
|
15
|
+
import os
|
|
16
|
+
import socket
|
|
17
|
+
import sys
|
|
18
|
+
|
|
19
|
+
from . import __version__, cli
|
|
20
|
+
from .model import RULE_FILES, SystemZero
|
|
21
|
+
|
|
22
|
+
HELP = """\
|
|
23
|
+
usage: system-zero STATE -q QUESTION (-o OPTION OPTION ... | --yes-no | --levels LEVEL ...)
|
|
24
|
+
system-zero serve [--host HOST] [--port PORT]
|
|
25
|
+
system-zero -j FILE
|
|
26
|
+
system-zero --stats | --version | --help
|
|
27
|
+
|
|
28
|
+
System Zero {version}: a decision model with no learned weights. Its rules are tables learned from data and
|
|
29
|
+
kept as Python literals you can read, plus hand-written modules, and every answer names the rule behind it.
|
|
30
|
+
Pure Python standard library, one CPU core.
|
|
31
|
+
|
|
32
|
+
commands:
|
|
33
|
+
[ask] STATE ... answer one question about STATE and show the rule behind the answer
|
|
34
|
+
serve the System One API over HTTP: POST /v1/systemone, /v1/systemone/batch and /v1/decisions;
|
|
35
|
+
GET /v1/models and /health (system-zero serve --help)
|
|
36
|
+
-j FILE answer {{"state", "questions"}} requests from a JSON or JSON-lines FILE ('-': stdin)
|
|
37
|
+
|
|
38
|
+
examples:
|
|
39
|
+
system-zero "Check out my channel and subscribe!" -q "Is this comment spam?" --yes-no
|
|
40
|
+
system-zero "Oh great, my flight got cancelled again." -q "Is this text intended to be sarcastic?" -o yes no
|
|
41
|
+
system-zero serve --port 8000
|
|
42
|
+
"""
|
|
43
|
+
|
|
44
|
+
SERVE = """\
|
|
45
|
+
Serve the System One API (systemone/0.2 with the vllm-sr/5.0 extensions) over HTTP:
|
|
46
|
+
|
|
47
|
+
POST /v1/systemone {"state", "questions"} -> {"model", "answers", "usage"}
|
|
48
|
+
POST /v1/systemone/batch {"model", "requests": {name: request}} -> {"model", "responses", "usage"}
|
|
49
|
+
POST /v1/decisions the native form: a question that fails carries its own error
|
|
50
|
+
GET /v1/models the model, its features and its card
|
|
51
|
+
GET /health ready once the rules are loaded
|
|
52
|
+
|
|
53
|
+
Question types: choice, noul (yes/no) and score. Set SYSTEM_ZERO_API_KEYS=KEY[,KEY...] to require
|
|
54
|
+
"Authorization: Bearer KEY" on the /v1/ paths.
|
|
55
|
+
"""
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def main(argv=None):
|
|
59
|
+
argv = sys.argv[1:] if argv is None else list(argv)
|
|
60
|
+
try:
|
|
61
|
+
if argv[:1] == ["serve"]:
|
|
62
|
+
return serve(argv[1:])
|
|
63
|
+
if argv[:1] in (["-h"], ["--help"]):
|
|
64
|
+
print(overview())
|
|
65
|
+
return 0
|
|
66
|
+
if argv[:1] == ["ask"]:
|
|
67
|
+
argv = argv[1:]
|
|
68
|
+
check_paths(argv)
|
|
69
|
+
return cli.main(argv)
|
|
70
|
+
except KeyboardInterrupt:
|
|
71
|
+
print(file=sys.stderr)
|
|
72
|
+
return 130
|
|
73
|
+
except BrokenPipeError:
|
|
74
|
+
os.dup2(os.open(os.devnull, os.O_WRONLY), sys.stdout.fileno())
|
|
75
|
+
return 1
|
|
76
|
+
except OSError as error:
|
|
77
|
+
return fail(describe(error), 1)
|
|
78
|
+
except UnicodeDecodeError:
|
|
79
|
+
return fail("the input is not UTF-8 text", 2)
|
|
80
|
+
except json.JSONDecodeError as error:
|
|
81
|
+
return fail(f"the input is not JSON: one {{state, questions}} object, or one per line ({error})", 2)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def serve(argv):
|
|
85
|
+
parser = argparse.ArgumentParser(prog="system-zero serve", description=SERVE,
|
|
86
|
+
formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
87
|
+
parser.add_argument("--host", default="127.0.0.1",
|
|
88
|
+
help="the address to listen on (default %(default)s; 0.0.0.0 listens on every interface)")
|
|
89
|
+
parser.add_argument("--port", type=int, default=8000,
|
|
90
|
+
help="the port to listen on (default %(default)s; 0 picks a free one)")
|
|
91
|
+
parser.add_argument("--rules", metavar="DIR", help="load rule files from DIR instead of the packaged ones")
|
|
92
|
+
args = parser.parse_args(argv)
|
|
93
|
+
if not 0 <= args.port <= 65535:
|
|
94
|
+
parser.error(f"--port {args.port} is not a port number (0 to 65535)")
|
|
95
|
+
if args.rules:
|
|
96
|
+
check_rules(args.rules)
|
|
97
|
+
try:
|
|
98
|
+
probe(args.host, args.port)
|
|
99
|
+
except OSError as error:
|
|
100
|
+
return fail(f"cannot listen on {args.host}:{args.port}: {describe(error)}", 1)
|
|
101
|
+
print(f"System Zero {__version__}: loading the rules ...", file=sys.stderr, flush=True)
|
|
102
|
+
from .server import serve as run
|
|
103
|
+
run(args.host, args.port, model=SystemZero(args.rules))
|
|
104
|
+
return 0
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def overview():
|
|
108
|
+
"""The help: the commands and examples, then every option of a decision (cli.py's own help)."""
|
|
109
|
+
text = io.StringIO()
|
|
110
|
+
with contextlib.redirect_stdout(text), contextlib.suppress(SystemExit):
|
|
111
|
+
cli.main(["--help"])
|
|
112
|
+
options = text.getvalue()
|
|
113
|
+
start = options.find("positional arguments:")
|
|
114
|
+
return HELP.format(version=__version__) + ("\n" + options[start:] if start >= 0 else "")
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def probe(host, port):
|
|
118
|
+
"""Take HOST:PORT for a moment, as the server will, so that a port in use fails now and not after the rules
|
|
119
|
+
have loaded."""
|
|
120
|
+
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
|
|
121
|
+
if os.name != "nt":
|
|
122
|
+
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
|
123
|
+
sock.bind((host, port))
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def check_paths(argv):
|
|
127
|
+
"""Refuse a missing --json file or --rules directory before loading the rules, which takes seconds."""
|
|
128
|
+
for flag, value in zip(argv, argv[1:]):
|
|
129
|
+
if flag in ("-j", "--json") and value != "-" and not os.path.isfile(value):
|
|
130
|
+
raise FileNotFoundError(errno.ENOENT, "no such file", value)
|
|
131
|
+
if flag == "--rules":
|
|
132
|
+
check_rules(value)
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def check_rules(path):
|
|
136
|
+
missing = [name for name in RULE_FILES if not os.path.isfile(os.path.join(path, name))]
|
|
137
|
+
if missing:
|
|
138
|
+
raise FileNotFoundError(errno.ENOENT, f"not a directory of rule files (no {', '.join(missing)})", path)
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def describe(error):
|
|
142
|
+
"""One line for an OSError: the file it is about, or why the server cannot take the address."""
|
|
143
|
+
if isinstance(error, socket.gaierror):
|
|
144
|
+
return f"unknown address ({error.strerror})"
|
|
145
|
+
if error.errno == errno.EADDRINUSE:
|
|
146
|
+
return "the port is in use (is another server running?); choose another port"
|
|
147
|
+
if error.errno == errno.EACCES and not error.filename:
|
|
148
|
+
return "permission denied (ports below 1024 need privileges); choose another port"
|
|
149
|
+
if error.errno == errno.EADDRNOTAVAIL:
|
|
150
|
+
return "this machine has no such address"
|
|
151
|
+
if error.filename:
|
|
152
|
+
return f"{error.filename}: {error.strerror or error}"
|
|
153
|
+
return error.strerror or str(error)
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def fail(message, status):
|
|
157
|
+
print(f"system-zero: {message}", file=sys.stderr)
|
|
158
|
+
return status
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
if __name__ == "__main__":
|
|
162
|
+
sys.exit(main())
|
system_zero/cues.py
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
"""Cues that read the options against their context. They need no option seen in training, so they answer any
|
|
2
|
+
question; the learner measures how often each one is right, and that count is the rule."""
|
|
3
|
+
import re
|
|
4
|
+
|
|
5
|
+
from .text import words
|
|
6
|
+
|
|
7
|
+
STOP = frozenset("""a an the of to in on at by for from with and or but not no nor is are was were be been being am
|
|
8
|
+
it its this that these those as if then than so such there here what which who whom whose when where why how all any
|
|
9
|
+
each both few more most other some own same only very can will just do does did has have had having i you he she we
|
|
10
|
+
they me him her us them my your his our their""".split())
|
|
11
|
+
|
|
12
|
+
ALL_ABOVE = re.compile(r"\ball of (the )?(above|these|them)\b|\bboth\b.*\band\b")
|
|
13
|
+
NONE_ABOVE = re.compile(r"\bnone of (the )?(above|these|them)\b|\bneither\b")
|
|
14
|
+
NUMBER = re.compile(r"^-?[\d,]*\.?\d+%?$")
|
|
15
|
+
|
|
16
|
+
NAMES = ("verbatim_state", "verbatim_question", "overlap_state", "overlap_question", "longest", "shortest",
|
|
17
|
+
"consensus", "all_of_the_above", "none_of_the_above", "number_in_state")
|
|
18
|
+
|
|
19
|
+
WHAT = {
|
|
20
|
+
"verbatim_state": "the only option whose words appear, in order, in the state",
|
|
21
|
+
"verbatim_question": "the only option whose words appear, in order, in the question",
|
|
22
|
+
"overlap_state": "the option sharing the most words with the state",
|
|
23
|
+
"overlap_question": "the option sharing the most words with the question",
|
|
24
|
+
"longest": "the longest option",
|
|
25
|
+
"shortest": "the shortest option",
|
|
26
|
+
"consensus": "the option sharing the most words with the other options",
|
|
27
|
+
"all_of_the_above": "the 'all of the above' option",
|
|
28
|
+
"none_of_the_above": "the 'none of the above' option",
|
|
29
|
+
"number_in_state": "the only number option that appears in the state",
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _content(text):
|
|
34
|
+
return {w for w in words(text) if w not in STOP and (len(w) > 1 or w.isdigit())}
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _best(scores):
|
|
38
|
+
"""Index of the one strictly highest positive score, else -1."""
|
|
39
|
+
top = max(scores)
|
|
40
|
+
if top <= 0 or scores.count(top) != 1:
|
|
41
|
+
return -1
|
|
42
|
+
return scores.index(top)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _only(flags):
|
|
46
|
+
"""Index of the one option that has the property, else -1."""
|
|
47
|
+
return flags.index(True) if flags.count(True) == 1 else -1
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def only_words(texts, per_option=30):
|
|
51
|
+
"""{word: index} for the words that appear in exactly one option: the cue 'only <word>' points at it."""
|
|
52
|
+
sets = [list(dict.fromkeys(w for w in words(t) if w not in STOP and len(w) > 1))[:per_option] for t in texts]
|
|
53
|
+
seen = {}
|
|
54
|
+
for s in sets:
|
|
55
|
+
for w in s:
|
|
56
|
+
seen[w] = seen.get(w, 0) + 1
|
|
57
|
+
return {w: i for i, s in enumerate(sets) for w in s if seen[w] == 1}
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def view(text):
|
|
61
|
+
"""A text as the cues read it: its words joined with spaces at both ends, and its content words."""
|
|
62
|
+
tokens = words(text)
|
|
63
|
+
return " " + " ".join(tokens) + " ", {w for w in tokens if w not in STOP and (len(w) > 1 or w.isdigit())}
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def read(state_text, question_text, texts, state_view=None):
|
|
67
|
+
"""{cue: index of the option it points at, or -1 when it does not point at exactly one}. `state_view` is
|
|
68
|
+
view(state_text), when the caller has it already."""
|
|
69
|
+
if len(texts) < 2:
|
|
70
|
+
return {name: -1 for name in NAMES}
|
|
71
|
+
joined = [" ".join(words(t)) for t in texts]
|
|
72
|
+
state, state_words = state_view or view(state_text)
|
|
73
|
+
question, question_words = view(question_text)
|
|
74
|
+
in_state = [len(j) >= 3 and (" " + j + " ") in state for j in joined]
|
|
75
|
+
in_question = [len(j) >= 3 and (" " + j + " ") in question for j in joined]
|
|
76
|
+
sets = [_content(t) for t in texts]
|
|
77
|
+
lengths = [len(t) for t in texts]
|
|
78
|
+
numbers = [bool(NUMBER.match(t.strip())) for t in texts]
|
|
79
|
+
return {
|
|
80
|
+
"verbatim_state": _only(in_state),
|
|
81
|
+
"verbatim_question": _only(in_question),
|
|
82
|
+
"overlap_state": _best([len(s & state_words) / (len(s) or 1) for s in sets]),
|
|
83
|
+
"overlap_question": _best([len(s & question_words) / (len(s) or 1) for s in sets]),
|
|
84
|
+
"longest": _best(lengths),
|
|
85
|
+
"shortest": _best([-x for x in lengths]) if min(lengths) > 0 else -1,
|
|
86
|
+
"consensus": _best([sum(len(s & o) for j, o in enumerate(sets) if j != i) for i, s in enumerate(sets)]),
|
|
87
|
+
"all_of_the_above": _only([bool(ALL_ABOVE.search(t.lower())) for t in texts]),
|
|
88
|
+
"none_of_the_above": _only([bool(NONE_ABOVE.search(t.lower())) for t in texts]),
|
|
89
|
+
"number_in_state": _only([n and i for n, i in zip(numbers, in_state)]) if any(numbers) else -1,
|
|
90
|
+
}
|