basal-engine 3.0.3__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.
Files changed (111) hide show
  1. basal/__init__.py +7 -0
  2. basal/adapter.py +420 -0
  3. basal/adapters.py +8 -0
  4. basal/agree.py +393 -0
  5. basal/attach.py +160 -0
  6. basal/attn512.py +132 -0
  7. basal/auth.py +194 -0
  8. basal/bench.py +367 -0
  9. basal/blockquant.py +227 -0
  10. basal/calibrate.py +2198 -0
  11. basal/chat.py +175 -0
  12. basal/cli.py +70 -0
  13. basal/client.py +8 -0
  14. basal/decision_log.py +189 -0
  15. basal/decision_rules.py +569 -0
  16. basal/decisions.py +158 -0
  17. basal/derive.py +98 -0
  18. basal/disconnect.py +85 -0
  19. basal/engine.py +6023 -0
  20. basal/evidence.py +133 -0
  21. basal/examples/choice.jsonl +8 -0
  22. basal/examples/complex.jsonl +5 -0
  23. basal/examples/labelled_tickets.jsonl +500 -0
  24. basal/examples/local_backend.py +34 -0
  25. basal/examples/noul.jsonl +8 -0
  26. basal/examples/questions.jsonl +20 -0
  27. basal/examples/score.jsonl +8 -0
  28. basal/examples/selfcheck_basal-omni-pico-Q8_0.json +1 -0
  29. basal/examples/selfcheck_basal-omni-pico.json +1 -0
  30. basal/examples/types_demo.py +74 -0
  31. basal/facts.py +497 -0
  32. basal/feedback.py +234 -0
  33. basal/file_identity.py +39 -0
  34. basal/finetune.py +321 -0
  35. basal/fit_decisions.py +944 -0
  36. basal/fla_configs.json +1822 -0
  37. basal/fold.py +206 -0
  38. basal/fonts/OFL-DMSans.txt +93 -0
  39. basal/fonts/OFL-SpaceGrotesk.txt +93 -0
  40. basal/fonts/dm-sans-latin-ext.woff2 +0 -0
  41. basal/fonts/dm-sans-latin.woff2 +0 -0
  42. basal/fonts/space-grotesk-latin-ext.woff2 +0 -0
  43. basal/fonts/space-grotesk-latin.woff2 +0 -0
  44. basal/fp8block.py +100 -0
  45. basal/gdn_graph.py +1792 -0
  46. basal/gemma4.py +726 -0
  47. basal/gemma4_graph.py +931 -0
  48. basal/gguf_export.py +497 -0
  49. basal/identity.py +217 -0
  50. basal/int8block.py +50 -0
  51. basal/interpolate.py +330 -0
  52. basal/jsonl.py +172 -0
  53. basal/lean.py +204 -0
  54. basal/llama_attn.py +252 -0
  55. basal/llama_attn_kernels.py +266 -0
  56. basal/llama_graph.py +587 -0
  57. basal/llama_kernels.py +593 -0
  58. basal/loadtest.py +189 -0
  59. basal/mcp_server.py +432 -0
  60. basal/media.py +138 -0
  61. basal/metrics.py +16 -0
  62. basal/mlx_attn_kernels.py +1057 -0
  63. basal/mlx_forward.py +326 -0
  64. basal/mlx_kernels.py +543 -0
  65. basal/mlx_metal.py +510 -0
  66. basal/navcut.py +283 -0
  67. basal/navigate.py +646 -0
  68. basal/navtree.py +397 -0
  69. basal/nvfp4.py +245 -0
  70. basal/ordercheck.py +165 -0
  71. basal/pdf.py +183 -0
  72. basal/prepared.py +355 -0
  73. basal/presets.py +8 -0
  74. basal/prompt.py +462 -0
  75. basal/rank.py +373 -0
  76. basal/readout.py +121 -0
  77. basal/request.py +327 -0
  78. basal/response_cache.py +105 -0
  79. basal/router.py +1551 -0
  80. basal/router_ui.html +902 -0
  81. basal/router_ui.py +277 -0
  82. basal/run.py +376 -0
  83. basal/selfcheck.py +215 -0
  84. basal/server.py +5279 -0
  85. basal/sets.py +214 -0
  86. basal/signals.py +28 -0
  87. basal/state_disk.py +942 -0
  88. basal/strix.py +505 -0
  89. basal/synth.py +92 -0
  90. basal/tasks.py +848 -0
  91. basal/textio.py +21 -0
  92. basal/think.py +390 -0
  93. basal/tools.py +171 -0
  94. basal/tpu.py +336 -0
  95. basal/tpu_kernels.py +129 -0
  96. basal/trace.py +125 -0
  97. basal/ui.html +861 -0
  98. basal/ui.py +526 -0
  99. basal/varloop.py +813 -0
  100. basal/varloop_graph.py +1377 -0
  101. basal/varloop_kernels.py +907 -0
  102. basal/viz.html +660 -0
  103. basal/viz.py +375 -0
  104. basal/vllm_unified.py +100 -0
  105. basal_engine-3.0.3.dist-info/METADATA +416 -0
  106. basal_engine-3.0.3.dist-info/RECORD +111 -0
  107. basal_engine-3.0.3.dist-info/WHEEL +5 -0
  108. basal_engine-3.0.3.dist-info/entry_points.txt +21 -0
  109. basal_engine-3.0.3.dist-info/licenses/LICENSE +202 -0
  110. basal_engine-3.0.3.dist-info/licenses/NOTICE +34 -0
  111. basal_engine-3.0.3.dist-info/top_level.txt +1 -0
