| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119 |
- """模型池:按需加载 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
|