from pathlib import Path import math import cv2 import numpy as np import onnxruntime as ort from numpy import ndarray from pydantic import BaseModel class BoundingBox(BaseModel): x1: int y1: int x2: int y2: int cls_id: int conf: float class TVFrameResult(BaseModel): frame_id: int boxes: 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"] sess_options = ort.SessionOptions() sess_options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL try: self.session = ort.InferenceSession( str(model_path), sess_options=sess_options, providers=["CUDAExecutionProvider", "CPUExecutionProvider"], ) except Exception: self.session = ort.InferenceSession( str(model_path), sess_options=sess_options, providers=["CPUExecutionProvider"], ) self.input_name = self.session.get_inputs()[0].name self.output_names = [o.name for o in self.session.get_outputs()] self.input_shape = self.session.get_inputs()[0].shape self.input_height = self._safe_dim(self.input_shape[2], 1280) self.input_width = self._safe_dim(self.input_shape[3], 1280) # Tuned for MAP50 (65%) + FALSE_POSITIVE (35%) scoring # Lower conf = more recall = higher MAP50, but more FP # Balance: slightly aggressive recall since MAP50 weight > FP weight self.conf_thres = 0.40 self.conf_high = 0.55 self.iou_thres = 0.50 self.tta_match_iou = 0.45 self.max_det = 200 self.use_tta = True # Box sanity filters self.min_box_area = 12 * 12 self.min_w = 6 self.min_h = 6 self.max_aspect_ratio = 7.0 self.max_box_area_ratio = 0.85 print(f"Model loaded: {model_path}, providers={self.session.get_providers()}") def __repr__(self) -> str: return f"ONNXRuntime(providers={self.session.get_providers()})" @staticmethod def _safe_dim(value, default: int) -> int: return value if isinstance(value, int) and value > 0 else default def _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_shape ratio = 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_LINEAR image = cv2.resize(image, (rw, rh), interpolation=interp) dw, dh = (new_w - rw) / 2.0, (new_h - rh) / 2.0 padded = cv2.copyMakeBorder( image, int(round(dh - 0.1)), int(round(dh + 0.1)), int(round(dw - 0.1)), int(round(dw + 0.1)), 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).astype(np.float32) / 255.0 img = np.ascontiguousarray(np.transpose(img, (2, 0, 1))[None, ...], dtype=np.float32) return img, ratio, pad, (orig_w, orig_h) @staticmethod def _clip_boxes(boxes: np.ndarray, size: tuple[int, int]) -> np.ndarray: w, h = size boxes[:, 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 @staticmethod def _xywh_to_xyxy(b: np.ndarray) -> np.ndarray: o = np.empty_like(b) o[:, 0] = b[:, 0] - b[:, 2] / 2 o[:, 1] = b[:, 1] - b[:, 3] / 2 o[:, 2] = b[:, 0] + b[:, 2] / 2 o[:, 3] = b[:, 1] + b[:, 3] / 2 return o @staticmethod def _hard_nms(boxes: np.ndarray, scores: np.ndarray, iou_thresh: float) -> np.ndarray: if len(boxes) == 0: return np.array([], dtype=np.intp) order = np.argsort(scores)[::-1] keep = [] while len(order) > 0: i = order[0] keep.append(i) if len(order) == 1: break rest = 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 = max(0, (boxes[i, 2] - boxes[i, 0]) * (boxes[i, 3] - boxes[i, 1])) area_r = np.maximum(0, boxes[rest, 2] - boxes[rest, 0]) * np.maximum(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) @staticmethod def _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, xx2 - xx1) * np.maximum(0, yy2 - yy1) a = max(0, (box[2] - box[0]) * (box[3] - box[1])) b = np.maximum(0, boxes[:, 2] - boxes[:, 0]) * np.maximum(0, boxes[:, 3] - boxes[:, 1]) return inter / (a + b - inter + 1e-7) def _filter_sane(self, boxes, scores, cls_ids, orig_size): if len(boxes) == 0: return boxes, scores, cls_ids ow, oh = orig_size area_img = float(ow * oh) keep = [] for i, box in enumerate(boxes): bw, bh = box[2] - box[0], box[3] - box[1] if bw <= 0 or bh <= 0 or bw < self.min_w or bh < self.min_h: continue area = bw * bh if area < self.min_box_area or area > self.max_box_area_ratio * area_img: continue if max(bw / max(bh, 1e-6), bh / max(bw, 1e-6)) > self.max_aspect_ratio: continue keep.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] def _decode_raw_yolo(self, preds, ratio, pad, orig_size): if preds.ndim == 3 and preds.shape[0] == 1: preds = preds[0] if preds.shape[0] <= 16 and preds.shape[1] > preds.shape[0]: preds = preds.T boxes_xywh = preds[:, :4].astype(np.float32) tail = preds[:, 4:] if tail.shape[1] == 1: scores = tail[:, 0] cls_ids = np.zeros(len(scores), dtype=np.int32) else: cls_ids = np.argmax(tail, axis=1).astype(np.int32) scores = tail[np.arange(len(tail)), cls_ids] # person only (class 0) mask = (cls_ids == 0) & (scores >= self.conf_thres) boxes_xywh, scores, cls_ids = boxes_xywh[mask], scores[mask], cls_ids[mask] if len(boxes_xywh) == 0: return [] boxes = self._xywh_to_xyxy(boxes_xywh) boxes[:, [0, 2]] -= pad[0] boxes[:, [1, 3]] -= pad[1] boxes /= ratio boxes = self._clip_boxes(boxes, orig_size) boxes, scores, cls_ids = self._filter_sane(boxes, scores, cls_ids, orig_size) if len(boxes) == 0: return [] keep = self._hard_nms(boxes, scores, self.iou_thres)[:self.max_det] return [BoundingBox( x1=int(math.floor(boxes[i, 0])), y1=int(math.floor(boxes[i, 1])), x2=int(math.ceil(boxes[i, 2])), y2=int(math.ceil(boxes[i, 3])), cls_id=0, conf=float(scores[i])) for i in keep if boxes[i, 2] > boxes[i, 0] and boxes[i, 3] > boxes[i, 1]] def _decode_final_dets(self, preds, ratio, pad, orig_size): if preds.ndim == 3 and preds.shape[0] == 1: preds = preds[0] boxes = preds[:, :4].astype(np.float32) scores = preds[:, 4].astype(np.float32) cls_ids = preds[:, 5].astype(np.int32) mask = (cls_ids == 0) & (scores >= self.conf_thres) boxes, scores, cls_ids = boxes[mask], scores[mask], cls_ids[mask] if len(boxes) == 0: return [] boxes[:, [0, 2]] -= pad[0] boxes[:, [1, 3]] -= pad[1] boxes /= ratio boxes = self._clip_boxes(boxes, orig_size) boxes, scores, cls_ids = self._filter_sane(boxes, scores, cls_ids, orig_size) if len(boxes) == 0: return [] keep = self._hard_nms(boxes, scores, self.iou_thres)[:self.max_det] return [BoundingBox( x1=int(math.floor(boxes[i, 0])), y1=int(math.floor(boxes[i, 1])), x2=int(math.ceil(boxes[i, 2])), y2=int(math.ceil(boxes[i, 3])), cls_id=0, conf=float(scores[i])) for i in keep if boxes[i, 2] > boxes[i, 0] and boxes[i, 3] > boxes[i, 1]] def _postprocess(self, output, ratio, pad, orig_size): 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.dtype != np.uint8: image = image.astype(np.uint8) tensor, ratio, pad, orig_size = self._preprocess(image) outputs = self.session.run(self.output_names, {self.input_name: tensor}) return self._postprocess(outputs[0], ratio, pad, orig_size) def _merge_tta(self, boxes_orig, boxes_flip): if not boxes_orig and not boxes_flip: return [] co = 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) so = np.array([b.conf for b in boxes_orig], dtype=np.float32) if boxes_orig else np.empty(0, dtype=np.float32) cf = 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) sf = np.array([b.conf for b in boxes_flip], dtype=np.float32) if boxes_flip else np.empty(0, dtype=np.float32) acc_b, acc_s = [], [] for i in range(len(co)): if so[i] >= self.conf_high: acc_b.append(co[i]); acc_s.append(so[i]) elif len(cf) > 0: ious = self._box_iou_one_to_many(co[i], cf) j = int(np.argmax(ious)) if ious[j] >= self.tta_match_iou: acc_b.append(co[i]); acc_s.append(max(so[i], sf[j])) for i in range(len(cf)): if sf[i] < self.conf_high: continue if len(co) == 0: acc_b.append(cf[i]); acc_s.append(sf[i]); continue if np.max(self._box_iou_one_to_many(cf[i], co)) < self.tta_match_iou: acc_b.append(cf[i]); acc_s.append(sf[i]) if not acc_b: return [] boxes = np.array(acc_b, dtype=np.float32) scores = np.array(acc_s, dtype=np.float32) keep = self._hard_nms(boxes, scores, self.iou_thres)[:self.max_det] return [BoundingBox( x1=int(math.floor(boxes[i, 0])), y1=int(math.floor(boxes[i, 1])), x2=int(math.ceil(boxes[i, 2])), y2=int(math.ceil(boxes[i, 3])), cls_id=0, conf=float(scores[i])) for i in keep] def _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(boxes_orig, boxes_flip) def predict_batch(self, batch_images: list[ndarray], offset: int, n_keypoints: int) -> list[TVFrameResult]: results = [] for i, image in enumerate(batch_images): try: boxes = self._predict_tta(image) if self.use_tta else self._predict_single(image) except Exception as e: print(f"Inference failed frame {offset + i}: {e}") boxes = [] results.append(TVFrameResult( frame_id=offset + i, boxes=boxes, keypoints=[(0, 0) for _ in range(max(0, int(n_keypoints)))])) return results