basal/chat.py ADDED
@@ -0,0 +1,175 @@
1
+ """POST /v1/chat/completions (basal-serve --chat-classify on, 3.0): the "pick 1..n or 0" call of an LLM gateway,
2
+ answered by one basal decision instead of a generated reply.
3
+
4
+ A gateway that routes, guards or tags text asks a chat model to "classify the text into one of these: 1. ..., 2. ...;
5
+ answer with the number, or 0 if none fits". This endpoint takes that OpenAI chat request and answers it with the
6
+ argmax of a calibrated `choice` question, in the shape of a chat completion whose message is the number:
7
+
8
+ options the numbered list of the system and user messages: one option per line ("1. text", "1) text",
9
+ "1: text", "1 - text", "[1] text"), numbered 1..n without a gap (2 <= n <= 255, or what the model
10
+ takes); a "0." line in it is the "none" option
11
+ 0 ("none") also an option when the prompt says to answer 0 for none ("or 0 if none fits", "0 = none", "jeśli
12
+ żadna, 0"), or with the request's "basal": {"none": true}; {"none": false} leaves it out
13
+ state the last user message (its text parts)
14
+ question the system messages, else "Which numbered option fits the text?"
15
+ answer "choices"[0].message.content: the chosen number as text ("0" for none); logprobs (with "logprobs":
16
+ true, "top_logprobs" k <= 20) are the calibrated probabilities' logs; "basal" gives the probabilities
17
+ and the options read; usage counts the prompt's tokens and 1 completion token
18
+
19
+ Refused with OpenAI's error object (HTTP 400): "stream", n > 1, tools or functions, a response_format other than text,
20
+ a message that is not system / user (one classification turn, no history), image or audio parts, a prompt without
21
+ such a list, and a user message with several lists when the system messages have none (which one is the options is
22
+ not clear: the text to classify may hold a list of its own). "model", temperature, top_p, max_tokens, seed, stop and user are accepted and do not matter: the
23
+ answer is the decision's argmax."""
24
+ import math
25
+ import re
26
+ import time
27
+ import uuid
28
+
29
+ from .decisions import DecisionsError
30
+
31
+ ITEM = re.compile(r"^\s*(?:\[(\d{1,3})\]|\(?(\d{1,3})\s*[.):\-–]|(\d{1,3})\s*=)\s*(\S.*?)\s*$")
32
+ NONE_WORDS = (r"(?<!\w)(?:none|nothing|neither|others?|not\s+(?:listed|any)|no\s+\w+\s+(?:fits?|applies|matches)"
33
+ r"|żaden|żadn(?:a|e|y|ej|ego|ych|ym|ą)|nic|brak(?:u)?|inn(?:a|e|y|i|ej|ego|ych|ym|ą))(?!\w)")
34
+ # (whole words: "other" is no part of "mother", "inn" of "beginning"; the Polish words by their forms, so "brake" and
35
+ # "Innovation" are not read as "brak" or "inne")
36
+ ZERO_NUM = r"(?<![\w.,])0(?![\w,]|\.\d)" # a 0 on its own (not 0.5, 0,5, 10 or 01)
37
+ ZERO = re.compile(ZERO_NUM + r".{0,48}" + NONE_WORDS + "|" + NONE_WORDS + r".{0,48}" + ZERO_NUM, re.I)
38
+ QUESTION = {"en": "Which numbered option fits the text?", "pl": "Która z ponumerowanych opcji pasuje do tekstu?"}
39
+ NONE = {"en": "None of the options", "pl": "Żadna z opcji"}
40
+ REFUSED = {"stream": "streaming is not supported: send \"stream\": false",
41
+ "tools": "tools are not supported: this endpoint answers a classification prompt with a number",
42
+ "tool_choice": "tools are not supported: this endpoint answers a classification prompt with a number",
43
+ "functions": "functions are not supported: this endpoint answers a classification prompt with a number",
44
+ "function_call": "functions are not supported: this endpoint answers a classification prompt with a number",
45
+ "audio": "audio output is not supported", "prediction": "predicted outputs are not supported"}
46
+
47
+
48
+ def _text(content, where):
49
+ """A message's content -> its text (a string, or the text parts of a list); image / audio parts are refused."""
50
+ if isinstance(content, str):
51
+ return content
52
+ if not isinstance(content, list):
53
+ raise DecisionsError("a message's content must be a string or a list of text parts", where)
54
+ out = []
55
+ for i, part in enumerate(content):
56
+ if not isinstance(part, dict) or part.get("type") != "text" or not isinstance(part.get("text"), str):
57
+ raise DecisionsError("only text parts are supported (no image or audio parts)", f"{where}[{i}]")
58
+ out.append(part["text"])
59
+ return "\n".join(out)
60
+
61
+
62
+ def lists(text):
63
+ """Every numbered list of a text, in order: each a run of lines numbered 1, 2, ... without a gap (blank lines may
64
+ stand between them; a "0" item may come first or last), with at least two numbered from 1 -> [[(line index,
65
+ number, text), ...], ...]."""
66
+ out, run = [], []
67
+ for i, line in enumerate(text.split("\n") + ["<end>"]):
68
+ if not line.strip():
69
+ continue
70
+ m = ITEM.match(line)
71
+ n = int(next(g for g in m.groups()[:3] if g is not None)) if m else None
72
+ if m and run and (n == run[-1][1] + 1 or n == 0 and all(k for _, k, _ in run)):
73
+ run.append((i, n, m.group(4)))
74
+ continue
75
+ if sum(1 for _, k, _ in run if k) >= 2:
76
+ out.append(run)
77
+ run = [(i, n, m.group(4))] if m and n in (0, 1) else []
78
+ return out
79
+
80
+
81
+ def options(text):
82
+ """The numbered list of a prompt -> ({"1": text, ...} in order, the "0" item's text or None, the text without the
83
+ list's lines), or (None, None, text): its first list (lists)."""
84
+ lines, found = text.split("\n"), lists(text)
85
+ best = found[0] if found else None
86
+ if best is None:
87
+ return None, None, text
88
+ taken = {i for i, _, _ in best}
89
+ return ({str(n): t for _, n, t in best if n}, next((t for _, n, t in best if n == 0), None),
90
+ "\n".join(x for i, x in enumerate(lines) if i not in taken))
91
+
92
+
93
+ def to_systemone(body, max_options=255):
94
+ """A chat completion request -> (the System One body of its choice question, its options {number: text})."""
95
+ if not isinstance(body, dict):
96
+ raise DecisionsError("the request body must be a JSON object")
97
+ for k, why in REFUSED.items():
98
+ if body.get(k) not in (None, False, [], {}):
99
+ raise DecisionsError(why, k)
100
+ if body.get("n") not in (None, 1): # (null: the default, as OpenAI reads it)
101
+ raise DecisionsError("n must be 1: the answer is the decision's argmax", "n")
102
+ k = body.get("top_logprobs")
103
+ if k is not None and (isinstance(k, bool) or not isinstance(k, int) or not 0 <= k <= 20):
104
+ raise DecisionsError("top_logprobs must be a whole number from 0 to 20", "top_logprobs")
105
+ fmt = body.get("response_format")
106
+ if fmt is not None and not (isinstance(fmt, dict) and fmt.get("type") == "text"):
107
+ raise DecisionsError('response_format must be {"type": "text"} (the answer is the number as text)',
108
+ "response_format")
109
+ msgs = body.get("messages")
110
+ if not isinstance(msgs, list) or not msgs:
111
+ raise DecisionsError("missing required parameter: 'messages'", "messages")
112
+ system, user = [], []
113
+ for i, m in enumerate(msgs):
114
+ where = f"messages[{i}]"
115
+ if not isinstance(m, dict):
116
+ raise DecisionsError("a message must be an object", where)
117
+ role = m.get("role")
118
+ if role in ("system", "developer"):
119
+ system.append(_text(m.get("content"), f"{where}.content"))
120
+ elif role == "user":
121
+ user.append(_text(m.get("content"), f"{where}.content"))
122
+ else:
123
+ raise DecisionsError("one classification turn: system (or developer) and user messages only, not "
124
+ f"{role!r}", f"{where}.role")
125
+ if not user:
126
+ raise DecisionsError("a user message with the text to classify is required", "messages")
127
+ instr, state = "\n".join(system), user[-1]
128
+ opts, zero, rest = options(instr)
129
+ where_opts = "system"
130
+ if opts is None: # (the user message's list: the only one it holds, which the text to classify might be)
131
+ if len(lists(state)) > 1:
132
+ raise DecisionsError(f"the user message holds {len(lists(state))} numbered lists, and which one is the "
133
+ "options is not clear: put the options in a system message (a numbered list in the "
134
+ "text to classify is then never read as options)", "messages")
135
+ opts, zero, rest = options(state)
136
+ where_opts = "user"
137
+ if opts is None:
138
+ raise DecisionsError("no numbered list of options in the messages (one option per line: \"1. ...\", "
139
+ "\"2. ...\", from 1 without a gap)", "messages")
140
+ ask = body.get("basal") if isinstance(body.get("basal"), dict) else {}
141
+ if "none" in ask and not isinstance(ask["none"], bool):
142
+ raise DecisionsError("basal.none must be true or false", "basal.none")
143
+ from .prompt import lang_of
144
+ lang = "pl" if lang_of(state) == "pl" or lang_of(instr) == "pl" else "en"
145
+ said_zero = bool(ZERO.search(rest if where_opts == "system" else instr + "\n" + rest))
146
+ none = ask.get("none", zero is not None or said_zero)
147
+ crit = dict(opts)
148
+ if none:
149
+ crit["0"] = zero or NONE[lang]
150
+ if len(crit) > max_options:
151
+ raise DecisionsError(f"{len(crit)} options, at most {max_options} for this model", "messages")
152
+ q = {"type": "choice", "instructions": instr or QUESTION[lang], "criteria": crit}
153
+ return {"state": state, "questions": {"pick": q}}, crit
154
+
155
+
156
+ def _lp(p):
157
+ return math.log(p) if p > 0 else -9999.0 # (a log of 0 is no JSON number)
158
+
159
+
160
+ def to_completion(out, crit, body, model):
161
+ """basal-serve's response -> the chat completion: the chosen number as the message, its logprobs if asked."""
162
+ a, keys = out["answers"]["pick"], list(crit)
163
+ probs, choice = a["probabilities"], a["choice"]
164
+ msg = {"index": 0, "message": {"role": "assistant", "content": str(choice)}, "finish_reason": "stop",
165
+ "logprobs": None}
166
+ if body.get("logprobs"):
167
+ k = body.get("top_logprobs") or 0
168
+ top = sorted(keys, key=lambda x: -probs[x])[:k]
169
+ tok = lambda x: {"token": x, "logprob": _lp(probs[x]), "bytes": list(x.encode())} # noqa: E731
170
+ msg["logprobs"] = {"content": [dict(tok(choice), top_logprobs=[tok(x) for x in top])], "refusal": None}
171
+ n = int(out.get("usage", {}).get("input_tokens", 0))
172
+ return {"id": f"chatcmpl-{uuid.uuid4().hex}", "object": "chat.completion", "created": int(time.time()),
173
+ "model": model, "choices": [msg],
174
+ "usage": {"prompt_tokens": n, "completion_tokens": 1, "total_tokens": n + 1},
175
+ "basal": {"probabilities": probs, "confidence": a["confidence"], "options": crit}}
basal/cli.py ADDED
@@ -0,0 +1,70 @@
1
+ """What the command-line tools share: counts that must be positive, the API key of a server started with
2
+ --api-keys (basal-run, basal-loadtest and basal-calibrate --url send it as "Authorization: Bearer <key>"), and the
3
+ start-up warning about basal 2.x installed next to basal-engine."""
4
+ import argparse
5
+ import os
6
+ import sys
7
+ from importlib import metadata
8
+
9
+ API_KEY_ENV = "BASAL_API_KEY"
10
+ OLD_DIST, DIST = "basal", "basal-engine" # the distribution up to 2.x, and from 3.0 (the import name is basal in both)
11
+
12
+
13
+ def mixed_install():
14
+ """The version of basal 2.x's distribution when it is installed next to basal-engine, else None. Both hold basal/:
15
+ installed over 2.x, uv and pip keep both and let them share the files, and uninstalling basal later deletes the
16
+ files basal-engine needs. A few metadata reads, no walk of the files; a distribution named basal that does not
17
+ hold basal/ (PyPI's basal is an unrelated package) does not count."""
18
+ try:
19
+ old = metadata.distribution(OLD_DIST)
20
+ metadata.distribution(DIST)
21
+ except metadata.PackageNotFoundError:
22
+ return None
23
+ top = (old.read_text("top_level.txt") or "").split()
24
+ if "basal" in top or any(str(f).replace("\\", "/").startswith("basal/") for f in old.files or []):
25
+ return old.version
26
+ return None
27
+
28
+
29
+ WARNED_ENV = "BASAL_MIXED_INSTALL_WARNED" # set once warned: the replicas basal-router starts do not say it again
30
+
31
+
32
+ def warn_mixed_install(out=None):
33
+ """basal-serve, basal-router and basal-calibrate: one line at start when basal 2.x is installed next to
34
+ basal-engine (not on import basal: a library user is not told)."""
35
+ if os.environ.get(WARNED_ENV):
36
+ return
37
+ old = mixed_install()
38
+ if old:
39
+ print(f"basal: warning: basal {old} is also installed and shares basal/ with basal-engine: run `pip uninstall "
40
+ "basal basal-engine` (uv: `uv pip uninstall basal basal-engine`) and then reinstall basal-engine",
41
+ file=out or sys.stderr, flush=True)
42
+ os.environ[WARNED_ENV] = "1"
43
+
44
+
45
+ def positive(s):
46
+ """An argparse type: an integer >= 1 (a count of 0 would wait for ever or divide by zero)."""
47
+ v = int(s)
48
+ if v < 1:
49
+ raise argparse.ArgumentTypeError(f"{s}: must be at least 1")
50
+ return v
51
+
52
+
53
+ def add_api_key(ap):
54
+ ap.add_argument("--api-key", dest="api_key", default=os.environ.get(API_KEY_ENV),
55
+ help="the API key of a basal-serve started with --api-keys, sent as \"Authorization: Bearer <key>\" "
56
+ f"(default: ${API_KEY_ENV}, which keeps the key out of the process list)")
57
+ return ap
58
+
59
+
60
+ def headers(api_key):
61
+ return {"Authorization": f"Bearer {api_key}"} if api_key else {}
62
+
63
+
64
+ def refused(url, status, api_key):
65
+ """The message for a request the server refused for its key (HTTP 401 / 403), else None."""
66
+ if status not in (401, 403):
67
+ return None
68
+ why = ("the API key was refused" if api_key else
69
+ f"the server needs an API key: give --api-key KEY or set {API_KEY_ENV}")
70
+ return f"{url}: HTTP {status}: {why}"
basal/client.py ADDED
@@ -0,0 +1,8 @@
1
+ """basal.client is basal_sdk.client, the same module (the Python client is the basal-sdk distribution since 3.0, and
2
+ basal-engine installs it at its own version): code written for basal 2.x keeps importing it from here, and a monkeypatch
3
+ of basal.client patches basal_sdk.client."""
4
+ import sys
5
+
6
+ from basal_sdk import client
7
+
8
+ sys.modules[__name__] = client
basal/decision_log.py ADDED
@@ -0,0 +1,189 @@
1
+ """basal-serve's decision log (--log-decisions) as calibration input (3.0): what a line records so that the decisions
2
+ people review in production can later be joined with their labels into a basal-calibrate input (basal/feedback.py),
3
+ and the audit sample (--review-sample) that keeps those labels unbiased. Torch-free.
4
+
5
+ A line (one per request, as before) also holds:
6
+ - "request_id": the request's X-Request-Id (or the one basal-serve generated and returned in that header), and "id"
7
+ and "group": the request body's own fields, null when it has none;
8
+ - "serving": what the decisions were served with: model, revision, adapter, mode, layout, orders and the sha256 of
9
+ the calibration file (null without one), and for a dual model also its --dual-reading and the sha256 of its prefix
10
+ reading's file (null when the main file serves both readings), so labels are joined only to decisions of one
11
+ configuration;
12
+ - per answer "review_p": the probability that basal-serve sent the decision to a person: 1 when it deferred (abstain;
13
+ an act whose action is the defer action, with or without max_error; a task answer, or one of its claims or fields,
14
+ not automated at one of its max_error targets and automated at none, a decision of a task taking its task answer's;
15
+ an answer with no task certificate, automated null at every target, is not deferred: basal-serve sends it to no
16
+ one, its client decides), the --review-sample rate otherwise (0 without the flag);
17
+ - "review_sample" (--review-sample): {"p": the rate, "in": whether this request was drawn};
18
+ - "request" (--log-requests): the request body as received, so the line can become a labelled request again. It holds
19
+ the state in plain text: in most uses personal data. Off by default. Its images and audio ("media", and the
20
+ "images" alias) are kept as {"type", "sha256", "bytes"} of each file, not their base64: a line would otherwise hold
21
+ every image and recording (up to --max-body-mb), and basal-feedback leaves such a request out;
22
+ - "cache": "hit" on the line written again for a response served from --response-cache-mb (with its own request_id).
23
+
24
+ The audit sample: a request is drawn when a keyed hash (HMAC-SHA256 under a per-server secret) of its id (the body's
25
+ "id", else the request id) and its content (the sha256 of its state, questions, media and language, as sent) is below
26
+ the rate. A retry of the same request is in or out as the first try was; the same id with other content is another
27
+ draw, so an id a client saw left out does not keep its other requests out, and a client that does not know the secret
28
+ cannot choose a request that stays out. What it cannot stop: a client sees the mark, so one that sends a request
29
+ again under another id until its answer comes back unmarked keeps the answer it acts on out of review (the sample stays
30
+ uniform over the requests answered, which the log holds, not over the answers a client used). Its automated answers
31
+ get "review": true; its deferred ones go to a person anyway. A uniform sample of requests, automated and deferred alike, is what the join keeps: labels
32
+ from deferred decisions alone would describe the hard tail only. The secret is random at every start unless
33
+ --review-secret FILE gives it (servers that must draw the same sample, e.g. behind a router).
34
+
35
+ The log file is created 0600, and an existing one is made 0600 (it may hold requests)."""
36
+ import hashlib
37
+ import hmac
38
+ import os
39
+ import secrets
40
+ import stat
41
+ import uuid
42
+
43
+ SECRET_MIN = 16 # bytes of a --review-secret file
44
+
45
+
46
+ def open_log(path):
47
+ """The decision log, appended to, line-buffered; created 0600, an existing file's group and other permissions
48
+ removed (POSIX)."""
49
+ fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_APPEND | getattr(os, "O_CLOEXEC", 0), 0o600)
50
+ try:
51
+ if hasattr(os, "fchmod") and stat.S_IMODE(os.fstat(fd).st_mode) & 0o077:
52
+ os.fchmod(fd, 0o600)
53
+ return os.fdopen(fd, "a", buffering=1, encoding="utf-8")
54
+ except BaseException:
55
+ os.close(fd)
56
+ raise
57
+
58
+
59
+ def secret(path=None):
60
+ """The audit sample's key: the bytes of a --review-secret file (at least SECRET_MIN), else random for this start."""
61
+ if path is None:
62
+ return secrets.token_bytes(32)
63
+ key = open(path, "rb").read().strip()
64
+ if len(key) < SECRET_MIN:
65
+ raise SystemExit(f"--review-secret {path}: at least {SECRET_MIN} bytes, not {len(key)}")
66
+ return key
67
+
68
+
69
+ def drawn(key, ident, rate, content=None):
70
+ """Whether the request of id `ident` and content `content` (the sha256 hex of its state, questions, media and
71
+ language; None: the id alone) is in the audit sample of `rate` under `key`: HMAC-SHA256 of both as a uniform number
72
+ in [0, 1), below the rate."""
73
+ msg = str(ident).encode("utf-8", "surrogatepass")
74
+ if content is not None: # (a fixed-length hex digest last: the message splits one way only)
75
+ msg += b"\0" + str(content).encode("ascii", "replace")
76
+ h = hmac.new(key, msg, hashlib.sha256).digest()
77
+ return int.from_bytes(h[:8], "big") / 2 ** 64 < rate
78
+
79
+
80
+ def defer_action(question):
81
+ """The defer action of an act question as basal-serve reads it (act_spec): its defer_action, else "defer" or
82
+ "human" among its costs; None for another question."""
83
+ if not isinstance(question, dict) or question.get("type") != "act":
84
+ return None
85
+ costs = question.get("costs") if isinstance(question.get("costs"), dict) else {}
86
+ return question.get("defer_action") or next((a for a in ("defer", "human") if a in costs), None)
87
+
88
+
89
+ def not_automated(flags):
90
+ """A task answer's `automated` (a bool, or {max_error: true | false | null}) that sends it to a person: false, or
91
+ false at one target and true at none. Null (no task certificate, at every target or as the value) is no deferral:
92
+ basal-serve sends such an answer to no one, and its client decides."""
93
+ if isinstance(flags, bool):
94
+ return not flags
95
+ if not isinstance(flags, dict):
96
+ return False
97
+ vals = list(flags.values())
98
+ return any(v is False for v in vals) and not any(v is True for v in vals)
99
+
100
+
101
+ def deferred(answer, question=None):
102
+ """Whether basal-serve sent this answer to a person: abstain (max_error); an act whose action is the defer action
103
+ (deferred with max_error, or the cheapest without: question gives the defer action); a task answer, or one of a
104
+ verify answer's claims or an extract answer's fields, not automated at a target and at none automated
105
+ (not_automated; null, without a certificate, is not deferred)."""
106
+ if not isinstance(answer, dict):
107
+ return False
108
+ if answer.get("abstain") is True or answer.get("deferred") is True:
109
+ return True
110
+ d = defer_action(question)
111
+ if d is not None and answer.get("type") == "act" and answer.get("action") == d:
112
+ return True
113
+ if "automated" in answer and not_automated(answer["automated"]):
114
+ return True
115
+ parts = {"verify": answer.get("claims"), "extract": answer.get("fields")}.get(answer.get("type"))
116
+ return isinstance(parts, dict) and any(isinstance(x, dict) and "automated" in x and not_automated(x["automated"])
117
+ for x in parts.values())
118
+
119
+
120
+ def body_field(body, name):
121
+ """The body's own id / group when it is a string or a number (not a bool), else None."""
122
+ v = body.get(name) if isinstance(body, dict) else None
123
+ return v if isinstance(v, (str, int)) and not isinstance(v, bool) else None
124
+
125
+
126
+ def review_of(body, request_id, rate=None, key=None, content=None):
127
+ """A request's review state: its ids, whether it is drawn (rate None: no sample; content: the request's sha256, see
128
+ drawn) -> {"request_id", "id", "group", "rate", "in"}. A request without a request id (served in process, not over
129
+ HTTP) gets a generated one."""
130
+ rid = request_id or f"req_{uuid.uuid4().hex}"
131
+ own = body_field(body, "id")
132
+ return {"request_id": rid, "id": own, "group": body_field(body, "group"), "rate": rate,
133
+ "in": bool(rate) and drawn(key, own if own is not None else rid, rate, content)}
134
+
135
+
136
+ def review_p(answer, review, question=None):
137
+ """The probability that this decision went to a person: 1 deferred, else the sample's rate (0 without one)."""
138
+ return 1.0 if deferred(answer, question) else float(review["rate"] or 0.0)
139
+
140
+
141
+ def calibration_sha256(path):
142
+ if path is None:
143
+ return None
144
+ h = hashlib.sha256()
145
+ with open(path, "rb") as f:
146
+ for chunk in iter(lambda: f.read(1 << 20), b""):
147
+ h.update(chunk)
148
+ return h.hexdigest()
149
+
150
+
151
+ def serving(name, revision=None, adapter=None, mode=None, layout=None, orders=None, calibration=None, dual=None):
152
+ """What a line's decisions were served with (computed once at start). dual: a dual model's (its --dual-reading, the
153
+ file of its prefix reading or None): its requests of several questions take that file's temperatures and
154
+ certificates, so it is part of the configuration; another model's lines keep the fields of before."""
155
+ out = {"model": name, "revision": revision, "adapter": adapter, "mode": mode, "layout": layout,
156
+ "orders": orders, "calibration_sha256": calibration_sha256(calibration)}
157
+ if dual is not None:
158
+ out["dual_reading"], out["prefix_calibration_sha256"] = dual[0], calibration_sha256(dual[1])
159
+ return out
160
+
161
+
162
+ def media_digest(kind, data):
163
+ """A media item's base64 (or data: URL) -> {"type", "sha256", "bytes"} of the file it holds, decoded as the request
164
+ path decodes it (basal/media.py: a data: URL in any case, wrapped lines, the URL-safe alphabet, missing padding)."""
165
+ from .media import _raw
166
+ try:
167
+ raw = _raw(data, 0)
168
+ except ValueError: # (not base64, or over the size limit: refused by the request's checks; its text is hashed)
169
+ raw = data.encode("utf-8", "surrogatepass") if isinstance(data, str) else str(data).encode()
170
+ return {"type": kind, "sha256": hashlib.sha256(raw).hexdigest(), "bytes": len(raw)}
171
+
172
+
173
+ def logged_request(body):
174
+ """The request as --log-requests stores it: the body as received, its media items without their bytes."""
175
+ if not isinstance(body, dict) or (body.get("media") is None and body.get("images") is None):
176
+ return body
177
+ out = dict(body)
178
+ if isinstance(body.get("media"), list):
179
+ out["media"] = [{**{k: v for k, v in m.items() if k != "data"}, **media_digest(m.get("type"), m.get("data"))}
180
+ if isinstance(m, dict) else media_digest(None, m) for m in body["media"]]
181
+ if isinstance(body.get("images"), list):
182
+ out["images"] = [media_digest("image", im.get("base64") if isinstance(im, dict) else im)
183
+ for im in body["images"]]
184
+ return out
185
+
186
+
187
+ def has_media(request):
188
+ """Whether a logged request carried images or audio (which the log keeps as digests: it cannot be read again)."""
189
+ return isinstance(request, dict) and bool(request.get("media") or request.get("images"))