scorevision: push artifact
Browse files
miner.py
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""SN44 TurboVision public-track miner for a raw YOLO head (the owner's element_trainer baselines: YOLO11n, detect or
|
| 2 |
+
seg, output [1, 4 + NC (+ mask coefficients), N]), decoded exactly as the owner's own baseline miner decodes it.
|
| 3 |
+
|
| 4 |
+
The validator hands predict_batch OpenCV BGR uint8 frames. Each frame is converted to RGB, resized (plain stretch, no
|
| 5 |
+
letterbox) to the model's input size, scaled to 0..1, and run on the CPU with 2 threads. Per anchor: the arg-max of the
|
| 6 |
+
NC class scores (mask coefficients ignored), kept when it reaches CONF; one class-agnostic greedy NMS at IOU over all
|
| 7 |
+
kept boxes; boxes mapped back by the stretch factors, floored / ceiled to whole pixels and clipped to the frame.
|
| 8 |
+
CLASS_MAP maps the model's classes to the element's `objects` indices (-1 drops a class; empty: the same order).
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
import math
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
|
| 14 |
+
import cv2
|
| 15 |
+
import numpy as np
|
| 16 |
+
import onnxruntime as ort
|
| 17 |
+
from numpy import ndarray
|
| 18 |
+
from pydantic import BaseModel
|
| 19 |
+
|
| 20 |
+
MODEL_FILE = "model.onnx"
|
| 21 |
+
NC = 5
|
| 22 |
+
CONF = 0.25
|
| 23 |
+
IOU = 0.45
|
| 24 |
+
THREADS = 2
|
| 25 |
+
CLASS_MAP = ()
|
| 26 |
+
WARMUP_RUNS = 3
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class BoundingBox(BaseModel):
|
| 30 |
+
x1: int
|
| 31 |
+
y1: int
|
| 32 |
+
x2: int
|
| 33 |
+
y2: int
|
| 34 |
+
cls_id: int
|
| 35 |
+
conf: float
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class Polygon(BaseModel):
|
| 39 |
+
cls_id: int
|
| 40 |
+
conf: float
|
| 41 |
+
points: list[tuple[int, int]]
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class TVFrameResult(BaseModel):
|
| 45 |
+
frame_id: int
|
| 46 |
+
boxes: list[BoundingBox] | None = None
|
| 47 |
+
polygons: list[Polygon] | None = None
|
| 48 |
+
keypoints: list[tuple[int, int]] | None = None
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def _as_bgr(img) -> ndarray:
|
| 52 |
+
if not isinstance(img, np.ndarray) or img.ndim not in (2, 3) or img.size == 0:
|
| 53 |
+
raise ValueError(f"unsupported frame: {type(img).__name__} {getattr(img, 'shape', None)}")
|
| 54 |
+
if img.dtype != np.uint8:
|
| 55 |
+
img = np.clip(np.nan_to_num(img), 0, 255).astype(np.uint8)
|
| 56 |
+
if img.ndim == 2 or img.shape[2] == 1:
|
| 57 |
+
return cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
|
| 58 |
+
if img.shape[2] == 4:
|
| 59 |
+
return cv2.cvtColor(img, cv2.COLOR_BGRA2BGR)
|
| 60 |
+
return img
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def _nms(boxes: ndarray, scores: ndarray, iou_thr: float) -> list[int]:
|
| 64 |
+
order = scores.argsort()[::-1]
|
| 65 |
+
keep = []
|
| 66 |
+
while order.size > 0:
|
| 67 |
+
i = order[0]
|
| 68 |
+
keep.append(int(i))
|
| 69 |
+
rest = order[1:]
|
| 70 |
+
xx1 = np.maximum(boxes[i, 0], boxes[rest, 0])
|
| 71 |
+
yy1 = np.maximum(boxes[i, 1], boxes[rest, 1])
|
| 72 |
+
xx2 = np.minimum(boxes[i, 2], boxes[rest, 2])
|
| 73 |
+
yy2 = np.minimum(boxes[i, 3], boxes[rest, 3])
|
| 74 |
+
inter = np.maximum(0.0, xx2 - xx1) * np.maximum(0.0, yy2 - yy1)
|
| 75 |
+
area_i = (boxes[i, 2] - boxes[i, 0]) * (boxes[i, 3] - boxes[i, 1])
|
| 76 |
+
area_r = (boxes[rest, 2] - boxes[rest, 0]) * (boxes[rest, 3] - boxes[rest, 1])
|
| 77 |
+
iou = inter / np.maximum(area_i + area_r - inter, 1e-6)
|
| 78 |
+
order = rest[np.where(iou <= iou_thr)[0]]
|
| 79 |
+
return keep
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
class Miner:
|
| 83 |
+
def __init__(self, path_hf_repo: Path) -> None:
|
| 84 |
+
so = ort.SessionOptions()
|
| 85 |
+
so.intra_op_num_threads = THREADS
|
| 86 |
+
so.inter_op_num_threads = 1
|
| 87 |
+
so.execution_mode = ort.ExecutionMode.ORT_SEQUENTIAL
|
| 88 |
+
so.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
|
| 89 |
+
so.add_session_config_entry("session.intra_op.allow_spinning", "0")
|
| 90 |
+
cv2.setNumThreads(1)
|
| 91 |
+
self.session = ort.InferenceSession(str(Path(path_hf_repo) / MODEL_FILE), sess_options=so,
|
| 92 |
+
providers=["CPUExecutionProvider"])
|
| 93 |
+
inp = self.session.get_inputs()[0]
|
| 94 |
+
self.input_name = inp.name
|
| 95 |
+
self.in_h, self.in_w = int(inp.shape[2]), int(inp.shape[3])
|
| 96 |
+
dummy = np.zeros((1024, 1024, 3), np.uint8)
|
| 97 |
+
for _ in range(WARMUP_RUNS):
|
| 98 |
+
self._frame_boxes(dummy)
|
| 99 |
+
|
| 100 |
+
def __repr__(self) -> str:
|
| 101 |
+
return f"{MODEL_FILE} @ {self.in_w}x{self.in_h} stretch, CPU {THREADS} threads, conf {CONF}, agnostic NMS {IOU}"
|
| 102 |
+
|
| 103 |
+
def _frame_boxes(self, img) -> list[BoundingBox]:
|
| 104 |
+
img = _as_bgr(img)
|
| 105 |
+
h, w = img.shape[:2]
|
| 106 |
+
rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
|
| 107 |
+
x = cv2.resize(rgb, (self.in_w, self.in_h)).astype(np.float32) / 255.0
|
| 108 |
+
x = np.ascontiguousarray(np.transpose(x, (2, 0, 1))[None])
|
| 109 |
+
pred = self.session.run(None, {self.input_name: x})[0][0]
|
| 110 |
+
if pred.shape[0] < pred.shape[1]:
|
| 111 |
+
pred = pred.T
|
| 112 |
+
scores = pred[:, 4:4 + NC]
|
| 113 |
+
cls = scores.argmax(1)
|
| 114 |
+
conf = scores.max(1)
|
| 115 |
+
m = np.isfinite(pred[:, :4]).all(1) & (conf >= CONF)
|
| 116 |
+
b, cls, conf = pred[m, :4], cls[m], conf[m]
|
| 117 |
+
if b.shape[0] == 0:
|
| 118 |
+
return []
|
| 119 |
+
sx, sy = w / float(self.in_w), h / float(self.in_h)
|
| 120 |
+
xyxy = np.stack([(b[:, 0] - b[:, 2] / 2) * sx, (b[:, 1] - b[:, 3] / 2) * sy,
|
| 121 |
+
(b[:, 0] + b[:, 2] / 2) * sx, (b[:, 1] + b[:, 3] / 2) * sy], 1)
|
| 122 |
+
boxes = []
|
| 123 |
+
for i in _nms(xyxy, conf, IOU):
|
| 124 |
+
c = int(cls[i])
|
| 125 |
+
if CLASS_MAP:
|
| 126 |
+
if c >= len(CLASS_MAP) or CLASS_MAP[c] < 0:
|
| 127 |
+
continue
|
| 128 |
+
c = CLASS_MAP[c]
|
| 129 |
+
x1, y1, x2, y2 = xyxy[i]
|
| 130 |
+
ix1, iy1 = max(0, min(w, math.floor(x1))), max(0, min(h, math.floor(y1)))
|
| 131 |
+
ix2, iy2 = max(0, min(w, math.ceil(x2))), max(0, min(h, math.ceil(y2)))
|
| 132 |
+
if ix2 - ix1 < 1 or iy2 - iy1 < 1:
|
| 133 |
+
continue
|
| 134 |
+
boxes.append(BoundingBox(x1=ix1, y1=iy1, x2=ix2, y2=iy2, cls_id=c, conf=float(max(0.0, min(1.0, conf[i])))))
|
| 135 |
+
return boxes
|
| 136 |
+
|
| 137 |
+
def predict_batch(self, batch_images: list[ndarray], offset: int, n_keypoints: int) -> list[TVFrameResult]:
|
| 138 |
+
results: list[TVFrameResult] = []
|
| 139 |
+
for i, img in enumerate(batch_images):
|
| 140 |
+
try:
|
| 141 |
+
boxes = self._frame_boxes(img)
|
| 142 |
+
except Exception as exc: # one bad frame must not fail the whole challenge
|
| 143 |
+
print(f"inference_failure frame {offset + i}: {type(exc).__name__}: {exc}")
|
| 144 |
+
boxes = []
|
| 145 |
+
results.append(TVFrameResult(frame_id=offset + i, boxes=boxes, polygons=[],
|
| 146 |
+
keypoints=[(0, 0)] * int(n_keypoints) if n_keypoints else []))
|
| 147 |
+
return results
|