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,536 @@
1
+ """Point and box questions: where in a picture the thing the instructions name is.
2
+
3
+ {"type": "point", "instructions": "Point to the yellow package closest to the robot arm.", "image": "belt"}
4
+ {"type": "point", "x": 812, "y": 455, "present": 0.97, "confidence": 0.91, "image": "belt", "width": 1920, "height": 1080}
5
+ {"type": "box", "x1": 300, "y1": 120, "x2": 520, "y2": 410, "present": 0.95, "confidence": 0.88, "image": "belt", ...}
6
+
7
+ The question. `instructions` (a string, object or array; required), `image` (the id of a picture of the request;
8
+ optional when the request carries exactly one), `units` ("pixels", the default, or "normalized"), `max` (an integer from
9
+ 2 to 16: a list of up to that many places in place of one). `criteria` and any other field are ignored. A request with a
10
+ point or box question needs a picture. Every faulty field is listed in one 422 (`question_errors`, the question's type
11
+ in the path: ["body", "questions", "pick", "point", "image"]); a missing `instructions` is then the 400 of every type.
12
+
13
+ How one is answered: a few readings of the model, pass by pass, each a prompt of its own, a later pass given what the
14
+ earlier ones read:
15
+
16
+ point pass 0: presence, x pass 1: y given x
17
+ box pass 0: presence, x (centre) pass 1: y (centre) given x pass 2: width and height given the centre
18
+
19
+ The presence reading is a yes/no question ("is it in the image?") and gives `present`. A coordinate reading lists no
20
+ options: code k is step k of 256 along one side of the picture (step k stands for the fraction (k + 0.5) / 256 of the
21
+ side), its scores read as a plain softmax. Its value is the most probable step (the lowest on a tie), then the
22
+ probability-weighted mean of the steps within WINDOW = 2 of it (the answer between steps; a distant second peak, another
23
+ object, stays out of the mean), and its peak mass is the probability within that window. A later reading is given the
24
+ earlier ones rounded to whole steps. `confidence` is the product of the coordinate readings' peak masses (provisional:
25
+ not calibrated).
26
+
27
+ Units: `pixels` are whole pixels of the picture as sent, after its EXIF orientation, halves up: a point within
28
+ [0, width - 1] x [0, height - 1], a box's corners within [0, width] x [0, height]; `normalized` gives fractions of the
29
+ width and height with 4 decimals, halves up, within [0, 1]. A box's corners are its centre minus and plus half its
30
+ size, clipped to the picture, so x1 <= x2 and y1 <= y2. `present` and `confidence` to 2 decimals.
31
+
32
+ Several places (`max`):
33
+
34
+ pass 0: presence, count pass 1: every place's x pass 2: every y given its x
35
+ pass 3 (a box): every width and height given its centre
36
+
37
+ The count reading answers 0 to 16, or 17 for more (codes 0 to 17): `count` is min(level, max), `complete` the
38
+ probability of a level at or under `max`. The k-th place's readings carry its rank among the level read ("of 5, the
39
+ 2nd from the left"). The answer lists the places from the left by the centre's x, ties from the top, each with its own
40
+ confidence; two boxes at an intersection over union of MERGE_IOU = 0.7 or more are one thing, and the one of lower
41
+ confidence is dropped (`count` is the places listed). A count of 0 ends after pass 0.
42
+ """
43
+
44
+ from __future__ import annotations
45
+
46
+ import math
47
+ from dataclasses import dataclass, field
48
+ from typing import Any, Iterator, Sequence
49
+
50
+ from .answers import round2
51
+
52
+ TYPES = ("point", "box")
53
+ UNITS = ("pixels", "normalized")
54
+ N_STEPS = 256 # steps per side: the model's 256 answer codes
55
+ WINDOW = 2 # a coordinate reading: the steps within this many of the most probable one are averaged
56
+ COUNT_MAX = 16 # the most places a list holds
57
+ COUNT_MORE = COUNT_MAX + 1 # the count reading's level for more than COUNT_MAX
58
+ COUNT_LEVELS = COUNT_MORE + 1 # the count reading's codes: 0 to 17
59
+ MAX_RANGE = (2, COUNT_MAX) # a question's `max`
60
+ MERGE_IOU = 0.7 # two listed boxes overlapping at this intersection over union or more are one thing
61
+ CHAIN = {"point": (("x", 0), ("y", 1)), "box": (("x", 0), ("y", 1), ("width", 2), ("height", 2))} # (axis, pass)
62
+ GIVEN = {"x": (), "y": ("x",), "width": ("x", "y"), "height": ("x", "y")} # the earlier readings an axis is given
63
+
64
+ _CONTENT_MEMBERS = (
65
+ ("string_type", "str", "Input should be a valid string"),
66
+ ("dict_type", "dict[any,any]", "Input should be a valid dictionary"),
67
+ ("list_type", "list[any]", "Input should be a valid list"),
68
+ )
69
+
70
+
71
+ def is_place_question(question: Any) -> bool:
72
+ return isinstance(question, dict) and question.get("type") in TYPES
73
+
74
+
75
+ @dataclass
76
+ class PlaceSpec:
77
+ """One point or box question of a request."""
78
+
79
+ qid: str
80
+ shape: str # "point" or "box"
81
+ instructions: str # as the prompt prints them
82
+ image: str # the id of the picture to look in
83
+ number: int # that picture's place among the request's pictures, from 1: how the readings name it
84
+ units: str = "pixels"
85
+ max: int | None = None # the most places to list (2 to 16); None: the one-place answer
86
+
87
+
88
+ # ---------------------------------------------------------------------------
89
+ # Validation
90
+ # ---------------------------------------------------------------------------
91
+
92
+
93
+ def field_error(kind: str, loc: Sequence[Any], msg: str, value: Any, **extra: Any) -> dict:
94
+ """One entry of a 422's `detail` list."""
95
+ return {"type": kind, "loc": list(loc), "msg": msg, "input": value, **extra}
96
+
97
+
98
+ def max_errors(value: Any, here: Sequence[Any]) -> Iterator[dict]:
99
+ """The entries of a question's `max`: not an integer (a bool is not one), under 2, over 16. Null is no `max`."""
100
+ lo, hi = MAX_RANGE
101
+ if value is None:
102
+ return
103
+ if isinstance(value, bool) or not isinstance(value, int):
104
+ yield field_error("int_type", (*here, "max"), "Input should be a valid integer", value)
105
+ elif value < lo:
106
+ yield field_error("greater_than_equal", (*here, "max"), f"Input should be greater than or equal to {lo}", value, ctx={"ge": lo})
107
+ elif value > hi:
108
+ yield field_error("less_than_equal", (*here, "max"), f"Input should be less than or equal to {hi}", value, ctx={"le": hi})
109
+
110
+
111
+ def question_errors(question: dict, loc: Sequence[Any], image_ids: Sequence[str] | None) -> Iterator[dict]:
112
+ """The 422 entries of one point or box question (`loc` ends in its id), in order: `instructions` of another kind than
113
+ a string, an object or an array, `units`, `max`, then `image` against the ids of the request's pictures. `image_ids`
114
+ is None when the pictures themselves are faulty (their own error names them), so only the question's fields are
115
+ checked. A missing `instructions` is not one of them (`missing_instructions`)."""
116
+ shape = question["type"]
117
+ here = (*loc, shape)
118
+ instructions = question.get("instructions")
119
+ if instructions is not None and not isinstance(instructions, (str, dict, list)):
120
+ for kind, member, msg in _CONTENT_MEMBERS:
121
+ yield field_error(kind, (*here, "instructions", member), msg, instructions)
122
+ units = question.get("units")
123
+ if units is not None and units not in UNITS:
124
+ yield field_error("literal_error", (*here, "units"), "Input should be 'pixels' or 'normalized'", units, ctx={"expected": "'pixels' or 'normalized'"})
125
+ yield from max_errors(question.get("max"), here)
126
+ image = question.get("image")
127
+ if image_ids is None:
128
+ if image is not None and not isinstance(image, str):
129
+ yield field_error("string_type", (*here, "image"), "Input should be a valid string", image)
130
+ return
131
+ if not image_ids:
132
+ yield field_error("image_required", here, f"A {shape} question needs an image in the request", question)
133
+ elif image is None:
134
+ if len(image_ids) > 1:
135
+ yield field_error("missing", (*here, "image"), "Field required", question)
136
+ elif not isinstance(image, str): # a picture's number is not an id: "Picture 2" goes in the instructions
137
+ yield field_error("string_type", (*here, "image"), "Input should be a valid string", image)
138
+ elif image not in image_ids:
139
+ yield field_error("unknown_image", (*here, "image"), "Input should be the id of an image of the request", image)
140
+
141
+
142
+ def missing_instructions(questions: Sequence[tuple[str, dict]]) -> str | None:
143
+ """The 400's message for the first point or box question without instructions, or None."""
144
+ for qid, question in questions:
145
+ if question.get("instructions") is None or question.get("instructions") == "":
146
+ return f"{question['type'].capitalize()} question must have instructions: {qid}"
147
+ return None
148
+
149
+
150
+ def where(entry: dict) -> str:
151
+ """Where a 422 entry points, for the error's message: body.questions.'pick'.'point'.'image': Field required."""
152
+ parts = (part[:100] + "..." if isinstance(part, str) and len(part) > 100 else part for part in entry["loc"])
153
+ return ".".join(str(part) if i < 2 else repr(part) for i, part in enumerate(parts)) + ": " + entry["msg"]
154
+
155
+
156
+ def reason(errors: Sequence[dict], shown: int = 5) -> str:
157
+ text = ", ".join(where(e) for e in errors[:shown])
158
+ return text + (f" and {len(errors) - shown} more" if len(errors) > shown else "")
159
+
160
+
161
+ # ---------------------------------------------------------------------------
162
+ # The readings' texts
163
+ # ---------------------------------------------------------------------------
164
+
165
+ PRESENCE_ANSWER = "answer: is it in the image?"
166
+ COUNT_ANSWER = f"answer: how many are in the image, from 0 to {COUNT_MAX}; {COUNT_MORE} if more"
167
+ FIND = {"point": "find: the point", "box": "find: the box"}
168
+ AXIS_ANSWER = {
169
+ ("point", "x"): "answer: x of the point, from 0 (left edge) to 255 (right edge)",
170
+ ("point", "y"): "answer: y of the point, from 0 (top edge) to 255 (bottom edge)",
171
+ ("box", "x"): "answer: x of the box centre, from 0 (left edge) to 255 (right edge)",
172
+ ("box", "y"): "answer: y of the box centre, from 0 (top edge) to 255 (bottom edge)",
173
+ ("box", "width"): "answer: width of the box, from 0 (none) to 255 (the whole width)",
174
+ ("box", "height"): "answer: height of the box, from 0 (none) to 255 (the whole height)",
175
+ }
176
+
177
+
178
+ def image_line(spec: PlaceSpec) -> str:
179
+ """The picture a reading looks in, in the words of the label in front of it (template.image_label)."""
180
+ return f"image: Picture {int(spec.number)} ({spec.image})"
181
+
182
+
183
+ def presence_text(spec: PlaceSpec) -> str:
184
+ """The presence reading's instructions (a yes/no question): the instructions, the picture, the question."""
185
+ return f"{spec.instructions}\n{image_line(spec)}\n{PRESENCE_ANSWER}"
186
+
187
+
188
+ def count_text(spec: PlaceSpec) -> str:
189
+ """The count reading's text: the presence reading's lines with another question (a point and a box count alike)."""
190
+ return f"{spec.instructions}\n{image_line(spec)}\n{COUNT_ANSWER}"
191
+
192
+
193
+ def ordinal(k: int) -> str:
194
+ """1st, 2nd, 3rd, 4th, ..., 11th, 12th, 13th, ..., 21st."""
195
+ k = int(k)
196
+ suffix = "th" if 10 <= k % 100 <= 20 else {1: "st", 2: "nd", 3: "rd"}.get(k % 10, "th")
197
+ return f"{k}{suffix}"
198
+
199
+
200
+ def rank_line(rank: int, rank_of: int) -> str:
201
+ """A listed place's line: `given: of 5, the 2nd from the left` (`of more than 16` for the level 17)."""
202
+ of = f"more than {COUNT_MAX}" if int(rank_of) == COUNT_MORE else str(int(rank_of))
203
+ return f"given: of {of}, the {ordinal(rank)} from the left"
204
+
205
+
206
+ def coordinate_text(spec: PlaceSpec, axis: str, given: dict, rank: int | None = None, rank_of: int | None = None) -> str:
207
+ """A coordinate reading's text, line by line: the instructions as they are, the picture, what to find, a listed
208
+ place's rank, the earlier readings as whole steps, the axis with its 0 and 255:
209
+
210
+ the damaged package
211
+ image: Picture 1 (belt)
212
+ find: the box
213
+ given: centre x 128, y 65
214
+ answer: width of the box, from 0 (none) to 255 (the whole width)
215
+ """
216
+ lines = [spec.instructions, image_line(spec), FIND[spec.shape]]
217
+ if rank is not None:
218
+ lines.append(rank_line(rank, rank_of))
219
+ if axis == "y":
220
+ lines.append(f"given: x {given['x']}" if spec.shape == "point" else f"given: centre x {given['x']}")
221
+ elif axis in ("width", "height"):
222
+ lines.append(f"given: centre x {given['x']}, y {given['y']}")
223
+ lines.append(AXIS_ANSWER[(spec.shape, axis)])
224
+ return "\n".join(lines)
225
+
226
+
227
+ def presence_row(spec: PlaceSpec) -> dict:
228
+ return {"type": "truth", "instructions": presence_text(spec)}
229
+
230
+
231
+ def count_row(spec: PlaceSpec) -> dict:
232
+ return {"type": "coord", "instructions": count_text(spec), "classes": COUNT_LEVELS, "axis": "count"}
233
+
234
+
235
+ def coordinate_row(spec: PlaceSpec, axis: str, given: dict, rank: int | None = None, rank_of: int | None = None) -> dict:
236
+ row = {"type": "coord", "instructions": coordinate_text(spec, axis, given, rank, rank_of), "classes": N_STEPS, "axis": axis}
237
+ if rank is not None:
238
+ row["rank"] = rank
239
+ return row
240
+
241
+
242
+ # ---------------------------------------------------------------------------
243
+ # Readings
244
+ # ---------------------------------------------------------------------------
245
+
246
+
247
+ class ReadingError(ValueError):
248
+ """Probabilities a reading cannot be read from (a fault of the model or the backend, never the caller's)."""
249
+
250
+
251
+ @dataclass(frozen=True)
252
+ class Reading:
253
+ """One coordinate reading: the step (between steps), the most probable step and the peak's mass."""
254
+
255
+ step: float
256
+ argmax: int
257
+ peak: float
258
+
259
+ @property
260
+ def fraction(self) -> float:
261
+ return step_fraction(self.step)
262
+
263
+
264
+ @dataclass(frozen=True)
265
+ class CountReading:
266
+ """The count reading: the level (0 to 16, 17 for more), `count` = min(level, max), `complete` = the probability
267
+ of a level at or under max, and the level's own probability."""
268
+
269
+ level: int
270
+ count: int
271
+ complete: float
272
+ peak: float
273
+
274
+
275
+ def step_fraction(step: float) -> float:
276
+ """The fraction of the side a (continuous) step stands for: (s + 0.5) / 256."""
277
+ return (float(step) + 0.5) / N_STEPS
278
+
279
+
280
+ def given_step(step: float) -> int:
281
+ """A reading as the whole step a later reading is given: halves up, within [0, 255]."""
282
+ return min(N_STEPS - 1, max(0, int(math.floor(float(step) + 0.5))))
283
+
284
+
285
+ def _argmax_first(p: Sequence[float]) -> int:
286
+ best = 0
287
+ for k, x in enumerate(p):
288
+ if x > p[best]:
289
+ best = k
290
+ return best
291
+
292
+
293
+ def check(probs: Sequence[float], n: int, what: str) -> None:
294
+ """A list's readings are read only from n probabilities that are finite, not negative and sum to 1."""
295
+ p = [float(x) for x in probs]
296
+ if len(p) != n:
297
+ raise ReadingError(f"a {what} reading has {n} probabilities, got {len(p)}")
298
+ if any(not math.isfinite(x) or x < -1e-6 for x in p) or abs(math.fsum(p) - 1.0) > 1e-3:
299
+ raise ReadingError(f"{what} probabilities must be finite, not negative, and sum to 1")
300
+
301
+
302
+ def read(probs: Sequence[float], window: int = WINDOW) -> Reading:
303
+ """A coordinate reading from its 256 step probabilities (the module text)."""
304
+ p = [max(0.0, float(x)) for x in probs]
305
+ if len(p) != N_STEPS:
306
+ raise ReadingError(f"a coordinate reading has {N_STEPS} probabilities, got {len(p)}")
307
+ best = _argmax_first(p)
308
+ lo, hi = max(0, best - window), min(N_STEPS - 1, best + window)
309
+ mass = math.fsum(p[k] for k in range(lo, hi + 1))
310
+ step = math.fsum(k * p[k] for k in range(lo, hi + 1)) / mass if mass > 0 else float(best)
311
+ return Reading(step=step, argmax=best, peak=min(1.0, mass))
312
+
313
+
314
+ def read_count(probs: Sequence[float], max_places: int) -> CountReading:
315
+ """The count reading from its 18 level probabilities for a list of at most `max_places` places."""
316
+ check(probs, COUNT_LEVELS, "count")
317
+ p = [float(x) for x in probs]
318
+ best = _argmax_first(p)
319
+ complete = min(1.0, math.fsum(max(0.0, x) for x in p[: max_places + 1]))
320
+ return CountReading(level=best, count=min(best, max_places), complete=complete, peak=max(0.0, p[best]))
321
+
322
+
323
+ # ---------------------------------------------------------------------------
324
+ # Answers
325
+ # ---------------------------------------------------------------------------
326
+
327
+
328
+ def _half_up(x: float, decimals: int = 0) -> float:
329
+ scale = 10.0**decimals
330
+ return math.floor(x * scale + 0.5 + 1e-9) / scale
331
+
332
+
333
+ def to_pixels(fraction: float, size: int, *, inclusive_end: bool) -> int:
334
+ """A fraction of a side of `size` pixels as a whole coordinate, halves up: a point names a pixel (0 to size - 1), a
335
+ box corner may lie on the far edge (0 to size)."""
336
+ value = int(_half_up(float(fraction) * int(size)))
337
+ return min(int(size) if inclusive_end else int(size) - 1, max(0, value))
338
+
339
+
340
+ def to_normalized(fraction: float) -> float:
341
+ """A fraction with 4 decimals, halves up, within [0, 1]."""
342
+ return min(1.0, max(0.0, _half_up(float(fraction), 4)))
343
+
344
+
345
+ def box_corners(cx: float, cy: float, w: float, h: float) -> tuple[float, float, float, float]:
346
+ """(x1, y1, x2, y2) as fractions from the centre and the size, clipped to the picture: x1 <= x2 and y1 <= y2."""
347
+ w, h = max(0.0, float(w)), max(0.0, float(h))
348
+ clip = lambda v: min(1.0, max(0.0, v)) # noqa: E731
349
+ return clip(cx - w / 2.0), clip(cy - h / 2.0), clip(cx + w / 2.0), clip(cy + h / 2.0)
350
+
351
+
352
+ def box_iou(a: Sequence[float], b: Sequence[float]) -> float:
353
+ """The intersection over union of two boxes (x1, y1, x2, y2) in fractions of the sides (0 when both are empty)."""
354
+ w = max(0.0, min(a[2], b[2]) - max(a[0], b[0]))
355
+ h = max(0.0, min(a[3], b[3]) - max(a[1], b[1]))
356
+ inter = w * h
357
+ union = (a[2] - a[0]) * (a[3] - a[1]) + (b[2] - b[0]) * (b[3] - b[1]) - inter
358
+ return inter / union if union > 0 else 0.0
359
+
360
+
361
+ def merge_boxes(places: Sequence[tuple[tuple[float, ...], float]], threshold: float = MERGE_IOU) -> list[int]:
362
+ """The boxes (fractions, confidence) kept when two on one thing are one: taken by confidence, highest first (ties:
363
+ the earlier in the list), a box that overlaps a box already kept at `threshold` or more is dropped. Returns the
364
+ indexes kept, in list order."""
365
+ kept: list[int] = []
366
+ for i in sorted(range(len(places)), key=lambda i: (-places[i][1], i)):
367
+ worst = max((box_iou(places[i][0], places[j][0]) for j in kept), default=0.0)
368
+ if worst < threshold:
369
+ kept.append(i)
370
+ return sorted(kept)
371
+
372
+
373
+ def place_order(fractions: Sequence[float]) -> tuple[float, float]:
374
+ """A listed place's key: from the left by the centre's x, ties from the top (a box's centre, or the point), as
375
+ fractions rounded to 6 digits."""
376
+ if len(fractions) == 2:
377
+ cx, cy = fractions
378
+ else:
379
+ cx, cy = (fractions[0] + fractions[2]) / 2.0, (fractions[1] + fractions[3]) / 2.0
380
+ return round(float(cx), 6), round(float(cy), 6)
381
+
382
+
383
+ def _place(shape: str, units: str, f: Sequence[float], width: int, height: int) -> dict:
384
+ """A point's x and y, or a box's corners, in the question's units."""
385
+ if shape == "point":
386
+ if units == "pixels":
387
+ return {"x": to_pixels(f[0], width, inclusive_end=False), "y": to_pixels(f[1], height, inclusive_end=False)}
388
+ return {"x": to_normalized(f[0]), "y": to_normalized(f[1])}
389
+ if units == "pixels":
390
+ x1, y1, x2, y2 = (to_pixels(v, side, inclusive_end=True) for v, side in zip(f, (width, height, width, height)))
391
+ else:
392
+ x1, y1, x2, y2 = (to_normalized(v) for v in f)
393
+ return {"x1": x1, "y1": y1, "x2": x2, "y2": y2}
394
+
395
+
396
+ # ---------------------------------------------------------------------------
397
+ # The passes of a request
398
+ # ---------------------------------------------------------------------------
399
+
400
+
401
+ @dataclass
402
+ class Chain:
403
+ """One place: the presence and the coordinate readings so far."""
404
+
405
+ spec: PlaceSpec
406
+ present: float | None = None
407
+ readings: dict = field(default_factory=dict) # axis -> Reading
408
+
409
+ @property
410
+ def passes(self) -> int:
411
+ return 1 + max(at for _, at in CHAIN[self.spec.shape])
412
+
413
+ def answer(self, width: int, height: int) -> dict:
414
+ spec = self.spec
415
+ confidence = 1.0
416
+ for axis, _ in CHAIN[spec.shape]:
417
+ confidence *= self.readings[axis].peak
418
+ r = self.readings
419
+ f = (r["x"].fraction, r["y"].fraction) if spec.shape == "point" else box_corners(r["x"].fraction, r["y"].fraction, r["width"].fraction, r["height"].fraction)
420
+ return {"type": spec.shape, **_place(spec.shape, spec.units, f, width, height), "present": round2(self.present), "confidence": round2(confidence),
421
+ "image": spec.image, "width": int(width), "height": int(height)} # fmt: skip
422
+
423
+
424
+ @dataclass
425
+ class ListChain:
426
+ """Several places (`max`): the presence, the count, and per listed place (rank 1 first) its readings so far."""
427
+
428
+ spec: PlaceSpec
429
+ present: float | None = None
430
+ counting: CountReading | None = None
431
+ readings: list = field(default_factory=list) # per place: {axis: Reading}
432
+ passes_done: int = 0
433
+
434
+ @property
435
+ def passes(self) -> int:
436
+ """1 for a count of 0, else 1 plus a single place's passes (a point 3, a box 4); before pass 0 the most."""
437
+ if self.counting is not None and self.counting.count == 0:
438
+ return 1
439
+ return 2 + max(at for _, at in CHAIN[self.spec.shape])
440
+
441
+ @property
442
+ def done(self) -> bool:
443
+ return self.passes_done >= self.passes
444
+
445
+ def rows(self) -> list[dict]:
446
+ """The next pass's readings: pass 0 the presence and the count, then place by place one pass of each chain."""
447
+ spec = self.spec
448
+ if self.passes_done == 0:
449
+ return [presence_row(spec), count_row(spec)]
450
+ at, level = self.passes_done - 1, self.counting.level
451
+ out = []
452
+ for k in range(1, self.counting.count + 1):
453
+ for axis, when in CHAIN[spec.shape]:
454
+ if when == at:
455
+ given = {name: given_step(self.readings[k - 1][name].step) for name in GIVEN[axis]}
456
+ out.append(coordinate_row(spec, axis, given, rank=k, rank_of=level))
457
+ return out
458
+
459
+ def take(self, rows: Sequence[dict], probs: Sequence[Sequence[float]]) -> None:
460
+ if self.passes_done == 0:
461
+ if len(probs[0]) != 2:
462
+ raise ReadingError("the presence reading has 2 probabilities")
463
+ self.present = float(probs[0][0])
464
+ self.counting = read_count(probs[1], self.spec.max)
465
+ self.readings = [{} for _ in range(self.counting.count)]
466
+ else:
467
+ for row, p in zip(rows, probs):
468
+ check(p, N_STEPS, "coordinate")
469
+ self.readings[row["rank"] - 1][row["axis"]] = read(p)
470
+ self.passes_done += 1
471
+
472
+ def answer(self, width: int, height: int) -> dict:
473
+ spec = self.spec
474
+ places = []
475
+ for r in self.readings:
476
+ confidence = 1.0
477
+ for axis, _ in CHAIN[spec.shape]:
478
+ confidence *= r[axis].peak
479
+ f = (r["x"].fraction, r["y"].fraction) if spec.shape == "point" else box_corners(r["x"].fraction, r["y"].fraction, r["width"].fraction, r["height"].fraction)
480
+ places.append((f, confidence))
481
+ kept = merge_boxes(places) if spec.shape == "box" else list(range(len(places)))
482
+ listed = [{**_place(spec.shape, spec.units, places[i][0], width, height), "confidence": round2(places[i][1])} for i in sorted(kept, key=lambda i: (place_order(places[i][0]), i))]
483
+ return {"type": spec.shape, "count": len(listed), "present": round2(self.present), "complete": round2(self.counting.complete),
484
+ "boxes" if spec.shape == "box" else "points": listed, "image": spec.image, "width": int(width), "height": int(height)} # fmt: skip
485
+
486
+
487
+ class Plan:
488
+ """The point and box questions of one request, answered pass by pass: `rows()` gives the next pass's readings (each
489
+ with the index of its question), `take` their probabilities in that order, until `rows()` is empty; then `answers`.
490
+ Pass 0 holds every single place's presence reading first, then per question its first readings."""
491
+
492
+ def __init__(self, specs: Sequence[PlaceSpec]):
493
+ self.chains: list = [ListChain(spec) if spec.max is not None else Chain(spec) for spec in specs]
494
+ self.passes_run = 0
495
+
496
+ @property
497
+ def passes(self) -> int:
498
+ return max((chain.passes for chain in self.chains), default=0)
499
+
500
+ def rows(self) -> list[tuple[int, dict]]:
501
+ at = self.passes_run
502
+ if at >= self.passes:
503
+ return []
504
+ out = [(n, presence_row(chain.spec)) for n, chain in enumerate(self.chains) if isinstance(chain, Chain)] if at == 0 else []
505
+ for n, chain in enumerate(self.chains):
506
+ if isinstance(chain, ListChain):
507
+ if not chain.done and chain.passes_done == at:
508
+ out += [(n, row) for row in chain.rows()]
509
+ continue
510
+ for axis, when in CHAIN[chain.spec.shape]:
511
+ if when == at:
512
+ given = {name: given_step(chain.readings[name].step) for name in GIVEN[axis]}
513
+ out.append((n, coordinate_row(chain.spec, axis, given)))
514
+ return out
515
+
516
+ def take(self, rows: Sequence[tuple[int, dict]], probs: Sequence[Sequence[float]]) -> None:
517
+ if len(rows) != len(probs):
518
+ raise ReadingError(f"expected {len(rows)} probability lists, got {len(probs)}")
519
+ lists: dict[int, tuple[list, list]] = {}
520
+ for (n, row), p in zip(rows, probs):
521
+ chain = self.chains[n]
522
+ if isinstance(chain, ListChain):
523
+ taken = lists.setdefault(n, ([], []))
524
+ taken[0].append(row)
525
+ taken[1].append([float(x) for x in p])
526
+ elif row["type"] == "truth":
527
+ chain.present = float(p[0])
528
+ else:
529
+ chain.readings[row["axis"]] = read(p)
530
+ for n, (rows_of, probs_of) in lists.items():
531
+ self.chains[n].take(rows_of, probs_of)
532
+ self.passes_run += 1
533
+
534
+ def answers(self, sizes: dict[str, tuple[int, int]]) -> dict[str, dict]:
535
+ """Every question's answer by id; `sizes` holds each picture's width and height as sent."""
536
+ return {chain.spec.qid: chain.answer(*sizes[chain.spec.image]) for chain in self.chains}