replay_check.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  1. """黄金语料回放断言(B-lite 的另外一半):把 C++ 边端 ``--dump-frames`` 的产物当"现场样本"来审。
  2. 为什么需要它(堵住"12 项阈值未整定"的整定通路):
  3. * C++ 侧只负责**采集一次**:逐帧灰度图(P5 PGM)+ 逐项证据 + 结论(``--dump-frames`` → JSONL);
  4. * 之后所有阈值迭代都在 PC 上秒级跑完 —— 本脚本对着基线 JSONL 逐帧比对,
  5. 无需相机、无需板卡、无需 GStreamer。
  6. 用法::
  7. # ① 只审"这一份导出自己站不站得住"(格式 / 自洽 / 像素 CRC / 图与行是否对得上)
  8. python scripts/replay_check.py runs/dump/dump.jsonl
  9. # ② 与基线逐帧对拍(改阈值后必须跑):状态、千分比置信度、14 项证据命中集合、逐帧像素 CRC
  10. python scripts/replay_check.py runs/dump/new.jsonl --baseline runs/dump/golden.jsonl
  11. # ③ 验收门禁:现场状态序列与期望序列的准确率(D2 条款)
  12. python scripts/replay_check.py runs/dump/dump.jsonl --expect-states 0,1,1,2 --min-accuracy 1.0
  13. 目录约定:JSONL 与图默认同目录下的 ``frames/``(C++ 的 ``--dump-dir`` 缺省值);
  14. 若同目录下直接放着 PGM(``--dump-dir`` 指成了 JSONL 同目录),自动识别;也可用 ``--images`` 强制指定。
  15. 只有 JSONL 没存图(行里 ``image`` 为 ``null``)时,像素断言降级为 WARN 而不是 FAIL。
  16. 导出里有**三个**状态字段,别混:
  17. * ``state`` —— 寄存器口径(PublishGate 之后;本帧无结论时是**保持值**,PLC 读到的就是它);
  18. * ``vote_state`` —— TemporalVoter 之后、发布门之前的内部结论(255 = 本帧不足以投票);
  19. * ``edge_state`` —— 本帧证据结论(255 = 本帧弃权 / 看不清 / 运动中不改变判定)。
  20. 安全断言(弃权 / 越界带不足 → 不输出 0/1/2)打在 ``edge_state`` 上;``state`` / ``vote_state`` /
  21. ``edge_state`` 三者不一致时要求 ``STABLE=0``(那只是发布门的保持/滞后,不是口径矛盾)。
  22. 验收序列默认看 ``state``,``--state-field edge_state`` 可改看本帧结论。
  23. 判定:
  24. * **FAIL** —— 契约被破坏(字段缺失/类型不对/帧号不递增/状态码非法/``gray_crc32`` 与像素不符/
  25. 证据摘要与 ``ev`` 不一致/与基线不一致),这些都会让"回放结论 ≠ 现场结论",必须修;
  26. * **WARN** —— 不影响判决的可疑点(例如没存图所以没法验像素);
  27. * 与基线对拍时,``--conf-tol``(默认 0)可放宽容差;``--max-diff``(默认 0)允许少量帧不同的
  28. "整定中间态"也能过——但把差异明细全部打出来,绝不静默;
  29. * 基线自己也会被逐帧验像素(`--baseline-images`,默认同 `--images`):基线被改坏/拷坏时不能拿它冤枉新结果。
  30. 其它:输入允许带 BOM(Windows 工具导出的 JSONL 常见);``--no-pixels`` 只审 JSONL。
  31. 退出码:``0`` 全部通过;``1`` 有 FAIL;``2`` 用法 / 环境问题(文件不存在、JSON 读不动)。
  32. """
  33. from __future__ import annotations
  34. import argparse
  35. import json
  36. import os
  37. import sys
  38. import zlib
  39. REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  40. # C++ 的 frame_dump.cpp 写出的字段(改字段名需两侧同步:见 cpp/include/portcv/frame_dump.hpp)
  41. REQUIRED_KEYS = (
  42. "frame", "ts", "width", "height", "state", "conf", "conf_x1000", "flags", "seq", "ts_s",
  43. "heartbeat", "fps_x10", "latency_ms", "reserved", "reason", "summary", "diag", "diag_name",
  44. "abstain", "conflict", "motion", "hold", "motion_held_s", "scale_ok", "view_limited",
  45. "boxes_seen", "segments_total", "px_per_m", "box_h_px", "box_w_px", "outline_quality",
  46. "out_left_px", "out_right_px", "ground_ratio_full", "ground_ratio_below", "strong_threshold",
  47. "score_a", "score_b", "score_c", "edge_state", "edge_conf", "vote_state", "ev", "image",
  48. "gray_crc32",
  49. )
  50. # EvidenceKey 的枚举顺序(cpp/include/portcv/edge_evidence.hpp),顺序即契约
  51. EVIDENCE_KEYS = ("P1", "P2", "P3", "P4", "F1", "F2", "F3", "F4", "G1", "G2", "G3", "C1", "C2", "C3")
  52. # SceneState:0 不在车上 / 1 车斗 / 2 平板车 / 255 不可信
  53. VALID_STATES = (0, 1, 2, 255)
  54. # StatusBits(schema.hpp)——位不可乱改
  55. BIT_READY, BIT_FRAME_OK, BIT_STABLE, BIT_LOW_FPS = 1, 2, 4, 8
  56. BIT_FRAME_TIMEOUT, BIT_ON_DEMAND, BIT_RESULT_VALID, BIT_PUBLISH_OK = 16, 32, 64, 128
  57. def read_pgm(path: str) -> tuple[int, int, bytes]:
  58. """读 P5 PGM → (宽, 高, 像素字节);解析失败抛 ``ValueError``。
  59. 只认 C++ 侧 ``write_pgm`` 写出的形态(无注释、单空格分隔),但仍按 PGM 规范容忍注释与任意空白,
  60. 这样"别人用 ImageMagick 转过的图"也能读。
  61. """
  62. with open(path, "rb") as fh:
  63. blob = fh.read()
  64. pos = 0
  65. def token() -> bytes:
  66. nonlocal pos
  67. while pos < len(blob):
  68. ch = blob[pos:pos + 1]
  69. if ch in (b" ", b"\t", b"\r", b"\n"):
  70. pos += 1
  71. elif ch == b"#": # 注释到行尾
  72. while pos < len(blob) and blob[pos:pos + 1] not in (b"\n", b"\r"):
  73. pos += 1
  74. else:
  75. break
  76. start = pos
  77. while pos < len(blob) and blob[pos:pos + 1] not in (b" ", b"\t", b"\r", b"\n"):
  78. pos += 1
  79. return blob[start:pos]
  80. magic = token()
  81. if magic != b"P5":
  82. raise ValueError("不是 P5 PGM(magic=%r)" % magic)
  83. try:
  84. width = int(token())
  85. height = int(token())
  86. maxval = int(token())
  87. except ValueError as exc: # 头部不是三个整数
  88. raise ValueError("PGM 头部不完整: %s" % exc) from exc
  89. if maxval != 255:
  90. raise ValueError("maxval 必须是 255(灰度 8bit),实际 %d" % maxval)
  91. if pos < len(blob) and blob[pos:pos + 1] in (b"\r", b"\n"):
  92. pos += 1 # 头部与像素之间只应有一个换行
  93. return width, height, blob[pos:]
  94. class Report:
  95. """收集 FAIL / WARN(明细带帧号,便于直接跳到那一帧看)。"""
  96. def __init__(self, limit: int) -> None:
  97. self.passed = 0
  98. self.fails: list[str] = []
  99. self.warns: list[str] = []
  100. self.limit = limit
  101. def ok(self) -> None:
  102. self.passed += 1
  103. def check(self, cond: bool, what: str) -> bool:
  104. if cond:
  105. self.ok()
  106. else:
  107. self.fail(what)
  108. return bool(cond)
  109. def fail(self, what: str) -> None:
  110. if len(self.fails) < self.limit:
  111. self.fails.append(what)
  112. def warn(self, what: str) -> None:
  113. if len(self.warns) < self.limit:
  114. self.warns.append(what)
  115. def load_jsonl(path: str) -> list:
  116. """读 JSONL → [dict];空行忽略,坏行抛 ``ValueError``(带行号)。
  117. 用 ``utf-8-sig`` 打开:手工编辑/Windows 工具导出的文件常带 BOM,不该因此读不动。
  118. """
  119. rows: list = []
  120. with open(path, "r", encoding="utf-8-sig") as fh:
  121. for lineno, line in enumerate(fh, start=1):
  122. if not line.strip():
  123. continue
  124. try:
  125. obj = json.loads(line)
  126. except ValueError as exc:
  127. raise ValueError("第 %d 行不是合法 JSON: %s" % (lineno, exc)) from exc
  128. if not isinstance(obj, dict):
  129. raise ValueError("第 %d 行不是 JSON 对象" % lineno)
  130. rows.append(obj)
  131. return rows
  132. def pick_images_dir(explicit: str | None, jsonl_dir: str, rows: list) -> str:
  133. """定 PGM 目录:显式给就用它;否则先猜 C++ 的缺省值(`<jsonl 同级>/frames`),
  134. 再退一步猜"PGM 就放在 JSONL 同目录"(现场常把 `--dump-dir` 指成同目录)。
  135. """
  136. if explicit:
  137. return explicit
  138. default_dir = os.path.join(jsonl_dir, "frames")
  139. names = [r.get("image") for r in rows if isinstance(r.get("image"), str)]
  140. if names and not os.path.exists(os.path.join(default_dir, names[0])) \
  141. and os.path.exists(os.path.join(jsonl_dir, names[0])):
  142. print(" (图目录自动识别为 JSONL 同目录;如不对请用 --images 指定)")
  143. return jsonl_dir
  144. return default_dir
  145. def check_one_row(row: dict, rep: Report) -> None:
  146. """单帧自洽性(格式 / 枚举 / 位 / 证据摘要 vs ev)。"""
  147. frame = row.get("frame")
  148. tag = "frame %s" % frame
  149. missing = [k for k in REQUIRED_KEYS if k not in row]
  150. if not rep.check(not missing, "%s: 缺字段 %s" % (tag, missing)):
  151. return
  152. state = row["state"]
  153. rep.check(state in VALID_STATES, "%s: 状态码 %r 不在 {0,1,2,255}" % (tag, state))
  154. # `state` = 寄存器口径(PublishGate 之后,**可能是保持值**);`vote_state` = 投票后结论;
  155. # `edge_state` = 本帧证据结论(255 = 本帧弃权/看不清/运动中不改变判定)。
  156. # 安全断言打在 `edge_state` 上 —— 否则"本帧弃权、寄存器保持上一稳定值"会被误判成
  157. # "弃权却不输出 255"。`state` 另有一条"只许等于投票结论或保持值"的一致性断言。
  158. edge_state = row.get("edge_state", state)
  159. vote_state = row.get("vote_state", state)
  160. rep.check(edge_state in VALID_STATES or edge_state == -1,
  161. "%s: edge_state=%r 不在 {-1,0,1,2,255}(-1 = 该后端不产出)" % (tag, edge_state))
  162. rep.check(vote_state in VALID_STATES or vote_state == -1,
  163. "%s: vote_state=%r 不在 {-1,0,1,2,255}(-1 = 该后端不产出)" % (tag, vote_state))
  164. flags = int(row["flags"])
  165. rep.check(0 <= flags <= 0xFFFF, "%s: flags 越出 16bit(%d)" % (tag, flags))
  166. # 千分比与实际置信度必须一致(PLC 读 1 字,日志读浮点,两者不许漂)
  167. conf = float(row["conf"])
  168. conf_x1000 = int(row["conf_x1000"])
  169. rep.check(abs(conf - conf_x1000 / 1000.0) <= 0.0005,
  170. "%s: conf=%s 与 conf_x1000=%d 不一致" % (tag, conf, conf_x1000))
  171. rep.check(0 <= conf_x1000 <= 1000, "%s: conf_x1000=%d 越界" % (tag, conf_x1000))
  172. edge_conf = row.get("edge_conf", 0.0)
  173. rep.check(isinstance(edge_conf, (int, float)) and 0.0 <= float(edge_conf) <= 1.0,
  174. "%s: edge_conf=%r 不在 0..1" % (tag, edge_conf))
  175. # flags 位语义(schema.hpp / plc_interface.md)
  176. if (flags & BIT_FRAME_OK) and (flags & BIT_FRAME_TIMEOUT):
  177. rep.fail("%s: FRAME_OK 与 FRAME_TIMEOUT 同时为 1(口径矛盾)" % tag)
  178. else:
  179. rep.ok()
  180. if flags & BIT_FRAME_TIMEOUT:
  181. rep.check(state == 255, "%s: FRAME_TIMEOUT=1 但 state=%r(必须 255)" % (tag, state))
  182. else:
  183. rep.ok()
  184. if flags & BIT_RESULT_VALID:
  185. rep.check(state != 255, "%s: RESULT_VALID=1 但 state=%r(契约矛盾)" % (tag, state))
  186. else:
  187. rep.ok()
  188. # 数值合理性(寄存器字宽)
  189. for key in ("heartbeat", "fps_x10", "latency_ms", "reserved"):
  190. rep.check(0 <= int(row[key]) <= 0xFFFF, "%s: %s=%s 越出 16bit" % (tag, key, row[key]))
  191. # 证据明细有两种口径,**都必须能过**(否则"换后端就回归不了"):
  192. # * `edge`(v1):`ev` 里 14 项证据齐全,summary 是 `[P1 F2 ] sA=...` 命中串;
  193. # * `edge-v2`:没有 14 项 `ev`(v2 的证据是动态 ROI 的结构量),summary 形如
  194. # `state=1 ... commit=1(commit) ... abstain=hoist_high`。
  195. ev = row["ev"]
  196. if not rep.check(isinstance(ev, dict), "%s: ev 不是对象" % tag):
  197. return
  198. has_v1_ev = all(k in ev for k in EVIDENCE_KEYS)
  199. summary = str(row["summary"])
  200. if has_v1_ev:
  201. bad_ev = [k for k, v in ev.items() if not isinstance(v, bool)]
  202. rep.check(not bad_ev, "%s: ev 取值不是布尔 %s" % (tag, bad_ev))
  203. hits = set(summary[1:summary.find("]")].split()) if "]" in summary else set()
  204. want = {k for k in EVIDENCE_KEYS if ev.get(k) is True}
  205. rep.check(hits == want, "%s: summary 命中 %s 与 ev 命中 %s 不一致"
  206. % (tag, sorted(hits), sorted(want)))
  207. else:
  208. # v2:summary 必须自带 state/commit(现场只看日志也能回答"为什么"),
  209. # 且 `state=` 必须等于本帧结论(255 = 弃权,summary 不带 state= 前缀)。
  210. rep.check("state=" in summary and "commit=" in summary,
  211. "%s: 既没有 14 项 ev,summary 也不是 v2 口径(缺 state=/commit=)" % tag)
  212. if edge_state in (0, 1, 2, 3):
  213. rep.check(("state=%d" % edge_state) in summary,
  214. "%s: summary 的 state= 与 edge_state=%d 不一致" % (tag, edge_state))
  215. else:
  216. rep.ok()
  217. # P0-0 图像侧安全门(吊具高悬 / 吊具仍夹箱):summary 里出现命中标记时,
  218. # 本帧结论必须是弃权(255)—— 这是"箱还在半空也照样攒够 5 帧 commit"的唯一刹车。
  219. if "hoist=" in summary or "spreader=1" in summary:
  220. rep.check(edge_state == 255,
  221. "%s: 高悬/夹箱门命中但本帧结论 edge_state=%r(必须 255)" % (tag, edge_state))
  222. rep.check(row["abstain"] is True, "%s: 高悬/夹箱门命中但 abstain=false" % tag)
  223. else:
  224. rep.ok()
  225. # 弃权 / 看不清 → 本帧结论绝不输出 0/1/2(安全铁律)。
  226. # 打在本帧结论 edge_state 上;寄存器口径允许"无结论时保持上一稳定值"。
  227. if row["abstain"] is True:
  228. rep.check(edge_state == 255,
  229. "%s: abstain=true 但本帧结论 edge_state=%r(必须 255)" % (tag, edge_state))
  230. else:
  231. rep.ok()
  232. if row["view_limited"] is True:
  233. rep.check(edge_state != 2,
  234. "%s: view_limited=true 但本帧结论 edge_state=2(越界带不足不许输出平板车)" % tag)
  235. else:
  236. rep.ok()
  237. # 发布值 / 投票结论 / 本帧结论三者不一致时,必须"未稳定"(STABLE=0)——
  238. # 那只是 PublishGate 的保持/滞后;STABLE=1 还不一致就是口径矛盾。
  239. if state != 255 and vote_state not in (state, 255, -1):
  240. rep.check(
  241. not (flags & BIT_STABLE),
  242. "%s: 发布 state=%r ≠ 投票 vote_state=%r,但 STABLE=1(不是保持滞后,是口径矛盾)"
  243. % (tag, state, vote_state))
  244. else:
  245. rep.ok()
  246. if edge_state in (0, 1, 2) and vote_state in (0, 1, 2) and vote_state != edge_state:
  247. rep.check(
  248. not (flags & BIT_STABLE),
  249. "%s: 本帧结论 edge_state=%r ≠ 投票 vote_state=%r,但 STABLE=1(投票器把 1/2 混了)"
  250. % (tag, edge_state, vote_state))
  251. else:
  252. rep.ok()
  253. def check_sequence(rows: list, rep: Report) -> None:
  254. """跨帧:帧号严格递增、时间戳非递减、序号/心跳单调。"""
  255. prev_frame, prev_ts, prev_hb = None, None, None
  256. for row in rows:
  257. frame = row.get("frame")
  258. if not rep.check(isinstance(frame, int), "帧号不是整数: %r" % frame):
  259. continue
  260. if prev_frame is not None:
  261. if not rep.check(frame > prev_frame, "帧号不严格递增: %s -> %s" % (prev_frame, frame)):
  262. prev_frame = frame
  263. continue
  264. prev_frame = frame
  265. ts = row.get("ts")
  266. if isinstance(ts, (int, float)):
  267. if prev_ts is not None and ts < prev_ts - 1e-6:
  268. rep.fail("时间戳倒退: %.6f -> %.6f(frame %s)" % (prev_ts, ts, frame))
  269. else:
  270. rep.ok()
  271. prev_ts = ts
  272. hb = row.get("heartbeat")
  273. if isinstance(hb, int) and prev_hb is not None:
  274. # 16bit 回绕:只允许"不变 / +1 / 从 65535 跳回 0"
  275. if hb == prev_hb or hb == (prev_hb + 1) & 0xFFFF:
  276. rep.ok()
  277. else:
  278. rep.fail("心跳跳变: %d -> %d(frame %s)" % (prev_hb, hb, frame))
  279. if isinstance(hb, int):
  280. prev_hb = hb
  281. def check_pixels(rows: list, images_dir: str, rep: Report) -> int:
  282. """像素逐字节断言:PGM 头 = 行里的 width/height、像素 CRC = ``zlib.crc32``。返回校验帧数。"""
  283. checked = 0
  284. for row in rows:
  285. frame = row.get("frame")
  286. tag = "frame %s" % frame
  287. name = row.get("image")
  288. if name is None:
  289. rep.warn("%s: 未存图(--dump-dir 没给?)—— 像素无法断言" % tag)
  290. continue
  291. if not rep.check(isinstance(name, str), "%s: image 字段不是字符串" % tag):
  292. continue
  293. path = os.path.join(images_dir, name)
  294. if not rep.check(os.path.exists(path), "%s: 图不存在 %s" % (tag, path)):
  295. continue
  296. try:
  297. w, h, pixels = read_pgm(path)
  298. except (OSError, ValueError) as exc:
  299. rep.fail("%s: PGM 读不动 %s: %s" % (tag, path, exc))
  300. continue
  301. rep.check((w, h) == (row["width"], row["height"]),
  302. "%s: PGM 尺寸 %dx%d 与行里 %rx%r 不一致"
  303. % (tag, w, h, row["width"], row["height"]))
  304. rep.check(len(pixels) == w * h, "%s: 像素字节数 %d ≠ %dx%d" % (tag, len(pixels), w, h))
  305. crc = row.get("gray_crc32")
  306. if crc is None:
  307. rep.fail("%s: 有图但 gray_crc32 为 null" % tag)
  308. else:
  309. ours = zlib.crc32(pixels) & 0xFFFFFFFF
  310. rep.check(int(crc) == ours,
  311. "%s: gray_crc32=%s 与像素实算 %d 不符(像素被改过)" % (tag, crc, ours))
  312. checked += 1
  313. return checked
  314. def compare_baseline(new_rows: list, base_rows: list, conf_tol: float, max_diff: int,
  315. rep: Report) -> dict:
  316. """与基线逐帧对拍:状态 / 千分比置信度 / 14 项证据命中 / 像素 CRC。"""
  317. base_by_frame = {}
  318. for row in base_rows:
  319. if isinstance(row.get("frame"), int):
  320. base_by_frame[row["frame"]] = row
  321. stats = {"state": 0, "edge_state": 0, "vote_state": 0, "conf": 0, "ev": 0, "pixels": 0,
  322. "missing": 0, "compared": 0}
  323. for row in new_rows:
  324. frame = row.get("frame")
  325. base = base_by_frame.get(frame)
  326. if base is None:
  327. stats["missing"] += 1
  328. rep.fail("frame %s: 基线里没有这一帧(样本集缩小了?)" % frame)
  329. continue
  330. stats["compared"] += 1
  331. if row["state"] != base.get("state"):
  332. stats["state"] += 1
  333. rep.fail("frame %s: 状态 %r -> %r(基线 %r)" % (frame, base.get("state"), row["state"],
  334. base.get("state")))
  335. if row.get("edge_state") != base.get("edge_state"):
  336. stats["edge_state"] += 1
  337. rep.fail("frame %s: 本帧结论 edge_state %r -> %r(基线 %r)"
  338. % (frame, base.get("edge_state"), row.get("edge_state"),
  339. base.get("edge_state")))
  340. if row.get("vote_state") != base.get("vote_state"):
  341. stats["vote_state"] += 1
  342. rep.fail("frame %s: 投票结论 vote_state %r -> %r(基线 %r)"
  343. % (frame, base.get("vote_state"), row.get("vote_state"),
  344. base.get("vote_state")))
  345. if abs(int(row["conf_x1000"]) - int(base.get("conf_x1000", 0))) > conf_tol * 1000:
  346. stats["conf"] += 1
  347. rep.fail("frame %s: 置信度 %s -> %s(容差 %.3f)"
  348. % (frame, base.get("conf_x1000"), row["conf_x1000"], conf_tol))
  349. base_hits = {k for k, v in (base.get("ev") or {}).items() if v is True}
  350. new_hits = {k for k, v in row["ev"].items() if v is True}
  351. if base_hits != new_hits:
  352. stats["ev"] += 1
  353. rep.fail("frame %s: 证据命中 +%s / -%s" % (frame, sorted(new_hits - base_hits),
  354. sorted(base_hits - new_hits)))
  355. if base.get("gray_crc32") is not None and row.get("gray_crc32") is not None:
  356. if int(base["gray_crc32"]) != int(row["gray_crc32"]):
  357. stats["pixels"] += 1
  358. rep.fail("frame %s: 像素 CRC 变了(%s -> %s)" % (frame, base["gray_crc32"],
  359. row["gray_crc32"]))
  360. total_diff = (stats["state"] + stats["edge_state"] + stats["vote_state"] + stats["conf"] +
  361. stats["ev"] + stats["pixels"] + stats["missing"])
  362. rep.check(total_diff <= max_diff,
  363. "与基线差异 %d 处超过 --max-diff=%d(明细见上)" % (total_diff, max_diff))
  364. return stats
  365. def state_sequence(rows: list, field: str = "state") -> list:
  366. """连续相同状态合并 → 状态变化序列(现场关心的其实是"切换")。
  367. 断流(255)也算一次变化:它正是"相机/网络异常"的现场证据。
  368. ``field`` 选 ``state``(寄存器口径,默认)或 ``edge_state``(本帧证据结论)。
  369. """
  370. seq: list = []
  371. for row in rows:
  372. state = row.get(field)
  373. if not seq or seq[-1] != state:
  374. seq.append(state)
  375. return seq
  376. def parse_states(text: str) -> list:
  377. """``"0,1,255"`` → ``[0, 1, 255]``;非法值抛 ``ValueError``。"""
  378. out: list = []
  379. for part in str(text).split(","):
  380. part = part.strip()
  381. if not part:
  382. continue
  383. value = int(part, 10)
  384. if value not in VALID_STATES:
  385. raise ValueError("期望序列里的 %d 不是合法状态码(只用 0/1/2/255)" % value)
  386. out.append(value)
  387. if not out:
  388. raise ValueError("--expect-states 为空")
  389. return out
  390. def check_expect_states(rows: list, want: list, min_accuracy: float, rep: Report,
  391. field: str = "state") -> None:
  392. """把"连续相同合并后的状态序列"与期望序列比对,报准确率(现场验收条款)。"""
  393. got = state_sequence(rows, field)
  394. hit = sum(1 for a, b in zip(got, want) if a == b)
  395. total = max(len(got), len(want))
  396. acc = hit / total if total else 0.0
  397. print(" 期望状态序列(%s): %s" % (field, ",".join(str(s) for s in want)))
  398. print(" 实际状态序列(%s): %s" % (field, ",".join(str(s) for s in got)))
  399. print(" 状态序列准确率: %d/%d = %.3f(门限 %.3f)" % (hit, total, acc, min_accuracy))
  400. rep.check(got == want, "状态序列与期望不一致(逐位看上面两行)")
  401. rep.check(acc >= min_accuracy, "状态序列准确率 %.3f < 门限 %.3f" % (acc, min_accuracy))
  402. def main(argv: list | None = None) -> int:
  403. parser = argparse.ArgumentParser(description="黄金语料回放断言(C++ --dump-frames 产物)")
  404. parser.add_argument("jsonl", help="--dump-frames 写出的 JSONL(每帧一行)")
  405. parser.add_argument("--baseline", default=None,
  406. help="基线 JSONL:逐帧对拍状态 / 置信度 / 证据命中 / 像素 CRC")
  407. parser.add_argument("--images", default=None,
  408. help="PGM 目录(默认:JSONL 同目录下的 frames/)")
  409. parser.add_argument("--baseline-images", default=None,
  410. help="基线 PGM 目录(默认同 --images;用来校验基线自己没被改坏)")
  411. parser.add_argument("--conf-tol", type=float, default=0.0,
  412. help="置信度容差(0 = 必须逐位一致;整定中间态可给 0.02)")
  413. parser.add_argument("--max-diff", type=int, default=0,
  414. help="允许与基线不同的帧数(0 = 必须完全一致)")
  415. parser.add_argument("--expect-states", default=None,
  416. help='期望状态序列(逗号分隔,如 "0,1,1,2";相邻重复自动合并)')
  417. parser.add_argument("--state-field", default="state", choices=("state", "edge_state"),
  418. help="状态序列比对用哪个字段:state = 寄存器口径(默认,含保持值);"
  419. "edge_state = 本帧证据结论")
  420. parser.add_argument("--min-accuracy", type=float, default=1.0, help="状态序列准确率门限")
  421. parser.add_argument("--no-pixels", action="store_true", help="跳过像素断言(只审 JSONL)")
  422. parser.add_argument("--limit", type=int, default=20, help="最多打印多少条 FAIL / WARN")
  423. parser.add_argument("--report", default=None, help="把报告另存一份(UTF-8)")
  424. args = parser.parse_args(argv)
  425. if not os.path.exists(args.jsonl):
  426. print("找不到导出文件: %s" % args.jsonl, file=sys.stderr)
  427. print("先生成:portcv_run --backend edge --source-type synth --source-uri gondola "
  428. "--dump-frames out/dump.jsonl --dump-dir out/frames --max-frames 30 --no-plc",
  429. file=sys.stderr)
  430. return 2
  431. jsonl_dir = os.path.dirname(os.path.abspath(args.jsonl))
  432. try:
  433. rows = load_jsonl(args.jsonl)
  434. base_rows = load_jsonl(args.baseline) if args.baseline else []
  435. want_states = parse_states(args.expect_states) if args.expect_states else []
  436. except (OSError, ValueError) as exc:
  437. print("读不动输入: %s" % exc, file=sys.stderr)
  438. return 2
  439. if not rows:
  440. print("导出文件里一帧都没有: %s" % args.jsonl, file=sys.stderr)
  441. return 2
  442. images = pick_images_dir(args.images, jsonl_dir, rows)
  443. if args.baseline:
  444. base_images = pick_images_dir(args.baseline_images,
  445. os.path.dirname(os.path.abspath(args.baseline)), base_rows)
  446. else:
  447. base_images = images
  448. rep = Report(args.limit)
  449. print("回放断言: %s(%d 帧)" % (args.jsonl, len(rows)))
  450. for row in rows:
  451. check_one_row(row, rep)
  452. check_sequence(rows, rep)
  453. pixel_frames = 0 if args.no_pixels else check_pixels(rows, images, rep)
  454. if args.baseline:
  455. print("与基线对拍: %s(容差 %.3f / 允许差异 %d 帧)"
  456. % (args.baseline, args.conf_tol, args.max_diff))
  457. stats = compare_baseline(rows, base_rows, args.conf_tol, args.max_diff, rep)
  458. print(" 逐帧比对 %d 帧;差异:状态 %d / 本帧结论 %d / 投票结论 %d / 置信度 %d / 证据 %d /"
  459. " 像素 %d / 缺帧 %d"
  460. % (stats["compared"], stats["state"], stats["edge_state"], stats["vote_state"],
  461. stats["conf"], stats["ev"], stats["pixels"], stats["missing"]))
  462. if not args.no_pixels and base_images:
  463. # 基线自己也要站得住:基线图被人改过 / 拷坏过时,上面的"差异"会冤枉新结果
  464. base_checked = check_pixels(base_rows, base_images, rep)
  465. print(" 基线像素逐字节校验帧数: %d" % base_checked)
  466. if want_states:
  467. check_expect_states(rows, want_states, args.min_accuracy, rep, args.state_field)
  468. print(" 像素逐字节校验帧数: %d" % pixel_frames)
  469. lines = ["===================== 汇总 =====================",
  470. "通过断言 %d 项" % rep.passed]
  471. for item in rep.warns:
  472. lines.append("[WARN] %s" % item)
  473. for item in rep.fails:
  474. lines.append("[FAIL] %s" % item)
  475. lines.append("结论: %s(FAIL %d / WARN %d)"
  476. % ("PASS" if not rep.fails else "FAIL", len(rep.fails), len(rep.warns)))
  477. text = "\n".join(lines)
  478. print(text)
  479. if args.report:
  480. os.makedirs(os.path.dirname(os.path.abspath(args.report)), exist_ok=True)
  481. with open(args.report, "w", encoding="utf-8") as fh:
  482. fh.write(text + "\n")
  483. print("报告已写入: %s" % args.report)
  484. return 1 if rep.fails else 0
  485. if __name__ == "__main__":
  486. sys.exit(main())