config.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. """配置加载与默认值。
  2. * 原生支持 ``.json``(标准库,现场零依赖)。
  3. * 若安装了 ``pyyaml``,``.yaml`` / ``.yml`` 同样可用;未安装时给出明确提示。
  4. * :data:`DEFAULTS` 是唯一的默认值来源,用户配置只需写要覆盖的字段(深合并)。
  5. """
  6. from __future__ import annotations
  7. import copy
  8. import json
  9. import os
  10. from typing import Any, Dict, List, Optional, Tuple
  11. __all__ = ["Config", "DEFAULTS", "load_config", "deep_update"]
  12. #: 默认配置。与 ``configs/default.json`` 保持一致(后者是给现场改的模板)。
  13. DEFAULTS: Dict[str, Any] = {
  14. "run": {
  15. "mode": "composed", # composed=检测+规则 | direct=模型直接输出三分类
  16. "backend": "mock", # mock | onnx | rknn | tensorrt
  17. "max_fps": 15.0,
  18. "warmup_frames": 3,
  19. "log_level": "INFO",
  20. "log_json": False,
  21. "save_on_change": False, # 状态变化时存图,便于复盘/挖难例
  22. "output_dir": "runs",
  23. "preview": False,
  24. "log_dir": "", # 非空时另写按天轮转文件(P0-4)
  25. "log_retention_days": 90, # 按天备份保留天数
  26. },
  27. "evidence": {
  28. "enabled": False, # 现场确认磁盘/权限后再开
  29. "dir": "", # 空 = <run.output_dir>/evidence
  30. "retention_days": 90,
  31. "segment_mb": 50,
  32. "ring_frames": 300, # 事件视频环缓帧数(15 fps ≈ 20 s)
  33. "fps": 15.0,
  34. "jpeg_quality": 85,
  35. "max_side": 960,
  36. },
  37. "health": {
  38. "enabled": True,
  39. "work_width": 320,
  40. "blur_var_min": 18.0,
  41. "dark_clip_ratio_max": 0.97,
  42. "bright_clip_ratio_max": 0.55,
  43. "low_texture_ratio_max": 0.88,
  44. "degrade_persist_s": 0.8,
  45. "recover_persist_s": 1.5,
  46. },
  47. "source": {
  48. "type": "file", # file | rtsp | usb | gst | images
  49. "uri": "samples/demo.mp4",
  50. "width": 0, # 0 = 用源分辨率
  51. "height": 0,
  52. "buffer_size": 2,
  53. "use_gst": False,
  54. "reconnect_s": 2.0,
  55. "stale_frame_s": 0.6, # 超过该时间没新帧 → FRAME_TIMEOUT
  56. },
  57. "model": {
  58. "path": "weights/model.onnx",
  59. "engine_path": "weights/model.plan", # tensorrt
  60. "rknn_path": "weights/model.rknn", # rockchip
  61. "labels": ["container", "bed", "flatbed", "not_on_train"],
  62. "input_size": [640, 640],
  63. "input_format": "rgb_float", # rgb_float | bgr_uint8 | rgb_uint8
  64. "conf": 0.35,
  65. "iou": 0.5,
  66. "max_det": 60,
  67. "nms_free": False, # True: 模型已内置 NMS(输出 Nx6)
  68. "quantized": False, # rknn int8
  69. "rknn_core": "auto", # auto | 0 | 1 | 2 | 0_1_2
  70. "onnx_providers": ["CUDAExecutionProvider", "CPUExecutionProvider"],
  71. "num_threads": 2,
  72. },
  73. "scene": {
  74. "mode": "composed", # 与 run.mode 同步,留作双保险
  75. "classes": {
  76. "container": ["container", "container_full", "container_empty", "container_20ft", "container_40ft"],
  77. "bed": ["bed", "wagon_bed", "hopper_wagon", "gondola"],
  78. "flatbed": ["flatbed", "flat_wagon", "platform_wagon"],
  79. "ignore": ["person", "people", "crane", "spreader", "truck", "wheel", "rail"],
  80. },
  81. # direct 模式下模型类别名 → 场景编码
  82. "direct_map": {"not_on_train": 0, "bed": 1, "flatbed": 2},
  83. # 归一化 ROI(图像占比),限定在目标车厢区域,抑制远处干扰
  84. "roi": [[0.03, 0.10], [0.97, 0.10], [0.97, 0.99], [0.03, 0.99]],
  85. "require_container": True, # 必须看到集装箱才算"在车上"
  86. "min_class_conf": 0.30,
  87. "roi_min_ratio": 0.30, # 框与 ROI 的重叠比例下限
  88. "support_overlap": 0.30, # 集装箱与车厢框的横向交叠下限
  89. "support_dy_ratio": 0.45, # |车厢顶边 - 箱底边| / 箱高 的容差
  90. "support_score_ratio": 0.60, # 车厢分数 / 集装箱分数的下限
  91. "unknown_on_no_detection": True, # 完全无检测 → UNKNOWN(否则判 0)
  92. "no_container_conf": 0.60, # "没看到集装箱" 时的基础置信度
  93. },
  94. "evidence_v2": {
  95. # P1b/P1c:默认关闭;启用后 VisionPipeline 不再走 SceneClassifier。
  96. "enabled": False,
  97. "view": "front", # front | high
  98. "work_width": 960,
  99. "window": [0.24, 0.02, 0.78, 0.95], # 归一化水平带搜索窗
  100. "band_min_h": 3,
  101. "band_max_h_ratio": 0.15,
  102. "bed_search_ratio": 0.40, # 车体上缘搜索窗 / 估计箱高
  103. "box_bottom_max_ratio": 0.78,
  104. "below_start_ratio": 0.07, # 动态 ROI 起点 = 箱底 + 7% 箱高(避开下侧梁)
  105. "below_height_ratio": 0.55, # 箱底以下动态 ROI 高 / 估计箱高
  106. "below_min_height_px": 24,
  107. "min_door_posts": 5, # 1 的门板立柱下限(A: 8–14, B: 0–4)
  108. "max_door_posts": 16, # 超过 → 箱体波纹/背景误检,弃权
  109. "max_bed_gap_px": 40.0, # 箱体高悬(>0.35m)时不做 1 分类
  110. "flat_max_door_posts": 4,
  111. "max_post_spacing_cv": 6.0,
  112. "min_post_len_ratio": 0.30,
  113. "min_wall_opacity": 0.35,
  114. "max_flat_gap_px": 40.0,
  115. "wall_edge_density_ref": 0.14,
  116. "wall_edge_density_span": 0.04,
  117. "ground_block_px": 32,
  118. "ground_density_lo": 0.02,
  119. "ground_density_hi": 0.35,
  120. "min_flat_ground_ratio": 0.40,
  121. "min_zero_ground_ratio": 0.65,
  122. "deck_min_len_ratio": 0.30,
  123. "box_height_m": 2.591,
  124. "px_per_m": 0.0, # 0 = 用箱体竖棱自标尺
  125. "min_scale_px": 60.0,
  126. "motion_diff_max": 12.0,
  127. "motion_grad_ratio_min": 0.72,
  128. "require_commit": True, # True: commit 不成立时内部输出 255
  129. "allow_state2": True, # 平车 2 已打开提交;与 commit.allow_state2 串联
  130. "structure_hits_min": 0.60,
  131. "commit": {
  132. "gap_m_max": 0.10,
  133. "gap_px_hard_max": 8.0, # 前视箱底 ±5 px 的安全硬门
  134. "stable_frames": 5,
  135. "structure_frames": 5,
  136. "min_structure_hits": 0.60,
  137. "max_gap_rise_m": 0.01,
  138. "allow_state1": True,
  139. "allow_state2": True,
  140. "require_motion_ok": True,
  141. "require_view_known": True,
  142. "use_plc_arrival": True,
  143. },
  144. },
  145. "decision": {
  146. "window": 9, # 滑窗帧数
  147. "window_s": 1.0, # 滑窗时间窗(秒),两者取小
  148. "min_votes": 4, # 窗内同状态最少票数
  149. "min_confidence": 0.45,
  150. "min_dwell_s": 0.20, # 新状态需持续该时长才提交(防抖)
  151. "hold_s": 0.60, # 短暂无有效观测时保持上一状态
  152. "lost_timeout_s": 1.50, # 超时后置 UNKNOWN,让 PLC 回安全态
  153. "low_fps_threshold": 3.0,
  154. "mrc_on_uncertain": True, # 感知不确定时置 MRC_REQUEST(整机 MRC 由 PLC 执行)
  155. },
  156. "calibration": {
  157. "stale": False, # 手工标记过期/漂移(覆盖自动判定)
  158. "record": "", # configs/calib/*.json 路径(P0-5)
  159. "max_age_days": 180, # 超过则 CALIB_STALE
  160. "px_per_m_tolerance": 0.10,
  161. "box_height_tolerance_m": 0.02,
  162. # 标定不可信时是否清 RESULT_VALID/STABLE(默认 True:不给可执行结果)。
  163. # C++ 侧同名同义(cpp/src/calibration.cpp);置 False = 只告警,由 PLC 联锁决定。
  164. "hold_on_stale": True,
  165. },
  166. "plc": {
  167. "enabled": True,
  168. "push": "modbus_server", # modbus_server | snap7 | both | none
  169. "modbus": {
  170. "host": "0.0.0.0",
  171. "port": 1502, # 标准 502 在 Linux 需 root,现场按 PLC 侧要求改
  172. "unit_id": 1,
  173. "input_addr": 0, # 输入寄存器(视觉 → PLC)起始地址
  174. "holding_addr": 0, # 保持寄存器(PLC → 视觉)起始地址
  175. "allow_unit_any": True,
  176. },
  177. "snap7": {
  178. "host": "192.168.0.10",
  179. "rack": 0,
  180. "slot": 1,
  181. "db_number": 100,
  182. "db_start": 0,
  183. "reconnect_s": 3.0,
  184. "tcp_port": 102,
  185. },
  186. "gating": False, # True: 只有 PLC 请求时才推理(省算力)
  187. "gating_timeout_ms": 800,
  188. "heartbeat_ms": 500,
  189. "confidence_scale": 1000,
  190. "min_publish_interval_ms": 50,
  191. },
  192. }
  193. def _load_yaml(path: str) -> Dict[str, Any]:
  194. try:
  195. import yaml # type: ignore
  196. except ImportError as exc: # pragma: no cover - 取决于环境
  197. raise RuntimeError(
  198. "读取 %s 需要 pyyaml,请 `pip install pyyaml`,或改用 .json 配置文件" % path
  199. ) from exc
  200. with open(path, "r", encoding="utf-8") as fh:
  201. return yaml.safe_load(fh) or {}
  202. def deep_update(base: Dict[str, Any], override: Dict[str, Any]) -> Dict[str, Any]:
  203. """把 ``override`` 递归合并进 ``base``(原地修改并返回 base)。"""
  204. for key, value in override.items():
  205. if isinstance(value, dict) and isinstance(base.get(key), dict):
  206. deep_update(base[key], value)
  207. else:
  208. base[key] = copy.deepcopy(value)
  209. return base
  210. class Config:
  211. """轻量配置访问器:``cfg.get_path("plc.modbus.port", 502)``。"""
  212. def __init__(self, data: Optional[Dict[str, Any]] = None) -> None:
  213. self.data: Dict[str, Any] = copy.deepcopy(DEFAULTS)
  214. if data:
  215. deep_update(self.data, data)
  216. # -- 读写 -------------------------------------------------------------
  217. def get_path(self, path: str, default: Any = None) -> Any:
  218. node: Any = self.data
  219. for part in path.split("."):
  220. if not isinstance(node, dict) or part not in node:
  221. return default
  222. node = node[part]
  223. return node
  224. def set_path(self, path: str, value: Any) -> None:
  225. parts = path.split(".")
  226. node = self.data
  227. for part in parts[:-1]:
  228. node = node.setdefault(part, {})
  229. node[parts[-1]] = value
  230. def section(self, name: str) -> Dict[str, Any]:
  231. value = self.data.get(name, {})
  232. return copy.deepcopy(value) if isinstance(value, dict) else {}
  233. def to_dict(self) -> Dict[str, Any]:
  234. return copy.deepcopy(self.data)
  235. def dump(self, path: str) -> None:
  236. """把当前配置写回文件(json),便于现场固化参数。"""
  237. folder = os.path.dirname(os.path.abspath(path))
  238. if folder:
  239. os.makedirs(folder, exist_ok=True)
  240. with open(path, "w", encoding="utf-8") as fh:
  241. json.dump(self.data, fh, ensure_ascii=False, indent=2)
  242. def __getitem__(self, key: str) -> Any:
  243. return self.data[key]
  244. def __contains__(self, key: str) -> bool:
  245. return key in self.data
  246. # -- 便捷属性 ---------------------------------------------------------
  247. @property
  248. def labels(self) -> List[str]:
  249. return list(self.get_path("model.labels", []) or [])
  250. @property
  251. def input_size(self) -> Tuple[int, int]:
  252. size = self.get_path("model.input_size", [640, 640])
  253. return (int(size[0]), int(size[1]))
  254. @property
  255. def roi(self) -> List[Tuple[float, float]]:
  256. return [tuple(map(float, p)) for p in (self.get_path("scene.roi") or [])]
  257. def load_config(path: Optional[str] = None, overrides: Optional[Dict[str, Any]] = None) -> Config:
  258. """加载配置文件(可为 None → 纯默认值),再套用 ``overrides``。"""
  259. data: Dict[str, Any] = {}
  260. if path:
  261. if not os.path.isfile(path):
  262. raise FileNotFoundError("配置文件不存在: %s" % path)
  263. ext = os.path.splitext(path)[1].lower()
  264. if ext in (".yaml", ".yml"):
  265. data = _load_yaml(path)
  266. elif ext == ".json":
  267. with open(path, "r", encoding="utf-8") as fh:
  268. data = json.load(fh) or {}
  269. else:
  270. raise ValueError("不支持的配置文件格式: %s(请用 .json / .yaml)" % ext)
  271. cfg = Config(data)
  272. if overrides:
  273. cfg.data = deep_update(cfg.data, overrides)
  274. return cfg