scorevision: push artifact
Browse files123456789101112131415161717 unmodified lines35363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871 unmodified line189190191192193194195196197198199200201202from pathlib import Pathimport mathimport osimport globimport siteimport ctypes# Preload pip-installed NVIDIA cuDNN so onnxruntime can use CUDAExecutionProviderfor sp in site.getsitepackages():for d in glob.glob(os.path.join(sp, 'nvidia', '*', 'lib')):os.environ['LD_LIBRARY_PATH'] = d + ':' + os.environ.get('LD_LIBRARY_PATH', '')_cudnn = os.path.join(d, 'libcudnn.so.9')if os.path.exists(_cudnn):ctypes.CDLL(_cudnn, mode=ctypes.RTLD_GLOBAL)import cv2import numpy as np17 unmodified lineskeypoints: list[tuple[int, int]]class Miner:"""Auto-generated by subnet_bridge from a Manako element repo.This miner is intentionally self-contained for chute import restrictions."""def __init__(self, path_hf_repo: Path) -> None:self.path_hf_repo = path_hf_repoself.class_names = ['numberplate']self.session = ort.InferenceSession(str(path_hf_repo / "weights.onnx"),providers=["CUDAExecutionProvider", "CPUExecutionProvider"],)self.input_name = self.session.get_inputs()[0].nameinput_shape = self.session.get_inputs()[0].shape# expected [N, C, H, W]self.input_h = int(input_shape[2])self.input_w = int(input_shape[3])self.conf_threshold = 0.15self.iou_threshold = 0.3self.use_tta = Truedef __repr__(self) -> str:return f"ONNX Miner session={type(self.session).__name__} classes={len(self.class_names)}"def _preprocess(self, image_bgr: ndarray) -> tuple[np.ndarray, tuple[int, int]]:h, w = image_bgr.shape[:2]rgb = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)resized = cv2.resize(rgb, (self.input_w, self.input_h))x = resized.astype(np.float32) / 255.0x = np.transpose(x, (2, 0, 1))[None, ...]return x, (h, w)def _normalize_predictions(self, raw: np.ndarray) -> np.ndarray:pred = raw[0]if pred.ndim != 2:raise ValueError(f"Unexpected prediction shape: {raw.shape}")if pred.shape[0] < pred.shape[1]:pred = pred.transpose(1, 0)return preddef _nms(self, dets: list[tuple[float, float, float, float, float, int]]) -> list[tuple[float, float, float, float, float, int]]:if not dets:return []boxes = np.array([[d[0], d[1], d[2], d[3]] for d in dets], dtype=np.float32)scores = np.array([d[4] for d in dets], dtype=np.float32)order = scores.argsort()[::-1]keep = []while order.size > 0:i = order[0]keep.append(i)xx1 = np.maximum(boxes[i, 0], boxes[order[1:], 0])yy1 = np.maximum(boxes[i, 1], boxes[order[1:], 1])xx2 = np.minimum(boxes[i, 2], boxes[order[1:], 2])yy2 = np.minimum(boxes[i, 3], boxes[order[1:], 3])w = np.maximum(0.0, xx2 - xx1)h = np.maximum(0.0, yy2 - yy1)inter = w * harea_i = (boxes[i, 2] - boxes[i, 0]) * (boxes[i, 3] - boxes[i, 1])area_rest = (boxes[order[1:], 2] - boxes[order[1:], 0]) * (boxes[order[1:], 3] - boxes[order[1:], 1])union = np.maximum(area_i + area_rest - inter, 1e-6)iou = inter / unionremaining = np.where(iou <= self.iou_threshold)[0]order = order[remaining + 1]return [dets[idx] for idx in keep]def _decode(self, image_bgr: ndarray) -> list[tuple[float, float, float, float, float, int]]:"""Run model and return raw detections before NMS."""inp, (orig_h, orig_w) = self._preprocess(image_bgr)out = self.session.run(None, {self.input_name: inp})[0]pred = self._normalize_predictions(out)if pred.shape[1] < 5:return []boxes = pred[:, :4]cls_scores = pred[:, 4:]if cls_scores.shape[1] == 0:return []cls_ids = np.argmax(cls_scores, axis=1)confs = np.max(cls_scores, axis=1)keep = confs >= self.conf_thresholdboxes = boxes[keep]confs = confs[keep]cls_ids = cls_ids[keep]if boxes.shape[0] == 0:return []sx = orig_w / float(self.input_w)sy = orig_h / float(self.input_h)dets: list[tuple[float, float, float, float, float, int]] = []for i in range(boxes.shape[0]):cx, cy, bw, bh = boxes[i].tolist()x1 = (cx - bw / 2.0) * sxy1 = (cy - bh / 2.0) * syx2 = (cx + bw / 2.0) * sxy2 = (cy + bh / 2.0) * sydets.append((x1, y1, x2, y2, float(confs[i]), int(cls_ids[i])))return detsdef _infer_single(self, image_bgr: ndarray) -> list[BoundingBox]:orig_h, orig_w = image_bgr.shape[:2]# Original passall_dets = self._decode(image_bgr)# TTA: horizontal flip passif self.use_tta:flipped = cv2.flip(image_bgr, 1)flip_dets = self._decode(flipped)for x1, y1, x2, y2, conf, cls_id in flip_dets:all_dets.append((orig_w - x2, y1, orig_w - x1, y2, conf, cls_id))# NMSall_dets = self._nms(all_dets)out_boxes: list[BoundingBox] = []for x1, y1, x2, y2, conf, cls_id in all_dets:ix1 = max(0, min(orig_w, math.floor(x1)))iy1 = max(0, min(orig_h, math.floor(y1)))ix2 = max(0, min(orig_w, math.ceil(x2)))iy2 = max(0, min(orig_h, math.ceil(y2)))out_boxes.append(BoundingBox(x1=ix1,y1=iy1,x2=ix2,y2=iy2,cls_id=cls_id,conf=max(0.0, min(1.0, conf)),))return out_boxesdef predict_batch(self,batch_images: list[ndarray],1 unmodified linen_keypoints: int,) -> list[TVFrameResult]:results: list[TVFrameResult] = []for idx, image in enumerate(batch_images):boxes = self._infer_single(image)keypoints = [(0, 0) for _ in range(max(0, int(n_keypoints)))]results.append(TVFrameResult(frame_id=offset + idx,boxes=boxes,keypoints=keypoints,))return results1234567891011121314151617181917 unmodified lines3738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074081 unmodified line410411412413414415416417418419420421422423424425426"""Plate-detection miner — v1 "sparse conditional tile-aug".Base weights: alfred8995/arabic002 (YOLO26s @ 1280, fp16, ~19 MB).Inference pipeline:1) Full-image primary pass with arabic002's strict tuning(conf=0.27, iou=0.444, sigma=0.5, soft-NMS + hflip TTA, max_det=18).2) If the primary returned fewer than SPARSE_THRESHOLD (5) boxes,run a 2x2 overlapping tile pass with higher conf (tile_conf=0.40)and novelty-merge: keep a tile box only when it does not overlapany primary box at IoU >= 0.10. Tile augmentation is skippedentirely on challenges where the primary already has enoughdetections, so the FP score stays intact on dense scenes."""from pathlib import Pathimport mathimport cv2import numpy as np17 unmodified lineskeypoints: list[tuple[int, int]]SIZE = 1280class Miner:def __init__(self, path_hf_repo: Path) -> None:model_path = path_hf_repo / "weights.onnx"cn_path = model_path.with_name("class_names.txt")if cn_path.is_file():lines = cn_path.read_text(encoding="utf-8").splitlines()self.class_names = [ln.strip()for ln in linesif ln.strip() and not ln.strip().startswith("#")]else:self.class_names = ["numberplate"]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 = [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], default=SIZE)self.input_width = self._safe_dim(self.input_shape[3], default=SIZE)# Primary pass: arabic002 strict tuningself.conf_thres = 0.27self.iou_thres = 0.444self.sigma = 0.5self.max_det = 18# Conditional tile-passself.sparse_threshold = 5 # fire tiles only if primary returns < thisself.tile_conf = 0.40self.tile_overlap = 0.20self.novelty_iou = 0.10self.final_max_det = 22self.use_tta = Trueprint(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 default# ---------- image preprocessing ----------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_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)def _preprocess(self, image: ndarray):img, ratio, pad = self._letterbox(image, (self.input_width, self.input_height))img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB).astype(np.float32) / 255.0img = np.transpose(img, (2, 0, 1))[None, ...]return np.ascontiguousarray(img, dtype=np.float32), ratio, pad@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# ---------- NMS primitives ----------@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)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.0, xx2 - xx1) * np.maximum(0.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-7)order = rest[iou <= iou_thresh]return np.array(keep, dtype=np.intp)def _soft_nms(self,boxes: np.ndarray,scores: np.ndarray,sigma: float,score_thresh: float = 0.01,) -> tuple[np.ndarray, np.ndarray]:N = len(boxes)if N == 0:return np.array([], dtype=np.intp), np.array([], dtype=np.float32)boxes = boxes.astype(np.float32, copy=True)scores = scores.astype(np.float32, copy=True)order = np.arange(N)for i in range(N):max_pos = i + int(np.argmax(scores[i:]))boxes[[i, max_pos]] = boxes[[max_pos, i]]scores[[i, max_pos]] = scores[[max_pos, i]]order[[i, max_pos]] = order[[max_pos, i]]if i + 1 >= N:breakxx1 = np.maximum(boxes[i, 0], boxes[i + 1:, 0])yy1 = np.maximum(boxes[i, 1], boxes[i + 1:, 1])xx2 = np.minimum(boxes[i, 2], boxes[i + 1:, 2])yy2 = np.minimum(boxes[i, 3], boxes[i + 1:, 3])inter = np.maximum(0.0, xx2 - xx1) * np.maximum(0.0, yy2 - yy1)area_i = float((boxes[i, 2] - boxes[i, 0]) * (boxes[i, 3] - boxes[i, 1]))areas_j = (np.maximum(0.0, boxes[i + 1:, 2] - boxes[i + 1:, 0])* np.maximum(0.0, boxes[i + 1:, 3] - boxes[i + 1:, 1]))iou = inter / (area_i + areas_j - inter + 1e-7)scores[i + 1:] *= np.exp(-(iou ** 2) / sigma)mask = scores > score_threshreturn order[mask], scores[mask]@staticmethoddef _box_iou_one_to_many(box: np.ndarray, boxes: np.ndarray) -> np.ndarray:if len(boxes) == 0:return np.zeros(0, dtype=np.float32)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)# ---------- raw-dets helper ----------def _raw_dets(self, image: ndarray, conf: float) -> np.ndarray:"""Run a single forward pass and return [N, 5] dets in ORIGINAL image coords."""x, ratio, (dw, dh) = self._preprocess(image)out = self.session.run(self.output_names, {self.input_name: x})[0]if out.ndim == 3:out = out[0]if out.shape[1] < 5:return np.zeros((0, 5), dtype=np.float32)boxes = out[:, :4].astype(np.float32)scores = out[:, 4].astype(np.float32)keep = scores >= confboxes, scores = boxes[keep], scores[keep]if len(boxes) == 0:return np.zeros((0, 5), dtype=np.float32)boxes[:, [0, 2]] -= dwboxes[:, [1, 3]] -= dhboxes /= ratiooh, ow = image.shape[:2]boxes = self._clip_boxes(boxes, (ow, oh))return np.concatenate([boxes, scores[:, None]], axis=1)# ---------- primary pass: soft-NMS + hflip TTA ----------def _primary(self, image: ndarray) -> np.ndarray:d1 = self._raw_dets(image, self.conf_thres)flipped = cv2.flip(image, 1)d2 = self._raw_dets(flipped, self.conf_thres)if len(d2):w = image.shape[1]x1 = w - d2[:, 2]x2 = w - d2[:, 0]d2 = np.stack([x1, d2[:, 1], x2, d2[:, 3], d2[:, 4]], axis=1)all_d = np.concatenate([d1, d2], axis=0) if len(d2) else d1if len(all_d) == 0:return np.zeros((0, 5), dtype=np.float32)# soft-NMS, then hard-NMSkeep_idx, scores = self._soft_nms(all_d[:, :4].copy(), all_d[:, 4].copy(), sigma=self.sigma)if len(keep_idx) == 0:return np.zeros((0, 5), dtype=np.float32)merged = np.concatenate([all_d[keep_idx, :4], scores[:, None]], axis=1)keep = self._hard_nms(merged[:, :4], merged[:, 4], self.iou_thres)merged = merged[keep]if len(merged) > self.max_det:merged = merged[np.argsort(-merged[:, 4])[: self.max_det]]return merged# ---------- conditional tile pass ----------def _tile_augment(self, image: ndarray, primary: np.ndarray) -> np.ndarray:"""Run 2x2 overlapping tiles + hflip, novelty-merge into primary."""oh, ow = image.shape[:2]tw, th = ow // 2, oh // 2ox, oy = int(tw * self.tile_overlap), int(th * self.tile_overlap)tiles = [(0, 0, min(ow, tw + ox), min(oh, th + oy)),(max(0, tw - ox), 0, ow, min(oh, th + oy)),(0, max(0, th - oy), min(ow, tw + ox), oh),(max(0, tw - ox), max(0, th - oy), ow, oh),]collected: list[np.ndarray] = []for x1, y1, x2, y2 in tiles:crop = image[y1:y2, x1:x2]if crop.size == 0:continued = self._raw_dets(crop, self.tile_conf)if len(d):d[:, 0] += x1d[:, 1] += y1d[:, 2] += x1d[:, 3] += y1collected.append(d)# hflip tile passflipped = cv2.flip(image, 1)for x1, y1, x2, y2 in tiles:fx1 = ow - x2fx2 = ow - x1if fx2 <= fx1:continuecrop = flipped[y1:y2, fx1:fx2]if crop.size == 0:continued = self._raw_dets(crop, self.tile_conf)if len(d):d_un = d.copy()d_un[:, 0] = (ow - (d[:, 2] + fx1))d_un[:, 2] = (ow - (d[:, 0] + fx1))d_un[:, 1] = d[:, 1] + y1d_un[:, 3] = d[:, 3] + y1collected.append(d_un)if not collected:return primarytile_dets = np.concatenate(collected, axis=0)keep = self._hard_nms(tile_dets[:, :4], tile_dets[:, 4], 0.5)tile_dets = tile_dets[keep]# Novelty: drop tile boxes that overlap any primary box at IoU >= novelty_iouif len(primary) > 0 and len(tile_dets) > 0:mask = np.ones(len(tile_dets), dtype=bool)for i in range(len(tile_dets)):ious = self._box_iou_one_to_many(tile_dets[i, :4], primary[:, :4])if len(ious) and np.max(ious) >= self.novelty_iou:mask[i] = Falsetile_dets = tile_dets[mask]if len(tile_dets) == 0:return primary# Sanity filter: min/max size, aspect ratiow = tile_dets[:, 2] - tile_dets[:, 0]h = tile_dets[:, 3] - tile_dets[:, 1]area = w * har = np.maximum(w / np.maximum(h, 1e-6), h / np.maximum(w, 1e-6))img_area = float(ow * oh)ok = (w >= 6) & (h >= 6) & (area >= 36) & (area <= 0.5 * img_area) & (ar <= 10.0)tile_dets = tile_dets[ok]if len(tile_dets) == 0:return primarymerged = np.concatenate([primary, tile_dets], axis=0)keep = self._hard_nms(merged[:, :4], merged[:, 4], self.iou_thres)merged = merged[keep]if len(merged) > self.final_max_det:merged = merged[np.argsort(-merged[:, 4])[: self.final_max_det]]return merged# ---------- single-image predict ----------def _predict_single(self, image: ndarray) -> list[BoundingBox]:if image is None or not isinstance(image, np.ndarray) or image.ndim != 3:return []if image.shape[0] <= 0 or image.shape[1] <= 0 or image.shape[2] != 3:return []if image.dtype != np.uint8:image = image.astype(np.uint8)primary = self._primary(image)if len(primary) < self.sparse_threshold:dets = self._tile_augment(image, primary)else:dets = primaryresults: list[BoundingBox] = []for row in dets:x1, y1, x2, y2, conf = row.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=0,conf=float(conf),))return results# ---------- chute entrypoint ----------def predict_batch(self,batch_images: list[ndarray],1 unmodified linen_keypoints: int,) -> list[TVFrameResult]:results: list[TVFrameResult] = []for frame_number_in_batch, image in enumerate(batch_images):try: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)))],))return results
miner.py+368-144