decisionnode-edge 0.9.2__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.
@@ -0,0 +1,597 @@
1
+ """POST /v1/systemone: the request and answer format public decision-model benchmarks use, read onto the runtime's own.
2
+
3
+ translate(body) the format's pictures onto the runtime's, before the parse:
4
+ - `assets`: {reference: {"type": "image", "format": "png" | "jpg" | "jpeg", "data_base64"}}.
5
+ Every place a reference appears (as a whole string value or inside a longer string, in the
6
+ state, a question's instructions or its criteria; never in an object key) is the picture
7
+ "in its place". The model reads every picture of a request before the state, labelled
8
+ `Picture <n> (<id>):`, so each reference is replaced in the text by `Picture <n>` and the
9
+ asset becomes picture n. A picture is read once however many times it is referenced, and
10
+ every question sees every picture.
11
+ - chat content parts, `{"type": "image_url", "image_url": {"url": "data:..."}}` (or
12
+ `"image_url": "data:..."`), anywhere in the state, the instructions or the criteria: the
13
+ same, the part replaced by `Picture <n>`; an array made only of such parts and
14
+ `{"type": "text", "text"}` parts is read as its text, the parts joined by a line break.
15
+ - `images` as a list of data URLs.
16
+ - `box` questions: in the picture the instructions name (`image_for_box`) when the request
17
+ holds several of the format's pictures; answered in fractions (`normalised_boxes`, after
18
+ the checks). A box with `max` keeps the runtime's list answer.
19
+ The legend of a score whose levels held a reference echoes the levels as sent.
20
+ box_answer(answer) a one-box answer in the format's shape: {"type": "box", "box": {"top", "bottom", "left",
21
+ "right"}, "confidence"}, the edges as fractions of the picture's height and width, and
22
+ `confidence` the probability that the box is right where the model folder has a box
23
+ calibration (BoxCalibration), else `present`.
24
+ mark_capacity(...) the words benchmark harnesses look for in an error ("maximum context length", "options per
25
+ choice", "a score takes 2 to 10 levels"), so that a limit of the model is recorded as one.
26
+
27
+ Choice and score probabilities on this route are normalised first and rounded to lists that sum to exactly 1.00
28
+ (answers.round_probabilities with exact_sum). Headers the format defines for pictures and long inputs are accepted and
29
+ never required. A multipart body (`part` assets) is not taken: an asset with `part` is a 400 that says to send
30
+ `data_base64`.
31
+ """
32
+
33
+ from __future__ import annotations
34
+
35
+ import base64
36
+ import binascii
37
+ import hashlib
38
+ import json
39
+ import math
40
+ import re
41
+ from dataclasses import dataclass, field
42
+ from typing import Any, Iterable
43
+
44
+ from .answers import round2
45
+ from .request import IMAGE_MEDIA_TYPES, MAX_LEVELS, MAX_OPTIONS, RequestError
46
+
47
+ ASSET_FORMATS = {"png": "image/png", "jpg": "image/jpeg", "jpeg": "image/jpeg"} # the format's Asset.format
48
+ MAX_REFERENCE_BYTES = 1024 # one reference, UTF-8
49
+ MAX_REFERENCES_BYTES = 65536 # every reference of a request together
50
+ MAX_NESTING = 128 # a body nested deeper is left as it is (the parse refuses it)
51
+ PICTURE = "Picture {n}" # what the text reads in a reference's place: the model's own label of picture n
52
+ BOX_CALIBRATION_FILE = "box_calibration.json" # in the model folder, optional
53
+ BOX_CALIBRATION_FORMAT = "dn-box-calibration-1"
54
+ BOX_CALIBRATION_FEATURES = ["logit_present", "logit_confidence"]
55
+ _WHITESPACE = re.compile(r"[\t\n\x0b\x0c\r ]")
56
+ _BACKTICKED = re.compile(r"`([^`\n]{1,512})`")
57
+ _PATH_PART = re.compile(r"([^.\[\]]+)|\[(\d+)\]")
58
+
59
+
60
+ @dataclass
61
+ class Translation:
62
+ """What translate() did to a body, for the parse and the answer."""
63
+
64
+ images: list[dict] = field(default_factory=list) # the image objects it added, in picture order
65
+ legends: dict[str, list] = field(default_factory=dict) # score question id -> its levels as sent
66
+ boxes: list[str] = field(default_factory=list) # the box questions, answered in the format's shape
67
+ references: int = 0 # the references replaced in the text
68
+
69
+
70
+ # ---------------------------------------------------------------------------
71
+ # Errors
72
+ # ---------------------------------------------------------------------------
73
+
74
+
75
+ def field_error(kind: str, loc: Iterable[Any], msg: str, value: Any, **extra: Any) -> dict:
76
+ return {"type": kind, "loc": list(loc), "msg": msg, "input": value, **extra}
77
+
78
+
79
+ def _invalid(entry: dict) -> RequestError:
80
+ return RequestError(f"{'.'.join(str(part) for part in entry['loc'])}: {entry['msg']}", 422, errors=[entry])
81
+
82
+
83
+ def _asset_error(ref: str, problem: str) -> RequestError:
84
+ shown = ref if len(ref) <= 80 else ref[:77] + "..."
85
+ return RequestError(f"Asset {shown!r}: {problem}.")
86
+
87
+
88
+ def _too_large(message: str) -> RequestError:
89
+ return RequestError(message, 413, "request_too_large_error")
90
+
91
+
92
+ # ---------------------------------------------------------------------------
93
+ # Pictures
94
+ # ---------------------------------------------------------------------------
95
+
96
+
97
+ def _sniff(text: str) -> str | None:
98
+ """The type of a base64 picture from its first bytes (PNG, JPEG, WebP), or None."""
99
+ head = text[:64]
100
+ try:
101
+ blob = base64.b64decode(head[: len(head) - len(head) % 4])
102
+ except (binascii.Error, ValueError):
103
+ return None
104
+ if blob.startswith(b"\x89PNG\r\n\x1a\n"):
105
+ return "image/png"
106
+ if blob.startswith(b"\xff\xd8\xff"):
107
+ return "image/jpeg"
108
+ if blob[:4] == b"RIFF" and blob[8:12] == b"WEBP":
109
+ return "image/webp"
110
+ return None
111
+
112
+
113
+ def _clean_base64(text: str) -> str:
114
+ """Base64 text as the decoder reads it: a `data:` prefix and any ASCII whitespace dropped, missing padding added."""
115
+ if text[:5].lower() == "data:":
116
+ text = text.partition(",")[2]
117
+ if _WHITESPACE.search(text):
118
+ text = _WHITESPACE.sub("", text)
119
+ if len(text) % 4 in (2, 3) and "=" not in text:
120
+ text += "=" * (4 - len(text) % 4)
121
+ return text
122
+
123
+
124
+ def _asset_image(ref: str, asset: Any) -> dict:
125
+ """The runtime's image object (without its id) for one asset. Raises RequestError."""
126
+ if asset.get("type") is not None and asset.get("type") != "image":
127
+ raise _invalid(field_error("literal_error", ("body", "assets", ref, "type"), "Input should be 'image'", asset.get("type"), ctx={"expected": "'image'"}))
128
+ if asset.get("part") is not None:
129
+ raise _asset_error(ref, "multipart image parts are not taken by this server; send the image base64-encoded in data_base64 in a JSON body")
130
+ data = asset.get("data_base64")
131
+ if data is None:
132
+ raise _asset_error(ref, "data_base64 is required")
133
+ if not isinstance(data, str):
134
+ raise _invalid(field_error("string_type", ("body", "assets", ref, "data_base64"), "Input should be a valid string", data))
135
+ fmt = asset.get("format")
136
+ declared = None
137
+ if fmt is not None:
138
+ if not isinstance(fmt, str) or fmt not in ASSET_FORMATS:
139
+ raise _asset_error(ref, "format must be png, jpg or jpeg")
140
+ declared = ASSET_FORMATS[fmt]
141
+ data = _clean_base64(data)
142
+ if not data:
143
+ raise _asset_error(ref, "data_base64 is empty")
144
+ media = _sniff(data) or declared # the format is read from the bytes
145
+ if media is None:
146
+ raise _asset_error(ref, "the data is not a PNG or JPEG image")
147
+ return {"media_type": media, "data": data}
148
+
149
+
150
+ def _part_image(part: dict) -> dict:
151
+ """The runtime's image object (without its id) for an `image_url` content part. Raises RequestError."""
152
+ url = part.get("image_url")
153
+ if isinstance(url, dict):
154
+ url = url.get("url")
155
+ if not isinstance(url, str) or not url:
156
+ raise RequestError("An image_url part needs a url: a data:image/...;base64 URL.")
157
+ scheme = url[:8].lower()
158
+ if scheme.startswith("data:"):
159
+ head, comma, data = url.partition(",")
160
+ fields = head[5:].split(";")
161
+ if not comma or len(fields) < 2 or fields[-1].strip().lower() != "base64":
162
+ raise RequestError("An image_url data URL must be data:<media type>;base64,<data>.")
163
+ data = _clean_base64(data)
164
+ declared = fields[0].strip().lower()
165
+ declared = "image/jpeg" if declared == "image/jpg" else declared
166
+ media = _sniff(data) or (declared if declared in IMAGE_MEDIA_TYPES else None)
167
+ if media is None:
168
+ raise RequestError("An image_url part must hold a PNG, JPEG or WebP image.")
169
+ return {"media_type": media, "data": data}
170
+ if scheme == "https://":
171
+ raise RequestError("Image URLs are not fetched on this deployment: send the image as a base64 data URL.")
172
+ raise RequestError("An image_url part must be a base64 data URL.")
173
+
174
+
175
+ def _is_image_part(value: Any) -> bool:
176
+ return isinstance(value, dict) and value.get("type") == "image_url" and "image_url" in value
177
+
178
+
179
+ def _is_text_part(value: Any) -> bool:
180
+ return isinstance(value, dict) and value.get("type") == "text" and isinstance(value.get("text"), str) and set(value) <= {"type", "text"}
181
+
182
+
183
+ # ---------------------------------------------------------------------------
184
+ # The walk
185
+ # ---------------------------------------------------------------------------
186
+
187
+
188
+ class _Walk:
189
+ """Replaces references and image parts in the free-form parts of a request, numbering the pictures as it meets them."""
190
+
191
+ def __init__(self, refs: Iterable[str], first: int):
192
+ self.refs = list(refs)
193
+ self.first = first # the picture number of the first picture this walk adds, less one (the body's own images)
194
+ self.order: list[tuple[str, Any]] = [] # ("ref", reference) or ("part", image object), in picture order
195
+ self.by_ref: dict[str, int] = {}
196
+ self.by_url: dict[str, int] = {}
197
+ self.replaced = 0
198
+ ordered = sorted(self.refs, key=len, reverse=True) # at one position the longest reference wins
199
+ self.pattern = re.compile("|".join(re.escape(ref) for ref in ordered)) if ordered else None
200
+ self.whole = set(self.refs)
201
+
202
+ def _number_of_ref(self, ref: str) -> int:
203
+ if ref not in self.by_ref:
204
+ self.order.append(("ref", ref))
205
+ self.by_ref[ref] = self.first + len(self.order)
206
+ return self.by_ref[ref]
207
+
208
+ def _number_of_part(self, part: dict) -> int:
209
+ image = _part_image(part)
210
+ key = image.get("data") or ""
211
+ if key not in self.by_url:
212
+ self.order.append(("part", image))
213
+ self.by_url[key] = self.first + len(self.order)
214
+ return self.by_url[key]
215
+
216
+ def text(self, value: str) -> str:
217
+ if self.pattern is None:
218
+ return value
219
+ if value in self.whole: # a whole value first
220
+ self.replaced += 1
221
+ return PICTURE.format(n=self._number_of_ref(value))
222
+ if not any(ref in value for ref in self.refs):
223
+ return value
224
+
225
+ def one(match: "re.Match[str]") -> str:
226
+ self.replaced += 1
227
+ return PICTURE.format(n=self._number_of_ref(match.group(0)))
228
+
229
+ return self.pattern.sub(one, value)
230
+
231
+ def value(self, value: Any) -> Any:
232
+ """`value` with every reference and image part replaced (a new object where anything changed)."""
233
+ if isinstance(value, str):
234
+ return self.text(value)
235
+ if _is_image_part(value):
236
+ self.replaced += 1
237
+ return PICTURE.format(n=self._number_of_part(value))
238
+ if isinstance(value, list):
239
+ if value and any(_is_image_part(item) for item in value) and all(_is_image_part(item) or _is_text_part(item) for item in value):
240
+ # a content-part array: its text, the pictures in their places
241
+ return "\n".join(self.value(item) if _is_image_part(item) else self.text(item["text"]) for item in value)
242
+ out = [self.value(item) for item in value]
243
+ return out if any(a is not b for a, b in zip(out, value)) else value
244
+ if isinstance(value, dict):
245
+ out = {key: self.value(item) for key, item in value.items()} # keys stay text
246
+ return out if any(out[key] is not value[key] for key in value) else value
247
+ return value
248
+
249
+
250
+ def _question(walk: _Walk, question: Any) -> Any:
251
+ """A question with its instructions and criteria walked (its type and every other field as sent)."""
252
+ if not isinstance(question, dict):
253
+ return question
254
+ out = dict(question)
255
+ if "instructions" in out:
256
+ out["instructions"] = walk.value(out["instructions"])
257
+ criteria = out.get("criteria")
258
+ if isinstance(criteria, dict):
259
+ out["criteria"] = {key: walk.value(item) for key, item in criteria.items()} # an option's name is a key: never replaced
260
+ elif isinstance(criteria, list):
261
+ out["criteria"] = [walk.value(item) for item in criteria]
262
+ return out
263
+
264
+
265
+ # ---------------------------------------------------------------------------
266
+ # Box questions
267
+ # ---------------------------------------------------------------------------
268
+
269
+
270
+ def _resolve(state: Any, path: str) -> Any:
271
+ """The value a backticked path names in the state (`photo`, `frames[2].frame`, `faces.happy`), or None."""
272
+ value = state
273
+ for name, index in _PATH_PART.findall(path.strip()):
274
+ if name:
275
+ if not isinstance(value, dict) or name not in value:
276
+ return None
277
+ value = value[name]
278
+ else:
279
+ if not isinstance(value, list) or int(index) >= len(value):
280
+ return None
281
+ value = value[int(index)]
282
+ return value
283
+
284
+
285
+ def _first_ref(value: Any, refs: set[str]) -> str | None:
286
+ """The first reference held whole by a string inside `value` (depth first, in order)."""
287
+ if isinstance(value, str):
288
+ return value if value in refs else None
289
+ items = value.values() if isinstance(value, dict) else value if isinstance(value, list) else ()
290
+ for item in items:
291
+ found = _first_ref(item, refs)
292
+ if found is not None:
293
+ return found
294
+ return None
295
+
296
+
297
+ def image_for_box(instructions: Any, state: Any, refs: set[str], numbers: dict[str, int], in_state: list[int], own: set[int], count: int) -> int:
298
+ """The picture number a box question looks in when the request holds several pictures (the path in backticks names
299
+ which one to search): the picture a backticked path of the instructions names in the state (a reference held there,
300
+ whole); else the first picture of the state; else the first picture the instructions do not hold themselves (a
301
+ picture in a box's instructions shows the target, it is not the picture to search); else picture 1."""
302
+ text = instructions if isinstance(instructions, str) else "" if instructions is None else str(instructions)
303
+ for path in _BACKTICKED.findall(text):
304
+ found = _first_ref(_resolve(state, path), refs)
305
+ if found is not None and found in numbers:
306
+ return numbers[found]
307
+ if in_state:
308
+ return in_state[0]
309
+ for n in range(1, count + 1):
310
+ if n not in own:
311
+ return n
312
+ return 1
313
+
314
+
315
+ def question_refs(question: dict, refs: Iterable[str]) -> set[str]:
316
+ """The references a question's own instructions and criteria hold (whole or inside a string)."""
317
+ found: set[str] = set()
318
+ wanted = list(refs)
319
+
320
+ def visit(value: Any) -> None:
321
+ if isinstance(value, str):
322
+ found.update(ref for ref in wanted if ref in value)
323
+ elif isinstance(value, dict):
324
+ for item in value.values():
325
+ visit(item)
326
+ elif isinstance(value, list):
327
+ for item in value:
328
+ visit(item)
329
+
330
+ visit(question.get("instructions"))
331
+ visit(question.get("criteria"))
332
+ return found
333
+
334
+
335
+ # ---------------------------------------------------------------------------
336
+ # The request
337
+ # ---------------------------------------------------------------------------
338
+
339
+
340
+ def _within_nesting(value: Any, limit: int = MAX_NESTING) -> bool:
341
+ """At most `limit` containers inside each other (walked without recursion)."""
342
+ stack = [(value, 0)]
343
+ while stack:
344
+ item, depth = stack.pop()
345
+ if isinstance(item, (dict, list)):
346
+ if depth + 1 > limit:
347
+ return False
348
+ stack.extend((child, depth + 1) for child in (item.values() if isinstance(item, dict) else item))
349
+ return True
350
+
351
+
352
+ def _check_assets(assets: Any) -> dict:
353
+ if not isinstance(assets, dict):
354
+ raise _invalid(field_error("dict_type", ("body", "assets"), "Input should be a valid dictionary", assets))
355
+ if not assets:
356
+ raise _invalid(field_error("too_short", ("body", "assets"), "Dictionary should have at least 1 item after validation, not 0", assets, ctx={"field_type": "Dictionary", "min_length": 1, "actual_length": 0}))
357
+ total = 0
358
+ for ref, asset in assets.items():
359
+ if not isinstance(asset, dict):
360
+ raise _invalid(field_error("model_attributes_type", ("body", "assets", ref), "Input should be a valid dictionary or object to extract fields from", asset))
361
+ if not ref.strip():
362
+ raise RequestError("An asset reference cannot be empty or only whitespace.")
363
+ size = len(ref.encode("utf-8", "surrogatepass"))
364
+ if size > MAX_REFERENCE_BYTES:
365
+ raise _too_large(f"An asset reference is at most {MAX_REFERENCE_BYTES} bytes of UTF-8.")
366
+ total += size
367
+ if total > MAX_REFERENCES_BYTES:
368
+ raise _too_large(f"The asset references of a request are at most {MAX_REFERENCES_BYTES} bytes of UTF-8 together.")
369
+ return assets
370
+
371
+
372
+ def _may_hold_parts(value: Any) -> bool:
373
+ """Cheap: whether a value may hold an image_url part (any dict with that type somewhere), walked without recursion."""
374
+ stack = [value]
375
+ while stack:
376
+ item = stack.pop()
377
+ if isinstance(item, dict):
378
+ if item.get("type") == "image_url":
379
+ return True
380
+ stack.extend(child for child in item.values() if isinstance(child, (dict, list)))
381
+ elif isinstance(item, list):
382
+ stack.extend(child for child in item if isinstance(child, (dict, list)))
383
+ return False
384
+
385
+
386
+ def translate(body: Any, *, max_images: int) -> tuple[Any, Translation]:
387
+ """A /v1/systemone body with the format's pictures on the runtime's (module docstring), and what was done. A body
388
+ that is not an object with a question map is returned as it is (the parse refuses it). Raises RequestError for an
389
+ asset or an image part the runtime cannot take."""
390
+ done = Translation()
391
+ if not isinstance(body, dict) or not isinstance(body.get("questions"), dict):
392
+ return body, done
393
+ assets = body.get("assets")
394
+ has_assets = assets is not None
395
+ questions = body["questions"]
396
+ has_parts = _may_hold_parts(body.get("state")) or any(_may_hold_parts(q.get("instructions")) or _may_hold_parts(q.get("criteria")) for q in questions.values() if isinstance(q, dict))
397
+ boxes = [qid for qid, q in questions.items() if isinstance(q, dict) and q.get("type") == "box"]
398
+ url_images = isinstance(body.get("images"), list) and any(isinstance(image, str) for image in body["images"])
399
+ if not has_assets and not has_parts and not boxes and not url_images:
400
+ if "assets" in body: # `"assets": null` equals no assets
401
+ body = {name: value for name, value in body.items() if name != "assets"}
402
+ return body, done
403
+ if not _within_nesting(body):
404
+ return body, done # the parse refuses it as it refuses any body that deep
405
+ out = {name: value for name, value in body.items() if name != "assets"}
406
+ refs: list[str] = list(_check_assets(assets)) if has_assets else []
407
+ if len(refs) > max_images:
408
+ raise RequestError(f"Too many images: {len(refs)}, the limit is {max_images}.")
409
+ own_images = body.get("images") if isinstance(body.get("images"), list) else []
410
+ if url_images:
411
+ # `images` as a list of data URLs: each an image object, in the list's order
412
+ if len(own_images) > max_images:
413
+ raise RequestError(f"Too many images: {len(own_images)}, the limit is {max_images}.")
414
+ listed = []
415
+ for i, image in enumerate(own_images):
416
+ if isinstance(image, str):
417
+ image = {"id": "image" if len(own_images) == 1 else f"image_{i + 1}", **_part_image({"image_url": image})}
418
+ listed.append(image)
419
+ own_images = listed
420
+ out["images"] = listed
421
+ walk = _Walk(refs, len(own_images))
422
+ state = body.get("state")
423
+ out["state"] = walk.value(state)
424
+ in_state = sorted(set(walk.by_ref.values()) | set(walk.by_url.values()))
425
+ walked: dict[str, Any] = {}
426
+ for qid, question in questions.items():
427
+ walked[qid] = _question(walk, question)
428
+ if isinstance(question, dict) and question.get("type") == "score" and walked[qid].get("criteria") != question.get("criteria"):
429
+ done.legends[str(qid)] = question.get("criteria") # the legend echoes the levels as sent
430
+ unused = [ref for ref in refs if ref not in walk.by_ref]
431
+ if unused:
432
+ raise _asset_error(unused[0], "it is not referenced in the state, the instructions or the criteria")
433
+ added = len(walk.order)
434
+ total = len(own_images) + added
435
+ if total > max_images:
436
+ raise RequestError(f"Too many images: {total}, the limit is {max_images}.")
437
+ taken = {image.get("id") for image in own_images if isinstance(image, dict)}
438
+ images = []
439
+ for i, (kind, item) in enumerate(walk.order):
440
+ n = len(own_images) + i + 1
441
+ image_id = "image" if total == 1 else f"image_{n}"
442
+ while image_id in taken:
443
+ image_id += "_"
444
+ taken.add(image_id)
445
+ image = _asset_image(item, assets[item]) if kind == "ref" else dict(item)
446
+ images.append({"id": image_id, **image})
447
+ if images:
448
+ out["images"] = list(own_images) + images
449
+ done.images = images
450
+ done.references = walk.replaced
451
+ ids = [image.get("id") for image in out.get("images") or [] if isinstance(image, dict)]
452
+ numbers = dict(walk.by_ref)
453
+ for qid in boxes:
454
+ # the picture is chosen only for the format's pictures (assets, image parts, data URLs), which no `image` field
455
+ # can name; with image objects alone a box without `image` among several stays the 422 of the runtime's parse
456
+ if walked[qid].get("image") is None and len(ids) > 1 and (added or url_images):
457
+ question = dict(walked[qid])
458
+ own = {numbers[ref] for ref in question_refs(questions[qid], refs) if ref in numbers}
459
+ n = image_for_box(questions[qid].get("instructions"), state, set(refs), numbers, in_state, own, len(ids))
460
+ question["image"] = ids[n - 1]
461
+ walked[qid] = question
462
+ done.boxes.append(str(qid))
463
+ out["questions"] = walked
464
+ return out, done
465
+
466
+
467
+ def normalised_boxes(specs: Iterable[Any]) -> None:
468
+ """The box questions of a /v1/systemone request answered in fractions of the picture (the format's edges), set on the
469
+ parsed specs (places.PlaceSpec) after their checks. A box with `max` keeps the units the caller sent."""
470
+ for spec in specs:
471
+ if spec.shape == "box" and spec.max is None:
472
+ spec.units = "normalized"
473
+
474
+
475
+ # ---------------------------------------------------------------------------
476
+ # The answer
477
+ # ---------------------------------------------------------------------------
478
+
479
+
480
+ class BoxCalibrationError(ValueError):
481
+ """A box calibration file the runtime does not take (the server does not start on it)."""
482
+
483
+
484
+ @dataclass(frozen=True)
485
+ class BoxCalibration:
486
+ """The `confidence` of a box on /v1/systemone: the probability that the box is right (an intersection over union of
487
+ 0.5 or more with the true box), read from the one-box answer's own two numbers, `present` and `confidence`, as the
488
+ answer writes them (2 decimals). A logistic map, fitted per model and kept beside it as box_calibration.json:
489
+
490
+ {"format": "dn-box-calibration-1", "features": ["logit_present", "logit_confidence"], "clip": 0.005,
491
+ "intercept": a, "coef": [b, c], "model": ..., "fit": {...}}
492
+
493
+ p = sigmoid(a + b logit(present) + c logit(confidence)), each input clipped to [clip, 1 - clip] first, the result
494
+ rounded to 2 decimals. Monotone: no coefficient below 0, so neither number can lower the probability by rising."""
495
+
496
+ intercept: float
497
+ coef: tuple[float, float]
498
+ clip: float
499
+ sha256: str
500
+ model: str = ""
501
+
502
+ @classmethod
503
+ def load(cls, path: str, sha256: str = "") -> "BoxCalibration":
504
+ """Read and check a calibration file; `sha256`, when given, must be the file's."""
505
+ try:
506
+ with open(path, "rb") as f:
507
+ data = f.read()
508
+ except OSError as error:
509
+ raise BoxCalibrationError(f"box calibration {path}: {error}") from None
510
+ digest = hashlib.sha256(data).hexdigest()
511
+ if sha256 and sha256.lower() != digest:
512
+ raise BoxCalibrationError(f"box calibration {path}: sha256 {digest}, expected {sha256}")
513
+ try:
514
+ spec = json.loads(data)
515
+ except ValueError as error:
516
+ raise BoxCalibrationError(f"box calibration {path}: not JSON ({error})") from None
517
+ if not isinstance(spec, dict) or spec.get("format") != BOX_CALIBRATION_FORMAT:
518
+ raise BoxCalibrationError(f"box calibration {path}: the format is not {BOX_CALIBRATION_FORMAT}")
519
+ if spec.get("features") != BOX_CALIBRATION_FEATURES:
520
+ raise BoxCalibrationError(f"box calibration {path}: features must be {BOX_CALIBRATION_FEATURES}")
521
+ coef, intercept, clip = spec.get("coef"), spec.get("intercept"), spec.get("clip")
522
+ numbers = [intercept, clip] + (list(coef) if isinstance(coef, list) else [])
523
+ if not isinstance(coef, list) or len(coef) != 2 or any(isinstance(x, bool) or not isinstance(x, (int, float)) or x != x or abs(x) == float("inf") for x in numbers):
524
+ raise BoxCalibrationError(f"box calibration {path}: intercept, coef (two numbers) and clip must be finite numbers")
525
+ if any(c < 0 for c in coef):
526
+ raise BoxCalibrationError(f"box calibration {path}: a coefficient below 0 is not monotone")
527
+ if not 0 < clip < 0.5:
528
+ raise BoxCalibrationError(f"box calibration {path}: clip must be above 0 and below 0.5")
529
+ return cls(float(intercept), (float(coef[0]), float(coef[1])), float(clip), digest, str(spec.get("model") or ""))
530
+
531
+ def probability(self, present: float, confidence: float) -> float:
532
+ """The unrounded probability that the box is right."""
533
+
534
+ def logit(p: float) -> float:
535
+ p = min(1.0 - self.clip, max(self.clip, float(p)))
536
+ return math.log(p / (1.0 - p))
537
+
538
+ z = self.intercept + self.coef[0] * logit(present) + self.coef[1] * logit(confidence)
539
+ return 1.0 / (1.0 + math.exp(-z)) if z >= 0 else math.exp(z) / (1.0 + math.exp(z))
540
+
541
+ def __call__(self, present: float, confidence: float) -> float:
542
+ return round2(self.probability(present, confidence))
543
+
544
+
545
+ def box_answer(answer: dict, calibration: BoxCalibration | None = None) -> dict:
546
+ """A one-box answer (normalized units) in the format's shape. `confidence`: the calibrated probability that the box
547
+ is right where there is a calibration, else `present`."""
548
+ return {
549
+ "type": "box",
550
+ "box": {"top": answer["y1"], "bottom": answer["y2"], "left": answer["x1"], "right": answer["x2"]},
551
+ "confidence": calibration(answer["present"], answer["confidence"]) if calibration is not None else answer["present"],
552
+ }
553
+
554
+
555
+ def box_answers(body: dict, calibration: BoxCalibration | None = None) -> dict:
556
+ """The response body with every one-box answer in the format's shape (a list answer, `max`, stays the runtime's)."""
557
+ answers = body.get("answers")
558
+ if isinstance(answers, dict):
559
+ for qid, answer in answers.items():
560
+ if isinstance(answer, dict) and answer.get("type") == "box" and "x1" in answer:
561
+ answers[qid] = box_answer(answer, calibration)
562
+ return body
563
+
564
+
565
+ # ---------------------------------------------------------------------------
566
+ # Errors with the capacity words
567
+ # ---------------------------------------------------------------------------
568
+
569
+ CONTEXT_MARKER = "maximum context length"
570
+ OPTIONS_MARKER = "options per choice"
571
+ LEVELS_MARKER = "a score takes 2 to 10 levels"
572
+ TOO_MANY_LEVELS = f"Too many score levels. Must have at most {MAX_LEVELS} levels."
573
+
574
+
575
+ def mark_capacity(error: RequestError) -> RequestError:
576
+ """A refusal of /v1/systemone for a limit of the model, in the words and bodies benchmark harnesses read:
577
+
578
+ over the length limit {"detail": {"error_type": "max_tokens_exceeded", "message": "The request does not fit
579
+ the model's maximum context length (<the count and the limit>)."}}
580
+ more than 255 options {"detail": "Too many choices. Must have at most 255 choices (255 options per choice)."}
581
+ more than 10 levels {"detail": "Too many score levels. Must have at most 10 levels (a score takes 2 to 10
582
+ levels; one level is answered without the model)."}
583
+
584
+ Every other refusal is returned as it is."""
585
+ message = str(error)
586
+ if error.status != 400:
587
+ return error
588
+ if error.error_type == "max_tokens_exceeded":
589
+ text = f"The request does not fit the model's {CONTEXT_MARKER} ({message})."
590
+ return RequestError(text, 400, error.error_type, detail={"error_type": error.error_type, "message": text})
591
+ if message.startswith("Too many choices"):
592
+ text = f"Too many choices. Must have at most {MAX_OPTIONS} choices ({MAX_OPTIONS} {OPTIONS_MARKER})."
593
+ return RequestError(text, 400, error.error_type, detail=text)
594
+ if message == TOO_MANY_LEVELS:
595
+ text = f"Too many score levels. Must have at most {MAX_LEVELS} levels ({LEVELS_MARKER}; one level is answered without the model)."
596
+ return RequestError(text, 400, error.error_type, detail=text)
597
+ return error