calibration.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. """P0-5 标定记录:内参/外参/ROI/比例尺/箱高的入库、哈希校验与过期判定。
  2. 为什么需要
  3. ----------
  4. 现场一旦换机位、调焦、换镜头或重装支架,所有基于像素的阈值(箱高、间隙、
  5. 门板间距)都会漂移;如果只把标定值散落在配置里,没人能回答“这份结果是用
  6. 哪次标定算的”。本模块把标定做成**可复核的记录**:
  7. * 记录文件 ``configs/calib/<site>.json``,字段含标定人/复核人/日期/方法;
  8. * ``sha256`` 覆盖除自身外的所有字段,现场改一个数就会校验失败;
  9. * 超过 ``max_age_days``、无复核人、运行期比例尺/箱高与记录不一致 → ``CALIB_STALE``;
  10. * 记录的 ``px_per_m`` / ``box_height_m`` 可直接对照 ``evidence_v2.*``,用于漂移检查。
  11. 注意:本模块只做“记录与判定”,不自动改配置;发现 ``CALIB_STALE`` 必须现场
  12. 重标并复核,不能靠调阈值掩盖。
  13. """
  14. from __future__ import annotations
  15. import copy
  16. import hashlib
  17. import hmac
  18. import json
  19. import os
  20. from dataclasses import dataclass, field
  21. from datetime import datetime, timezone
  22. from typing import Any, Dict, List, Optional
  23. from .config import Config
  24. __all__ = [
  25. "CalibrationRecord",
  26. "CalibrationStatus",
  27. "compute_hash",
  28. "evaluate",
  29. "load_record",
  30. "seal",
  31. "verify",
  32. ]
  33. _REQUIRED = ("site", "camera_id", "calibrated_at")
  34. def _canonical(record: Dict[str, Any]) -> bytes:
  35. payload = {key: value for key, value in record.items() if key != "sha256"}
  36. return json.dumps(
  37. payload, ensure_ascii=False, sort_keys=True, separators=(",", ":"), default=str
  38. ).encode("utf-8")
  39. def compute_hash(record: Dict[str, Any]) -> str:
  40. """记录内容的 sha256(不含 ``sha256`` 字段本身)。"""
  41. return hashlib.sha256(_canonical(record)).hexdigest()
  42. def seal(record: Dict[str, Any]) -> Dict[str, Any]:
  43. """写入/刷新 ``sha256``,返回同一个 dict。"""
  44. record = copy.deepcopy(record)
  45. record["sha256"] = compute_hash(record)
  46. return record
  47. def verify(record: Dict[str, Any]) -> bool:
  48. expected = str(record.get("sha256", ""))
  49. return bool(expected) and hmac.compare_digest(expected, compute_hash(record))
  50. def _parse_time(value: object) -> Optional[datetime]:
  51. text = str(value or "").strip()
  52. if not text:
  53. return None
  54. if text.endswith("Z"):
  55. text = text[:-1] + "+00:00"
  56. try:
  57. parsed = datetime.fromisoformat(text)
  58. except ValueError:
  59. return None
  60. return parsed if parsed.tzinfo is not None else parsed.replace(tzinfo=timezone.utc)
  61. @dataclass
  62. class CalibrationRecord:
  63. site: str
  64. camera_id: str
  65. calibrated_at: datetime
  66. reviewer: str
  67. method: str = ""
  68. px_per_m: float = 0.0
  69. box_height_m: float = 0.0
  70. intrinsics: Dict[str, object] = field(default_factory=dict)
  71. extrinsics: Dict[str, object] = field(default_factory=dict)
  72. roi: List[List[float]] = field(default_factory=list)
  73. raw: Dict[str, object] = field(default_factory=dict)
  74. @classmethod
  75. def from_dict(cls, data: Dict[str, Any]) -> "CalibrationRecord":
  76. missing = [key for key in _REQUIRED if not str(data.get(key, "")).strip()]
  77. if missing:
  78. raise ValueError("标定记录缺少字段: %s" % ", ".join(missing))
  79. ts = _parse_time(data.get("calibrated_at"))
  80. if ts is None:
  81. raise ValueError("calibrated_at 不是 ISO-8601 时间: %r" % data.get("calibrated_at"))
  82. return cls(
  83. site=str(data["site"]),
  84. camera_id=str(data["camera_id"]),
  85. calibrated_at=ts,
  86. reviewer=str(data.get("reviewer", "") or ""),
  87. method=str(data.get("method", "")),
  88. px_per_m=float(data.get("px_per_m", 0.0) or 0.0),
  89. box_height_m=float(data.get("box_height_m", 0.0) or 0.0),
  90. intrinsics=dict(data.get("intrinsics") or {}),
  91. extrinsics=dict(data.get("extrinsics") or {}),
  92. roi=[list(map(float, point)) for point in data.get("roi") or []],
  93. raw=dict(data),
  94. )
  95. def to_dict(self) -> Dict[str, object]:
  96. return copy.deepcopy(self.raw)
  97. @dataclass
  98. class CalibrationStatus:
  99. stale: bool = False
  100. reasons: List[str] = field(default_factory=list)
  101. age_days: Optional[float] = None
  102. hash_ok: bool = False
  103. record: Optional[CalibrationRecord] = None
  104. path: str = ""
  105. # calibration.hold_on_stale:标定不可信时是否清 RESULT_VALID/STABLE(默认 True)。
  106. # 与 C++ 侧 `portcv::CalibrationStatus::hold` **同名同义**(cpp/include/portcv/calibration.hpp)。
  107. hold: bool = True
  108. def to_dict(self) -> Dict[str, object]:
  109. return {
  110. "stale": bool(self.stale),
  111. "reasons": list(self.reasons),
  112. "age_days": None if self.age_days is None else round(float(self.age_days), 1),
  113. "hash_ok": bool(self.hash_ok),
  114. "hold": bool(self.hold),
  115. "path": self.path,
  116. "site": self.record.site if self.record is not None else "",
  117. "camera_id": self.record.camera_id if self.record is not None else "",
  118. "reviewer": self.record.reviewer if self.record is not None else "",
  119. "calibrated_at": (
  120. self.record.calibrated_at.isoformat() if self.record is not None else ""
  121. ),
  122. }
  123. def load_record(path: str) -> CalibrationRecord:
  124. with open(path, "r", encoding="utf-8") as fh:
  125. data = json.load(fh)
  126. if not isinstance(data, dict):
  127. raise ValueError("标定记录必须是 JSON 对象")
  128. return CalibrationRecord.from_dict(data)
  129. def evaluate(
  130. cfg: Config,
  131. *,
  132. now: Optional[datetime] = None,
  133. record_path: Optional[str] = None,
  134. ) -> CalibrationStatus:
  135. """按配置评估标定记录;``calibration.record`` 为空时不做判定(保持兼容)。"""
  136. override = bool(cfg.get_path("calibration.stale", False))
  137. hold = bool(cfg.get_path("calibration.hold_on_stale", True))
  138. path = str(
  139. cfg.get_path("calibration.record", "") if record_path is None else record_path
  140. ).strip()
  141. if not path:
  142. return CalibrationStatus(
  143. stale=override, reasons=["manual_stale"] if override else [], hold=hold
  144. )
  145. status = CalibrationStatus(path=path, hold=hold)
  146. if not os.path.isfile(path):
  147. status.stale = True
  148. status.reasons.append("missing")
  149. return status
  150. now_dt = now or datetime.now(timezone.utc)
  151. if now_dt.tzinfo is None:
  152. now_dt = now_dt.replace(tzinfo=timezone.utc)
  153. try:
  154. with open(path, "r", encoding="utf-8") as fh:
  155. data = json.load(fh)
  156. if not isinstance(data, dict):
  157. raise ValueError("not an object")
  158. status.hash_ok = verify(data)
  159. if not status.hash_ok:
  160. status.reasons.append("hash_mismatch")
  161. record = CalibrationRecord.from_dict(data)
  162. status.record = record
  163. except Exception as exc: # 记录损坏/字段缺失都按 stale 处理
  164. status.stale = True
  165. status.reasons.append("invalid:%s" % type(exc).__name__)
  166. return status
  167. age_days = (
  168. now_dt - record.calibrated_at.astimezone(timezone.utc)
  169. ).total_seconds() / 86400.0
  170. status.age_days = age_days
  171. max_age = float(cfg.get_path("calibration.max_age_days", 180) or 180)
  172. if max_age > 0 and age_days > max_age:
  173. status.reasons.append("expired")
  174. if not record.reviewer.strip():
  175. status.reasons.append("unreviewed")
  176. run_px = float(cfg.get_path("evidence_v2.px_per_m", 0.0) or 0.0)
  177. if record.px_per_m > 0 and run_px > 0:
  178. tol = max(1e-6, float(cfg.get_path("calibration.px_per_m_tolerance", 0.10) or 0.10))
  179. if abs(run_px - record.px_per_m) / record.px_per_m > tol:
  180. status.reasons.append("px_per_m_drift")
  181. run_box_h = float(cfg.get_path("evidence_v2.box_height_m", 0.0) or 0.0)
  182. if record.box_height_m > 0 and run_box_h > 0:
  183. tol_m = max(
  184. 1e-6, float(cfg.get_path("calibration.box_height_tolerance_m", 0.02) or 0.02)
  185. )
  186. if abs(run_box_h - record.box_height_m) > tol_m:
  187. status.reasons.append("box_height_drift")
  188. if override:
  189. status.reasons.append("manual_stale")
  190. status.stale = bool(status.reasons)
  191. return status