| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230 |
- """P0-5 标定记录:内参/外参/ROI/比例尺/箱高的入库、哈希校验与过期判定。
- 为什么需要
- ----------
- 现场一旦换机位、调焦、换镜头或重装支架,所有基于像素的阈值(箱高、间隙、
- 门板间距)都会漂移;如果只把标定值散落在配置里,没人能回答“这份结果是用
- 哪次标定算的”。本模块把标定做成**可复核的记录**:
- * 记录文件 ``configs/calib/<site>.json``,字段含标定人/复核人/日期/方法;
- * ``sha256`` 覆盖除自身外的所有字段,现场改一个数就会校验失败;
- * 超过 ``max_age_days``、无复核人、运行期比例尺/箱高与记录不一致 → ``CALIB_STALE``;
- * 记录的 ``px_per_m`` / ``box_height_m`` 可直接对照 ``evidence_v2.*``,用于漂移检查。
- 注意:本模块只做“记录与判定”,不自动改配置;发现 ``CALIB_STALE`` 必须现场
- 重标并复核,不能靠调阈值掩盖。
- """
- from __future__ import annotations
- import copy
- import hashlib
- import hmac
- import json
- import os
- from dataclasses import dataclass, field
- from datetime import datetime, timezone
- from typing import Any, Dict, List, Optional
- from .config import Config
- __all__ = [
- "CalibrationRecord",
- "CalibrationStatus",
- "compute_hash",
- "evaluate",
- "load_record",
- "seal",
- "verify",
- ]
- _REQUIRED = ("site", "camera_id", "calibrated_at")
- def _canonical(record: Dict[str, Any]) -> bytes:
- payload = {key: value for key, value in record.items() if key != "sha256"}
- return json.dumps(
- payload, ensure_ascii=False, sort_keys=True, separators=(",", ":"), default=str
- ).encode("utf-8")
- def compute_hash(record: Dict[str, Any]) -> str:
- """记录内容的 sha256(不含 ``sha256`` 字段本身)。"""
- return hashlib.sha256(_canonical(record)).hexdigest()
- def seal(record: Dict[str, Any]) -> Dict[str, Any]:
- """写入/刷新 ``sha256``,返回同一个 dict。"""
- record = copy.deepcopy(record)
- record["sha256"] = compute_hash(record)
- return record
- def verify(record: Dict[str, Any]) -> bool:
- expected = str(record.get("sha256", ""))
- return bool(expected) and hmac.compare_digest(expected, compute_hash(record))
- def _parse_time(value: object) -> Optional[datetime]:
- text = str(value or "").strip()
- if not text:
- return None
- if text.endswith("Z"):
- text = text[:-1] + "+00:00"
- try:
- parsed = datetime.fromisoformat(text)
- except ValueError:
- return None
- return parsed if parsed.tzinfo is not None else parsed.replace(tzinfo=timezone.utc)
- @dataclass
- class CalibrationRecord:
- site: str
- camera_id: str
- calibrated_at: datetime
- reviewer: str
- method: str = ""
- px_per_m: float = 0.0
- box_height_m: float = 0.0
- intrinsics: Dict[str, object] = field(default_factory=dict)
- extrinsics: Dict[str, object] = field(default_factory=dict)
- roi: List[List[float]] = field(default_factory=list)
- raw: Dict[str, object] = field(default_factory=dict)
- @classmethod
- def from_dict(cls, data: Dict[str, Any]) -> "CalibrationRecord":
- missing = [key for key in _REQUIRED if not str(data.get(key, "")).strip()]
- if missing:
- raise ValueError("标定记录缺少字段: %s" % ", ".join(missing))
- ts = _parse_time(data.get("calibrated_at"))
- if ts is None:
- raise ValueError("calibrated_at 不是 ISO-8601 时间: %r" % data.get("calibrated_at"))
- return cls(
- site=str(data["site"]),
- camera_id=str(data["camera_id"]),
- calibrated_at=ts,
- reviewer=str(data.get("reviewer", "") or ""),
- method=str(data.get("method", "")),
- px_per_m=float(data.get("px_per_m", 0.0) or 0.0),
- box_height_m=float(data.get("box_height_m", 0.0) or 0.0),
- intrinsics=dict(data.get("intrinsics") or {}),
- extrinsics=dict(data.get("extrinsics") or {}),
- roi=[list(map(float, point)) for point in data.get("roi") or []],
- raw=dict(data),
- )
- def to_dict(self) -> Dict[str, object]:
- return copy.deepcopy(self.raw)
- @dataclass
- class CalibrationStatus:
- stale: bool = False
- reasons: List[str] = field(default_factory=list)
- age_days: Optional[float] = None
- hash_ok: bool = False
- record: Optional[CalibrationRecord] = None
- path: str = ""
- # calibration.hold_on_stale:标定不可信时是否清 RESULT_VALID/STABLE(默认 True)。
- # 与 C++ 侧 `portcv::CalibrationStatus::hold` **同名同义**(cpp/include/portcv/calibration.hpp)。
- hold: bool = True
- def to_dict(self) -> Dict[str, object]:
- return {
- "stale": bool(self.stale),
- "reasons": list(self.reasons),
- "age_days": None if self.age_days is None else round(float(self.age_days), 1),
- "hash_ok": bool(self.hash_ok),
- "hold": bool(self.hold),
- "path": self.path,
- "site": self.record.site if self.record is not None else "",
- "camera_id": self.record.camera_id if self.record is not None else "",
- "reviewer": self.record.reviewer if self.record is not None else "",
- "calibrated_at": (
- self.record.calibrated_at.isoformat() if self.record is not None else ""
- ),
- }
- def load_record(path: str) -> CalibrationRecord:
- with open(path, "r", encoding="utf-8") as fh:
- data = json.load(fh)
- if not isinstance(data, dict):
- raise ValueError("标定记录必须是 JSON 对象")
- return CalibrationRecord.from_dict(data)
- def evaluate(
- cfg: Config,
- *,
- now: Optional[datetime] = None,
- record_path: Optional[str] = None,
- ) -> CalibrationStatus:
- """按配置评估标定记录;``calibration.record`` 为空时不做判定(保持兼容)。"""
- override = bool(cfg.get_path("calibration.stale", False))
- hold = bool(cfg.get_path("calibration.hold_on_stale", True))
- path = str(
- cfg.get_path("calibration.record", "") if record_path is None else record_path
- ).strip()
- if not path:
- return CalibrationStatus(
- stale=override, reasons=["manual_stale"] if override else [], hold=hold
- )
- status = CalibrationStatus(path=path, hold=hold)
- if not os.path.isfile(path):
- status.stale = True
- status.reasons.append("missing")
- return status
- now_dt = now or datetime.now(timezone.utc)
- if now_dt.tzinfo is None:
- now_dt = now_dt.replace(tzinfo=timezone.utc)
- try:
- with open(path, "r", encoding="utf-8") as fh:
- data = json.load(fh)
- if not isinstance(data, dict):
- raise ValueError("not an object")
- status.hash_ok = verify(data)
- if not status.hash_ok:
- status.reasons.append("hash_mismatch")
- record = CalibrationRecord.from_dict(data)
- status.record = record
- except Exception as exc: # 记录损坏/字段缺失都按 stale 处理
- status.stale = True
- status.reasons.append("invalid:%s" % type(exc).__name__)
- return status
- age_days = (
- now_dt - record.calibrated_at.astimezone(timezone.utc)
- ).total_seconds() / 86400.0
- status.age_days = age_days
- max_age = float(cfg.get_path("calibration.max_age_days", 180) or 180)
- if max_age > 0 and age_days > max_age:
- status.reasons.append("expired")
- if not record.reviewer.strip():
- status.reasons.append("unreviewed")
- run_px = float(cfg.get_path("evidence_v2.px_per_m", 0.0) or 0.0)
- if record.px_per_m > 0 and run_px > 0:
- tol = max(1e-6, float(cfg.get_path("calibration.px_per_m_tolerance", 0.10) or 0.10))
- if abs(run_px - record.px_per_m) / record.px_per_m > tol:
- status.reasons.append("px_per_m_drift")
- run_box_h = float(cfg.get_path("evidence_v2.box_height_m", 0.0) or 0.0)
- if record.box_height_m > 0 and run_box_h > 0:
- tol_m = max(
- 1e-6, float(cfg.get_path("calibration.box_height_tolerance_m", 0.02) or 0.02)
- )
- if abs(run_box_h - record.box_height_m) > tol_m:
- status.reasons.append("box_height_drift")
- if override:
- status.reasons.append("manual_stale")
- status.stale = bool(status.reasons)
- return status
|