scorevision: push artifact
Browse files1234567891011121314151617181920212220 unmodified lines434445464748495051525354555657585960616263646566676869707172737475767778798081828384851 unmodified line878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591 unmodified line161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605"""TurboVision crime-detection miner.YOLO11s @ 1280x1280, 6-class detection (balaclava, bat, glove, graffiti, hoodie,spray paint), ONNX with end-to-end NMS baked in.Output of weights.onnx: [1, 300, 6] = x1, y1, x2, y2, conf, cls (post-NMS).Inference pipeline:1) Primary forward pass on the full image.2) Hflip TTA: forward on horizontally-flipped image, transform boxes back.3) Per-class hard-NMS to merge primary + flip outputs.4) Cross-class IoU dedup (suppresses same physical object getting two class labels).5) Consensus-confidence boost: when both views agree on a cluster, take max score.6) Sanity filter (min size, aspect ratio).Class taxonomy (must match the validator manifest's `objects` list for this element):0 balaclava 1 bat 2 glove 3 graffiti 4 hoodie 5 spray paint"""from pathlib import Pathimport math20 unmodified linesclass Miner:def __init__(self, path_hf_repo: Path) -> None:model_path = path_hf_repo / "weights.onnx"# Validator manifest order (from spec.json `objects`):# 0=balaclava 1=hoodie 2=glove 3=bat 4="spray paint" 5=graffiti# v5 weights.onnx was trained with this exact order, so cls_remap is identity.cn_path = model_path.with_name("class_names.txt")if cn_path.is_file():self.class_names = [ln.strip()for ln in cn_path.read_text(encoding="utf-8").splitlines()if ln.strip() and not ln.strip().startswith("#")]else:self.class_names = ["balaclava", "hoodie", "glove", "bat", "spray paint", "graffiti"]self.cls_remap = np.arange(len(self.class_names), dtype=np.int32)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,1 unmodified line)print("ORT session providers:", self.session.get_providers())inp = self.session.get_inputs()[0]self.input_name = inp.nameself.output_names = [o.name for o in self.session.get_outputs()]self.input_shape = inp.shapeself.input_dtype = np.float16 if "float16" in inp.type else np.float32self.input_height = self._safe_dim(self.input_shape[2], default=1280)self.input_width = self._safe_dim(self.input_shape[3], default=1280)# Tuning matched to alfred's deployed model — bias toward precision to dodge# the false_positive pillar penalty (validator weights FP heavily on this element).# v13 sweet spot on starter (true GT): uniform conf=0.50.# Tuning per-class on 7 images overfits — leave-one-out CV showed it# collapsed to 0.314 on held-out shards. Uniform 0.50 is robust.self.conf_thres = 0.50self.conf_thres_per_class = np.array([0.50] * 6, dtype=np.float32)self.iou_thres = 0.4self.cross_iou_thresh = 0.7self.max_det = 100self.use_tta = False# Sanity filter — reject obviously bad boxesself.min_box_area = 14 * 14self.min_side = 8self.max_aspect_ratio = 8.0self.max_box_area_ratio = 0.95print(f"✅ ONNX loaded: {model_path}")print(f"✅ providers: {self.session.get_providers()}")print(f"✅ input: name={self.input_name}, shape={self.input_shape}, dtype={self.input_dtype}")print(f"✅ classes: {self.class_names}")print(f"✅ config: conf={self.conf_thres}, iou={self.iou_thres}, "f"cross_iou={self.cross_iou_thresh}, TTA={self.use_tta}")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_w) / 2.0dh = (new_h - resized_h) / 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)1 unmodified lineorig_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(self.input_dtype) / 255.0img = np.transpose(img, (2, 0, 1))[None, ...]img = np.ascontiguousarray(img)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 boxesdef _filter_sane_boxes(self,boxes: np.ndarray,scores: np.ndarray,cls_ids: np.ndarray,orig_size: tuple[int, int],):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_side or bh < self.min_side: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),)k = np.array(keep, dtype=np.intp)return boxes[k], scores[k], cls_ids[k]@staticmethoddef _hard_nms(boxes: np.ndarray,scores: np.ndarray,iou_thresh: float,) -> np.ndarray:N = len(boxes)if N == 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: list[int] = []suppressed = np.zeros(N, dtype=bool)for i in range(N):idx = order[i]if suppressed[idx]:continuekeep.append(int(idx))bi = boxes[idx]for k in range(i + 1, N):jdx = order[k]if suppressed[jdx]:continuebj = boxes[jdx]xx1 = max(bi[0], bj[0])yy1 = max(bi[1], bj[1])xx2 = min(bi[2], bj[2])yy2 = min(bi[3], bj[3])inter = max(0.0, xx2 - xx1) * max(0.0, yy2 - yy1)area_i = (bi[2] - bi[0]) * (bi[3] - bi[1])area_j = (bj[2] - bj[0]) * (bj[3] - bj[1])iou = inter / (area_i + area_j - inter + 1e-7)if iou > iou_thresh:suppressed[jdx] = Truereturn np.array(keep, dtype=np.intp)def _per_class_hard_nms(self,boxes: np.ndarray,scores: np.ndarray,cls_ids: np.ndarray,iou_thresh: float,) -> np.ndarray:if len(boxes) == 0:return np.array([], dtype=np.intp)all_keep: list[int] = []for c in np.unique(cls_ids):mask = cls_ids == cindices = np.where(mask)[0]keep = self._hard_nms(boxes[mask], scores[mask], iou_thresh)all_keep.extend(indices[keep].tolist())all_keep.sort()return np.array(all_keep, dtype=np.intp)@staticmethoddef _cross_class_dedup(boxes: np.ndarray,scores: np.ndarray,cls_ids: np.ndarray,iou_thresh: float,) -> tuple[np.ndarray, np.ndarray, np.ndarray]:n = len(boxes)if n <= 1:return boxes, scores, cls_idsboxes = np.asarray(boxes, dtype=np.float32)scores = np.asarray(scores, dtype=np.float32)cls_ids = np.asarray(cls_ids, dtype=np.int32)areas = np.maximum(0.0, boxes[:, 2] - boxes[:, 0]) * np.maximum(0.0, boxes[:, 3] - boxes[:, 1])# Keep larger boxes first, then higher score.order = np.lexsort((-scores, -areas))suppressed = np.zeros(n, dtype=bool)keep: list[int] = []for i in order:if suppressed[i]:continuekeep.append(int(i))bi = boxes[i]xx1 = np.maximum(bi[0], boxes[:, 0])yy1 = np.maximum(bi[1], boxes[:, 1])xx2 = np.minimum(bi[2], boxes[:, 2])yy2 = np.minimum(bi[3], boxes[:, 3])inter = np.maximum(0.0, xx2 - xx1) * np.maximum(0.0, yy2 - yy1)area_i = max(1e-7, float((bi[2] - bi[0]) * (bi[3] - bi[1])))union = area_i + areas - inter + 1e-7iou = inter / uniondup = iou > iou_threshdup[i] = Falsesuppressed |= dupkeep_idx = np.array(keep, dtype=np.intp)return boxes[keep_idx], scores[keep_idx], cls_ids[keep_idx]@staticmethoddef _max_score_per_cluster(coords: np.ndarray,scores: np.ndarray,keep_indices: np.ndarray,iou_thresh: float,) -> np.ndarray:n_keep = len(keep_indices)if n_keep == 0:return np.array([], dtype=np.float32)coords = np.asarray(coords, dtype=np.float32)scores = np.asarray(scores, dtype=np.float32)out = np.empty(n_keep, dtype=np.float32)for i in range(n_keep):idx = keep_indices[i]bi = coords[idx]xx1 = np.maximum(bi[0], coords[:, 0])yy1 = np.maximum(bi[1], coords[:, 1])xx2 = np.minimum(bi[2], coords[:, 2])yy2 = np.minimum(bi[3], coords[:, 3])inter = np.maximum(0.0, xx2 - xx1) * np.maximum(0.0, yy2 - yy1)area_i = (bi[2] - bi[0]) * (bi[3] - bi[1])areas_j = (coords[:, 2] - coords[:, 0]) * (coords[:, 3] - coords[:, 1])iou = inter / (area_i + areas_j - inter + 1e-7)in_cluster = iou >= iou_threshout[i] = float(np.max(scores[in_cluster]))return outdef _decode_raw_dets(self,preds: np.ndarray,ratio: float,pad: tuple[float, float],orig_size: tuple[int, int],*,apply_conf_thresh: bool = True,) -> tuple[np.ndarray, np.ndarray, np.ndarray]:"""Decode end2end NMS output and return (boxes, scores, cls_ids)in original image coordinates, after conf-threshold + remap + letterbox-reverse + sanity.When apply_conf_thresh=False, the conf-threshold filter is skipped (used forthe no-detection fallback path: take the single top-conf raw box)."""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 output shape: {preds.shape}")boxes = preds[:, :4].astype(np.float32)scores = preds[:, 4].astype(np.float32)cls_ids = preds[:, 5].astype(np.int32)valid = (cls_ids >= 0) & (cls_ids < len(self.cls_remap)) & (scores > 0)boxes, scores, cls_ids = boxes[valid], scores[valid], cls_ids[valid]cls_ids = self.cls_remap[cls_ids]if apply_conf_thresh:# Per-class threshold: each box compared against its own class's thresholdcls_thresh = np.full(len(scores), self.conf_thres, dtype=np.float32)valid_cls = (cls_ids >= 0) & (cls_ids < len(self.conf_thres_per_class))cls_thresh[valid_cls] = self.conf_thres_per_class[cls_ids[valid_cls]]keep = scores >= cls_threshboxes = boxes[keep]scores = scores[keep]cls_ids = cls_ids[keep]if len(boxes) == 0:return (np.empty((0, 4), dtype=np.float32),np.empty((0,), dtype=np.float32),np.empty((0,), dtype=np.int32),)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)return boxes, scores, cls_idsdef _forward(self, image: np.ndarray) -> tuple[np.ndarray, np.ndarray, np.ndarray]:x, ratio, pad, orig_size = self._preprocess(image)out = self.session.run(self.output_names, {self.input_name: x})[0]return self._decode_raw_dets(out, ratio, pad, orig_size)def _forward_with_fallback(self, image: np.ndarray) -> tuple[tuple[np.ndarray, np.ndarray, np.ndarray],tuple[np.ndarray, np.ndarray, np.ndarray],]:"""Run ONNX once, decode twice: (filtered @ conf_thres, all-survived sanity)."""x, ratio, pad, orig_size = self._preprocess(image)out = self.session.run(self.output_names, {self.input_name: x})[0]primary = self._decode_raw_dets(out, ratio, pad, orig_size, apply_conf_thresh=True)fallback = self._decode_raw_dets(out, ratio, pad, orig_size, apply_conf_thresh=False)return primary, fallbackdef _predict_single(self, image: np.ndarray) -> list[BoundingBox]:(boxes, scores, cls_ids), (fb_b, fb_s, fb_c) = self._forward_with_fallback(image)ih, iw = image.shape[:2]if len(boxes) > 0:return self._build_results(boxes, scores, cls_ids, image_size=(iw, ih))# FALLBACK: nothing passed conf_thres — return single top-conf box# (any class, any conf > 0) so the validator's mAP isn't a hard zero.if len(fb_b) == 0:return []i = int(np.argmax(fb_s))return self._build_results(fb_b[i:i + 1], fb_s[i:i + 1], fb_c[i:i + 1], image_size=(iw, ih))def _predict_tta(self, image: np.ndarray) -> list[BoundingBox]:"""Hflip TTA: merge primary + flipped via per-class hard-NMS,then cross-class dedup, with consensus-confidence boost."""ow = image.shape[1]b1, s1, c1 = self._forward(image)flipped = cv2.flip(image, 1)b2, s2, c2 = self._forward(flipped)if len(b2):x1f = ow - b2[:, 2]x2f = ow - b2[:, 0]b2 = np.stack([x1f, b2[:, 1], x2f, b2[:, 3]], axis=1)if len(b1) == 0 and len(b2) == 0:return []boxes = np.concatenate([b1, b2], axis=0) if len(b2) else b1scores = np.concatenate([s1, s2], axis=0) if len(b2) else s1cls_ids = np.concatenate([c1, c2], axis=0) if len(b2) else c1keep = self._per_class_hard_nms(boxes, scores, cls_ids, self.iou_thres)if len(keep) == 0:return []keep = keep[: self.max_det]# Consensus-confidence boost: cluster by IoU and take max score.boosted = self._max_score_per_cluster(boxes, scores, keep, self.iou_thres)boxes = boxes[keep]cls_ids = cls_ids[keep]scores = boostedboxes, scores, cls_ids = self._cross_class_dedup(boxes, scores, cls_ids, self.cross_iou_thresh)if len(boxes) == 0:return []ih, iw = image.shape[:2]return self._build_results(boxes, scores, cls_ids, image_size=(iw, ih))def _filter_balaclava_geometry(self,boxes: np.ndarray,scores: np.ndarray,cls_ids: np.ndarray,image_size: tuple[int, int] | None = None,) -> tuple[np.ndarray, np.ndarray, np.ndarray]:# Real-balaclava prior (from 43 manual GT labels):# aspect ratio max(w/h, h/w): p5=1.11, median=1.33, p99=1.71# rel area % of image: p1=0.041, p5=0.070, p10=0.087# FP balaclavas frequently violate these (very thin/wide boxes from# face-fragment matches, or tiny ~0.01%-area boxes from texture noise).BALACLAVA = 0ASPECT_MAX = 1.8 # above p99 of realREL_AREA_MIN = 0.0004 # below p1 of real (0.04%)if len(boxes) == 0:return boxes, scores, cls_idsis_bal = cls_ids == BALACLAVAif not is_bal.any():return boxes, scores, cls_idskeep = np.ones(len(boxes), dtype=bool)if image_size is not None:iw, ih = image_sizeimg_area = max(1.0, iw * ih)else:img_area = Nonefor i in np.where(is_bal)[0]:x1, y1, x2, y2 = boxes[i]bw = max(1.0, x2 - x1)bh = max(1.0, y2 - y1)aspect = max(bw / bh, bh / bw)if aspect > ASPECT_MAX:keep[i] = Falsecontinueif img_area is not None:rel = (bw * bh) / img_areaif rel < REL_AREA_MIN:keep[i] = Falsereturn boxes[keep], scores[keep], cls_ids[keep]def _suppress_balaclava_under_hoodie(self,boxes: np.ndarray,scores: np.ndarray,cls_ids: np.ndarray,) -> tuple[np.ndarray, np.ndarray, np.ndarray]:# Validator rule: "balaclavas worn under a hoodie hood are IGNORED# (a hoodie includes the jacket and its hood)". A small balaclava# box can sit fully inside a much larger hoodie box — IoU between# them stays low (intersection / large union), but containment# (intersection / balaclava_area) is ~1.0. So drop any balaclava# whose containment by any hoodie box is >= COVER_THRESH.BALACLAVA, HOODIE = 0, 1COVER_THRESH = 0.5if len(boxes) == 0:return boxes, scores, cls_idsis_hood = cls_ids == HOODIEis_bal = cls_ids == BALACLAVAif not is_hood.any() or not is_bal.any():return boxes, scores, cls_idshood_boxes = boxes[is_hood]keep = np.ones(len(boxes), dtype=bool)for i in np.where(is_bal)[0]:bx1, by1, bx2, by2 = boxes[i]bal_area = max(1.0, (bx2 - bx1) * (by2 - by1))ix1 = np.maximum(bx1, hood_boxes[:, 0])iy1 = np.maximum(by1, hood_boxes[:, 1])ix2 = np.minimum(bx2, hood_boxes[:, 2])iy2 = np.minimum(by2, hood_boxes[:, 3])iw = np.clip(ix2 - ix1, 0.0, None)ih = np.clip(iy2 - iy1, 0.0, None)inter = iw * ihcover = inter / bal_areaif (cover >= COVER_THRESH).any():keep[i] = Falsereturn boxes[keep], scores[keep], cls_ids[keep]def _build_results(self,boxes: np.ndarray,scores: np.ndarray,cls_ids: np.ndarray,image_size: tuple[int, int] | None = None,) -> list[BoundingBox]:boxes, scores, cls_ids = self._filter_balaclava_geometry(boxes, scores, cls_ids, image_size)boxes, scores, cls_ids = self._suppress_balaclava_under_hoodie(boxes, scores, cls_ids)results: list[BoundingBox] = []for box, conf, cls_id in zip(boxes, scores, cls_ids):x1, y1, x2, y2 = box.tolist()if 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=int(cls_id),conf=float(conf),))return resultsdef 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):if image is None or not isinstance(image, np.ndarray) or image.ndim != 3:results.append(TVFrameResult(frame_id=offset + frame_number_in_batch,boxes=[],keypoints=[(0, 0) for _ in range(max(0, int(n_keypoints)))],))continueif image.dtype != np.uint8:image = image.astype(np.uint8)try:if self.use_tta:boxes = self._predict_tta(image)else:boxes = self._predict_single(image)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)))],)123420 unmodified lines252627282930313233343536373839404142434445464748495051525354555657585960616263641 unmodified line666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111 unmodified line113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307"""ScoreVision crime detector — YOLOv11s with flip TTA + per-class conf + cross-class NMS."""from pathlib import Pathimport math20 unmodified linesclass Miner:"""ONNX Runtime miner with horizontal-flip TTA and per-class confidence."""class_names = ["balaclava", "hoodie", "glove", "bat", "spray paint", "graffiti"]input_size = 1280iou_thres = 0.45cross_iou_thresh = 0.50max_aspect_ratio = 10.0max_det = 150# tuned on held-out SAM3-labeled crime set_conf_thres_array = np.array([0.50, 0.50, 0.30, 0.30, 0.40, 0.40], dtype=np.float32)def __init__(self, path_hf_repo: Path) -> None:model_path = path_hf_repo / "weights.onnx"print("ORT version:", ort.__version__)try:ort.preload_dlls()print("preload_dlls success")except Exception as e:print(f"preload_dlls failed: {e}")print("ORT available providers:", 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,1 unmodified line)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 = [o.name for o in self.session.get_outputs()]self.input_shape = self.session.get_inputs()[0].shapeself.input_height = self._safe_dim(self.input_shape[2], self.input_size)self.input_width = self._safe_dim(self.input_shape[3], self.input_size)print(f"ONNX loaded: {model_path} input={self.input_shape}")print("per-class conf: "+ ", ".join(f"{n}={t:.3f}" for n, t in zip(self.class_names, self._conf_thres_array.tolist())))def __repr__(self) -> str:return f"ONNXRuntime(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)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, dh = (new_w - rw) / 2.0, (new_h - rh) / 2.0top, bot = int(round(dh - 0.1)), int(round(dh + 0.1))lt, rt = int(round(dw - 0.1)), int(round(dw + 0.1))padded = cv2.copyMakeBorder(image, top, bot, lt, rt, cv2.BORDER_CONSTANT, value=color)return padded, ratio, (dw, dh)1 unmodified lineorig_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, size):w, h = 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 _hard_nms(boxes, scores, iou_thr):n = len(boxes)if n == 0:return np.array([], dtype=np.intp)order = np.argsort(-scores)keep = []while len(order) > 0: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.0, xx2 - xx1) * np.maximum(0.0, yy2 - yy1)a_i = max(0.0, boxes[i, 2] - boxes[i, 0]) * max(0.0, boxes[i, 3] - boxes[i, 1])a_r = (np.maximum(0.0, boxes[rest, 2] - boxes[rest, 0])* np.maximum(0.0, boxes[rest, 3] - boxes[rest, 1]))iou = inter / (a_i + a_r - inter + 1e-7)order = rest[iou <= iou_thr]return np.array(keep, dtype=np.intp)def _per_class_hard_nms(self, boxes, scores, cls_ids, iou_thr):if len(boxes) == 0:return np.array([], dtype=np.intp)keep_all = []for c in np.unique(cls_ids):mask = cls_ids == cidx = np.where(mask)[0]keep = self._hard_nms(boxes[mask], scores[mask], iou_thr)keep_all.extend(idx[keep].tolist())keep_all.sort()return np.array(keep_all, dtype=np.intp)def _cross_class_dedup(self, boxes, scores, cls_ids, iou_thr):"""If two boxes (any class) heavily overlap, keep only the higher-scoring one."""n = len(boxes)if n == 0:return np.array([], dtype=np.intp)order = np.argsort(-scores)keep = []suppressed = np.zeros(n, dtype=bool)for i in order:if suppressed[i]:continuekeep.append(int(i))ix1 = np.maximum(boxes[i, 0], boxes[:, 0])iy1 = np.maximum(boxes[i, 1], boxes[:, 1])ix2 = np.minimum(boxes[i, 2], boxes[:, 2])iy2 = np.minimum(boxes[i, 3], boxes[:, 3])inter = np.maximum(0.0, ix2 - ix1) * np.maximum(0.0, iy2 - iy1)a_i = max(0.0, boxes[i, 2] - boxes[i, 0]) * max(0.0, boxes[i, 3] - boxes[i, 1])a_r = (np.maximum(0.0, boxes[:, 2] - boxes[:, 0])* np.maximum(0.0, boxes[:, 3] - boxes[:, 1]))iou = inter / (a_i + a_r - inter + 1e-7)iou[i] = 0.0suppressed |= iou >= iou_thrreturn np.array(keep, dtype=np.intp)def _filter_sane(self, boxes, scores, cls_ids, orig_size):if len(boxes) == 0:return boxes, scores, cls_idsw, h = orig_sizearea_img = float(w * h)bw = np.maximum(0.0, boxes[:, 2] - boxes[:, 0])bh = np.maximum(0.0, boxes[:, 3] - boxes[:, 1])area = bw * bhar = np.where((bw > 0) & (bh > 0),np.maximum(bw / np.maximum(bh, 1e-6), bh / np.maximum(bw, 1e-6)),np.inf,)keep = (area <= 0.95 * area_img) & (ar <= self.max_aspect_ratio)return boxes[keep], scores[keep], cls_ids[keep]def _decode(self, preds: ndarray, ratio: float, pad: tuple[float, float],orig_size: tuple[int, int]) -> tuple[np.ndarray, np.ndarray, np.ndarray]:"""ONNX output is [1,300,6]: x1,y1,x2,y2,conf,cls in letterboxed coords."""if preds.ndim == 3 and preds.shape[0] == 1:preds = preds[0]if preds.ndim != 2 or preds.shape[1] < 6:return (np.empty((0, 4), dtype=np.float32),np.empty((0,), dtype=np.float32),np.empty((0,), dtype=np.int32),)boxes = preds[:, :4].astype(np.float32)scores = preds[:, 4].astype(np.float32)cls_ids = preds[:, 5].astype(np.int32)# drop padded rowskeep = (scores > 0) & (cls_ids >= 0) & (cls_ids < len(self.class_names))boxes, scores, cls_ids = boxes[keep], scores[keep], cls_ids[keep]if len(boxes) == 0:return boxes, scores, cls_ids# per-class confidencethr = self._conf_thres_array[cls_ids]keep = scores >= thrboxes, scores, cls_ids = boxes[keep], scores[keep], cls_ids[keep]if len(boxes) == 0:return boxes, scores, cls_ids# untransform: subtract pad, divide ratiopad_w, pad_h = padboxes[:, [0, 2]] -= pad_wboxes[:, [1, 3]] -= pad_hboxes /= ratioboxes = self._clip(boxes, orig_size)return boxes, scores, cls_idsdef _predict_single(self, image: ndarray):x, ratio, pad, orig_size = self._preprocess(image)out = self.session.run(self.output_names, {self.input_name: x})[0]return self._decode(out, ratio, pad, orig_size)def _predict_tta(self, image: ndarray) -> list[BoundingBox]:b0, s0, c0 = self._predict_single(image)flipped = cv2.flip(image, 1)bf, sf, cf = self._predict_single(flipped)if len(bf):w = image.shape[1]bf2 = bf.copy()bf2[:, 0] = w - bf[:, 2]bf2[:, 2] = w - bf[:, 0]bf = bf2boxes = np.concatenate([b0, bf], axis=0) if len(b0) or len(bf) else b0scores = np.concatenate([s0, sf], axis=0) if len(b0) or len(bf) else s0cls_ids = np.concatenate([c0, cf], axis=0) if len(b0) or len(bf) else c0if len(boxes) == 0:return []# filter + per-class NMS + cross-class dedupboxes, scores, cls_ids = self._filter_sane(boxes, scores, cls_ids, (image.shape[1], image.shape[0]))if len(boxes) == 0:return []keep = self._per_class_hard_nms(boxes, scores, cls_ids, self.iou_thres)if len(keep) == 0:return []boxes, scores, cls_ids = boxes[keep], scores[keep], cls_ids[keep]keep = self._cross_class_dedup(boxes, scores, cls_ids, self.cross_iou_thresh)boxes, scores, cls_ids = boxes[keep], scores[keep], cls_ids[keep]if len(scores) > self.max_det:top = np.argsort(-scores)[: self.max_det]boxes, scores, cls_ids = boxes[top], scores[top], cls_ids[top]return [BoundingBox(x1=int(math.floor(b[0])),y1=int(math.floor(b[1])),x2=int(math.ceil(b[2])),y2=int(math.ceil(b[3])),cls_id=int(c),conf=float(s),)for b, s, c in zip(boxes, scores, cls_ids)if b[2] > b[0] and b[3] > b[1]]def predict_batch(self, batch_images: list[ndarray], offset: int,n_keypoints: int) -> list[TVFrameResult]:results: list[TVFrameResult] = []for j, image in enumerate(batch_images):try:boxes = self._predict_tta(image)except Exception as e:print(f"Inference failed for frame {offset + j}: {e}")boxes = []results.append(TVFrameResult(frame_id=offset + j,boxes=boxes,keypoints=[(0, 0) for _ in range(max(0, int(n_keypoints)))],)
miner.py+177-475