model_pool.py 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. """模型池:按需加载 YOLO 权重,统一推理接口,自动选择设备。"""
  2. from __future__ import annotations
  3. import logging
  4. import threading
  5. from pathlib import Path
  6. import numpy as np
  7. from .. import config
  8. log = logging.getLogger("dccai.models")
  9. _LOCK = threading.Lock()
  10. _CACHE: dict[str, object] = {}
  11. def resolve_device() -> str:
  12. if config.DEVICE != "auto":
  13. return config.DEVICE
  14. try:
  15. import torch
  16. if torch.cuda.is_available():
  17. return "cuda:0"
  18. if getattr(torch.backends, "mps", None) and torch.backends.mps.is_available():
  19. return "mps"
  20. except Exception: # pragma: no cover
  21. pass
  22. return "cpu"
  23. DEVICE = resolve_device()
  24. def model_exists(path: str) -> bool:
  25. return bool(path) and Path(path).exists()
  26. class YoloModel:
  27. """薄封装,保证线程安全推理。"""
  28. def __init__(self, path: str, key: str, imgsz: int | None = None):
  29. from ultralytics import YOLO
  30. self.key = key
  31. self.path = path
  32. self.imgsz = imgsz or config.IMG_SIZE
  33. self._model = YOLO(path)
  34. self.names: dict[int, str] = dict(self._model.names)
  35. def predict(self, frame: np.ndarray, conf: float = 0.35):
  36. """返回 [{cls, name, conf, xyxy:[x1,y1,x2,y2]}, ...]。"""
  37. results = self._model.predict(
  38. frame, imgsz=self.imgsz, conf=conf, verbose=False, device=DEVICE
  39. )
  40. out: list[dict] = []
  41. for r in results:
  42. boxes = getattr(r, "boxes", None)
  43. if boxes is None:
  44. continue
  45. xyxy = boxes.xyxy.cpu().numpy()
  46. confs = boxes.conf.cpu().numpy()
  47. clss = boxes.cls.cpu().numpy().astype(int)
  48. for (x1, y1, x2, y2), c, k in zip(xyxy, confs, clss):
  49. out.append(
  50. {
  51. "cls": int(k),
  52. "name": self.names.get(int(k), str(k)),
  53. "conf": float(c),
  54. "xyxy": [float(x1), float(y1), float(x2), float(y2)],
  55. }
  56. )
  57. return out
  58. def get_model(key: str) -> YoloModel | None:
  59. """key: safety | generic | shoe | harness | plate"""
  60. path = {
  61. "safety": config.SAFETY_MODEL,
  62. "generic": config.GENERIC_MODEL,
  63. **config.OPTIONAL_MODELS,
  64. }.get(key)
  65. if not model_exists(path):
  66. return None
  67. with _LOCK:
  68. if key not in _CACHE:
  69. log.info("加载模型 %s <- %s (device=%s)", key, path, DEVICE)
  70. _CACHE[key] = YoloModel(path, key)
  71. return _CACHE[key] # type: ignore[return-value]
  72. def availability() -> dict[str, bool]:
  73. return {
  74. "safety": model_exists(config.SAFETY_MODEL),
  75. "generic": model_exists(config.GENERIC_MODEL),
  76. **{k: model_exists(v) for k, v in config.OPTIONAL_MODELS.items()},
  77. }
  78. def categories_payload(lang: str = "zh") -> list[dict]:
  79. """给前端的检测大类清单(按语言本地化),带可用性。"""
  80. avail = availability()
  81. groups = []
  82. for g in config.CATEGORY_GROUPS:
  83. items = []
  84. for it in g["items"]:
  85. need = it.get("need")
  86. items.append(
  87. {
  88. "id": it["id"],
  89. "name": config.category_name(lang, it["id"]),
  90. "desc": config.category_desc(lang, it["id"]),
  91. "available": True if need is None else avail.get(need, False),
  92. "need": need,
  93. }
  94. )
  95. groups.append({"id": g["id"], "name": config.group_name(lang, g["id"]), "items": items})
  96. return groups