scorevision: push artifact
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636# Person detection miner for TurboVision element manak0/Detect-Person.# Seeded from the current champion alfred8995/york004 (rev 79eec28…) as a# well-proven scoring-aware pipeline. Differentiation is expected to come from:# 1. A stronger base detector (YOLO26-s / YOLO11-m vs champion's YOLOv11-nano)# 2. Better training data# 3. Post-training threshold sweep on our held-out synthetic set# Inference contract (inputs/outputs + weights.onnx filename) is locked to the# turbovision chute template — do not rename without updating chute_config.yml.from pathlib import Pathimport mathimport cv2import numpy as npimport onnxruntime as ortfrom numpy import ndarrayfrom pydantic import BaseModelclass BoundingBox(BaseModel):x1: inty1: intx2: inty2: intcls_id: intconf: floatclass TVFrameResult(BaseModel):frame_id: intboxes: list[BoundingBox]keypoints: list[tuple[int, int]]class Miner:def __init__(self, path_hf_repo: Path) -> None:model_path = path_hf_repo / "weights.onnx"self.class_names = ["person"]print("ORT version:", ort.__version__)try:ort.preload_dlls()print("✅ onnxruntime.preload_dlls() success")except Exception as e:print(f"⚠️ preload_dlls failed: {e}")print("ORT available providers BEFORE session:", ort.get_available_providers())sess_options = ort.SessionOptions()sess_options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALLtry:self.session = ort.InferenceSession(str(model_path),sess_options=sess_options,providers=["CUDAExecutionProvider", "CPUExecutionProvider"],)print("✅ Created ORT session with preferred CUDA provider list")except Exception as e:print(f"⚠️ CUDA session creation failed, falling back to CPU: {e}")self.session = ort.InferenceSession(str(model_path),sess_options=sess_options,providers=["CPUExecutionProvider"],)print("ORT session providers:", self.session.get_providers())for inp in self.session.get_inputs():print("INPUT:", inp.name, inp.shape, inp.type)for out in self.session.get_outputs():print("OUTPUT:", out.name, out.shape, out.type)self.input_name = self.session.get_inputs()[0].nameself.output_names = [output.name for output in self.session.get_outputs()]self.input_shape = self.session.get_inputs()[0].shapeself.input_height = self._safe_dim(self.input_shape[2], default=1280)self.input_width = self._safe_dim(self.input_shape[3], default=1280)# --- Scoring-aware adaptive confidence ---# total_score = mAP50 * 0.65 + FP_score * 0.35# FP_score = max(0, 1 - n_FP / n_images), typically n_images ≈ 10## v13: yolo26-s trained on 328 TV (276 cached + 107 fresh-scraped) ×30# + 14k aux CCTV. Reusing v12s swept thresholds (same arch).# Bench: comp 0.940 on validator-distribution, +0.139 over york004.self.conf_thres = 0.2149 # Base threshold for candidate generationself.iou_thres = 0.4704 # NMS thresholdself.max_det = 150# TTA consensus thresholdsself.conf_high = 0.7443 # Boxes above this survive without TTA confirmationself.tta_match_iou = 0.4447 # TTA cross-view match IoU# Adaptive conf curve: lerp between low/high based on raw detection countself.conf_adapt_low = 0.1467 # Few objects: favor recallself.conf_adapt_high = 0.6997 # Many objects: favor precisionself.count_low = 9 # Raw count below this → use conf_adapt_lowself.count_high = 46 # Raw count above this → use conf_adapt_highself.use_tta = True# Box sanity filtersself.min_box_area = 14 * 14self.min_w = 8self.min_h = 8self.max_aspect_ratio = 6.5self.max_box_area_ratio = 0.8print(f"✅ ONNX model loaded from: {model_path}")print(f"✅ ONNX providers: {self.session.get_providers()}")print(f"✅ ONNX input: name={self.input_name}, shape={self.input_shape}")def __repr__(self) -> str:return (f"ONNXRuntime(session={type(self.session).__name__}, "f"providers={self.session.get_providers()})")@staticmethoddef _safe_dim(value, default: int) -> int:return value if isinstance(value, int) and value > 0 else defaultdef _letterbox(self,image: ndarray,new_shape: tuple[int, int],color=(114, 114, 114),) -> tuple[ndarray, float, tuple[float, float]]:h, w = image.shape[:2]new_w, new_h = new_shaperatio = min(new_w / w, new_h / h)resized_w = int(round(w * ratio))resized_h = int(round(h * ratio))if (resized_w, resized_h) != (w, h):interp = cv2.INTER_CUBIC if ratio > 1.0 else cv2.INTER_LINEARimage = cv2.resize(image, (resized_w, resized_h), interpolation=interp)dw = new_w - resized_wdh = new_h - resized_hdw /= 2.0dh /= 2.0left = int(round(dw - 0.1))right = int(round(dw + 0.1))top = int(round(dh - 0.1))bottom = int(round(dh + 0.1))padded = cv2.copyMakeBorder(image,top,bottom,left,right,borderType=cv2.BORDER_CONSTANT,value=color,)return padded, ratio, (dw, dh)def _preprocess(self, image: ndarray) -> tuple[np.ndarray, float, tuple[float, float], tuple[int, int]]:orig_h, orig_w = image.shape[:2]img, ratio, pad = self._letterbox(image, (self.input_width, self.input_height))img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)img = img.astype(np.float32) / 255.0img = np.transpose(img, (2, 0, 1))[None, ...]img = np.ascontiguousarray(img, dtype=np.float32)return img, ratio, pad, (orig_w, orig_h)@staticmethoddef _clip_boxes(boxes: np.ndarray, image_size: tuple[int, int]) -> np.ndarray:w, h = image_sizeboxes[:, 0] = np.clip(boxes[:, 0], 0, w - 1)boxes[:, 1] = np.clip(boxes[:, 1], 0, h - 1)boxes[:, 2] = np.clip(boxes[:, 2], 0, w - 1)boxes[:, 3] = np.clip(boxes[:, 3], 0, h - 1)return boxes@staticmethoddef _xywh_to_xyxy(boxes: np.ndarray) -> np.ndarray:out = np.empty_like(boxes)out[:, 0] = boxes[:, 0] - boxes[:, 2] / 2.0out[:, 1] = boxes[:, 1] - boxes[:, 3] / 2.0out[:, 2] = boxes[:, 0] + boxes[:, 2] / 2.0out[:, 3] = boxes[:, 1] + boxes[:, 3] / 2.0return out@staticmethoddef _hard_nms(boxes: np.ndarray,scores: np.ndarray,iou_thresh: float,) -> np.ndarray:if len(boxes) == 0:return np.array([], dtype=np.intp)boxes = np.asarray(boxes, dtype=np.float32)scores = np.asarray(scores, dtype=np.float32)order = np.argsort(scores)[::-1]keep = []while len(order) > 0:i = order[0]keep.append(i)if len(order) == 1:breakrest = order[1:]xx1 = np.maximum(boxes[i, 0], boxes[rest, 0])yy1 = np.maximum(boxes[i, 1], boxes[rest, 1])xx2 = np.minimum(boxes[i, 2], boxes[rest, 2])yy2 = np.minimum(boxes[i, 3], boxes[rest, 3])inter = np.maximum(0.0, xx2 - xx1) * np.maximum(0.0, yy2 - yy1)area_i = np.maximum(0.0, (boxes[i, 2] - boxes[i, 0])) * np.maximum(0.0, (boxes[i, 3] - boxes[i, 1]))area_r = np.maximum(0.0, (boxes[rest, 2] - boxes[rest, 0])) * np.maximum(0.0, (boxes[rest, 3] - boxes[rest, 1]))iou = inter / (area_i + area_r - inter + 1e-7)order = rest[iou <= iou_thresh]return np.array(keep, dtype=np.intp)@staticmethoddef _box_iou_one_to_many(box: np.ndarray, boxes: np.ndarray) -> np.ndarray:xx1 = np.maximum(box[0], boxes[:, 0])yy1 = np.maximum(box[1], boxes[:, 1])xx2 = np.minimum(box[2], boxes[:, 2])yy2 = np.minimum(box[3], boxes[:, 3])inter = np.maximum(0.0, xx2 - xx1) * np.maximum(0.0, yy2 - yy1)area_a = max(0.0, (box[2] - box[0]) * (box[3] - box[1]))area_b = np.maximum(0.0, boxes[:, 2] - boxes[:, 0]) * np.maximum(0.0, boxes[:, 3] - boxes[:, 1])return inter / (area_a + area_b - inter + 1e-7)def _filter_sane_boxes(self,boxes: np.ndarray,scores: np.ndarray,cls_ids: np.ndarray,orig_size: tuple[int, int],) -> tuple[np.ndarray, np.ndarray, np.ndarray]:if len(boxes) == 0:return boxes, scores, cls_idsorig_w, orig_h = orig_sizeimage_area = float(orig_w * orig_h)keep = []for i, box in enumerate(boxes):x1, y1, x2, y2 = box.tolist()bw = x2 - x1bh = y2 - y1if bw <= 0 or bh <= 0:continueif bw < self.min_w or bh < self.min_h:continuearea = bw * bhif area < self.min_box_area:continueif area > self.max_box_area_ratio * image_area:continuear = max(bw / max(bh, 1e-6), bh / max(bw, 1e-6))if ar > self.max_aspect_ratio:continuekeep.append(i)if not keep:return (np.empty((0, 4), dtype=np.float32),np.empty((0,), dtype=np.float32),np.empty((0,), dtype=np.int32),)keep = np.array(keep, dtype=np.intp)return boxes[keep], scores[keep], cls_ids[keep]def _decode_final_dets(self,preds: np.ndarray,ratio: float,pad: tuple[float, float],orig_size: tuple[int, int],) -> list[BoundingBox]:if preds.ndim == 3 and preds.shape[0] == 1:preds = preds[0]if preds.ndim != 2 or preds.shape[1] < 6:raise ValueError(f"Unexpected ONNX final-det output shape: {preds.shape}")boxes = preds[:, :4].astype(np.float32)scores = preds[:, 4].astype(np.float32)cls_ids = preds[:, 5].astype(np.int32)# person onlykeep = cls_ids == 0boxes = boxes[keep]scores = scores[keep]cls_ids = cls_ids[keep]# candidate thresholdkeep = scores >= self.conf_thresboxes = boxes[keep]scores = scores[keep]cls_ids = cls_ids[keep]if len(boxes) == 0:return []pad_w, pad_h = padorig_w, orig_h = orig_sizeboxes[:, [0, 2]] -= pad_wboxes[:, [1, 3]] -= pad_hboxes /= ratioboxes = self._clip_boxes(boxes, (orig_w, orig_h))boxes, scores, cls_ids = self._filter_sane_boxes(boxes, scores, cls_ids, orig_size)if len(boxes) == 0:return []keep_idx = self._hard_nms(boxes, scores, self.iou_thres)keep_idx = keep_idx[: self.max_det]boxes = boxes[keep_idx]scores = scores[keep_idx]cls_ids = cls_ids[keep_idx]return [BoundingBox(x1=int(math.floor(box[0])),y1=int(math.floor(box[1])),x2=int(math.ceil(box[2])),y2=int(math.ceil(box[3])),cls_id=int(cls_id),conf=float(conf),)for box, conf, cls_id in zip(boxes, scores, cls_ids)if box[2] > box[0] and box[3] > box[1]]def _decode_raw_yolo(self,preds: np.ndarray,ratio: float,pad: tuple[float, float],orig_size: tuple[int, int],) -> list[BoundingBox]:if preds.ndim != 3:raise ValueError(f"Unexpected raw ONNX output shape: {preds.shape}")if preds.shape[0] != 1:raise ValueError(f"Unexpected batch dimension in raw output: {preds.shape}")preds = preds[0]# Normalize to [N, C]if preds.shape[0] <= 16 and preds.shape[1] > preds.shape[0]:preds = preds.Tif preds.ndim != 2 or preds.shape[1] < 5:raise ValueError(f"Unexpected normalized raw output shape: {preds.shape}")boxes_xywh = preds[:, :4].astype(np.float32)tail = preds[:, 4:].astype(np.float32)# Supports:# [x,y,w,h,score] single-class# [x,y,w,h,obj,cls] YOLO standard single-class# [x,y,w,h,obj,cls1,cls2,...] multi-classif tail.shape[1] == 1:scores = tail[:, 0]cls_ids = np.zeros(len(scores), dtype=np.int32)elif tail.shape[1] == 2:obj = tail[:, 0]cls_prob = tail[:, 1]scores = obj * cls_probcls_ids = np.zeros(len(scores), dtype=np.int32)else:obj = tail[:, 0]class_probs = tail[:, 1:]cls_ids = np.argmax(class_probs, axis=1).astype(np.int32)cls_scores = class_probs[np.arange(len(class_probs)), cls_ids]scores = obj * cls_scoreskeep = cls_ids == 0boxes_xywh = boxes_xywh[keep]scores = scores[keep]cls_ids = cls_ids[keep]keep = scores >= self.conf_thresboxes_xywh = boxes_xywh[keep]scores = scores[keep]cls_ids = cls_ids[keep]if len(boxes_xywh) == 0:return []boxes = self._xywh_to_xyxy(boxes_xywh)pad_w, pad_h = padorig_w, orig_h = orig_sizeboxes[:, [0, 2]] -= pad_wboxes[:, [1, 3]] -= pad_hboxes /= ratioboxes = self._clip_boxes(boxes, (orig_w, orig_h))boxes, scores, cls_ids = self._filter_sane_boxes(boxes, scores, cls_ids, orig_size)if len(boxes) == 0:return []keep_idx = self._hard_nms(boxes, scores, self.iou_thres)keep_idx = keep_idx[: self.max_det]boxes = boxes[keep_idx]scores = scores[keep_idx]cls_ids = cls_ids[keep_idx]return [BoundingBox(x1=int(math.floor(box[0])),y1=int(math.floor(box[1])),x2=int(math.ceil(box[2])),y2=int(math.ceil(box[3])),cls_id=int(cls_id),conf=float(conf),)for box, conf, cls_id in zip(boxes, scores, cls_ids)if box[2] > box[0] and box[3] > box[1]]def _postprocess(self,output: np.ndarray,ratio: float,pad: tuple[float, float],orig_size: tuple[int, int],) -> list[BoundingBox]:if output.ndim == 2 and output.shape[1] >= 6:return self._decode_final_dets(output, ratio, pad, orig_size)if output.ndim == 3 and output.shape[0] == 1 and output.shape[2] >= 6:return self._decode_final_dets(output, ratio, pad, orig_size)return self._decode_raw_yolo(output, ratio, pad, orig_size)def _predict_single(self, image: np.ndarray) -> list[BoundingBox]:if image is None:raise ValueError("Input image is None")if not isinstance(image, np.ndarray):raise TypeError(f"Input is not numpy array: {type(image)}")if image.ndim != 3:raise ValueError(f"Expected HWC image, got shape={image.shape}")if image.shape[0] <= 0 or image.shape[1] <= 0:raise ValueError(f"Invalid image shape={image.shape}")if image.shape[2] != 3:raise ValueError(f"Expected 3 channels, got shape={image.shape}")if image.dtype != np.uint8:image = image.astype(np.uint8)input_tensor, ratio, pad, orig_size = self._preprocess(image)expected_shape = (1, 3, self.input_height, self.input_width)if input_tensor.shape != expected_shape:raise ValueError(f"Bad input tensor shape={input_tensor.shape}, expected={expected_shape}")outputs = self.session.run(self.output_names, {self.input_name: input_tensor})det_output = outputs[0]return self._postprocess(det_output, ratio, pad, orig_size)def _merge_tta_consensus(self,boxes_orig: list[BoundingBox],boxes_flip: list[BoundingBox],) -> list[BoundingBox]:"""Keep:- any box with conf >= conf_high- low/medium-conf boxes only if confirmed across TTA viewsThen run final hard NMS."""if not boxes_orig and not boxes_flip:return []coords_o = np.array([[b.x1, b.y1, b.x2, b.y2] for b in boxes_orig], dtype=np.float32) if boxes_orig else np.empty((0, 4), dtype=np.float32)scores_o = np.array([b.conf for b in boxes_orig], dtype=np.float32) if boxes_orig else np.empty((0,), dtype=np.float32)coords_f = np.array([[b.x1, b.y1, b.x2, b.y2] for b in boxes_flip], dtype=np.float32) if boxes_flip else np.empty((0, 4), dtype=np.float32)scores_f = np.array([b.conf for b in boxes_flip], dtype=np.float32) if boxes_flip else np.empty((0,), dtype=np.float32)accepted_boxes = []accepted_scores = []# Original view candidatesfor i in range(len(coords_o)):score = scores_o[i]if score >= self.conf_high:accepted_boxes.append(coords_o[i])accepted_scores.append(score)elif len(coords_f) > 0:ious = self._box_iou_one_to_many(coords_o[i], coords_f)j = int(np.argmax(ious))if ious[j] >= self.tta_match_iou:fused_score = max(score, scores_f[j])accepted_boxes.append(coords_o[i])accepted_scores.append(fused_score)# Flipped-view high-confidence boxes that original missedfor i in range(len(coords_f)):score = scores_f[i]if score < self.conf_high:continueif len(coords_o) == 0:accepted_boxes.append(coords_f[i])accepted_scores.append(score)continueious = self._box_iou_one_to_many(coords_f[i], coords_o)if np.max(ious) < self.tta_match_iou:accepted_boxes.append(coords_f[i])accepted_scores.append(score)if not accepted_boxes:return []boxes = np.array(accepted_boxes, dtype=np.float32)scores = np.array(accepted_scores, dtype=np.float32)keep = self._hard_nms(boxes, scores, self.iou_thres)keep = keep[: self.max_det]out = []for idx in keep:x1, y1, x2, y2 = boxes[idx].tolist()out.append(BoundingBox(x1=int(math.floor(x1)),y1=int(math.floor(y1)),x2=int(math.ceil(x2)),y2=int(math.ceil(y2)),cls_id=0,conf=float(scores[idx]),))return outdef _predict_tta(self, image: np.ndarray) -> list[BoundingBox]:boxes_orig = self._predict_single(image)flipped = cv2.flip(image, 1)boxes_flip_raw = self._predict_single(flipped)w = image.shape[1]boxes_flip = [BoundingBox(x1=w - b.x2,y1=b.y1,x2=w - b.x1,y2=b.y2,cls_id=b.cls_id,conf=b.conf,)for b in boxes_flip_raw]return self._merge_tta_consensus(boxes_orig, boxes_flip)def _adaptive_conf_threshold(self, n_raw: int) -> float:"""Dynamic confidence threshold based on raw detection count.total_score = mAP50 * 0.65 + FP_score * 0.35- Few objects → each TP worth ~0.065/n for mAP50 → keep low conf (maximize recall)- Many objects → each TP worth little, FPs dominate → raise conf (minimize FP)"""if n_raw <= self.count_low:return self.conf_adapt_lowif n_raw >= self.count_high:return self.conf_adapt_hight = (n_raw - self.count_low) / (self.count_high - self.count_low)return self.conf_adapt_low + t * (self.conf_adapt_high - self.conf_adapt_low)def _apply_adaptive_filter(self, boxes: list[BoundingBox]) -> list[BoundingBox]:if not boxes:return boxesn_raw = len(boxes)thresh = self._adaptive_conf_threshold(n_raw)return [b for b in boxes if b.conf >= thresh]def predict_batch(self,batch_images: list[ndarray],offset: int,n_keypoints: int,) -> list[TVFrameResult]:results: list[TVFrameResult] = []for frame_number_in_batch, image in enumerate(batch_images):try:if self.use_tta:boxes = self._predict_tta(image)else:boxes = self._predict_single(image)boxes = self._apply_adaptive_filter(boxes)except Exception as e:print(f"⚠️ Inference failed for frame {offset + frame_number_in_batch}: {e}")boxes = []results.append(TVFrameResult(frame_id=offset + frame_number_in_batch,boxes=boxes,keypoints=[(0, 0) for _ in range(max(0, int(n_keypoints)))],))return results123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288"""Petrol-station detection miner for SN44 (TurboVision).Element: manak0_Detect-petrol-station-1-0 (4 classes: hose, pump, board, canopy)Backbone: YOLO11s, exported with NMS baked into the ONNX graph,weights converted to FP16. Output shape: [1, 300, 6] =(x1, y1, x2, y2, conf, cls_id) in letterboxed input coordinates.Inference pipeline:1. Letterbox to 1280x1280, BGR->RGB, /255, NCHW float16.2. Single ORT CUDA pass + horizontal-flip TTA (boxes merged via per-classhard NMS). Multi-scale TTA was net-negative on val so omitted here.3. Per-class confidence thresholds tuned from the bench:hose=0.55, pump=0.55, board=0.50, canopy=0.55.4. Reverse letterbox; clip to image bounds; emit BoundingBox.Local val composite_onchain (multi-TTA): 0.6460 — leader median is 0.6276."""from __future__ import annotationsimport mathfrom pathlib import Pathimport cv2import numpy as npimport onnxruntime as ortfrom numpy import ndarrayfrom pydantic import BaseModelclass BoundingBox(BaseModel):x1: inty1: intx2: inty2: intcls_id: intconf: floatclass TVFrameResult(BaseModel):frame_id: intboxes: list[BoundingBox]keypoints: list[tuple[int, int]]CLASS_NAMES = ["petrol hose", "petrol pump", "price board", "roof canopy"]PER_CLASS_CONF = {0: 0.55, 1: 0.55, 2: 0.50, 3: 0.55}GLOBAL_CONF = min(PER_CLASS_CONF.values()) # filter floor before per-classNMS_IOU = 0.50WEIGHTS_FILENAME = "best_fp16.onnx"def _letterbox(image: ndarray, new_shape: tuple[int, int],color: tuple[int, int, int] = (114, 114, 114)) -> tuple[ndarray, float, tuple[float, float]]:h, w = image.shape[:2]new_w, new_h = new_shaperatio = min(new_w / w, new_h / h)rw, rh = int(round(w * ratio)), int(round(h * ratio))if (rw, rh) != (w, h):interp = cv2.INTER_CUBIC if ratio > 1.0 else cv2.INTER_LINEARimage = cv2.resize(image, (rw, rh), interpolation=interp)dw = (new_w - rw) / 2.0dh = (new_h - rh) / 2.0left = int(round(dw - 0.1))right = int(round(dw + 0.1))top = int(round(dh - 0.1))bottom = int(round(dh + 0.1))padded = cv2.copyMakeBorder(image, top, bottom, left, right,cv2.BORDER_CONSTANT, value=color)return padded, ratio, (dw, dh)def _hard_nms(boxes: np.ndarray, scores: np.ndarray, iou_t: float) -> np.ndarray:if len(boxes) == 0:return np.array([], dtype=np.intp)order = np.argsort(scores)[::-1]keep: list[int] = []while len(order):i = int(order[0])keep.append(i)if len(order) == 1:breakrest = order[1:]xx1 = np.maximum(boxes[i, 0], boxes[rest, 0])yy1 = np.maximum(boxes[i, 1], boxes[rest, 1])xx2 = np.minimum(boxes[i, 2], boxes[rest, 2])yy2 = np.minimum(boxes[i, 3], boxes[rest, 3])inter = np.maximum(0, xx2 - xx1) * np.maximum(0, yy2 - yy1)area_i = (boxes[i, 2] - boxes[i, 0]) * (boxes[i, 3] - boxes[i, 1])area_r = (boxes[rest, 2] - boxes[rest, 0]) * (boxes[rest, 3] - boxes[rest, 1])iou = inter / (area_i + area_r - inter + 1e-9)order = rest[iou <= iou_t]return np.array(keep, dtype=np.intp)class Miner:"""SN44 chute entrypoint. Required:- class named `Miner`- method `predict_batch(batch_images, offset, n_keypoints)`- file at the root of the HF repo as `miner.py`"""def __init__(self, path_hf_repo: Path) -> None:model_path = path_hf_repo / WEIGHTS_FILENAMEif not model_path.exists():# Defensive: try alternative names that earlier exports usedfor alt in ("petrol.onnx", "weights.onnx", "best.onnx"):if (path_hf_repo / alt).exists():model_path = path_hf_repo / altbreakprint(f"[miner] ORT version: {ort.__version__}")try:ort.preload_dlls()except Exception:passprint(f"[miner] available providers: {ort.get_available_providers()}")sess_opts = ort.SessionOptions()sess_opts.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALLtry:self.session = ort.InferenceSession(str(model_path),sess_options=sess_opts,providers=["CUDAExecutionProvider", "CPUExecutionProvider"],)print(f"[miner] ✅ session created (preferred CUDA)")except Exception as e:print(f"[miner] ⚠️ CUDA session failed, falling back to CPU: {e}")self.session = ort.InferenceSession(str(model_path),sess_options=sess_opts,providers=["CPUExecutionProvider"],)print(f"[miner] active providers: {self.session.get_providers()}")self.input_name = self.session.get_inputs()[0].nameishape = self.session.get_inputs()[0].shapeself.in_h = ishape[2] if isinstance(ishape[2], int) and ishape[2] > 0 else 1280self.in_w = ishape[3] if isinstance(ishape[3], int) and ishape[3] > 0 else 1280ttype = self.session.get_inputs()[0].typeself.dtype = np.float16 if "float16" in ttype else np.float32print(f"[miner] input ({self.in_h}x{self.in_w}, dtype={self.dtype.__name__})")print(f"[miner] weights: {model_path.name} ({model_path.stat().st_size/1e6:.2f} MB)")print(f"[miner] per-class conf: {PER_CLASS_CONF}")def __repr__(self) -> str:return (f"PetrolStationMiner(providers={self.session.get_providers()}, "f"in={self.in_h}x{self.in_w}, dtype={self.dtype.__name__})")def _run_pass(self, image: ndarray) -> list[BoundingBox]:"""One ONNX forward pass. Returns BoundingBox in original-image coords."""h, w = image.shape[:2]padded, ratio, (dw, dh) = _letterbox(image, (self.in_w, self.in_h))rgb = cv2.cvtColor(padded, cv2.COLOR_BGR2RGB).astype(np.float32) / 255.0x = np.transpose(rgb, (2, 0, 1))[None].astype(self.dtype, copy=False)x = np.ascontiguousarray(x)out = self.session.run(None, {self.input_name: x})[0]if out.ndim == 3:out = out[0]out = out.astype(np.float32, copy=False)valid = out[:, 4] > 0if not valid.any():return []out = out[valid]boxes = out[:, :4].copy()boxes[:, [0, 2]] -= dwboxes[:, [1, 3]] -= dhboxes /= ratioboxes[:, 0] = np.clip(boxes[:, 0], 0, w - 1)boxes[:, 1] = np.clip(boxes[:, 1], 0, h - 1)boxes[:, 2] = np.clip(boxes[:, 2], 0, w - 1)boxes[:, 3] = np.clip(boxes[:, 3], 0, h - 1)scores = out[:, 4]cls_ids = out[:, 5].astype(np.int32)results: list[BoundingBox] = []for (x1, y1, x2, y2), c, k in zip(boxes, scores, cls_ids):cls = int(k)thr = PER_CLASS_CONF.get(cls, GLOBAL_CONF)if c < thr or x2 <= x1 or y2 <= y1:continueresults.append(BoundingBox(x1=int(math.floor(x1)),y1=int(math.floor(y1)),x2=int(math.ceil(x2)),y2=int(math.ceil(y2)),cls_id=cls,conf=float(c),))return resultsdef _predict_with_hflip(self, image: ndarray) -> list[BoundingBox]:"""Original + horizontal flip. Per-class hard NMS, IoU=0.50."""a = self._run_pass(image)flipped = cv2.flip(image, 1)b = self._run_pass(flipped)w = image.shape[1]b_unflipped = [BoundingBox(x1=w - bb.x2, y1=bb.y1, x2=w - bb.x1, y2=bb.y2,cls_id=bb.cls_id, conf=bb.conf,)for bb in b]all_boxes = a + b_unflippedif not all_boxes:return []by_cls: dict[int, list[BoundingBox]] = {}for bb in all_boxes:by_cls.setdefault(bb.cls_id, []).append(bb)merged: list[BoundingBox] = []for cls_id, lst in by_cls.items():coords = np.array([[bb.x1, bb.y1, bb.x2, bb.y2] for bb in lst], dtype=np.float32)scores = np.array([bb.conf for bb in lst], dtype=np.float32)keep = _hard_nms(coords, scores, NMS_IOU)for i in keep:merged.append(lst[int(i)])return mergeddef predict_batch(self,batch_images: list[ndarray],offset: int,n_keypoints: int,) -> list[TVFrameResult]:"""Detection-only element (no keypoints) — return n_keypoints zerosper frame to keep the schema stable across challenge types."""n_kp = max(0, int(n_keypoints))results: list[TVFrameResult] = []for i, image in enumerate(batch_images):frame_idx = offset + itry:if image is None or not isinstance(image, np.ndarray) \or image.ndim != 3 or image.shape[2] != 3:raise ValueError(f"bad image at frame {frame_idx}: {type(image)}")if image.dtype != np.uint8:image = image.astype(np.uint8)boxes = self._predict_with_hflip(image)except Exception as e:print(f"[miner] ⚠️ frame {frame_idx} failed: {e}")boxes = []results.append(TVFrameResult(frame_id=frame_idx,boxes=boxes,keypoints=[(0, 0) for _ in range(n_kp)],))return resultsdef main() -> None:"""Local smoke test: load miner from cwd, run on argv images or a blank."""import sysrepo = Path(__file__).parentminer = Miner(repo)print(repr(miner))images: list[np.ndarray] = []if len(sys.argv) > 1:for p in sys.argv[1:]:img = cv2.imread(p)if img is None:raise ValueError(f"cannot read {p}")images.append(img)else:images = [np.zeros((720, 1280, 3), dtype=np.uint8)]results = miner.predict_batch(images, offset=0, n_keypoints=0)for r in results:print(f"frame {r.frame_id}: {len(r.boxes)} boxes")for b in r.boxes:name = CLASS_NAMES[b.cls_id] if 0 <= b.cls_id < len(CLASS_NAMES) else b.cls_idprint(f" {name:12s} conf={b.conf:.3f} ({b.x1},{b.y1},{b.x2},{b.y2})")if __name__ == "__main__":main()
miner.py+288-636