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.
- basal/__init__.py +7 -0
- basal/adapter.py +420 -0
- basal/adapters.py +8 -0
- basal/agree.py +393 -0
- basal/attach.py +160 -0
- basal/attn512.py +132 -0
- basal/auth.py +194 -0
- basal/bench.py +367 -0
- basal/blockquant.py +227 -0
- basal/calibrate.py +2198 -0
- basal/chat.py +175 -0
- basal/cli.py +70 -0
- basal/client.py +8 -0
- basal/decision_log.py +189 -0
- basal/decision_rules.py +569 -0
- basal/decisions.py +158 -0
- basal/derive.py +98 -0
- basal/disconnect.py +85 -0
- basal/engine.py +6023 -0
- basal/evidence.py +133 -0
- basal/examples/choice.jsonl +8 -0
- basal/examples/complex.jsonl +5 -0
- basal/examples/labelled_tickets.jsonl +500 -0
- basal/examples/local_backend.py +34 -0
- basal/examples/noul.jsonl +8 -0
- basal/examples/questions.jsonl +20 -0
- basal/examples/score.jsonl +8 -0
- basal/examples/selfcheck_basal-omni-pico-Q8_0.json +1 -0
- basal/examples/selfcheck_basal-omni-pico.json +1 -0
- basal/examples/types_demo.py +74 -0
- basal/facts.py +497 -0
- basal/feedback.py +234 -0
- basal/file_identity.py +39 -0
- basal/finetune.py +321 -0
- basal/fit_decisions.py +944 -0
- basal/fla_configs.json +1822 -0
- basal/fold.py +206 -0
- basal/fonts/OFL-DMSans.txt +93 -0
- basal/fonts/OFL-SpaceGrotesk.txt +93 -0
- basal/fonts/dm-sans-latin-ext.woff2 +0 -0
- basal/fonts/dm-sans-latin.woff2 +0 -0
- basal/fonts/space-grotesk-latin-ext.woff2 +0 -0
- basal/fonts/space-grotesk-latin.woff2 +0 -0
- basal/fp8block.py +100 -0
- basal/gdn_graph.py +1792 -0
- basal/gemma4.py +726 -0
- basal/gemma4_graph.py +931 -0
- basal/gguf_export.py +497 -0
- basal/identity.py +217 -0
- basal/int8block.py +50 -0
- basal/interpolate.py +330 -0
- basal/jsonl.py +172 -0
- basal/lean.py +204 -0
- basal/llama_attn.py +252 -0
- basal/llama_attn_kernels.py +266 -0
- basal/llama_graph.py +587 -0
- basal/llama_kernels.py +593 -0
- basal/loadtest.py +189 -0
- basal/mcp_server.py +432 -0
- basal/media.py +138 -0
- basal/metrics.py +16 -0
- basal/mlx_attn_kernels.py +1057 -0
- basal/mlx_forward.py +326 -0
- basal/mlx_kernels.py +543 -0
- basal/mlx_metal.py +510 -0
- basal/navcut.py +283 -0
- basal/navigate.py +646 -0
- basal/navtree.py +397 -0
- basal/nvfp4.py +245 -0
- basal/ordercheck.py +165 -0
- basal/pdf.py +183 -0
- basal/prepared.py +355 -0
- basal/presets.py +8 -0
- basal/prompt.py +462 -0
- basal/rank.py +373 -0
- basal/readout.py +121 -0
- basal/request.py +327 -0
- basal/response_cache.py +105 -0
- basal/router.py +1551 -0
- basal/router_ui.html +902 -0
- basal/router_ui.py +277 -0
- basal/run.py +376 -0
- basal/selfcheck.py +215 -0
- basal/server.py +5279 -0
- basal/sets.py +214 -0
- basal/signals.py +28 -0
- basal/state_disk.py +942 -0
- basal/strix.py +505 -0
- basal/synth.py +92 -0
- basal/tasks.py +848 -0
- basal/textio.py +21 -0
- basal/think.py +390 -0
- basal/tools.py +171 -0
- basal/tpu.py +336 -0
- basal/tpu_kernels.py +129 -0
- basal/trace.py +125 -0
- basal/ui.html +861 -0
- basal/ui.py +526 -0
- basal/varloop.py +813 -0
- basal/varloop_graph.py +1377 -0
- basal/varloop_kernels.py +907 -0
- basal/viz.html +660 -0
- basal/viz.py +375 -0
- basal/vllm_unified.py +100 -0
- basal_engine-3.0.3.dist-info/METADATA +416 -0
- basal_engine-3.0.3.dist-info/RECORD +111 -0
- basal_engine-3.0.3.dist-info/WHEEL +5 -0
- basal_engine-3.0.3.dist-info/entry_points.txt +21 -0
- basal_engine-3.0.3.dist-info/licenses/LICENSE +202 -0
- basal_engine-3.0.3.dist-info/licenses/NOTICE +34 -0
- basal_engine-3.0.3.dist-info/top_level.txt +1 -0
basal/tasks.py
ADDED
|
@@ -0,0 +1,848 @@
|
|
|
1
|
+
"""Task types (experimental, 2.1): classify, verify, compress, extract.
|
|
2
|
+
|
|
3
|
+
A task question is expanded into the decision types (choice, noul, multi) over the request's state, so it shares the
|
|
4
|
+
state (SOAM) with the request's other questions and uses their calibration; its answer is assembled from theirs. Text
|
|
5
|
+
fields of `extract` are two decisions: which line of the state holds the value, then which of that line's candidate
|
|
6
|
+
spans is the value (second_round), so a value is always exact source text, with its character offsets.
|
|
7
|
+
|
|
8
|
+
classify {"labels": {key: rubric} | [keys], "multi_label": false, "none": false, "max_error": [0.01, 0.05]}
|
|
9
|
+
verify {"claims": {key: claim} | [claims], "binary": false}
|
|
10
|
+
compress {"instructions": "<query>", "unit": "sentence" | "line" | "paragraph", "keep_ratio": 0.4 | "threshold": 0.5}
|
|
11
|
+
extract {"schema": <JSON schema: object properties, enum / oneOf const, boolean, string, number, integer, arrays of enum,
|
|
12
|
+
arrays of strings / numbers / objects (line items, 3.0)>, "max_error": [0.01, 0.05]}
|
|
13
|
+
|
|
14
|
+
A list field (an array of strings, numbers or objects: the lines of an invoice or an order) is one yes / no per line
|
|
15
|
+
of the state (is this line one item of the list?), then, for each line taken as an item, the decisions of its fields
|
|
16
|
+
over that line (second_round): the span of a text or number field among the line's candidate spans, the value of an
|
|
17
|
+
enum or boolean field. Every item is one line of the document; at most `maxItems` items (default MAX_ITEMS).
|
|
18
|
+
|
|
19
|
+
`automated` (classify, each verify claim, each extract field) needs a threshold certified for the task in the
|
|
20
|
+
calibration file ("task_thresholds"); basal-calibrate fits them on labelled task questions.
|
|
21
|
+
"""
|
|
22
|
+
import json
|
|
23
|
+
import math
|
|
24
|
+
import re
|
|
25
|
+
from collections import Counter
|
|
26
|
+
from decimal import Decimal, InvalidOperation
|
|
27
|
+
|
|
28
|
+
from .prompt import lang_of, reads_request
|
|
29
|
+
|
|
30
|
+
TASKS = ("classify", "verify", "compress", "extract")
|
|
31
|
+
SEP = "::" # expanded question names: <task question>::<part>
|
|
32
|
+
RISKS = (0.01, 0.05)
|
|
33
|
+
MAX_UNITS = 600
|
|
34
|
+
|
|
35
|
+
W = {
|
|
36
|
+
"pl": dict(
|
|
37
|
+
classify="Która kategoria najlepiej opisuje ten tekst?", none="Żadna z powyższych kategorii",
|
|
38
|
+
classify_multi="Które kategorie opisują ten tekst?",
|
|
39
|
+
verify="Twierdzenie: {claim}\nCo źródło mówi o tym twierdzeniu?", supported="Źródło to potwierdza",
|
|
40
|
+
contradicted="Źródło temu przeczy", not_stated="Źródło tego nie mówi",
|
|
41
|
+
verify_binary="Twierdzenie: {claim}\nCzy źródło potwierdza to twierdzenie?",
|
|
42
|
+
compress="Fragment: „{unit}”\nCzy ten fragment zawiera informację potrzebną do odpowiedzi na pytanie: {q}",
|
|
43
|
+
compress_generic="Fragment: „{unit}”\nCzy ten fragment zawiera ważną informację z dokumentu?",
|
|
44
|
+
line="W której linii dokumentu jest wartość pola: {field}?", enum="Jaka jest wartość pola: {field}?",
|
|
45
|
+
span="Linia: „{line}”\nKtóry fragment tej linii to dokładnie wartość pola: {field}?",
|
|
46
|
+
enum_multi="Które wartości ma pole: {field}?", missing="Nie podano w dokumencie", yes="Tak", no="Nie",
|
|
47
|
+
item="Linia: „{line}”\nCzy ta linia to jedna pozycja listy: {field}?",
|
|
48
|
+
item_value="Linia: „{line}”\nJaka jest wartość pola: {field}?",
|
|
49
|
+
),
|
|
50
|
+
"en": dict(
|
|
51
|
+
classify="Which label best describes this text?", none="None of the labels above",
|
|
52
|
+
classify_multi="Which labels describe this text?",
|
|
53
|
+
verify="Claim: {claim}\nWhat does the source say about this claim?", supported="The source supports it",
|
|
54
|
+
contradicted="The source contradicts it", not_stated="The source does not say",
|
|
55
|
+
verify_binary="Claim: {claim}\nDoes the source support this claim?",
|
|
56
|
+
compress="Passage: \"{unit}\"\nDoes this passage hold information needed to answer this question: {q}",
|
|
57
|
+
compress_generic="Passage: \"{unit}\"\nDoes this passage hold important information of the document?",
|
|
58
|
+
line="Which line of the document gives the value of the field: {field}?",
|
|
59
|
+
enum="What is the value of the field: {field}?",
|
|
60
|
+
span="Line: \"{line}\"\nWhich part of this line is exactly the value of the field: {field}?",
|
|
61
|
+
enum_multi="Which values does the field have: {field}?", missing="Not stated in the document", yes="Yes",
|
|
62
|
+
no="No", item="Line: \"{line}\"\nIs this line one item of the list: {field}?",
|
|
63
|
+
item_value="Line: \"{line}\"\nWhat is the value of the field: {field}?"),
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def is_task(q):
|
|
68
|
+
return isinstance(q, dict) and q.get("type") in TASKS
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _risks(q):
|
|
72
|
+
r = q.get("max_error", list(RISKS))
|
|
73
|
+
return [float(x) for x in (r if isinstance(r, list) else [r])]
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _labels(spec, name):
|
|
77
|
+
"""{key: rubric}, [keys] or [{"name": key, "rubric": ...}] (the ScaleDown-style list) -> {key: rubric or None}."""
|
|
78
|
+
if isinstance(spec, list) and spec and all(isinstance(x, dict) and "name" in x for x in spec):
|
|
79
|
+
return {str(x["name"]): x.get("rubric") or x.get("description") for x in spec}
|
|
80
|
+
if isinstance(spec, list) and spec:
|
|
81
|
+
return {str(k): None for k in spec}
|
|
82
|
+
if isinstance(spec, dict) and spec:
|
|
83
|
+
return {str(k): v for k, v in spec.items()}
|
|
84
|
+
raise ValueError(f"question {name!r}: labels must be a non-empty object {{key: rubric}} or a list of keys")
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
# --- compress units -------------------------------------------------------------------------------------------------
|
|
88
|
+
|
|
89
|
+
ABBREV = {"np", "itd", "itp", "tzw", "ul", "nr", "sp", "o.o", "tj", "ok", "godz", "pkt", "art", "ust", "zł", "e.g",
|
|
90
|
+
"i.e", "etc", "mr", "mrs", "dr", "prof", "inc", "ltd", "co", "no", "vs", "st", "jr", "fig", "al"}
|
|
91
|
+
SENT_END = re.compile(r"[.!?…]+[\"”»)\]]*\s+(?=[\"„«(\[]?[A-ZĄĆĘŁŃÓŚŹŻ0-9])")
|
|
92
|
+
WORD_BEFORE = re.compile(r"[.!?…]*(\w[\w.]*)") # matched on the reversed text before a sentence end
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def units(text, unit="sentence"):
|
|
96
|
+
"""The text's units as (start, end) character spans, whitespace trimmed: lines, paragraphs (blank-line separated) or
|
|
97
|
+
sentences (sentence ends, blank lines and line breaks before a capital, digit or bullet; common abbreviations and
|
|
98
|
+
single letters do not end a sentence)."""
|
|
99
|
+
if unit not in ("sentence", "line", "paragraph"):
|
|
100
|
+
raise ValueError('unit must be "sentence", "line" or "paragraph"')
|
|
101
|
+
if unit == "line":
|
|
102
|
+
cuts = [m.end() for m in re.finditer(r"\n", text)]
|
|
103
|
+
elif unit == "paragraph":
|
|
104
|
+
cuts = [m.end() for m in re.finditer(r"\n[ \t]*\n", text)]
|
|
105
|
+
else:
|
|
106
|
+
cuts, prev = [], 0
|
|
107
|
+
for m in SENT_END.finditer(text):
|
|
108
|
+
# The word before the sentence end: the window starts after the previous match (no word spans its
|
|
109
|
+
# whitespace) and is read backwards from the end, so every character is scanned once (O(n) per document).
|
|
110
|
+
word = WORD_BEFORE.match(text[prev:m.start() + 1][::-1])
|
|
111
|
+
prev = m.end()
|
|
112
|
+
w = word.group(1)[::-1].lower() if word else ""
|
|
113
|
+
if m.group(0)[0] == "." and (w in ABBREV or len(w) == 1 and w.isalpha()):
|
|
114
|
+
continue
|
|
115
|
+
cuts.append(m.end())
|
|
116
|
+
cuts += [m.end() for m in re.finditer(r"\n[ \t]*\n|\n(?=[ \t]*[A-ZĄĆĘŁŃÓŚŹŻ0-9•\-*–])", text)]
|
|
117
|
+
out, s = [], 0
|
|
118
|
+
for c in sorted(set(cuts)) + [len(text)]:
|
|
119
|
+
a, b = s, c
|
|
120
|
+
while a < b and text[a].isspace():
|
|
121
|
+
a += 1
|
|
122
|
+
while b > a and text[b - 1].isspace():
|
|
123
|
+
b -= 1
|
|
124
|
+
if b > a:
|
|
125
|
+
out.append((a, b))
|
|
126
|
+
s = c
|
|
127
|
+
return out
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def join_units(text, spans):
|
|
131
|
+
"""Kept units in source order; neighbours in the source keep their separator, gaps become a line break or space."""
|
|
132
|
+
parts, prev = [], None
|
|
133
|
+
for k, (a, b) in spans:
|
|
134
|
+
if prev is not None:
|
|
135
|
+
pk, pb = prev
|
|
136
|
+
parts.append(text[pb:a] if k == pk + 1 else ("\n" if "\n" in text[pb:a] else " "))
|
|
137
|
+
parts.append(text[a:b])
|
|
138
|
+
prev = (k, b)
|
|
139
|
+
return "".join(parts)
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
# --- extract schema -------------------------------------------------------------------------------------------------
|
|
143
|
+
|
|
144
|
+
def _type(s):
|
|
145
|
+
t = s.get("type")
|
|
146
|
+
if isinstance(t, list):
|
|
147
|
+
t = next((x for x in t if x != "null"), None)
|
|
148
|
+
return t
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def _consts(s):
|
|
152
|
+
for key in ("oneOf", "anyOf"):
|
|
153
|
+
alts = s.get(key)
|
|
154
|
+
if alts and all(isinstance(a, dict) and "const" in a for a in alts):
|
|
155
|
+
return [(a["const"], a.get("description") or a.get("title")) for a in alts]
|
|
156
|
+
if "enum" in s:
|
|
157
|
+
return [(v, None) for v in s["enum"] if v is not None]
|
|
158
|
+
return None
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
MISSING = "__missing__" # the option key of "not stated" (enum values never take it: enum_keys)
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def leaves(schema):
|
|
165
|
+
"""A JSON schema -> [(path, kind, spec)]: kind is enum, enum_list, boolean, string, number or integer; path is the
|
|
166
|
+
property names joined by "." (the key of the answer's fields). Two fields with the same path (a property named
|
|
167
|
+
"a.b" next to an object "a" with a property "b") are refused: field_keys() gives each path its property names."""
|
|
168
|
+
out, seen = [], set() # (seen: linear in the fields; a set built per field made 32,000 of them take 25 s)
|
|
169
|
+
for path, keys, kind, spec in _leaves(schema):
|
|
170
|
+
if path in seen:
|
|
171
|
+
raise ValueError(f"extract: two fields have the path {path!r} (a property name with a dot and a nested "
|
|
172
|
+
"object): rename one")
|
|
173
|
+
seen.add(path)
|
|
174
|
+
out.append((path, kind, spec))
|
|
175
|
+
return out
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def field_keys(schema):
|
|
179
|
+
"""{path: the property names from the root} of every field of leaves(schema). A scalar schema is one field at the
|
|
180
|
+
root, under the name "" (its data {"": value}, as when paths were split at their dots)."""
|
|
181
|
+
leaves(schema) # the same checks
|
|
182
|
+
return {path: keys or ("",) for path, keys, _, _ in _leaves(schema)}
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def _leaves(schema, keys=()):
|
|
186
|
+
path = ".".join(keys)
|
|
187
|
+
if not isinstance(schema, dict):
|
|
188
|
+
raise ValueError(f"extract: schema at {path or 'root'!r} must be an object")
|
|
189
|
+
t = _type(schema)
|
|
190
|
+
if t == "object" or "properties" in schema:
|
|
191
|
+
props = schema.get("properties") or {}
|
|
192
|
+
if not props:
|
|
193
|
+
raise ValueError(f"extract: object {path or 'root'!r} has no properties")
|
|
194
|
+
for k, sub in props.items():
|
|
195
|
+
yield from _leaves(sub, keys + (str(k),))
|
|
196
|
+
return
|
|
197
|
+
if _consts(schema):
|
|
198
|
+
enum_keys([v for v, _ in _consts(schema)], path)
|
|
199
|
+
yield path, keys, "enum", schema
|
|
200
|
+
elif t == "boolean":
|
|
201
|
+
yield path, keys, "boolean", schema
|
|
202
|
+
elif t == "array":
|
|
203
|
+
items = schema.get("items") or {}
|
|
204
|
+
if not isinstance(items, dict):
|
|
205
|
+
raise ValueError(f"extract: field {path!r}: an array's items must be one schema (an object)")
|
|
206
|
+
if _consts(items):
|
|
207
|
+
enum_keys([v for v, _ in _consts(items)], path)
|
|
208
|
+
yield path, keys, "enum_list", schema
|
|
209
|
+
else:
|
|
210
|
+
item_fields(schema, path) # (the items' own checks)
|
|
211
|
+
yield path, keys, "list", schema
|
|
212
|
+
elif t in ("string", "number", "integer", None):
|
|
213
|
+
yield path, keys, t or "string", schema
|
|
214
|
+
else:
|
|
215
|
+
raise ValueError(f"extract: field {path!r}: type {t!r} is not supported")
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
MAX_ITEMS = 50 # items of a list field without maxItems (each line taken as an item costs a decision per item field)
|
|
219
|
+
TEXT_KINDS = ("string", "number", "integer")
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def max_items(spec):
|
|
223
|
+
"""The most items of a list field: its schema's maxItems (a whole number >= 1), else MAX_ITEMS."""
|
|
224
|
+
n = spec.get("maxItems")
|
|
225
|
+
return n if isinstance(n, int) and not isinstance(n, bool) and n >= 1 else MAX_ITEMS
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def item_fields(spec, path=""):
|
|
229
|
+
"""The fields of one item of a list field -> [(path in the item, kind, spec)]: an object's fields (enum, boolean,
|
|
230
|
+
string, number, integer; nested objects), or [("", kind, items)] for items that are one value. Arrays inside an
|
|
231
|
+
item are refused."""
|
|
232
|
+
items = spec.get("items") or {}
|
|
233
|
+
if (_type(items) == "object" or "properties" in items) and not items.get("properties"):
|
|
234
|
+
raise ValueError(f"extract: field {path!r}: its items are objects without properties")
|
|
235
|
+
try:
|
|
236
|
+
fields = list(leaves(items))
|
|
237
|
+
except ValueError as e:
|
|
238
|
+
raise ValueError(f"extract: field {path!r}: its items: {str(e).removeprefix('extract: ')}") from None
|
|
239
|
+
for p, kind, _ in fields:
|
|
240
|
+
if kind in ("list", "enum_list"):
|
|
241
|
+
raise ValueError(f"extract: field {path!r}: an array inside its items ({p!r}) is not supported")
|
|
242
|
+
if len(fields) == 1 and fields[0][:2] == ("", "boolean"):
|
|
243
|
+
raise ValueError(f"extract: field {path!r}: an array of booleans is not supported (ask a boolean field per "
|
|
244
|
+
"case, or an array of enum values)")
|
|
245
|
+
return fields
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
MAX_CODES = 254 # option codes left for candidates (one is "not stated")
|
|
249
|
+
TRIM = " \t,;:()[]{}\"'„”«»|*"
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def _shown(t, limit=400):
|
|
253
|
+
t = " ".join(t.split())
|
|
254
|
+
return t if len(t) <= limit else t[:limit] + " …"
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def line_regions(text, cap=None):
|
|
258
|
+
"""The text's non-empty lines as (start, end); more than `cap` lines are grouped into consecutive blocks."""
|
|
259
|
+
cap = cap or MAX_CODES
|
|
260
|
+
lines = units(text, "line")
|
|
261
|
+
if len(lines) <= cap:
|
|
262
|
+
return lines
|
|
263
|
+
k = -(-len(lines) // cap)
|
|
264
|
+
return [(lines[i][0], lines[min(i + k, len(lines)) - 1][1]) for i in range(0, len(lines), k)]
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def _trim(text, a, b):
|
|
268
|
+
while a < b and text[a] in TRIM:
|
|
269
|
+
a += 1
|
|
270
|
+
while b > a and text[b - 1] in TRIM:
|
|
271
|
+
b -= 1
|
|
272
|
+
return a, b
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def span_candidates(text, a, b, cap=None, *, with_status=False):
|
|
276
|
+
"""Candidate values inside text[a:b] as (start, end): the parts between separators (, ; | tab, and after a colon),
|
|
277
|
+
then runs of up to L words (L as large as the cap allows, at most 8), each trimmed of punctuation, deduplicated."""
|
|
278
|
+
cap = cap or MAX_CODES
|
|
279
|
+
out, seen, capped = [], set(), False
|
|
280
|
+
|
|
281
|
+
def add(s, e):
|
|
282
|
+
nonlocal capped
|
|
283
|
+
if capped:
|
|
284
|
+
return
|
|
285
|
+
s, e = _trim(text, s, e)
|
|
286
|
+
if e > s and text[s:e] not in seen and any(ch.isalnum() for ch in text[s:e]):
|
|
287
|
+
if len(out) >= cap:
|
|
288
|
+
capped = True
|
|
289
|
+
return
|
|
290
|
+
seen.add(text[s:e])
|
|
291
|
+
out.append((s, e))
|
|
292
|
+
for m in re.finditer(r"[^,;|\t\n]+", text[a:b]):
|
|
293
|
+
s, e = a + m.start(), a + m.end()
|
|
294
|
+
add(s, e)
|
|
295
|
+
c = text.find(":", s, e)
|
|
296
|
+
if c >= 0:
|
|
297
|
+
add(c + 1, e)
|
|
298
|
+
words = [(a + m.start(), a + m.end()) for m in re.finditer(r"\S+", text[a:b])]
|
|
299
|
+
L = max(1, min(8, cap // max(1, len(words))))
|
|
300
|
+
for i in range(len(words)):
|
|
301
|
+
for j in range(i, min(len(words), i + L)):
|
|
302
|
+
add(words[i][0], words[j][1])
|
|
303
|
+
return (out, capped) if with_status else out
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def second_round(out, body, plans, max_options=255):
|
|
307
|
+
"""Extract's text fields after the line decisions -> the request of span decisions (one choice per field over
|
|
308
|
+
the candidates of its chosen line), and of the decisions of each list field's items (item_questions), or None.
|
|
309
|
+
The candidates and the items are kept in the plans for finish()."""
|
|
310
|
+
state = body.get("state") if isinstance(body.get("state"), str) else ""
|
|
311
|
+
qs = {}
|
|
312
|
+
for name, p in plans.items():
|
|
313
|
+
if p["type"] != "extract":
|
|
314
|
+
continue
|
|
315
|
+
w = W[p["lang"]]
|
|
316
|
+
p["cands"] = {}
|
|
317
|
+
for path, kind, spec in p["fields"]:
|
|
318
|
+
if kind == "list":
|
|
319
|
+
x = p["lists"][path]
|
|
320
|
+
x["chosen"], x["p"], x["dropped"] = list_items(out["answers"].__getitem__, name, p, path)
|
|
321
|
+
qs.update(item_questions(name, p, path, state, w, max_options))
|
|
322
|
+
continue
|
|
323
|
+
if kind not in ("string", "number", "integer"):
|
|
324
|
+
continue
|
|
325
|
+
c = out["answers"][f"{name}{SEP}f{SEP}{path}"]["choice"]
|
|
326
|
+
if c == "__missing__":
|
|
327
|
+
continue
|
|
328
|
+
cands, question = span_question(p, path, spec, state, c, max_options)
|
|
329
|
+
p["cands"][path] = cands
|
|
330
|
+
if question is not None:
|
|
331
|
+
qs[f"{name}{SEP}s{SEP}{path}"] = question
|
|
332
|
+
if not qs:
|
|
333
|
+
return None
|
|
334
|
+
# (the request's think too: a think server reads the span decisions of a request that thinks, never of one that
|
|
335
|
+
# does not, "think": "off"; and its early_exit: a fast-exit server reads them at the request's policy, as round 1)
|
|
336
|
+
return {k: v for k, v in body.items() if k in ("state", "lang", "facts", "think", "early_exit")} | {"questions": qs}
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
def span_question(p, path, spec, state, line, max_options=255):
|
|
340
|
+
"""A text field's line (its line decision's choice "L<i>") -> (the candidate spans of that line, the span decision
|
|
341
|
+
over them; None when there is at most one candidate: nothing to choose)."""
|
|
342
|
+
a, b = p["regions"][int(line[1:])]
|
|
343
|
+
cands, capped = span_candidates(state, a, b, max_options - 1, with_status=True)
|
|
344
|
+
if capped:
|
|
345
|
+
p.setdefault("capped_fields", set()).add(path)
|
|
346
|
+
if not cands:
|
|
347
|
+
return cands, None
|
|
348
|
+
w = W[p["lang"]]
|
|
349
|
+
crit = {f"S{j}": state[s:e] for j, (s, e) in enumerate(cands)}
|
|
350
|
+
crit[MISSING] = w["missing"]
|
|
351
|
+
return cands, {"type": "choice", "criteria": crit, "option_keys": "hide",
|
|
352
|
+
"instructions": p["pre"] + w["span"].format(line=_shown(state[a:b]), field=_field_text(path, spec))}
|
|
353
|
+
|
|
354
|
+
|
|
355
|
+
def _field_text(path, spec):
|
|
356
|
+
name = path.replace("_", " ").replace(".", " / ")
|
|
357
|
+
d = spec.get("description") or spec.get("title")
|
|
358
|
+
return f"{name} ({d})" if d else name
|
|
359
|
+
|
|
360
|
+
|
|
361
|
+
def list_text(path, spec, props):
|
|
362
|
+
"""A list field as its questions name it: its name, with its description and the fields of an item in brackets
|
|
363
|
+
("items (the invoice lines; name, qty, price)")."""
|
|
364
|
+
name = path.replace("_", " ").replace(".", " / ")
|
|
365
|
+
inside = [x for x in (spec.get("description") or spec.get("title"),
|
|
366
|
+
", ".join(p.replace("_", " ").replace(".", " / ") for p, _, _ in props if p)) if x]
|
|
367
|
+
return f"{name} ({'; '.join(inside)})" if inside else name
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
def _value_criteria(kind, spec, path, w):
|
|
371
|
+
"""The options of an enum or boolean field's decision: its values (an enum value with its description), then "not
|
|
372
|
+
stated"."""
|
|
373
|
+
if kind == "boolean":
|
|
374
|
+
return {"true": w["yes"], "false": w["no"], MISSING: w["missing"]}
|
|
375
|
+
vals = _consts(spec)
|
|
376
|
+
crit = {k: f"{v} ({d})" if d else str(v) for k, (v, d) in zip(enum_keys([v for v, _ in vals], path), vals)}
|
|
377
|
+
crit[MISSING] = w["missing"]
|
|
378
|
+
return crit
|
|
379
|
+
|
|
380
|
+
|
|
381
|
+
def list_items(answer, name, p, path):
|
|
382
|
+
"""The lines a list field takes as its items, from the yes / no of each line (answer: the decision answer of an
|
|
383
|
+
expanded question name) -> (their indices in document order, P(item) of every line, items dropped): the lines with
|
|
384
|
+
P >= 0.5, at most maxItems of them (the most probable; the others are dropped)."""
|
|
385
|
+
x = p["lists"][path]
|
|
386
|
+
pr = [answer(f"{name}{SEP}l{SEP}{x['index']}{SEP}{r}")["noul"] for r in range(len(x["lines"]))]
|
|
387
|
+
chosen = [r for r, v in enumerate(pr) if v >= 0.5]
|
|
388
|
+
dropped = max(0, len(chosen) - x["max"])
|
|
389
|
+
if dropped:
|
|
390
|
+
chosen = sorted(sorted(chosen, key=lambda r: -pr[r])[:x["max"]])
|
|
391
|
+
return chosen, pr, dropped
|
|
392
|
+
|
|
393
|
+
|
|
394
|
+
MARKER = re.compile(r"(?:[-•*–·]|\d{1,3}[.)])\s+") # a list marker at the start of an item's line ("- ", "2. ")
|
|
395
|
+
|
|
396
|
+
|
|
397
|
+
PAIRS = {"(": ")", "[": "]", "„": "”", "«": "»", "\"": "\""} # a closer the trim cut, kept when its opener is in
|
|
398
|
+
|
|
399
|
+
|
|
400
|
+
def item_cands(state, a, b, cap):
|
|
401
|
+
"""The candidate spans of an item's line: span_candidates after its list marker, if it has one, each with the
|
|
402
|
+
closing bracket or quote the trim cut when its opener is inside ("Paper cups (pack of 50)", not "... of 50")."""
|
|
403
|
+
m = MARKER.match(state, a, b)
|
|
404
|
+
out, seen = [], set()
|
|
405
|
+
for s, e in span_candidates(state, m.end() if m and m.end() < b else a, b, cap):
|
|
406
|
+
t = state[s:e]
|
|
407
|
+
for o, c in PAIRS.items(): # (a quote is open when the span holds an odd number of it)
|
|
408
|
+
if e < b and state[e] == c and (t.count(c) % 2 == 1 if o == c else t.count(o) > t.count(c)):
|
|
409
|
+
e += 1
|
|
410
|
+
break
|
|
411
|
+
if state[s:e] not in seen:
|
|
412
|
+
seen.add(state[s:e])
|
|
413
|
+
out.append((s, e))
|
|
414
|
+
return out
|
|
415
|
+
|
|
416
|
+
|
|
417
|
+
def item_questions(name, p, path, state, w, max_options):
|
|
418
|
+
"""The second-round decisions of a list field's items (list_items chose them): per item and field of an item, the
|
|
419
|
+
span of a text / number field among the line's candidate spans or "not stated", or the value of an enum / boolean
|
|
420
|
+
field, both asked about that line. A field of an object item is asked with one candidate too (the line being an
|
|
421
|
+
item does not say it holds that field); an item that is one value takes its line's only candidate unasked."""
|
|
422
|
+
x, qs = p["lists"][path], {}
|
|
423
|
+
x["cands"] = {}
|
|
424
|
+
scalar = len(x["props"]) == 1 and x["props"][0][0] == ""
|
|
425
|
+
for j, r in enumerate(x["chosen"]):
|
|
426
|
+
a, b = x["lines"][r]
|
|
427
|
+
line, cands = _shown(state[a:b]), item_cands(state, a, b, x["cap"])
|
|
428
|
+
x["cands"][j] = cands
|
|
429
|
+
for k, (ip, kind, spec) in enumerate(x["props"]):
|
|
430
|
+
key = f"{name}{SEP}i{SEP}{x['index']}{SEP}{j}{SEP}{k}"
|
|
431
|
+
f = _field_text(".".join(s for s in (path, ip) if s), spec)
|
|
432
|
+
if kind in TEXT_KINDS:
|
|
433
|
+
if len(cands) > 1 or cands and not scalar:
|
|
434
|
+
crit = {f"S{c}": state[s:e] for c, (s, e) in enumerate(cands)}
|
|
435
|
+
crit[MISSING] = w["missing"]
|
|
436
|
+
qs[key] = {"type": "choice", "criteria": crit, "option_keys": "hide",
|
|
437
|
+
"instructions": p["pre"] + w["span"].format(line=line, field=f)}
|
|
438
|
+
else:
|
|
439
|
+
qs[key] = {"type": "choice", "criteria": _value_criteria(kind, spec, ip or path, w),
|
|
440
|
+
"option_keys": "hide", "instructions": p["pre"] + w["item_value"].format(line=line, field=f)}
|
|
441
|
+
return qs
|
|
442
|
+
|
|
443
|
+
|
|
444
|
+
def enum_keys(values, path=""):
|
|
445
|
+
"""The option keys of an enum's values: the value as text (as before), or its JSON form where two values would get
|
|
446
|
+
the same text (1 and "1") or a value would take the key of "not stated" -> [key per value]."""
|
|
447
|
+
text = [str(v) for v in values]
|
|
448
|
+
n = Counter(text) # (counted once: text.count per value made 32,000 values take 19 s)
|
|
449
|
+
keys = [t if n[t] == 1 and t != MISSING else json.dumps(v, ensure_ascii=False) for t, v in zip(text, values)]
|
|
450
|
+
if len(set(keys)) < len(keys):
|
|
451
|
+
raise ValueError(f"extract: field {path!r}: enum values repeat ({values[:10]})")
|
|
452
|
+
return keys
|
|
453
|
+
|
|
454
|
+
|
|
455
|
+
def enum_values(values):
|
|
456
|
+
"""{option key: value} of an enum's values (enum_keys)."""
|
|
457
|
+
return dict(zip(enum_keys(values), values))
|
|
458
|
+
|
|
459
|
+
|
|
460
|
+
def _set_path(obj, path, value):
|
|
461
|
+
"""Puts value at path: a tuple of property names (field_keys), or a dotted path."""
|
|
462
|
+
*head, last = path.split(".") if isinstance(path, str) else path
|
|
463
|
+
for k in head:
|
|
464
|
+
obj = obj.setdefault(k, {})
|
|
465
|
+
obj[last] = value
|
|
466
|
+
|
|
467
|
+
|
|
468
|
+
# digits with their separators: a space only before a digit, "." and "," only between digits ("1, 2" is two numbers)
|
|
469
|
+
NUM = re.compile(r"[-+]?(?:[.,](?=\d))?\d(?:\d|[.,'’ \u00a0\u202f](?=\d))*")
|
|
470
|
+
GROUPED_INTEGER = re.compile(r"\d{1,3}([.,'’ ])\d{3}(?:\1\d{3})*")
|
|
471
|
+
|
|
472
|
+
|
|
473
|
+
def parse_number(text, integer=False, lang=None):
|
|
474
|
+
"""One numeric value in a source span, allowing units and validated thousands groups."""
|
|
475
|
+
text = (text or "").replace("\u2212", "-")
|
|
476
|
+
matches = NUM.finditer(text)
|
|
477
|
+
match = next(matches, None)
|
|
478
|
+
if match is None or next(matches, None) is not None:
|
|
479
|
+
return None
|
|
480
|
+
if match.start() > 0 and (text[match.start() - 1].isalnum() or text[match.start() - 1] == "_"):
|
|
481
|
+
return None
|
|
482
|
+
raw = match.group().replace("\u00a0", " ").replace("\u202f", " ")
|
|
483
|
+
sign = raw[:1] if raw.startswith(("+", "-")) else ""
|
|
484
|
+
raw = raw.lstrip("+-")
|
|
485
|
+
point, comma = raw.rfind("."), raw.rfind(",")
|
|
486
|
+
sep = "." if point > comma else ","
|
|
487
|
+
split = max(point, comma)
|
|
488
|
+
decimal = False
|
|
489
|
+
if split >= 0 and raw.count(sep) == 1:
|
|
490
|
+
left, right = raw[:split], raw[split + 1:]
|
|
491
|
+
decimal = (min(point, comma) >= 0 or not left or left.strip("0") == ""
|
|
492
|
+
or len(right) != 3 or (sep == "." and lang != "pl") or (sep == "," and lang == "pl"))
|
|
493
|
+
whole, fraction = (raw[:split] or "0", raw[split + 1:]) if decimal else (raw, "")
|
|
494
|
+
if not whole.isdecimal():
|
|
495
|
+
if not GROUPED_INTEGER.fullmatch(whole):
|
|
496
|
+
return None
|
|
497
|
+
whole = re.sub(r"[^\d]", "", whole)
|
|
498
|
+
if decimal and not fraction.isdecimal():
|
|
499
|
+
return None
|
|
500
|
+
s = sign + whole + ("." + fraction if decimal else "")
|
|
501
|
+
try:
|
|
502
|
+
v = int(s) if "." not in s else Decimal(s) # an int is exact: 9007199254740993 stays itself (not ...992)
|
|
503
|
+
f = float(v)
|
|
504
|
+
except (ValueError, InvalidOperation, OverflowError): # no number, more digits than int() takes, beyond a float
|
|
505
|
+
return None
|
|
506
|
+
if not math.isfinite(f): # 309 digits or more are beyond a float: no value, like text that is no number
|
|
507
|
+
return None
|
|
508
|
+
if isinstance(v, int):
|
|
509
|
+
return v
|
|
510
|
+
if integer:
|
|
511
|
+
return int(v) if v == v.to_integral_value() else None
|
|
512
|
+
return f
|
|
513
|
+
|
|
514
|
+
|
|
515
|
+
# --- expansion ------------------------------------------------------------------------------------------------------
|
|
516
|
+
|
|
517
|
+
@reads_request
|
|
518
|
+
def expand(body, max_options=255):
|
|
519
|
+
"""A request with task questions -> (the request with only decision questions, plans to assemble the answers)."""
|
|
520
|
+
state = body.get("state")
|
|
521
|
+
text = state if isinstance(state, str) else ""
|
|
522
|
+
questions, plans = {}, {}
|
|
523
|
+
text_pl = not body.get("lang") and lang_of(text) == "pl" # once per request, not once per task question
|
|
524
|
+
for name, q in body["questions"].items():
|
|
525
|
+
if SEP in name: # the expanded names are <task question>::<part>: another "::" name could be one of them
|
|
526
|
+
raise ValueError(f"question {name!r}: in a request with task questions, a question's name may not "
|
|
527
|
+
f"contain {SEP!r}")
|
|
528
|
+
if not is_task(q):
|
|
529
|
+
questions[name] = q
|
|
530
|
+
continue
|
|
531
|
+
t = q["type"]
|
|
532
|
+
lang = body.get("lang") or ("pl" if text_pl else lang_of(str(q.get("instructions") or "")))
|
|
533
|
+
w = W[lang]
|
|
534
|
+
sub = {}
|
|
535
|
+
if t == "classify":
|
|
536
|
+
labels = _labels(q.get("labels") or q.get("criteria"), name)
|
|
537
|
+
multi = bool(q.get("multi_label"))
|
|
538
|
+
if q.get("none") and not multi:
|
|
539
|
+
labels["none"] = w["none"]
|
|
540
|
+
spec = {"type": "multi" if multi else "choice", "criteria": labels,
|
|
541
|
+
"instructions": q.get("instructions") or w["classify_multi" if multi else "classify"],
|
|
542
|
+
"option_keys": q.get("option_keys", "show")}
|
|
543
|
+
if multi:
|
|
544
|
+
spec.update({k: q[k] for k in ("threshold", "min", "max", "objective") if k in q})
|
|
545
|
+
sub["labels"] = spec
|
|
546
|
+
plans[name] = dict(type=t, multi=multi, risks=_risks(q))
|
|
547
|
+
elif t == "verify":
|
|
548
|
+
claims = q.get("claims")
|
|
549
|
+
claims = {str(i): c for i, c in enumerate(claims)} if isinstance(claims, list) else claims
|
|
550
|
+
if not isinstance(claims, dict) or not claims:
|
|
551
|
+
raise ValueError(f"question {name!r}: claims must be a non-empty object or list")
|
|
552
|
+
binary = bool(q.get("binary"))
|
|
553
|
+
pre = (str(q["instructions"]) + "\n") if q.get("instructions") else ""
|
|
554
|
+
for k, c in claims.items():
|
|
555
|
+
c = c if isinstance(c, str) else json.dumps(c, ensure_ascii=False)
|
|
556
|
+
if binary:
|
|
557
|
+
sub[f"c{SEP}{k}"] = {"type": "noul", "instructions": pre + w["verify_binary"].format(claim=c)}
|
|
558
|
+
else:
|
|
559
|
+
sub[f"c{SEP}{k}"] = {"type": "choice", "instructions": pre + w["verify"].format(claim=c),
|
|
560
|
+
"criteria": {"supported": w["supported"], "contradicted": w["contradicted"],
|
|
561
|
+
"not_stated": w["not_stated"]}, "option_keys": "hide"}
|
|
562
|
+
plans[name] = dict(type=t, keys=list(claims), binary=binary, risks=_risks(q))
|
|
563
|
+
elif t == "compress":
|
|
564
|
+
if not text:
|
|
565
|
+
raise ValueError(f"question {name!r}: compress needs a text state")
|
|
566
|
+
unit = q.get("unit", "sentence")
|
|
567
|
+
spans = units(text, unit)
|
|
568
|
+
if not spans:
|
|
569
|
+
raise ValueError(f"question {name!r}: the state has no text to compress")
|
|
570
|
+
if len(spans) > MAX_UNITS:
|
|
571
|
+
raise ValueError(f"question {name!r}: {len(spans)} {unit}s (at most {MAX_UNITS}); use a larger unit "
|
|
572
|
+
"or split the document")
|
|
573
|
+
query = str(q.get("instructions") or "").strip()
|
|
574
|
+
for i, (a, b) in enumerate(spans):
|
|
575
|
+
u = text[a:b]
|
|
576
|
+
sub[f"u{SEP}{i}"] = {"type": "noul", "instructions": w["compress"].format(q=query, unit=u) if query
|
|
577
|
+
else w["compress_generic"].format(unit=u)}
|
|
578
|
+
keep_ratio, thr = q.get("keep_ratio"), float(q.get("threshold", 0.5))
|
|
579
|
+
if keep_ratio is not None and not 0 < float(keep_ratio) <= 1:
|
|
580
|
+
raise ValueError(f"question {name!r}: keep_ratio must be in (0, 1]")
|
|
581
|
+
raw = q.get("min_keep", 1) # (read with int() as in 2.8: 2.0 and "2" are 2, 2.5 is 2)
|
|
582
|
+
try:
|
|
583
|
+
min_keep = None if isinstance(raw, bool) else int(raw)
|
|
584
|
+
except (TypeError, ValueError, OverflowError):
|
|
585
|
+
min_keep = None
|
|
586
|
+
if min_keep is None:
|
|
587
|
+
raise ValueError(f"question {name!r}: min_keep must be a number of units, not {json.dumps(raw)}")
|
|
588
|
+
if min_keep < 0: # (a negative one kept every unit but the last few: order[:-1])
|
|
589
|
+
raise ValueError(f"question {name!r}: min_keep must be at least 0, not {json.dumps(raw)}")
|
|
590
|
+
plans[name] = dict(type=t, spans=spans, unit=unit, keep_ratio=keep_ratio, threshold=thr,
|
|
591
|
+
min_keep=min_keep)
|
|
592
|
+
elif t == "extract":
|
|
593
|
+
fields, regions, lists = list(leaves(q.get("schema") or {})), None, {}
|
|
594
|
+
pre = (str(q["instructions"]) + "\n") if q.get("instructions") else ""
|
|
595
|
+
for fi, (path, kind, spec) in enumerate(fields):
|
|
596
|
+
f = _field_text(path, spec)
|
|
597
|
+
if kind == "list": # one yes / no per line: is it an item? (its fields: second_round, per item)
|
|
598
|
+
if not text.strip(): # (blank: no line to ask, "\n" as an empty page after OCR)
|
|
599
|
+
raise ValueError(f"question {name!r}: list field {path!r} is taken from the state's text, "
|
|
600
|
+
"which is empty")
|
|
601
|
+
lines = units(text, "line")
|
|
602
|
+
if len(lines) > MAX_UNITS:
|
|
603
|
+
raise ValueError(f"question {name!r}: list field {path!r} reads the state line by line, and it "
|
|
604
|
+
f"has {len(lines)} lines (at most {MAX_UNITS}); split the document")
|
|
605
|
+
props = item_fields(spec, path)
|
|
606
|
+
f = list_text(path, spec, props)
|
|
607
|
+
for r, (a, b) in enumerate(lines):
|
|
608
|
+
sub[f"l{SEP}{fi}{SEP}{r}"] = {"type": "noul", "instructions": pre + w["item"].format(
|
|
609
|
+
line=_shown(text[a:b]), field=f)}
|
|
610
|
+
lists[path] = dict(index=fi, lines=lines, props=props, items=spec.get("items") or {},
|
|
611
|
+
max=max_items(spec), cap=max_options - 1)
|
|
612
|
+
continue
|
|
613
|
+
if kind in ("enum", "enum_list"):
|
|
614
|
+
vals = _consts(spec if kind == "enum" else spec["items"])
|
|
615
|
+
crit = {k: f"{v} ({d})" if d else str(v) # shown: the value (+ its description)
|
|
616
|
+
for k, (v, d) in zip(enum_keys([v for v, _ in vals], path), vals)}
|
|
617
|
+
if kind == "enum":
|
|
618
|
+
crit[MISSING] = w["missing"]
|
|
619
|
+
sub[f"f{SEP}{path}"] = {"type": "choice", "criteria": crit, "option_keys": "hide",
|
|
620
|
+
"instructions": pre + w["enum"].format(field=f)}
|
|
621
|
+
else:
|
|
622
|
+
sub[f"f{SEP}{path}"] = {"type": "multi", "criteria": crit,
|
|
623
|
+
"instructions": pre + w["enum_multi"].format(field=f)}
|
|
624
|
+
elif kind == "boolean":
|
|
625
|
+
sub[f"f{SEP}{path}"] = {"type": "choice", "instructions": pre + w["enum"].format(field=f),
|
|
626
|
+
"criteria": {"true": w["yes"], "false": w["no"], "__missing__": w["missing"]},
|
|
627
|
+
"option_keys": "hide"}
|
|
628
|
+
else:
|
|
629
|
+
if not text.strip(): # (blank: no line to choose)
|
|
630
|
+
raise ValueError(f"question {name!r}: field {path!r} is taken from the state's text, which is "
|
|
631
|
+
"empty (fields from media: enum and boolean only)")
|
|
632
|
+
regions = regions or line_regions(text, max_options - 1)
|
|
633
|
+
crit = {f"L{i}": _shown(text[a:b]) for i, (a, b) in enumerate(regions)}
|
|
634
|
+
crit[MISSING] = w["missing"]
|
|
635
|
+
sub[f"f{SEP}{path}"] = {"type": "choice", "criteria": crit, "option_keys": "hide",
|
|
636
|
+
"instructions": pre + w["line"].format(field=f)}
|
|
637
|
+
plans[name] = dict(type=t, fields=fields, lang=lang, pre=pre, regions=regions, risks=_risks(q),
|
|
638
|
+
keys=field_keys(q.get("schema") or {}))
|
|
639
|
+
if regions and any(len(" ".join(text[a:b].split())) > 400 for a, b in regions):
|
|
640
|
+
plans[name]["partial_candidates"] = True
|
|
641
|
+
if lists: # (the most decisions their items can take in the second round: counted before the run)
|
|
642
|
+
plans[name].update(lists=lists, later=sum(min(x["max"], len(x["lines"])) * len(x["props"])
|
|
643
|
+
for x in lists.values()))
|
|
644
|
+
for k, v in sub.items():
|
|
645
|
+
questions[f"{name}{SEP}{k}"] = v
|
|
646
|
+
return dict(body, questions=questions), plans
|
|
647
|
+
|
|
648
|
+
|
|
649
|
+
# --- assembly -------------------------------------------------------------------------------------------------------
|
|
650
|
+
|
|
651
|
+
def _automated(cal, task, conf, risks):
|
|
652
|
+
"""Whether a task answer may be used without review at each max_error: only with a threshold certified for that task
|
|
653
|
+
(calibration file: "task_thresholds": {task: {"0.01": confidence, ...}}, fitted on the user's own labelled
|
|
654
|
+
decisions); the thresholds of the decision types do not hold on task label sets (measured 2026-10-15), so without
|
|
655
|
+
one the answer is null."""
|
|
656
|
+
own = (cal.get("task_thresholds") or {}).get(task) or {}
|
|
657
|
+
out = {}
|
|
658
|
+
for r in risks:
|
|
659
|
+
thr = own.get(str(float(r)))
|
|
660
|
+
out[str(r)] = None if thr is None else bool(conf >= float(thr))
|
|
661
|
+
return out
|
|
662
|
+
|
|
663
|
+
|
|
664
|
+
def _item_value(name, x, j, k, kind, spec, cands, second, state, lang):
|
|
665
|
+
"""One field of one item of a list field, from its second-round decision (none: an item that is one value and its
|
|
666
|
+
line's only candidate, or no candidate at all) -> its answer {"value", ...}."""
|
|
667
|
+
b2 = (second or {}).get(f"{name}{SEP}i{SEP}{x['index']}{SEP}{j}{SEP}{k}")
|
|
668
|
+
if kind not in TEXT_KINDS: # enum / boolean: a choice over its values
|
|
669
|
+
if b2 is None: # (finish without a second round)
|
|
670
|
+
return {"value": None, "confidence": None, "source": "choice"}
|
|
671
|
+
c = b2["choice"]
|
|
672
|
+
value = None if c == MISSING else (c == "true" if kind == "boolean" else enum_values(
|
|
673
|
+
[v for v, _ in _consts(spec)])[c])
|
|
674
|
+
return {"value": value, "probabilities": b2["probabilities"], "confidence": b2["confidence"],
|
|
675
|
+
"source": "choice"}
|
|
676
|
+
if not cands:
|
|
677
|
+
return {"value": None, "confidence": None, "source": "span"}
|
|
678
|
+
if b2 is None: # one candidate of an item that is one value: the line itself
|
|
679
|
+
c, p_span = 0, 1.0
|
|
680
|
+
elif b2["choice"] == MISSING:
|
|
681
|
+
return {"value": None, "span_probability": b2["probabilities"][MISSING],
|
|
682
|
+
"confidence": b2["probabilities"][MISSING], "source": "span"}
|
|
683
|
+
else:
|
|
684
|
+
c, p_span = int(b2["choice"][1:]), b2["confidence"]
|
|
685
|
+
s0, e0 = cands[c]
|
|
686
|
+
txt = state[s0:e0]
|
|
687
|
+
f = {"value": txt, "text": txt, "start": s0, "end": e0, "span_probability": p_span, "confidence": p_span,
|
|
688
|
+
"source": "span"}
|
|
689
|
+
if kind in ("number", "integer"):
|
|
690
|
+
f["value"] = parse_number(txt, kind == "integer", lang)
|
|
691
|
+
if f["value"] is None:
|
|
692
|
+
f["error"] = f"not a {kind}"
|
|
693
|
+
return f
|
|
694
|
+
|
|
695
|
+
|
|
696
|
+
def list_answer(name, p, path, part, second, state):
|
|
697
|
+
"""A list field's answer: "value" the items (each a value, or an object of its fields), "items" per item its line
|
|
698
|
+
(start, end, text, P(item)) and its fields' answers, "count", "confidence" the probability that the set of lines
|
|
699
|
+
taken is right (the product of every line's decision), "dropped" the lines past maxItems; automated is null (no
|
|
700
|
+
threshold is certified for a list)."""
|
|
701
|
+
x = p["lists"][path]
|
|
702
|
+
if "chosen" not in x: # (no second round was asked: the items from the line decisions here)
|
|
703
|
+
x["chosen"], x["p"], x["dropped"] = list_items(lambda k: part[k[len(name) + len(SEP):]], name, p, path)
|
|
704
|
+
x["cands"] = {j: item_cands(state, *x["lines"][r], x["cap"]) for j, r in enumerate(x["chosen"])}
|
|
705
|
+
scalar = len(x["props"]) == 1 and x["props"][0][0] == ""
|
|
706
|
+
keys = None if scalar else field_keys(x["items"])
|
|
707
|
+
values, items = [], []
|
|
708
|
+
for j, r in enumerate(x["chosen"]):
|
|
709
|
+
a, b = x["lines"][r]
|
|
710
|
+
got = {ip: _item_value(name, x, j, k, kind, spec, x["cands"].get(j) or [], second, state, p["lang"])
|
|
711
|
+
for k, (ip, kind, spec) in enumerate(x["props"])}
|
|
712
|
+
if scalar:
|
|
713
|
+
values.append(got[""]["value"])
|
|
714
|
+
else:
|
|
715
|
+
v = {}
|
|
716
|
+
for ip, g in got.items():
|
|
717
|
+
_set_path(v, keys[ip], g["value"])
|
|
718
|
+
values.append(v)
|
|
719
|
+
items.append({"start": a, "end": b, "text": state[a:b], "probability": x["p"][r], "fields": got})
|
|
720
|
+
chosen, conf = set(x["chosen"]), 1.0
|
|
721
|
+
for r, v in enumerate(x["p"]):
|
|
722
|
+
conf *= v if r in chosen else 1 - v
|
|
723
|
+
f = {"value": values, "items": items, "count": len(items), "confidence": conf, "source": "list"}
|
|
724
|
+
if x["dropped"]:
|
|
725
|
+
f["dropped"] = x["dropped"]
|
|
726
|
+
f["automated"] = {str(r): None for r in p["risks"]}
|
|
727
|
+
f["calibration"] = "per decision"
|
|
728
|
+
return f
|
|
729
|
+
|
|
730
|
+
|
|
731
|
+
def finish(out, body, plans, cal, second=None):
|
|
732
|
+
"""The expanded answers of a response (and of second_round's request, `second`) -> one answer per task question."""
|
|
733
|
+
ans = out["answers"]
|
|
734
|
+
state = body.get("state") if isinstance(body.get("state"), str) else ""
|
|
735
|
+
for name, p in plans.items():
|
|
736
|
+
part = {k[len(name) + len(SEP):]: ans.pop(k) for k in list(ans) if k.startswith(name + SEP)}
|
|
737
|
+
t = p["type"]
|
|
738
|
+
if t == "classify":
|
|
739
|
+
a = part["labels"]
|
|
740
|
+
if p["multi"]:
|
|
741
|
+
res = {"type": "classify", "labels": a["selected"], "scores": a["probabilities"],
|
|
742
|
+
"set_confidence": a["set_confidence"]}
|
|
743
|
+
else:
|
|
744
|
+
res = {"type": "classify", "label": a["choice"], "top_label": a["choice"],
|
|
745
|
+
"scores": a["probabilities"], "confidence": a["confidence"],
|
|
746
|
+
"automated": _automated(cal, "classify", a["confidence"], p["risks"])}
|
|
747
|
+
elif t == "verify":
|
|
748
|
+
claims, flagged = {}, []
|
|
749
|
+
for k in p["keys"]:
|
|
750
|
+
a = part[f"c{SEP}{k}"]
|
|
751
|
+
if p["binary"]:
|
|
752
|
+
pr = {"supported": a["noul"], "not_supported": 1 - a["noul"]}
|
|
753
|
+
verdict = "supported" if a["noul"] >= 0.5 else "not_supported"
|
|
754
|
+
else:
|
|
755
|
+
pr, verdict = a["probabilities"], a["choice"]
|
|
756
|
+
conf = max(pr.values())
|
|
757
|
+
claims[k] = {"verdict": verdict, "probabilities": pr, "confidence": conf,
|
|
758
|
+
"automated": _automated(cal, "verify", conf, p["risks"])}
|
|
759
|
+
if verdict != "supported":
|
|
760
|
+
flagged.append(k)
|
|
761
|
+
res = {"type": "verify", "claims": claims, "all_supported": not flagged, "not_supported": flagged}
|
|
762
|
+
elif t == "compress":
|
|
763
|
+
spans = p["spans"]
|
|
764
|
+
pr = [part[f"u{SEP}{i}"]["noul"] for i in range(len(spans))]
|
|
765
|
+
order = sorted(range(len(spans)), key=lambda i: -pr[i])
|
|
766
|
+
total = sum(b - a for a, b in spans)
|
|
767
|
+
if p["keep_ratio"] is not None:
|
|
768
|
+
keep, n = set(), 0
|
|
769
|
+
for i in order:
|
|
770
|
+
if n >= float(p["keep_ratio"]) * total:
|
|
771
|
+
break
|
|
772
|
+
keep.add(i)
|
|
773
|
+
n += spans[i][1] - spans[i][0]
|
|
774
|
+
else:
|
|
775
|
+
keep = {i for i in range(len(spans)) if pr[i] >= p["threshold"]}
|
|
776
|
+
keep |= set(order[:p["min_keep"]])
|
|
777
|
+
kept = sorted(keep)
|
|
778
|
+
text = join_units(state, [(i, spans[i]) for i in kept])
|
|
779
|
+
res = {"type": "compress", "compressed": text, "kept": kept, "unit": p["unit"],
|
|
780
|
+
"units": [{"start": a, "end": b, "probability": round(x, 6)} for (a, b), x in zip(spans, pr)],
|
|
781
|
+
"original_chars": len(state), "compressed_chars": len(text),
|
|
782
|
+
"ratio": round(len(text) / max(1, len(state)), 4)}
|
|
783
|
+
else: # extract
|
|
784
|
+
data, fields = {}, {}
|
|
785
|
+
for path, kind, spec in p["fields"]:
|
|
786
|
+
if kind == "list":
|
|
787
|
+
fields[path] = list_answer(name, p, path, part, second, state)
|
|
788
|
+
_set_path(data, p["keys"][path], fields[path]["value"])
|
|
789
|
+
continue
|
|
790
|
+
a = part[f"f{SEP}{path}"]
|
|
791
|
+
if kind == "enum":
|
|
792
|
+
vals = enum_values([v for v, _ in _consts(spec)])
|
|
793
|
+
c = a["choice"]
|
|
794
|
+
f = {"value": None if c == "__missing__" else vals[c], "probabilities": a["probabilities"],
|
|
795
|
+
"confidence": a["confidence"], "source": "choice"}
|
|
796
|
+
elif kind == "enum_list":
|
|
797
|
+
vals = enum_values([v for v, _ in _consts(spec["items"])])
|
|
798
|
+
f = {"value": [vals[k] for k in a["selected"]], "probabilities": a["probabilities"],
|
|
799
|
+
"confidence": a["set_confidence"], "source": "choice"}
|
|
800
|
+
elif kind == "boolean":
|
|
801
|
+
c = a["choice"]
|
|
802
|
+
f = {"value": None if c == "__missing__" else c == "true", "probabilities": a["probabilities"],
|
|
803
|
+
"confidence": a["confidence"], "source": "choice"}
|
|
804
|
+
else:
|
|
805
|
+
pl = a["probabilities"]
|
|
806
|
+
p_line = 1 - pl["__missing__"]
|
|
807
|
+
f = {"value": None, "present_probability": p_line, "source": "span"}
|
|
808
|
+
cands = (p.get("cands") or {}).get(path)
|
|
809
|
+
if a["choice"] == "__missing__" or not cands:
|
|
810
|
+
f["confidence"] = pl["__missing__"]
|
|
811
|
+
else:
|
|
812
|
+
b2 = (second or {}).get(f"{name}{SEP}s{SEP}{path}")
|
|
813
|
+
if b2 is None:
|
|
814
|
+
j, p_span = None, None
|
|
815
|
+
elif b2["choice"] == "__missing__":
|
|
816
|
+
j, p_span = None, b2["probabilities"]["__missing__"]
|
|
817
|
+
else:
|
|
818
|
+
j, p_span = int(b2["choice"][1:]), b2["confidence"]
|
|
819
|
+
if j is None:
|
|
820
|
+
f["confidence"] = p_span
|
|
821
|
+
else:
|
|
822
|
+
s0, e0 = cands[j]
|
|
823
|
+
txt = state[s0:e0]
|
|
824
|
+
f.update(text=txt, start=s0, end=e0, line_probability=a["confidence"],
|
|
825
|
+
span_probability=p_span, confidence=a["confidence"] * p_span)
|
|
826
|
+
if kind in ("number", "integer"):
|
|
827
|
+
f["value"] = parse_number(txt, kind == "integer", p["lang"])
|
|
828
|
+
if f["value"] is None:
|
|
829
|
+
f["error"] = f"not a {kind}"
|
|
830
|
+
else:
|
|
831
|
+
f["value"] = txt
|
|
832
|
+
if "error" in f: # a number that does not parse is never used without review
|
|
833
|
+
f["automated"] = {str(r): False for r in p["risks"]}
|
|
834
|
+
elif kind == "enum_list": # a label set has no certified threshold
|
|
835
|
+
f["automated"] = {str(r): None for r in p["risks"]}
|
|
836
|
+
else:
|
|
837
|
+
f["automated"] = _automated(cal, "extract", f["confidence"], p["risks"])
|
|
838
|
+
f["calibration"] = "validated" if f["source"] == "choice" else "per decision"
|
|
839
|
+
if (p.get("partial_candidates") or path in p.get("capped_fields", ())) and f["source"] == "span":
|
|
840
|
+
f["candidate_coverage"] = "partial"
|
|
841
|
+
f["automated"] = {str(r): False for r in p["risks"]}
|
|
842
|
+
fields[path] = f
|
|
843
|
+
_set_path(data, p["keys"][path], f["value"])
|
|
844
|
+
res = {"type": "extract", "data": data, "fields": fields}
|
|
845
|
+
res["experimental"] = True
|
|
846
|
+
ans[name] = res
|
|
847
|
+
out["usage"]["questions"] = len(body["questions"])
|
|
848
|
+
return out
|