ArthurSword commited on
Commit
5a221aa
·
verified ·
1 Parent(s): 857b115

scorevision: push artifact

Browse files
Files changed (1) hide show
  1. miner.py +556 -0
miner.py ADDED
@@ -0,0 +1,556 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Strict config-driven consumer for Ultralytics end-to-end NMS ONNX.
2
+
3
+ The model contract is a static batch-1 input and one fixed ``[1, 300, 6]``
4
+ output whose rows are ``x1, y1, x2, y2, confidence, model_class_id``. NMS is
5
+ inside the ONNX graph. Python only validates, applies the element confidence
6
+ threshold and model-class mapping from the hardcoded element config, unletterboxes, filters
7
+ geometrically impossible boxes, sorts, and caps the configured result count.
8
+
9
+ This module intentionally uses no ``dataclass`` declarations. ScoreVision's
10
+ current ``spec_from_file_location`` loader does not register the dynamic module
11
+ in ``sys.modules`` before executing it, which makes Python dataclass decoration
12
+ fail during import.
13
+ """
14
+
15
+ import ast
16
+ import json
17
+ import math
18
+ import os
19
+ from collections.abc import Mapping
20
+ from pathlib import Path
21
+ from typing import Any
22
+
23
+ import cv2
24
+ import numpy as np
25
+ import onnxruntime as ort
26
+ from numpy import ndarray
27
+ from pydantic import BaseModel
28
+
29
+
30
+ # The deployment rail currently recognizes this strict-inference contract
31
+ # version for every cycle-2 miner. The tensor layout is separately enforced by
32
+ # this module's fixed [1, 300, 6] startup check.
33
+ API_VERSION = "c2-strict-v1"
34
+ STRICT_INFERENCE_ENV = "SV_STRICT_INFERENCE"
35
+ INPUT_CHANNELS = 3
36
+ OUTPUT_ROWS = 300
37
+ OUTPUT_COLUMNS = 6
38
+ IMGSZ_MIN, IMGSZ_MAX, IMGSZ_MULTIPLE = 320, 1280, 32
39
+ MAX_DET_LIMIT = 300
40
+ _ROOT_KEYS = {
41
+ "element_id", "classes", "emit_order", "coco_ids", "missing_classes", "imgsz",
42
+ "conf", "nms_iou", "max_det",
43
+ }
44
+
45
+
46
+ class InferenceInvariantError(RuntimeError):
47
+ """A model tensor or decoded detection violated the serving contract."""
48
+
49
+
50
+ class BoundingBox(BaseModel):
51
+ x1: int
52
+ y1: int
53
+ x2: int
54
+ y2: int
55
+ cls_id: int
56
+ conf: float
57
+
58
+
59
+ class TVFrameResult(BaseModel):
60
+ frame_id: int
61
+ boxes: list[BoundingBox]
62
+ keypoints: list[tuple[int, int]]
63
+
64
+
65
+ def strict_inference_from_env(environ: Mapping[str, str] | None = None) -> bool:
66
+ raw = (os.environ if environ is None else environ).get(STRICT_INFERENCE_ENV, "")
67
+ if raw in ("", "0"):
68
+ return False
69
+ if raw == "1":
70
+ return True
71
+ raise ValueError(
72
+ f"{STRICT_INFERENCE_ENV} must be '1' or unset/'0', got {raw!r}"
73
+ )
74
+
75
+
76
+ def _strict_int(value: Any, where: str, low: int, high: int) -> int:
77
+ if isinstance(value, bool) or not isinstance(value, int) or not low <= value <= high:
78
+ raise ValueError(f"element config {where} must be an integer in [{low}, {high}], got {value!r}")
79
+ return value
80
+
81
+
82
+ def _strict_unit(value: Any, where: str) -> float:
83
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
84
+ raise ValueError(f"element config {where} must be a finite number in (0, 1], got {value!r}")
85
+ number = float(value)
86
+ if not math.isfinite(number) or not 0.0 < number <= 1.0:
87
+ raise ValueError(f"element config {where} must be a finite number in (0, 1], got {value!r}")
88
+ return number
89
+
90
+
91
+ class ElementConfig:
92
+ """Strict immutable-by-convention config without dynamic-loader dataclasses."""
93
+
94
+ __slots__ = (
95
+ "element_id", "classes", "emit_order", "output_cls_ids", "coco_ids", "emitted_cls_ids",
96
+ "missing_classes", "imgsz", "conf", "nms_iou", "max_det",
97
+ )
98
+
99
+ def __init__(
100
+ self,
101
+ element_id: str,
102
+ classes: tuple[str, ...],
103
+ coco_ids: tuple[int, ...],
104
+ emitted_cls_ids: tuple[int, ...],
105
+ missing_classes: tuple[str, ...],
106
+ imgsz: int,
107
+ conf: float,
108
+ nms_iou: float,
109
+ max_det: int,
110
+ *,
111
+ emit_order: tuple[str, ...] | None = None,
112
+ output_cls_ids: tuple[int, ...] = (),
113
+ ) -> None:
114
+ self.element_id = element_id
115
+ self.classes = classes
116
+ self.emit_order = emit_order
117
+ self.output_cls_ids = output_cls_ids
118
+ self.coco_ids = coco_ids
119
+ self.emitted_cls_ids = emitted_cls_ids
120
+ self.missing_classes = missing_classes
121
+ self.imgsz = imgsz
122
+ self.conf = conf
123
+ self.nms_iou = nms_iou
124
+ self.max_det = max_det
125
+
126
+ @classmethod
127
+ def from_mapping(cls, data: dict[str, Any]) -> "ElementConfig":
128
+ required = {"element_id", "classes", "coco_ids", "imgsz", "conf", "nms_iou", "max_det"}
129
+ missing = sorted(required - set(data))
130
+ if missing:
131
+ raise ValueError(f"element config missing required field(s): {', '.join(missing)}")
132
+ unknown = sorted(set(data) - _ROOT_KEYS)
133
+ if unknown:
134
+ raise ValueError(f"element config root has unknown key(s): {', '.join(unknown)}")
135
+ element_id = data["element_id"]
136
+ classes = data["classes"]
137
+ coco_ids = data["coco_ids"]
138
+ missing_classes = data.get("missing_classes", [])
139
+ if not isinstance(element_id, str) or not element_id:
140
+ raise ValueError("element config element_id must be a non-empty string")
141
+ if not isinstance(classes, list) or not classes or not all(isinstance(name, str) and name for name in classes):
142
+ raise ValueError("element config classes must be a non-empty list of strings")
143
+ if len(set(classes)) != len(classes):
144
+ raise ValueError("element config classes must not contain duplicates")
145
+ emit_order_raw = data.get("emit_order")
146
+ if "emit_order" not in data:
147
+ emit_order = None
148
+ else:
149
+ if not isinstance(emit_order_raw, list) or not emit_order_raw \
150
+ or not all(isinstance(name, str) and name for name in emit_order_raw):
151
+ raise ValueError("element config emit_order must be a non-empty list of class names")
152
+ if len(set(emit_order_raw)) != len(emit_order_raw):
153
+ raise ValueError("element config emit_order must not contain duplicates")
154
+ unknown = sorted(set(emit_order_raw) - set(classes))
155
+ omitted = sorted(set(classes) - set(emit_order_raw))
156
+ if unknown or omitted or len(emit_order_raw) != len(classes):
157
+ raise ValueError(
158
+ "element config emit_order must be an exact permutation of classes; "
159
+ f"unknown={unknown}, missing={omitted}"
160
+ )
161
+ emit_order = tuple(emit_order_raw)
162
+ output_order = emit_order if emit_order is not None else tuple(classes)
163
+ output_cls_ids = tuple(output_order.index(name) for name in classes)
164
+ if not isinstance(missing_classes, list) or not all(isinstance(name, str) for name in missing_classes):
165
+ raise ValueError("element config missing_classes must be a list of strings")
166
+ if len(set(missing_classes)) != len(missing_classes) or any(name not in classes for name in missing_classes):
167
+ raise ValueError("element config missing_classes must be unique members of classes")
168
+ if not isinstance(coco_ids, list) or not all(
169
+ isinstance(class_id, int) and not isinstance(class_id, bool) and class_id >= 0
170
+ for class_id in coco_ids
171
+ ):
172
+ raise ValueError("element config coco_ids must be non-negative integer model class ids")
173
+ if len(set(coco_ids)) != len(coco_ids):
174
+ raise ValueError("element config coco_ids must not contain duplicates")
175
+ emitted_cls_ids = tuple(index for index, name in enumerate(classes) if name not in missing_classes)
176
+ if len(coco_ids) != len(emitted_cls_ids):
177
+ raise ValueError(
178
+ "element config classes/coco_ids length mismatch: "
179
+ f"{len(classes)} classes minus {len(missing_classes)} missing classes requires "
180
+ f"{len(emitted_cls_ids)} ids, got {len(coco_ids)}"
181
+ )
182
+ imgsz = _strict_int(data["imgsz"], "imgsz", IMGSZ_MIN, IMGSZ_MAX)
183
+ if imgsz % IMGSZ_MULTIPLE:
184
+ raise ValueError(f"element config imgsz must be a multiple of {IMGSZ_MULTIPLE}, got {imgsz}")
185
+ return cls(
186
+ element_id,
187
+ tuple(classes),
188
+ tuple(coco_ids),
189
+ emitted_cls_ids,
190
+ tuple(missing_classes),
191
+ imgsz,
192
+ _strict_unit(data["conf"], "conf"),
193
+ _strict_unit(data["nms_iou"], "nms_iou"),
194
+ _strict_int(data["max_det"], "max_det", 1, MAX_DET_LIMIT),
195
+ emit_order=emit_order,
196
+ output_cls_ids=output_cls_ids,
197
+ )
198
+
199
+
200
+ ELEMENT_CONFIG: dict[str, Any] = {
201
+ "element_id": "person",
202
+ "classes": ["person"],
203
+ "coco_ids": [0],
204
+ "imgsz": 640,
205
+ "conf": 0.4,
206
+ "nms_iou": 0.7,
207
+ "max_det": 300,
208
+ }
209
+
210
+
211
+ class Miner:
212
+ api_version = API_VERSION
213
+ strict_inference = False
214
+ inference_failures = 0
215
+ invariant_failures = 0
216
+ input_dims_source = "unbound"
217
+ input_shape_declared: list[Any] = []
218
+ min_side = 3.0
219
+ max_aspect_ratio = 10.0
220
+
221
+ def __init__(self, path_hf_repo: Path) -> None:
222
+ repo = Path(path_hf_repo)
223
+ self.config = ElementConfig.from_mapping(ELEMENT_CONFIG)
224
+ self.class_names = list(self.config.emit_order or self.config.classes)
225
+ self.conf_threshold = self.config.conf
226
+ self.nms_iou = self.config.nms_iou # retained for API parity; NMS is in the graph
227
+ self.max_det = self.config.max_det
228
+ self.strict_inference = strict_inference_from_env()
229
+ self.inference_failures = 0
230
+ self.invariant_failures = 0
231
+
232
+ # The referee grants one physical core (two SMT threads). Let ORT own
233
+ # both threads for the convolution graph, but keep OpenCV's short
234
+ # resize/blob stages single-threaded: a second OpenCV worker is slower
235
+ # and adds tail jitter on two sibling logical CPUs.
236
+ cv2.setNumThreads(1)
237
+
238
+ options = ort.SessionOptions()
239
+ options.intra_op_num_threads = 2
240
+ options.inter_op_num_threads = 1
241
+ options.execution_mode = ort.ExecutionMode.ORT_SEQUENTIAL
242
+ options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
243
+ model_path = repo / "weights.onnx"
244
+ try:
245
+ self.session = ort.InferenceSession(
246
+ str(model_path), sess_options=options,
247
+ providers=["CUDAExecutionProvider", "CPUExecutionProvider"],
248
+ )
249
+ except Exception as exc:
250
+ print(f"CUDA session failed, falling back to CPU: {exc}")
251
+ self.session = ort.InferenceSession(
252
+ str(model_path), sess_options=options, providers=["CPUExecutionProvider"]
253
+ )
254
+ self.input_name = self.session.get_inputs()[0].name
255
+ self.output_names = [output.name for output in self.session.get_outputs()]
256
+ self._bind_input_dims(self.session.get_inputs()[0].shape)
257
+ self._check_output_shape(self.session.get_outputs()[0].shape)
258
+ self.model_names = self._read_model_names()
259
+ self._bind_class_map()
260
+ self._warmup(3)
261
+ print(
262
+ f"api_version={self.api_version} element={self.config.element_id} "
263
+ f"imgsz={self.config.imgsz} conf={self.conf_threshold} "
264
+ f"providers={self.session.get_providers()} warmups=3"
265
+ )
266
+
267
+ @staticmethod
268
+ def _static_dim(value: Any) -> bool:
269
+ return isinstance(value, int) and not isinstance(value, bool) and value > 0
270
+
271
+ def _bind_input_dims(self, shape: Any) -> None:
272
+ if not isinstance(shape, (list, tuple)) or len(shape) != 4:
273
+ raise ValueError(f"model input must be rank-4 NCHW, got {shape!r}")
274
+ batch, channels, height, width = shape
275
+ self.input_shape_declared = [value if self._static_dim(value) else str(value) for value in shape]
276
+ if self._static_dim(batch) and batch != 1:
277
+ raise ValueError(f"model input batch must be 1, got {batch}")
278
+ if self._static_dim(channels) and channels != INPUT_CHANNELS:
279
+ raise ValueError(f"model input channels must be 3, got {channels}")
280
+ if not (self._static_dim(height) and self._static_dim(width)):
281
+ raise ValueError(f"e2e shipping export must have static spatial dims, got {height}x{width}")
282
+ if (height, width) != (self.config.imgsz, self.config.imgsz):
283
+ raise ValueError(
284
+ f"model input spatial dims {height}x{width} != config imgsz "
285
+ f"{self.config.imgsz}x{self.config.imgsz}"
286
+ )
287
+ self.input_height = self.input_width = self.config.imgsz
288
+ self.input_dims_source = "static"
289
+
290
+ @staticmethod
291
+ def _check_output_shape(shape: Any) -> None:
292
+ if list(shape) != [1, OUTPUT_ROWS, OUTPUT_COLUMNS]:
293
+ raise ValueError(
294
+ f"e2e model output must be exactly [1, {OUTPUT_ROWS}, {OUTPUT_COLUMNS}], got {shape!r}"
295
+ )
296
+
297
+ def _read_model_names(self) -> tuple[str, ...]:
298
+ try:
299
+ raw = self.session.get_modelmeta().custom_metadata_map["names"]
300
+ parsed = ast.literal_eval(raw)
301
+ if not isinstance(parsed, dict):
302
+ raise TypeError("names metadata is not a dict")
303
+ keys = sorted(parsed)
304
+ if keys != list(range(len(keys))):
305
+ raise ValueError(f"names metadata keys are not consecutive from zero: {keys[:8]}")
306
+ names = tuple(str(parsed[index]) for index in keys)
307
+ except Exception as exc:
308
+ raise ValueError(f"e2e ONNX requires valid consecutive names metadata: {exc}") from exc
309
+ if not names:
310
+ raise ValueError("e2e ONNX names metadata is empty")
311
+ return names
312
+
313
+ def _bind_class_map(self) -> None:
314
+ self.model_to_element: dict[int, int] = {}
315
+ for model_id, element_id in zip(self.config.coco_ids, self.config.emitted_cls_ids):
316
+ if model_id >= len(self.model_names):
317
+ raise ValueError(
318
+ f"config model class id {model_id} outside ONNX names range 0..{len(self.model_names)-1}"
319
+ )
320
+ expected = self.config.classes[element_id]
321
+ actual = self.model_names[model_id]
322
+ if actual != expected:
323
+ raise ValueError(
324
+ f"config class mapping mismatch: model class {model_id} is {actual!r}, "
325
+ f"element class {element_id} is {expected!r}"
326
+ )
327
+ self.model_to_element[model_id] = element_id
328
+
329
+ @staticmethod
330
+ def _letterbox(image: ndarray, new_shape: tuple[int, int], color=(114, 114, 114)):
331
+ height, width = image.shape[:2]
332
+ new_width, new_height = new_shape
333
+ ratio = min(new_width / width, new_height / height)
334
+ resized_width, resized_height = int(round(width * ratio)), int(round(height * ratio))
335
+ if (resized_width, resized_height) != (width, height):
336
+ image = cv2.resize(
337
+ image, (resized_width, resized_height),
338
+ interpolation=cv2.INTER_CUBIC if ratio > 1.0 else cv2.INTER_LINEAR,
339
+ )
340
+ dw, dh = (new_width - resized_width) / 2.0, (new_height - resized_height) / 2.0
341
+ padded = cv2.copyMakeBorder(
342
+ image,
343
+ int(round(dh - 0.1)), int(round(dh + 0.1)),
344
+ int(round(dw - 0.1)), int(round(dw + 0.1)),
345
+ cv2.BORDER_CONSTANT, value=color,
346
+ )
347
+ return padded, ratio, (dw, dh)
348
+
349
+ def _preprocess(self, image: ndarray):
350
+ original_height, original_width = image.shape[:2]
351
+ padded, ratio, pad = self._letterbox(image, (self.input_width, self.input_height))
352
+ blob = cv2.dnn.blobFromImage(padded, scalefactor=1 / 255.0, swapRB=True)
353
+ return blob, ratio, pad, (original_width, original_height)
354
+
355
+ @staticmethod
356
+ def _check_image(image: np.ndarray) -> np.ndarray:
357
+ if not isinstance(image, np.ndarray) or image.ndim != 3 or image.shape[2] != 3:
358
+ raise ValueError(f"expected HWC 3-channel image, got {getattr(image, 'shape', type(image))}")
359
+ return image if image.dtype == np.uint8 else image.astype(np.uint8)
360
+
361
+ @staticmethod
362
+ def _check_finite(tensor: np.ndarray, where: str) -> None:
363
+ if not np.isfinite(tensor).all():
364
+ raise InferenceInvariantError(
365
+ f"{where} must be finite everywhere: NaN={int(np.isnan(tensor).sum())} "
366
+ f"Inf={int(np.isinf(tensor).sum())}"
367
+ )
368
+
369
+ def _check_outputs(self, outputs: Any) -> np.ndarray:
370
+ if not isinstance(outputs, (list, tuple)) or len(outputs) != len(self.output_names):
371
+ raise ValueError(f"session returned invalid output list, expected {len(self.output_names)} tensors")
372
+ for name, tensor in zip(self.output_names, outputs):
373
+ if not isinstance(tensor, np.ndarray):
374
+ raise ValueError(f"model output {name!r} is not an ndarray")
375
+ if np.issubdtype(tensor.dtype, np.floating):
376
+ self._check_finite(tensor, f"model output {name!r}")
377
+ output = outputs[0]
378
+ if not np.issubdtype(output.dtype, np.floating) or list(output.shape) != [1, OUTPUT_ROWS, OUTPUT_COLUMNS]:
379
+ raise ValueError(
380
+ f"e2e output tensor must be float [1, {OUTPUT_ROWS}, {OUTPUT_COLUMNS}], "
381
+ f"got {output.dtype} {list(output.shape)}"
382
+ )
383
+ return output
384
+
385
+ def _decode_e2e(
386
+ self,
387
+ output: np.ndarray,
388
+ ratio: float,
389
+ pad: tuple[float, float],
390
+ original_size: tuple[int, int],
391
+ ) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
392
+ rows = output[0]
393
+ boxes = rows[:, :4].astype(np.float32, copy=True)
394
+ scores = rows[:, 4].astype(np.float32, copy=False)
395
+ raw_classes = rows[:, 5]
396
+ if (scores < 0).any() or (scores > 1).any():
397
+ raise InferenceInvariantError("e2e confidence outside [0, 1]")
398
+ rounded = np.rint(raw_classes)
399
+ if not np.array_equal(raw_classes, rounded):
400
+ raise InferenceInvariantError("e2e model class ids must be exact integers")
401
+ model_classes = rounded.astype(np.int64)
402
+ if (model_classes < 0).any() or (model_classes >= len(self.model_names)).any():
403
+ bad = model_classes[(model_classes < 0) | (model_classes >= len(self.model_names))]
404
+ raise InferenceInvariantError(f"e2e model class id outside range: {bad[:8].tolist()}")
405
+
406
+ active = scores > 0.0
407
+ reversed_rows = active & ((boxes[:, 2] < boxes[:, 0]) | (boxes[:, 3] < boxes[:, 1]))
408
+ if reversed_rows.any():
409
+ raise InferenceInvariantError(f"e2e output contains reversed boxes: {boxes[reversed_rows][:4].tolist()}")
410
+ mapped = np.fromiter((int(class_id) in self.model_to_element for class_id in model_classes), bool, len(rows))
411
+ keep = mapped & (scores >= np.float32(self.conf_threshold))
412
+ if not keep.any():
413
+ return (
414
+ np.empty((0, 4), np.float32),
415
+ np.empty((0,), np.float32),
416
+ np.empty((0,), np.int64),
417
+ )
418
+ boxes = boxes[keep]
419
+ scores = scores[keep]
420
+ model_classes = model_classes[keep]
421
+ element_classes = np.fromiter(
422
+ (self.model_to_element[int(class_id)] for class_id in model_classes),
423
+ dtype=np.int64,
424
+ count=len(model_classes),
425
+ )
426
+ boxes[:, [0, 2]] = (boxes[:, [0, 2]] - pad[0]) / ratio
427
+ boxes[:, [1, 3]] = (boxes[:, [1, 3]] - pad[1]) / ratio
428
+ width, height = original_size
429
+ boxes[:, [0, 2]] = np.clip(boxes[:, [0, 2]], 0, width - 1)
430
+ boxes[:, [1, 3]] = np.clip(boxes[:, [1, 3]], 0, height - 1)
431
+ self._check_decoded(boxes, scores, element_classes, original_size)
432
+
433
+ box_widths = boxes[:, 2] - boxes[:, 0]
434
+ box_heights = boxes[:, 3] - boxes[:, 1]
435
+ areas = box_widths * box_heights
436
+ image_area = float(width * height)
437
+ sane = (
438
+ (box_widths >= self.min_side)
439
+ & (box_heights >= self.min_side)
440
+ & (areas <= 0.95 * image_area)
441
+ & (
442
+ np.maximum(
443
+ box_widths / np.maximum(box_heights, 1e-6),
444
+ box_heights / np.maximum(box_widths, 1e-6),
445
+ )
446
+ <= self.max_aspect_ratio
447
+ )
448
+ )
449
+ boxes, scores, element_classes = boxes[sane], scores[sane], element_classes[sane]
450
+ if len(scores):
451
+ order = np.argsort(-scores, kind="stable")[: self.max_det]
452
+ boxes, scores, element_classes = boxes[order], scores[order], element_classes[order]
453
+ # Thresholds, model-name checks and all head semantics above stay in
454
+ # ``classes`` order. Only the validator-facing ids are remapped here.
455
+ if len(element_classes):
456
+ element_classes = np.asarray(self.config.output_cls_ids, dtype=np.int64)[element_classes]
457
+ return boxes, scores, element_classes
458
+
459
+ def _check_decoded(
460
+ self,
461
+ boxes: np.ndarray,
462
+ scores: np.ndarray,
463
+ class_ids: np.ndarray,
464
+ original_size: tuple[int, int],
465
+ ) -> None:
466
+ if not len(boxes):
467
+ return
468
+ width, height = original_size
469
+ if not np.isfinite(boxes).all():
470
+ raise InferenceInvariantError("decoded boxes contain non-finite coordinates")
471
+ if (boxes[:, 2] < boxes[:, 0]).any() or (boxes[:, 3] < boxes[:, 1]).any():
472
+ raise InferenceInvariantError("decoded boxes are reversed")
473
+ xs, ys = boxes[:, [0, 2]], boxes[:, [1, 3]]
474
+ if (xs < 0).any() or (xs > width - 1).any() or (ys < 0).any() or (ys > height - 1).any():
475
+ raise InferenceInvariantError(f"decoded boxes outside {width}x{height} image")
476
+ if not np.isfinite(scores).all() or (scores < 0).any() or (scores > 1).any():
477
+ raise InferenceInvariantError("decoded confidence outside [0, 1]")
478
+ if (class_ids < 0).any() or (class_ids >= len(self.class_names)).any():
479
+ raise InferenceInvariantError("decoded cls_id outside element class range")
480
+
481
+ @staticmethod
482
+ def _to_bounding_boxes(
483
+ boxes: np.ndarray,
484
+ scores: np.ndarray,
485
+ class_ids: np.ndarray,
486
+ ) -> list[BoundingBox]:
487
+ return [
488
+ BoundingBox(
489
+ x1=int(math.floor(box[0])), y1=int(math.floor(box[1])),
490
+ x2=int(math.ceil(box[2])), y2=int(math.ceil(box[3])),
491
+ cls_id=int(class_id), conf=float(score),
492
+ )
493
+ for box, score, class_id in zip(boxes, scores, class_ids)
494
+ if box[2] > box[0] and box[3] > box[1]
495
+ ]
496
+
497
+ def _predict_single(self, image: np.ndarray) -> list[BoundingBox]:
498
+ image = self._check_image(image)
499
+ blob, ratio, pad, original_size = self._preprocess(image)
500
+ outputs = self.session.run(self.output_names, {self.input_name: blob})
501
+ output = self._check_outputs(outputs)
502
+ arrays = self._decode_e2e(output, ratio, pad, original_size)
503
+ return self._to_bounding_boxes(*arrays)
504
+
505
+ def _warmup(self, iterations: int) -> None:
506
+ dummy = np.zeros((720, 1280, 3), dtype=np.uint8)
507
+ original_strict = self.strict_inference
508
+ self.strict_inference = True
509
+ try:
510
+ for _ in range(iterations):
511
+ self.predict_batch(batch_images=[dummy], offset=0, n_keypoints=0)
512
+ except Exception as exc:
513
+ raise RuntimeError(f"warmup failed, refusing to serve: {type(exc).__name__}: {exc}") from exc
514
+ finally:
515
+ self.strict_inference = original_strict
516
+
517
+ def _record_failure(self, frame_id: int, exc: Exception) -> None:
518
+ self.inference_failures += 1
519
+ invariant = isinstance(exc, InferenceInvariantError)
520
+ if invariant:
521
+ self.invariant_failures += 1
522
+ print(json.dumps({
523
+ "event": "inference_failure",
524
+ "frame_id": frame_id,
525
+ "error_type": type(exc).__name__,
526
+ "error": str(exc),
527
+ "invariant": invariant,
528
+ "inference_failures": self.inference_failures,
529
+ "invariant_failures": self.invariant_failures,
530
+ }, sort_keys=True))
531
+
532
+ def predict_batch(
533
+ self,
534
+ batch_images: list[np.ndarray],
535
+ offset: int,
536
+ n_keypoints: int,
537
+ ) -> list[TVFrameResult]:
538
+ _ = n_keypoints
539
+ results: list[TVFrameResult] = []
540
+ for index, image in enumerate(batch_images):
541
+ frame_id = offset + index
542
+ try:
543
+ boxes = self._predict_single(image)
544
+ except Exception as exc:
545
+ if self.strict_inference:
546
+ raise
547
+ self._record_failure(frame_id, exc)
548
+ boxes = []
549
+ results.append(TVFrameResult(frame_id=frame_id, boxes=boxes, keypoints=[]))
550
+ return results
551
+
552
+ def __repr__(self) -> str:
553
+ return (
554
+ f"E2EONNXRuntime(session={type(self.session).__name__}, "
555
+ f"providers={self.session.get_providers()})"
556
+ )