deploy road-signs
Browse filesFiles changed (2)
- miner.py+69-59
- carwash.onnx → roadsign.onnxRenamed+2-2
123456789101112131415163 unmodified lines2021222324252627282930313233343518 unmodified lines545556575859606131 unmodified lines939495969798991001011021031041051061071081091101111121131141151161171 unmodified line119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170"""TurboVision miner for element `manak0/Detect-car-wash` — ONNX / CPU-safe.Why ONNX-only: the latency-loop compliance checker (branch `latency-loop`) loads THISminer.py in a sandbox whose image has ONLY onnxruntime + cv2 + numpy + pydantic(NO torch, NO ultralytics), forbids `.pt/.pth/.safetensors` files, forbids importingsocket/urllib/http/subprocess and calling open()/eval/exec, blocks the network duringinference, caps memory at 8 GiB, and requires the repo to contain a `.onnx` model.It times `predict_batch` on CPU and needs p95 <= element.latency_p95_ms (target 100 ms),and it re-checks that these outputs match your submitted responses at IoU >= 0.85.So: pure onnxruntime, deterministic, small input size. Classes MUST be in manifestorder (cls_id == index): 0=broom 1=drainage gate 2=nozzle 3=track."""from pathlib import Pathimport os3 unmodified linesimport onnxruntime as ortfrom pydantic import BaseModelCLASSES = ["broom", "drainage gate", "nozzle", "track"]CONF = float(os.environ.get("CARWASH_CONF", "0.15")) # global floor; per-class overrides below# Per-class confidence floors (index == cls_id). Each object sits at its own map50/FP# sweet spot. Override via CARWASH_CONF_PER_CLASS="0.30,0.45,0.20,0.35"._pc = os.environ.get("CARWASH_CONF_PER_CLASS", "")PER_CLASS_CONF = ([float(x) for x in _pc.split(",")] if _pc else [0.20, 0.40, 0.20, 0.20])IOU_NMS = float(os.environ.get("CARWASH_IOU", "0.6"))MAX_DET = int(os.environ.get("CARWASH_MAX_DET", "50"))MODEL_FILE = os.environ.get("CARWASH_MODEL", "carwash.onnx")class BoundingBox(BaseModel):18 unmodified lineskeypoints: list[tuple[int, int]] | None = Nonedef _letterbox(img: np.ndarray, new_shape: tuple[int, int]) -> tuple[np.ndarray, float, float, float]:"""Resize+pad BGR image to new_shape (H,W), keep aspect. Return (img, ratio, pad_w, pad_h)."""h, w = img.shape[:2]nh, nw = new_shaper = min(nh / h, nw / w)31 unmodified linesclass Miner:def __init__(self, path_hf_repo: Path) -> None:model_path = str(Path(path_hf_repo) / MODEL_FILE)providers = os.environ.get("CARWASH_PROVIDERS", "CPUExecutionProvider").split(",")avail = ort.get_available_providers()providers = [p for p in providers if p in avail] or ["CPUExecutionProvider"]so = ort.SessionOptions()so.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALLso.intra_op_num_threads = int(os.environ.get("CARWASH_THREADS", "0")) # 0 = ORT defaultself.sess = ort.InferenceSession(model_path, sess_options=so, providers=providers)self.inp = self.sess.get_inputs()[0]shape = self.inp.shape # [1,3,H,W]; may contain strings if dynamicself.H = int(shape[2]) if isinstance(shape[2], int) else 640self.W = int(shape[3]) if isinstance(shape[3], int) else 640self.nc = len(CLASSES)# warmup so first real call isn't a cold-start outlier in p95dummy = np.zeros((1, 3, self.H, self.W), dtype=np.float32)self.sess.run(None, {self.inp.name: dummy})print(f"✅ Car-wash ONNX loaded {MODEL_FILE} input={self.H}x{self.W} providers={providers} conf={CONF}")def __repr__(self) -> str:return f"CarWash ONNX ({MODEL_FILE}) {self.H}x{self.W} classes={CLASSES} conf={CONF}"def _preprocess(self, img_bgr: np.ndarray):lb, r, pad_w, pad_h = _letterbox(img_bgr, (self.H, self.W))1 unmodified linechw = np.transpose(rgb, (2, 0, 1))return chw, r, pad_w, pad_hdef _postprocess(self, out: np.ndarray, r: float, pad_w: float, pad_h: float,orig_w: int, orig_h: int) -> list[BoundingBox]:# YOLOv8/11 detect ONNX head: (1, 4+nc, N) -> (N, 4+nc), xywh in input pixelspred = out[0]if pred.shape[0] == (4 + self.nc):pred = pred.transpose(1, 0)boxes_xywh = pred[:, :4]cls_scores = pred[:, 4:4 + self.nc]cls_id = cls_scores.argmax(1)conf = cls_scores.max(1)# per-class confidence floorthr = np.array(PER_CLASS_CONF, dtype=np.float32)[cls_id]m = conf >= thrif not m.any():return []boxes_xywh, cls_id, conf = boxes_xywh[m], cls_id[m], conf[m]cx, cy, w, h = boxes_xywh[:, 0], boxes_xywh[:, 1], boxes_xywh[:, 2], boxes_xywh[:, 3]x1 = (cx - w / 2 - pad_w) / ry1 = (cy - h / 2 - pad_h) / rx2 = (cx + w / 2 - pad_w) / ry2 = (cy + h / 2 - pad_h) / rxyxy = np.stack([x1, y1, x2, y2], 1)xyxy[:, [0, 2]] = xyxy[:, [0, 2]].clip(0, orig_w)xyxy[:, [1, 3]] = xyxy[:, [1, 3]].clip(0, orig_h)out_boxes: list[BoundingBox] = []for c in np.unique(cls_id):idx = np.where(cls_id == c)[0]keep = _nms(xyxy[idx], conf[idx], IOU_NMS)for k in keep:j = idx[k]out_boxes.append(BoundingBox(x1=int(xyxy[j, 0]), y1=int(xyxy[j, 1]),x2=int(xyxy[j, 2]), y2=int(xyxy[j, 3]),cls_id=int(c), conf=float(conf[j]),))out_boxes.sort(key=lambda b: b.conf, reverse=True)return out_boxes[:MAX_DET]def predict_batch(self, batch_images, offset: int, n_keypoints: int) -> list[TVFrameResult]:# Run one frame at a time: the exported ONNX has a fixed batch dim of 1, and# per-challenge latency is what the checker measures, so keep each run minimal.results: list[TVFrameResult] = []for i, img in enumerate(batch_images):chw, r, pw, ph = self._preprocess(img)inp = np.ascontiguousarray(chw[None], dtype=np.float32)out = self.sess.run(None, {self.inp.name: inp})[0] # (1, 4+nc, N)boxes = self._postprocess(out, r, pw, ph, img.shape[1], img.shape[0])results.append(TVFrameResult(frame_id=offset + i, boxes=boxes, polygons=[], keypoints=[]))return results1234567891011123 unmodified lines16171819202122232425262728293031323318 unmodified lines5253545556575831 unmodified lines909192939495969798991001011021031041051061071081091101111121131 unmodified line115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180"""TurboVision miner for element `manak0/Detect-road-signs` — ONNX / CPU-safe.Single class: cls_id 0 == "road sign". Element scoring:composite = max(0.6*map50 + 0.4*false_positive - 0.37, 0.01), per-challenge ceiling 0.63.Pure onnxruntime, deterministic, sandbox-safe (only cv2/numpy/onnxruntime/os imports;no network or dynamic-exec calls), requires a `.onnx` in the repo. Runs on a GPU chute,but ALSO passes the 2-vCPU CPU compliance loop (100ms gate): imgsz 512, no TTA -> ~58ms."""from pathlib import Pathimport os3 unmodified linesimport onnxruntime as ortfrom pydantic import BaseModelCLASSES = ["road sign"]# Defaults = winning config from the Optuna postproc study (golden real-GT val,# composite 0.4992 @512, latency 58ms). Compliant, TTA off.CONF = float(os.environ.get("RS_CONF", "0.25")) # single-class conf floorIOU_NMS = float(os.environ.get("RS_IOU", "0.50")) # hard NMS IoUMAX_DET = int(os.environ.get("RS_MAX_DET", "300"))MAX_ASPECT = float(os.environ.get("RS_MAX_ASPECT", "6.0")) # sanity: drop boxes w/ aspect > thisMIN_SIDE = float(os.environ.get("RS_MIN_SIDE", "12")) # sanity: drop boxes w/ min side < this (px)MIN_AREA = float(os.environ.get("RS_MIN_AREA", "100")) # sanity: drop boxes w/ area < this (px^2)USE_TTA = os.environ.get("RS_TTA", "0") not in ("0", "", "false") # OFF for 100ms complianceMODEL_FILE = os.environ.get("RS_MODEL", "roadsign.onnx")class BoundingBox(BaseModel):18 unmodified lineskeypoints: list[tuple[int, int]] | None = Nonedef _letterbox(img: np.ndarray, new_shape: tuple[int, int]):h, w = img.shape[:2]nh, nw = new_shaper = min(nh / h, nw / w)31 unmodified linesclass Miner:def __init__(self, path_hf_repo: Path) -> None:model_path = str(Path(path_hf_repo) / MODEL_FILE)providers = os.environ.get("RS_PROVIDERS", "CPUExecutionProvider").split(",")avail = ort.get_available_providers()providers = [p for p in providers if p in avail] or ["CPUExecutionProvider"]so = ort.SessionOptions()so.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALLso.intra_op_num_threads = int(os.environ.get("RS_THREADS", "0"))self.sess = ort.InferenceSession(model_path, sess_options=so, providers=providers)self.inp = self.sess.get_inputs()[0]shape = self.inp.shape # [1,3,H,W]self.H = int(shape[2]) if isinstance(shape[2], int) else 1024self.W = int(shape[3]) if isinstance(shape[3], int) else 1024self.nc = len(CLASSES)dummy = np.zeros((1, 3, self.H, self.W), dtype=np.float32)self.sess.run(None, {self.inp.name: dummy})print(f"RoadSign ONNX loaded {MODEL_FILE} input={self.H}x{self.W} providers={providers} conf={CONF}")def __repr__(self) -> str:return f"RoadSign ONNX ({MODEL_FILE}) {self.H}x{self.W} conf={CONF} tta={USE_TTA}"def _preprocess(self, img_bgr: np.ndarray):lb, r, pad_w, pad_h = _letterbox(img_bgr, (self.H, self.W))1 unmodified linechw = np.transpose(rgb, (2, 0, 1))return chw, r, pad_w, pad_hdef _decode(self, out: np.ndarray, r: float, pad_w: float, pad_h: float,orig_w: int, orig_h: int, flipped: bool):pred = out[0]if pred.shape[0] == (4 + self.nc):pred = pred.transpose(1, 0)boxes_xywh = pred[:, :4]cls_scores = pred[:, 4:4 + self.nc]conf = cls_scores.max(1)m = conf >= CONFif not m.any():return np.zeros((0, 4), np.float32), np.zeros((0,), np.float32)boxes_xywh, conf = boxes_xywh[m], conf[m]cx, cy, w, h = boxes_xywh[:, 0], boxes_xywh[:, 1], boxes_xywh[:, 2], boxes_xywh[:, 3]x1 = (cx - w / 2 - pad_w) / ry1 = (cy - h / 2 - pad_h) / rx2 = (cx + w / 2 - pad_w) / ry2 = (cy + h / 2 - pad_h) / rif flipped:nx1 = orig_w - x2nx2 = orig_w - x1x1, x2 = nx1, nx2xyxy = np.stack([x1, y1, x2, y2], 1)xyxy[:, [0, 2]] = xyxy[:, [0, 2]].clip(0, orig_w)xyxy[:, [1, 3]] = xyxy[:, [1, 3]].clip(0, orig_h)return xyxy, confdef _finalize(self, xyxy, conf) -> list[BoundingBox]:if len(xyxy) == 0:return []keep = _nms(xyxy, conf, IOU_NMS)[:MAX_DET]out = []for j in keep:w = max(1e-6, xyxy[j, 2] - xyxy[j, 0])h = max(1e-6, xyxy[j, 3] - xyxy[j, 1])if MIN_SIDE > 0 and min(w, h) < MIN_SIDE: # sanity: tiny sidecontinueif MIN_AREA > 0 and (w * h) < MIN_AREA: # sanity: tiny areacontinueif MAX_ASPECT > 0 and max(w / h, h / w) > MAX_ASPECT: # sanity: extreme aspectcontinueout.append(BoundingBox(x1=int(xyxy[j, 0]), y1=int(xyxy[j, 1]),x2=int(xyxy[j, 2]), y2=int(xyxy[j, 3]),cls_id=0, conf=float(conf[j])))return outdef _infer(self, img, flipped: bool):src = img[:, ::-1, :] if flipped else imgchw, r, pw, ph = self._preprocess(src)inp = np.ascontiguousarray(chw[None], dtype=np.float32)out = self.sess.run(None, {self.inp.name: inp})[0]return self._decode(out, r, pw, ph, img.shape[1], img.shape[0], flipped)def predict_batch(self, batch_images, offset: int, n_keypoints: int) -> list[TVFrameResult]:results: list[TVFrameResult] = []for i, img in enumerate(batch_images):xyxy, conf = self._infer(img, flipped=False)if USE_TTA:fx, fs = self._infer(img, flipped=True)xyxy = np.concatenate([xyxy, fx], 0)conf = np.concatenate([conf, fs], 0)boxes = self._finalize(xyxy, conf)results.append(TVFrameResult(frame_id=offset + i, boxes=boxes, polygons=[], keypoints=[]))return results
123version https://git-lfs.github.com/spec/v1oid sha256:261da6e9f7751c04e7e5aa7e78e0977d444b1ffa31447332c2d79ec1d96cf75dsize 10606431123version https://git-lfs.github.com/spec/v1oid sha256:fa9c0d85d9a9beef23beb983c14684c5c57f1caaad8aec2db51d064b983b8186size 10543583
miner.py+69-59
carwash.onnx → roadsign.onnxRenamed+2-2