"""模型池:按需加载 YOLO 权重,统一推理接口,自动选择设备。""" from __future__ import annotations import logging import threading from pathlib import Path import numpy as np from .. import config log = logging.getLogger("dccai.models") _LOCK = threading.Lock() _CACHE: dict[str, object] = {} def resolve_device() -> str: if config.DEVICE != "auto": return config.DEVICE try: import torch if torch.cuda.is_available(): return "cuda:0" if getattr(torch.backends, "mps", None) and torch.backends.mps.is_available(): return "mps" except Exception: # pragma: no cover pass return "cpu" DEVICE = resolve_device() def model_exists(path: str) -> bool: return bool(path) and Path(path).exists() class YoloModel: """薄封装,保证线程安全推理。""" def __init__(self, path: str, key: str, imgsz: int | None = None): from ultralytics import YOLO self.key = key self.path = path self.imgsz = imgsz or config.IMG_SIZE self._model = YOLO(path) self.names: dict[int, str] = dict(self._model.names) def predict(self, frame: np.ndarray, conf: float = 0.35): """返回 [{cls, name, conf, xyxy:[x1,y1,x2,y2]}, ...]。""" results = self._model.predict( frame, imgsz=self.imgsz, conf=conf, verbose=False, device=DEVICE ) out: list[dict] = [] for r in results: boxes = getattr(r, "boxes", None) if boxes is None: continue xyxy = boxes.xyxy.cpu().numpy() confs = boxes.conf.cpu().numpy() clss = boxes.cls.cpu().numpy().astype(int) for (x1, y1, x2, y2), c, k in zip(xyxy, confs, clss): out.append( { "cls": int(k), "name": self.names.get(int(k), str(k)), "conf": float(c), "xyxy": [float(x1), float(y1), float(x2), float(y2)], } ) return out def get_model(key: str) -> YoloModel | None: """key: safety | generic | shoe | harness | plate""" path = { "safety": config.SAFETY_MODEL, "generic": config.GENERIC_MODEL, **config.OPTIONAL_MODELS, }.get(key) if not model_exists(path): return None with _LOCK: if key not in _CACHE: log.info("加载模型 %s <- %s (device=%s)", key, path, DEVICE) _CACHE[key] = YoloModel(path, key) return _CACHE[key] # type: ignore[return-value] def availability() -> dict[str, bool]: return { "safety": model_exists(config.SAFETY_MODEL), "generic": model_exists(config.GENERIC_MODEL), **{k: model_exists(v) for k, v in config.OPTIONAL_MODELS.items()}, } def categories_payload() -> list[dict]: """给前端的检测大类清单,带可用性。""" avail = availability() groups = [] for g in config.CATEGORY_GROUPS: items = [] for it in g["items"]: need = it.get("need") items.append( { "id": it["id"], "name": it["name"], "desc": it.get("desc", ""), "available": True if need is None else avail.get(need, False), "need": need, } ) groups.append({"id": g["id"], "name": g["name"], "items": items}) return groups