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/scopes.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"""Which rules may answer a question. The learner and the runtime both call these, with the frames, option sets
|
|
2
|
+
and templates the learner found often enough in training to learn from."""
|
|
3
|
+
import hashlib
|
|
4
|
+
|
|
5
|
+
from . import text
|
|
6
|
+
|
|
7
|
+
MIN_COUNT = 30
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def label_scopes(question, signatures, frames, subframes=()):
|
|
11
|
+
"""Scopes whose rules answer a question with a known option set, most specific first; [] if the set is unknown.
|
|
12
|
+
A sub-frame is one whole question asked with one option set, a frame one template with one option set."""
|
|
13
|
+
signature = text.signature(question)
|
|
14
|
+
if signature not in signatures:
|
|
15
|
+
return []
|
|
16
|
+
template = text.template(question.get("instructions"))
|
|
17
|
+
frame = template + "\t" + signature
|
|
18
|
+
found = ["F " + frame] if frame in frames else []
|
|
19
|
+
if subframes:
|
|
20
|
+
full = text.full_question(question.get("instructions"))
|
|
21
|
+
if full and subframe_digest(template, full, signature) in subframes:
|
|
22
|
+
found.insert(0, "U " + subframe_key(template, full, signature))
|
|
23
|
+
return found + ["S " + signature]
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def subframe_key(template, full, signature):
|
|
27
|
+
return template + "\t" + full + "\t" + signature
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def subframe_digest(template, full, signature):
|
|
31
|
+
"""A short name for a sub-frame, for counting them: whole questions are many and long."""
|
|
32
|
+
return hashlib.sha1(subframe_key(template, full, signature).encode()).hexdigest()[:16]
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def free_scope(question, templates):
|
|
36
|
+
"""The scope of context cues for a question whose options are not a known set."""
|
|
37
|
+
template = text.template(question.get("instructions"))
|
|
38
|
+
return "T " + template if template in templates else "T *"
|
system_zero/server.py
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
"""A small HTTP server for System Zero, standard library only. It speaks the System One API (system_zero/systemone.py):
|
|
2
|
+
|
|
3
|
+
POST /v1/systemone {"model"?, "state", "questions", "options"?} -> {"model", "answers", "usage"}
|
|
4
|
+
POST /v1/systemone/batch {"model", "requests": {name: request}} -> {"model", "responses", "usage"}
|
|
5
|
+
POST /v1/decisions the native form: each failed question answers with its own error
|
|
6
|
+
GET /v1/models the model, its features and its card
|
|
7
|
+
GET /health {"api_version", "status": "ready", "model"}
|
|
8
|
+
|
|
9
|
+
and, for the Space's page:
|
|
10
|
+
|
|
11
|
+
POST /api/decide a /v1/systemone request -> every answer with the rule behind it and the code around it
|
|
12
|
+
GET /api/stats how many rules, and what they were learned from
|
|
13
|
+
|
|
14
|
+
With api_keys (or SYSTEM_ZERO_API_KEYS, comma-separated) the API takes `Authorization: Bearer KEY` or `Api-Key: KEY`.
|
|
15
|
+
With static=DIR it also serves the files in DIR (the Space's page).
|
|
16
|
+
"""
|
|
17
|
+
import hmac
|
|
18
|
+
import json
|
|
19
|
+
import os
|
|
20
|
+
import time
|
|
21
|
+
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
|
|
22
|
+
|
|
23
|
+
from . import __version__
|
|
24
|
+
from .model import SystemZero
|
|
25
|
+
from .systemone import (API, BODY_LIMIT, PATH_BATCH, PATH_DECISIONS, PATH_EXPLAIN, PATH_SYSTEMONE, Problem)
|
|
26
|
+
|
|
27
|
+
CONTEXT = 3
|
|
28
|
+
POSTS = (PATH_SYSTEMONE, PATH_BATCH, PATH_DECISIONS, PATH_EXPLAIN)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def code_around(model, why):
|
|
32
|
+
"""The lines of the rule file around the rule that fired, for showing it in place."""
|
|
33
|
+
path, line = why.get("file", ""), why.get("line")
|
|
34
|
+
source = {"system_zero/rules/frames.py": model.frame_source, "system_zero/rules/options.py": model.option_source,
|
|
35
|
+
"system_zero/rules/cues.py": model.cue_source}.get(path)
|
|
36
|
+
if source is None and why.get("module"):
|
|
37
|
+
source = model.module_source.get(why["module"])
|
|
38
|
+
if not source or not line:
|
|
39
|
+
return None
|
|
40
|
+
start = max(1, line - CONTEXT)
|
|
41
|
+
return {"start": start, "line": line, "lines": source[start - 1: line + CONTEXT]}
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def make_handler(model, static=None, api_keys=None):
|
|
45
|
+
api = API(model)
|
|
46
|
+
keys = [k for k in (api_keys if api_keys is not None else
|
|
47
|
+
os.environ.get("SYSTEM_ZERO_API_KEYS", "").split(",")) if k.strip()]
|
|
48
|
+
|
|
49
|
+
class Handler(SimpleHTTPRequestHandler):
|
|
50
|
+
server_version = f"SystemZero/{__version__}"
|
|
51
|
+
|
|
52
|
+
def __init__(self, *args, **kwargs):
|
|
53
|
+
super().__init__(*args, directory=static or os.getcwd(), **kwargs)
|
|
54
|
+
|
|
55
|
+
def log_message(self, format, *args): # noqa: A002 - the base class's name
|
|
56
|
+
pass
|
|
57
|
+
|
|
58
|
+
def end_headers(self):
|
|
59
|
+
if self.path.split("?", 1)[0].endswith((".html", ".js", ".css", "/")):
|
|
60
|
+
self.send_header("Cache-Control", "no-cache")
|
|
61
|
+
super().end_headers()
|
|
62
|
+
|
|
63
|
+
def reply(self, status, body, headers=None):
|
|
64
|
+
data = json.dumps(body, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
|
|
65
|
+
self.send_response(status)
|
|
66
|
+
self.send_header("Content-Type", "application/json; charset=utf-8")
|
|
67
|
+
self.send_header("Content-Length", str(len(data)))
|
|
68
|
+
self.send_header("Cache-Control", "no-store")
|
|
69
|
+
for name, value in (headers or {}).items():
|
|
70
|
+
self.send_header(name, value)
|
|
71
|
+
self.end_headers()
|
|
72
|
+
self.wfile.write(data)
|
|
73
|
+
|
|
74
|
+
def admitted(self):
|
|
75
|
+
"""Whether the request carries one of the API keys (always, with none set)."""
|
|
76
|
+
if not keys:
|
|
77
|
+
return True
|
|
78
|
+
value = self.headers.get("Authorization", "")
|
|
79
|
+
given = [value[7:].strip()] if value[:7].lower() == "bearer " else []
|
|
80
|
+
given += [self.headers.get("Api-Key", "")]
|
|
81
|
+
if any(g and any(hmac.compare_digest(g, k) for k in keys) for g in given):
|
|
82
|
+
return True
|
|
83
|
+
self.reply(401, {"detail": "the API key is missing or invalid", "code": "invalid_api_key"},
|
|
84
|
+
{"WWW-Authenticate": 'Bearer realm="system-zero"'})
|
|
85
|
+
return False
|
|
86
|
+
|
|
87
|
+
def do_GET(self): # noqa: N802 - the base class's name
|
|
88
|
+
path = self.path.split("?", 1)[0]
|
|
89
|
+
if path == "/api/stats":
|
|
90
|
+
return self.reply(200, dict(model.stats(), parameters=0, load_seconds=round(model.load_seconds, 2),
|
|
91
|
+
layout=model.layout()))
|
|
92
|
+
if path.startswith("/v1/") and not self.admitted():
|
|
93
|
+
return None
|
|
94
|
+
found = api.get(path)
|
|
95
|
+
if found is None and path == PATH_EXPLAIN:
|
|
96
|
+
found = 405, {"error": {"code": "invalid_request", "message": "method not allowed"}}
|
|
97
|
+
if found is not None:
|
|
98
|
+
return self.reply(*found)
|
|
99
|
+
if static is None:
|
|
100
|
+
return self.reply(404, {"error": {"code": "invalid_request", "message": f"no route {path[:128]}"}})
|
|
101
|
+
return super().do_GET()
|
|
102
|
+
|
|
103
|
+
def do_HEAD(self): # noqa: N802
|
|
104
|
+
if static is None:
|
|
105
|
+
return self.reply(404, {"error": {"code": "invalid_request", "message": "no route"}})
|
|
106
|
+
return super().do_HEAD()
|
|
107
|
+
|
|
108
|
+
def body(self):
|
|
109
|
+
"""The request body as sent, or None after refusing it."""
|
|
110
|
+
if self.headers.get("Transfer-Encoding", "").lower() == "chunked":
|
|
111
|
+
chunks, size = [], 0
|
|
112
|
+
while True:
|
|
113
|
+
length = int(self.rfile.readline().split(b";")[0].strip() or b"0", 16)
|
|
114
|
+
if length == 0:
|
|
115
|
+
self.rfile.readline()
|
|
116
|
+
return b"".join(chunks)
|
|
117
|
+
size += length
|
|
118
|
+
if size > BODY_LIMIT:
|
|
119
|
+
break
|
|
120
|
+
chunks.append(self.rfile.read(length))
|
|
121
|
+
self.rfile.readline()
|
|
122
|
+
else:
|
|
123
|
+
try:
|
|
124
|
+
size = int(self.headers.get("Content-Length", "0"))
|
|
125
|
+
except ValueError:
|
|
126
|
+
size = -1
|
|
127
|
+
if 0 <= size <= BODY_LIMIT:
|
|
128
|
+
return self.rfile.read(size)
|
|
129
|
+
problem = Problem("request_too_large", f"the request body exceeds {BODY_LIMIT} bytes") if size > 0 \
|
|
130
|
+
else Problem("invalid_request", "send the request body with a Content-Length")
|
|
131
|
+
self.close_connection = True
|
|
132
|
+
self.reply(*problem.five())
|
|
133
|
+
return None
|
|
134
|
+
|
|
135
|
+
def do_POST(self): # noqa: N802
|
|
136
|
+
path = self.path.split("?", 1)[0]
|
|
137
|
+
if path not in POSTS:
|
|
138
|
+
return self.reply(404, {"error": {"code": "invalid_request", "message": f"no route {path[:128]}"}})
|
|
139
|
+
if path != PATH_EXPLAIN and not self.admitted():
|
|
140
|
+
return None
|
|
141
|
+
raw = self.body()
|
|
142
|
+
if raw is None:
|
|
143
|
+
return None
|
|
144
|
+
headers = {name.lower(): value for name, value in self.headers.items()}
|
|
145
|
+
started = time.perf_counter()
|
|
146
|
+
status, response, extra = api.post(path, raw, headers)
|
|
147
|
+
if path == PATH_EXPLAIN and status == 200:
|
|
148
|
+
for answer in response["answers"].values():
|
|
149
|
+
why = answer.get("explanation")
|
|
150
|
+
code = code_around(model, why) if why else None
|
|
151
|
+
if code:
|
|
152
|
+
why["context"] = code
|
|
153
|
+
response["microseconds"] = round((time.perf_counter() - started) * 1e6, 1)
|
|
154
|
+
response["parameters"] = 0
|
|
155
|
+
return self.reply(status, response, extra)
|
|
156
|
+
|
|
157
|
+
return Handler
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def serve(host="127.0.0.1", port=8000, static=None, model=None, api_keys=None):
|
|
161
|
+
model = model or SystemZero()
|
|
162
|
+
server = ThreadingHTTPServer((host, port), make_handler(model, static, api_keys))
|
|
163
|
+
print(f"System Zero is listening on http://{host}:{server.server_address[1]} (POST /v1/systemone)", flush=True)
|
|
164
|
+
try:
|
|
165
|
+
server.serve_forever()
|
|
166
|
+
except KeyboardInterrupt:
|
|
167
|
+
pass
|
|
168
|
+
finally:
|
|
169
|
+
server.server_close()
|