deploy road-signs
Browse filesFiles changed (2)
- miner.py+69-59
- carwash.onnx → roadsign.onnxRenamed+2-2
12345678910111213234567891011123 unmodified lines16171823192025262728293031322122232425262728293031323318 unmodified lines52535457585556575831 unmodified lines90919296939495969710198991001041051061011021031041081051061111071081091141101111121131 unmodified line115116117122123124118119120121122123124130125132133134126127136137128129130131132133134135136137138139140141146147148149150151152153154155156157158142143144145146147148149150151152153154155156157158159160161162163164165166167168169170161162171172165166167168173174175176177178179180"""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.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 BaseModel
CLASSES = ["broom", "drainage gate", "nozzle", "track"]CLASSES = ["road sign"]
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")# 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 lines keypoints: list[tuple[int, int]] | None = None
def _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)."""def _letterbox(img: np.ndarray, new_shape: tuple[int, int]): h, w = img.shape[:2] nh, nw = new_shape r = 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(",") 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_ALL so.intra_op_num_threads = int(os.environ.get("CARWASH_THREADS", "0")) # 0 = ORT default so.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]; may contain strings if dynamic self.H = int(shape[2]) if isinstance(shape[2], int) else 640 self.W = int(shape[3]) if isinstance(shape[3], int) else 640 shape = self.inp.shape # [1,3,H,W] self.H = int(shape[2]) if isinstance(shape[2], int) else 1024 self.W = int(shape[3]) if isinstance(shape[3], int) else 1024 self.nc = len(CLASSES) # warmup so first real call isn't a cold-start outlier in p95 dummy = 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}") print(f"RoadSign 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}" 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 line chw = np.transpose(rgb, (2, 0, 1)) return chw, r, pad_w, pad_h
def _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 pixels def _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] cls_id = cls_scores.argmax(1) conf = cls_scores.max(1) # per-class confidence floor thr = np.array(PER_CLASS_CONF, dtype=np.float32)[cls_id] m = conf >= thr m = conf >= CONF if not m.any(): return [] boxes_xywh, cls_id, conf = boxes_xywh[m], cls_id[m], conf[m] 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) / r y1 = (cy - h / 2 - pad_h) / r x2 = (cx + w / 2 - pad_w) / r y2 = (cy + h / 2 - pad_h) / r if flipped: nx1 = orig_w - x2 nx2 = orig_w - x1 x1, x2 = nx1, nx2 xyxy = 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] return xyxy, conf
def _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 side continue if MIN_AREA > 0 and (w * h) < MIN_AREA: # sanity: tiny area continue if MAX_ASPECT > 0 and max(w / h, h / w) > MAX_ASPECT: # sanity: extreme aspect continue out.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 out
def _infer(self, img, flipped: bool): src = img[:, ::-1, :] if flipped else img chw, 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]: # 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]) 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 results12323version https://git-lfs.github.com/spec/v1oid sha256:261da6e9f7751c04e7e5aa7e78e0977d444b1ffa31447332c2d79ec1d96cf75dsize 10606431oid sha256:fa9c0d85d9a9beef23beb983c14684c5c57f1caaad8aec2db51d064b983b8186size 10543583miner.py+69-59
carwash.onnx → roadsign.onnxRenamed+2-2