| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566 |
- """黄金语料回放断言(B-lite 的另外一半):把 C++ 边端 ``--dump-frames`` 的产物当"现场样本"来审。
- 为什么需要它(堵住"12 项阈值未整定"的整定通路):
- * C++ 侧只负责**采集一次**:逐帧灰度图(P5 PGM)+ 逐项证据 + 结论(``--dump-frames`` → JSONL);
- * 之后所有阈值迭代都在 PC 上秒级跑完 —— 本脚本对着基线 JSONL 逐帧比对,
- 无需相机、无需板卡、无需 GStreamer。
- 用法::
- # ① 只审"这一份导出自己站不站得住"(格式 / 自洽 / 像素 CRC / 图与行是否对得上)
- python scripts/replay_check.py runs/dump/dump.jsonl
- # ② 与基线逐帧对拍(改阈值后必须跑):状态、千分比置信度、14 项证据命中集合、逐帧像素 CRC
- python scripts/replay_check.py runs/dump/new.jsonl --baseline runs/dump/golden.jsonl
- # ③ 验收门禁:现场状态序列与期望序列的准确率(D2 条款)
- python scripts/replay_check.py runs/dump/dump.jsonl --expect-states 0,1,1,2 --min-accuracy 1.0
- 目录约定:JSONL 与图默认同目录下的 ``frames/``(C++ 的 ``--dump-dir`` 缺省值);
- 若同目录下直接放着 PGM(``--dump-dir`` 指成了 JSONL 同目录),自动识别;也可用 ``--images`` 强制指定。
- 只有 JSONL 没存图(行里 ``image`` 为 ``null``)时,像素断言降级为 WARN 而不是 FAIL。
- 导出里有**三个**状态字段,别混:
- * ``state`` —— 寄存器口径(PublishGate 之后;本帧无结论时是**保持值**,PLC 读到的就是它);
- * ``vote_state`` —— TemporalVoter 之后、发布门之前的内部结论(255 = 本帧不足以投票);
- * ``edge_state`` —— 本帧证据结论(255 = 本帧弃权 / 看不清 / 运动中不改变判定)。
- 安全断言(弃权 / 越界带不足 → 不输出 0/1/2)打在 ``edge_state`` 上;``state`` / ``vote_state`` /
- ``edge_state`` 三者不一致时要求 ``STABLE=0``(那只是发布门的保持/滞后,不是口径矛盾)。
- 验收序列默认看 ``state``,``--state-field edge_state`` 可改看本帧结论。
- 判定:
- * **FAIL** —— 契约被破坏(字段缺失/类型不对/帧号不递增/状态码非法/``gray_crc32`` 与像素不符/
- 证据摘要与 ``ev`` 不一致/与基线不一致),这些都会让"回放结论 ≠ 现场结论",必须修;
- * **WARN** —— 不影响判决的可疑点(例如没存图所以没法验像素);
- * 与基线对拍时,``--conf-tol``(默认 0)可放宽容差;``--max-diff``(默认 0)允许少量帧不同的
- "整定中间态"也能过——但把差异明细全部打出来,绝不静默;
- * 基线自己也会被逐帧验像素(`--baseline-images`,默认同 `--images`):基线被改坏/拷坏时不能拿它冤枉新结果。
- 其它:输入允许带 BOM(Windows 工具导出的 JSONL 常见);``--no-pixels`` 只审 JSONL。
- 退出码:``0`` 全部通过;``1`` 有 FAIL;``2`` 用法 / 环境问题(文件不存在、JSON 读不动)。
- """
- from __future__ import annotations
- import argparse
- import json
- import os
- import sys
- import zlib
- REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
- # C++ 的 frame_dump.cpp 写出的字段(改字段名需两侧同步:见 cpp/include/portcv/frame_dump.hpp)
- REQUIRED_KEYS = (
- "frame", "ts", "width", "height", "state", "conf", "conf_x1000", "flags", "seq", "ts_s",
- "heartbeat", "fps_x10", "latency_ms", "reserved", "reason", "summary", "diag", "diag_name",
- "abstain", "conflict", "motion", "hold", "motion_held_s", "scale_ok", "view_limited",
- "boxes_seen", "segments_total", "px_per_m", "box_h_px", "box_w_px", "outline_quality",
- "out_left_px", "out_right_px", "ground_ratio_full", "ground_ratio_below", "strong_threshold",
- "score_a", "score_b", "score_c", "edge_state", "edge_conf", "vote_state", "ev", "image",
- "gray_crc32",
- )
- # EvidenceKey 的枚举顺序(cpp/include/portcv/edge_evidence.hpp),顺序即契约
- EVIDENCE_KEYS = ("P1", "P2", "P3", "P4", "F1", "F2", "F3", "F4", "G1", "G2", "G3", "C1", "C2", "C3")
- # SceneState:0 不在车上 / 1 车斗 / 2 平板车 / 255 不可信
- VALID_STATES = (0, 1, 2, 255)
- # StatusBits(schema.hpp)——位不可乱改
- BIT_READY, BIT_FRAME_OK, BIT_STABLE, BIT_LOW_FPS = 1, 2, 4, 8
- BIT_FRAME_TIMEOUT, BIT_ON_DEMAND, BIT_RESULT_VALID, BIT_PUBLISH_OK = 16, 32, 64, 128
- def read_pgm(path: str) -> tuple[int, int, bytes]:
- """读 P5 PGM → (宽, 高, 像素字节);解析失败抛 ``ValueError``。
- 只认 C++ 侧 ``write_pgm`` 写出的形态(无注释、单空格分隔),但仍按 PGM 规范容忍注释与任意空白,
- 这样"别人用 ImageMagick 转过的图"也能读。
- """
- with open(path, "rb") as fh:
- blob = fh.read()
- pos = 0
- def token() -> bytes:
- nonlocal pos
- while pos < len(blob):
- ch = blob[pos:pos + 1]
- if ch in (b" ", b"\t", b"\r", b"\n"):
- pos += 1
- elif ch == b"#": # 注释到行尾
- while pos < len(blob) and blob[pos:pos + 1] not in (b"\n", b"\r"):
- pos += 1
- else:
- break
- start = pos
- while pos < len(blob) and blob[pos:pos + 1] not in (b" ", b"\t", b"\r", b"\n"):
- pos += 1
- return blob[start:pos]
- magic = token()
- if magic != b"P5":
- raise ValueError("不是 P5 PGM(magic=%r)" % magic)
- try:
- width = int(token())
- height = int(token())
- maxval = int(token())
- except ValueError as exc: # 头部不是三个整数
- raise ValueError("PGM 头部不完整: %s" % exc) from exc
- if maxval != 255:
- raise ValueError("maxval 必须是 255(灰度 8bit),实际 %d" % maxval)
- if pos < len(blob) and blob[pos:pos + 1] in (b"\r", b"\n"):
- pos += 1 # 头部与像素之间只应有一个换行
- return width, height, blob[pos:]
- class Report:
- """收集 FAIL / WARN(明细带帧号,便于直接跳到那一帧看)。"""
- def __init__(self, limit: int) -> None:
- self.passed = 0
- self.fails: list[str] = []
- self.warns: list[str] = []
- self.limit = limit
- def ok(self) -> None:
- self.passed += 1
- def check(self, cond: bool, what: str) -> bool:
- if cond:
- self.ok()
- else:
- self.fail(what)
- return bool(cond)
- def fail(self, what: str) -> None:
- if len(self.fails) < self.limit:
- self.fails.append(what)
- def warn(self, what: str) -> None:
- if len(self.warns) < self.limit:
- self.warns.append(what)
- def load_jsonl(path: str) -> list:
- """读 JSONL → [dict];空行忽略,坏行抛 ``ValueError``(带行号)。
- 用 ``utf-8-sig`` 打开:手工编辑/Windows 工具导出的文件常带 BOM,不该因此读不动。
- """
- rows: list = []
- with open(path, "r", encoding="utf-8-sig") as fh:
- for lineno, line in enumerate(fh, start=1):
- if not line.strip():
- continue
- try:
- obj = json.loads(line)
- except ValueError as exc:
- raise ValueError("第 %d 行不是合法 JSON: %s" % (lineno, exc)) from exc
- if not isinstance(obj, dict):
- raise ValueError("第 %d 行不是 JSON 对象" % lineno)
- rows.append(obj)
- return rows
- def pick_images_dir(explicit: str | None, jsonl_dir: str, rows: list) -> str:
- """定 PGM 目录:显式给就用它;否则先猜 C++ 的缺省值(`<jsonl 同级>/frames`),
- 再退一步猜"PGM 就放在 JSONL 同目录"(现场常把 `--dump-dir` 指成同目录)。
- """
- if explicit:
- return explicit
- default_dir = os.path.join(jsonl_dir, "frames")
- names = [r.get("image") for r in rows if isinstance(r.get("image"), str)]
- if names and not os.path.exists(os.path.join(default_dir, names[0])) \
- and os.path.exists(os.path.join(jsonl_dir, names[0])):
- print(" (图目录自动识别为 JSONL 同目录;如不对请用 --images 指定)")
- return jsonl_dir
- return default_dir
- def check_one_row(row: dict, rep: Report) -> None:
- """单帧自洽性(格式 / 枚举 / 位 / 证据摘要 vs ev)。"""
- frame = row.get("frame")
- tag = "frame %s" % frame
- missing = [k for k in REQUIRED_KEYS if k not in row]
- if not rep.check(not missing, "%s: 缺字段 %s" % (tag, missing)):
- return
- state = row["state"]
- rep.check(state in VALID_STATES, "%s: 状态码 %r 不在 {0,1,2,255}" % (tag, state))
- # `state` = 寄存器口径(PublishGate 之后,**可能是保持值**);`vote_state` = 投票后结论;
- # `edge_state` = 本帧证据结论(255 = 本帧弃权/看不清/运动中不改变判定)。
- # 安全断言打在 `edge_state` 上 —— 否则"本帧弃权、寄存器保持上一稳定值"会被误判成
- # "弃权却不输出 255"。`state` 另有一条"只许等于投票结论或保持值"的一致性断言。
- edge_state = row.get("edge_state", state)
- vote_state = row.get("vote_state", state)
- rep.check(edge_state in VALID_STATES or edge_state == -1,
- "%s: edge_state=%r 不在 {-1,0,1,2,255}(-1 = 该后端不产出)" % (tag, edge_state))
- rep.check(vote_state in VALID_STATES or vote_state == -1,
- "%s: vote_state=%r 不在 {-1,0,1,2,255}(-1 = 该后端不产出)" % (tag, vote_state))
- flags = int(row["flags"])
- rep.check(0 <= flags <= 0xFFFF, "%s: flags 越出 16bit(%d)" % (tag, flags))
- # 千分比与实际置信度必须一致(PLC 读 1 字,日志读浮点,两者不许漂)
- conf = float(row["conf"])
- conf_x1000 = int(row["conf_x1000"])
- rep.check(abs(conf - conf_x1000 / 1000.0) <= 0.0005,
- "%s: conf=%s 与 conf_x1000=%d 不一致" % (tag, conf, conf_x1000))
- rep.check(0 <= conf_x1000 <= 1000, "%s: conf_x1000=%d 越界" % (tag, conf_x1000))
- edge_conf = row.get("edge_conf", 0.0)
- rep.check(isinstance(edge_conf, (int, float)) and 0.0 <= float(edge_conf) <= 1.0,
- "%s: edge_conf=%r 不在 0..1" % (tag, edge_conf))
- # flags 位语义(schema.hpp / plc_interface.md)
- if (flags & BIT_FRAME_OK) and (flags & BIT_FRAME_TIMEOUT):
- rep.fail("%s: FRAME_OK 与 FRAME_TIMEOUT 同时为 1(口径矛盾)" % tag)
- else:
- rep.ok()
- if flags & BIT_FRAME_TIMEOUT:
- rep.check(state == 255, "%s: FRAME_TIMEOUT=1 但 state=%r(必须 255)" % (tag, state))
- else:
- rep.ok()
- if flags & BIT_RESULT_VALID:
- rep.check(state != 255, "%s: RESULT_VALID=1 但 state=%r(契约矛盾)" % (tag, state))
- else:
- rep.ok()
- # 数值合理性(寄存器字宽)
- for key in ("heartbeat", "fps_x10", "latency_ms", "reserved"):
- rep.check(0 <= int(row[key]) <= 0xFFFF, "%s: %s=%s 越出 16bit" % (tag, key, row[key]))
- # 证据明细有两种口径,**都必须能过**(否则"换后端就回归不了"):
- # * `edge`(v1):`ev` 里 14 项证据齐全,summary 是 `[P1 F2 ] sA=...` 命中串;
- # * `edge-v2`:没有 14 项 `ev`(v2 的证据是动态 ROI 的结构量),summary 形如
- # `state=1 ... commit=1(commit) ... abstain=hoist_high`。
- ev = row["ev"]
- if not rep.check(isinstance(ev, dict), "%s: ev 不是对象" % tag):
- return
- has_v1_ev = all(k in ev for k in EVIDENCE_KEYS)
- summary = str(row["summary"])
- if has_v1_ev:
- bad_ev = [k for k, v in ev.items() if not isinstance(v, bool)]
- rep.check(not bad_ev, "%s: ev 取值不是布尔 %s" % (tag, bad_ev))
- hits = set(summary[1:summary.find("]")].split()) if "]" in summary else set()
- want = {k for k in EVIDENCE_KEYS if ev.get(k) is True}
- rep.check(hits == want, "%s: summary 命中 %s 与 ev 命中 %s 不一致"
- % (tag, sorted(hits), sorted(want)))
- else:
- # v2:summary 必须自带 state/commit(现场只看日志也能回答"为什么"),
- # 且 `state=` 必须等于本帧结论(255 = 弃权,summary 不带 state= 前缀)。
- rep.check("state=" in summary and "commit=" in summary,
- "%s: 既没有 14 项 ev,summary 也不是 v2 口径(缺 state=/commit=)" % tag)
- if edge_state in (0, 1, 2):
- rep.check(("state=%d" % edge_state) in summary,
- "%s: summary 的 state= 与 edge_state=%d 不一致" % (tag, edge_state))
- else:
- rep.ok()
- # P0-0 图像侧安全门(吊具高悬 / 吊具仍夹箱):summary 里出现命中标记时,
- # 本帧结论必须是弃权(255)—— 这是"箱还在半空也照样攒够 5 帧 commit"的唯一刹车。
- if "hoist=" in summary or "spreader=1" in summary:
- rep.check(edge_state == 255,
- "%s: 高悬/夹箱门命中但本帧结论 edge_state=%r(必须 255)" % (tag, edge_state))
- rep.check(row["abstain"] is True, "%s: 高悬/夹箱门命中但 abstain=false" % tag)
- else:
- rep.ok()
- # 弃权 / 看不清 → 本帧结论绝不输出 0/1/2(安全铁律)。
- # 打在本帧结论 edge_state 上;寄存器口径允许"无结论时保持上一稳定值"。
- if row["abstain"] is True:
- rep.check(edge_state == 255,
- "%s: abstain=true 但本帧结论 edge_state=%r(必须 255)" % (tag, edge_state))
- else:
- rep.ok()
- if row["view_limited"] is True:
- rep.check(edge_state != 2,
- "%s: view_limited=true 但本帧结论 edge_state=2(越界带不足不许输出平板车)" % tag)
- else:
- rep.ok()
- # 发布值 / 投票结论 / 本帧结论三者不一致时,必须"未稳定"(STABLE=0)——
- # 那只是 PublishGate 的保持/滞后;STABLE=1 还不一致就是口径矛盾。
- if state != 255 and vote_state not in (state, 255, -1):
- rep.check(
- not (flags & BIT_STABLE),
- "%s: 发布 state=%r ≠ 投票 vote_state=%r,但 STABLE=1(不是保持滞后,是口径矛盾)"
- % (tag, state, vote_state))
- else:
- rep.ok()
- if edge_state in (0, 1, 2) and vote_state in (0, 1, 2) and vote_state != edge_state:
- rep.check(
- not (flags & BIT_STABLE),
- "%s: 本帧结论 edge_state=%r ≠ 投票 vote_state=%r,但 STABLE=1(投票器把 1/2 混了)"
- % (tag, edge_state, vote_state))
- else:
- rep.ok()
- def check_sequence(rows: list, rep: Report) -> None:
- """跨帧:帧号严格递增、时间戳非递减、序号/心跳单调。"""
- prev_frame, prev_ts, prev_hb = None, None, None
- for row in rows:
- frame = row.get("frame")
- if not rep.check(isinstance(frame, int), "帧号不是整数: %r" % frame):
- continue
- if prev_frame is not None:
- if not rep.check(frame > prev_frame, "帧号不严格递增: %s -> %s" % (prev_frame, frame)):
- prev_frame = frame
- continue
- prev_frame = frame
- ts = row.get("ts")
- if isinstance(ts, (int, float)):
- if prev_ts is not None and ts < prev_ts - 1e-6:
- rep.fail("时间戳倒退: %.6f -> %.6f(frame %s)" % (prev_ts, ts, frame))
- else:
- rep.ok()
- prev_ts = ts
- hb = row.get("heartbeat")
- if isinstance(hb, int) and prev_hb is not None:
- # 16bit 回绕:只允许"不变 / +1 / 从 65535 跳回 0"
- if hb == prev_hb or hb == (prev_hb + 1) & 0xFFFF:
- rep.ok()
- else:
- rep.fail("心跳跳变: %d -> %d(frame %s)" % (prev_hb, hb, frame))
- if isinstance(hb, int):
- prev_hb = hb
- def check_pixels(rows: list, images_dir: str, rep: Report) -> int:
- """像素逐字节断言:PGM 头 = 行里的 width/height、像素 CRC = ``zlib.crc32``。返回校验帧数。"""
- checked = 0
- for row in rows:
- frame = row.get("frame")
- tag = "frame %s" % frame
- name = row.get("image")
- if name is None:
- rep.warn("%s: 未存图(--dump-dir 没给?)—— 像素无法断言" % tag)
- continue
- if not rep.check(isinstance(name, str), "%s: image 字段不是字符串" % tag):
- continue
- path = os.path.join(images_dir, name)
- if not rep.check(os.path.exists(path), "%s: 图不存在 %s" % (tag, path)):
- continue
- try:
- w, h, pixels = read_pgm(path)
- except (OSError, ValueError) as exc:
- rep.fail("%s: PGM 读不动 %s: %s" % (tag, path, exc))
- continue
- rep.check((w, h) == (row["width"], row["height"]),
- "%s: PGM 尺寸 %dx%d 与行里 %rx%r 不一致"
- % (tag, w, h, row["width"], row["height"]))
- rep.check(len(pixels) == w * h, "%s: 像素字节数 %d ≠ %dx%d" % (tag, len(pixels), w, h))
- crc = row.get("gray_crc32")
- if crc is None:
- rep.fail("%s: 有图但 gray_crc32 为 null" % tag)
- else:
- ours = zlib.crc32(pixels) & 0xFFFFFFFF
- rep.check(int(crc) == ours,
- "%s: gray_crc32=%s 与像素实算 %d 不符(像素被改过)" % (tag, crc, ours))
- checked += 1
- return checked
- def compare_baseline(new_rows: list, base_rows: list, conf_tol: float, max_diff: int,
- rep: Report) -> dict:
- """与基线逐帧对拍:状态 / 千分比置信度 / 14 项证据命中 / 像素 CRC。"""
- base_by_frame = {}
- for row in base_rows:
- if isinstance(row.get("frame"), int):
- base_by_frame[row["frame"]] = row
- stats = {"state": 0, "edge_state": 0, "vote_state": 0, "conf": 0, "ev": 0, "pixels": 0,
- "missing": 0, "compared": 0}
- for row in new_rows:
- frame = row.get("frame")
- base = base_by_frame.get(frame)
- if base is None:
- stats["missing"] += 1
- rep.fail("frame %s: 基线里没有这一帧(样本集缩小了?)" % frame)
- continue
- stats["compared"] += 1
- if row["state"] != base.get("state"):
- stats["state"] += 1
- rep.fail("frame %s: 状态 %r -> %r(基线 %r)" % (frame, base.get("state"), row["state"],
- base.get("state")))
- if row.get("edge_state") != base.get("edge_state"):
- stats["edge_state"] += 1
- rep.fail("frame %s: 本帧结论 edge_state %r -> %r(基线 %r)"
- % (frame, base.get("edge_state"), row.get("edge_state"),
- base.get("edge_state")))
- if row.get("vote_state") != base.get("vote_state"):
- stats["vote_state"] += 1
- rep.fail("frame %s: 投票结论 vote_state %r -> %r(基线 %r)"
- % (frame, base.get("vote_state"), row.get("vote_state"),
- base.get("vote_state")))
- if abs(int(row["conf_x1000"]) - int(base.get("conf_x1000", 0))) > conf_tol * 1000:
- stats["conf"] += 1
- rep.fail("frame %s: 置信度 %s -> %s(容差 %.3f)"
- % (frame, base.get("conf_x1000"), row["conf_x1000"], conf_tol))
- base_hits = {k for k, v in (base.get("ev") or {}).items() if v is True}
- new_hits = {k for k, v in row["ev"].items() if v is True}
- if base_hits != new_hits:
- stats["ev"] += 1
- rep.fail("frame %s: 证据命中 +%s / -%s" % (frame, sorted(new_hits - base_hits),
- sorted(base_hits - new_hits)))
- if base.get("gray_crc32") is not None and row.get("gray_crc32") is not None:
- if int(base["gray_crc32"]) != int(row["gray_crc32"]):
- stats["pixels"] += 1
- rep.fail("frame %s: 像素 CRC 变了(%s -> %s)" % (frame, base["gray_crc32"],
- row["gray_crc32"]))
- total_diff = (stats["state"] + stats["edge_state"] + stats["vote_state"] + stats["conf"] +
- stats["ev"] + stats["pixels"] + stats["missing"])
- rep.check(total_diff <= max_diff,
- "与基线差异 %d 处超过 --max-diff=%d(明细见上)" % (total_diff, max_diff))
- return stats
- def state_sequence(rows: list, field: str = "state") -> list:
- """连续相同状态合并 → 状态变化序列(现场关心的其实是"切换")。
- 断流(255)也算一次变化:它正是"相机/网络异常"的现场证据。
- ``field`` 选 ``state``(寄存器口径,默认)或 ``edge_state``(本帧证据结论)。
- """
- seq: list = []
- for row in rows:
- state = row.get(field)
- if not seq or seq[-1] != state:
- seq.append(state)
- return seq
- def parse_states(text: str) -> list:
- """``"0,1,255"`` → ``[0, 1, 255]``;非法值抛 ``ValueError``。"""
- out: list = []
- for part in str(text).split(","):
- part = part.strip()
- if not part:
- continue
- value = int(part, 10)
- if value not in VALID_STATES:
- raise ValueError("期望序列里的 %d 不是合法状态码(只用 0/1/2/255)" % value)
- out.append(value)
- if not out:
- raise ValueError("--expect-states 为空")
- return out
- def check_expect_states(rows: list, want: list, min_accuracy: float, rep: Report,
- field: str = "state") -> None:
- """把"连续相同合并后的状态序列"与期望序列比对,报准确率(现场验收条款)。"""
- got = state_sequence(rows, field)
- hit = sum(1 for a, b in zip(got, want) if a == b)
- total = max(len(got), len(want))
- acc = hit / total if total else 0.0
- print(" 期望状态序列(%s): %s" % (field, ",".join(str(s) for s in want)))
- print(" 实际状态序列(%s): %s" % (field, ",".join(str(s) for s in got)))
- print(" 状态序列准确率: %d/%d = %.3f(门限 %.3f)" % (hit, total, acc, min_accuracy))
- rep.check(got == want, "状态序列与期望不一致(逐位看上面两行)")
- rep.check(acc >= min_accuracy, "状态序列准确率 %.3f < 门限 %.3f" % (acc, min_accuracy))
- def main(argv: list | None = None) -> int:
- parser = argparse.ArgumentParser(description="黄金语料回放断言(C++ --dump-frames 产物)")
- parser.add_argument("jsonl", help="--dump-frames 写出的 JSONL(每帧一行)")
- parser.add_argument("--baseline", default=None,
- help="基线 JSONL:逐帧对拍状态 / 置信度 / 证据命中 / 像素 CRC")
- parser.add_argument("--images", default=None,
- help="PGM 目录(默认:JSONL 同目录下的 frames/)")
- parser.add_argument("--baseline-images", default=None,
- help="基线 PGM 目录(默认同 --images;用来校验基线自己没被改坏)")
- parser.add_argument("--conf-tol", type=float, default=0.0,
- help="置信度容差(0 = 必须逐位一致;整定中间态可给 0.02)")
- parser.add_argument("--max-diff", type=int, default=0,
- help="允许与基线不同的帧数(0 = 必须完全一致)")
- parser.add_argument("--expect-states", default=None,
- help='期望状态序列(逗号分隔,如 "0,1,1,2";相邻重复自动合并)')
- parser.add_argument("--state-field", default="state", choices=("state", "edge_state"),
- help="状态序列比对用哪个字段:state = 寄存器口径(默认,含保持值);"
- "edge_state = 本帧证据结论")
- parser.add_argument("--min-accuracy", type=float, default=1.0, help="状态序列准确率门限")
- parser.add_argument("--no-pixels", action="store_true", help="跳过像素断言(只审 JSONL)")
- parser.add_argument("--limit", type=int, default=20, help="最多打印多少条 FAIL / WARN")
- parser.add_argument("--report", default=None, help="把报告另存一份(UTF-8)")
- args = parser.parse_args(argv)
- if not os.path.exists(args.jsonl):
- print("找不到导出文件: %s" % args.jsonl, file=sys.stderr)
- print("先生成:portcv_run --backend edge --source-type synth --source-uri gondola "
- "--dump-frames out/dump.jsonl --dump-dir out/frames --max-frames 30 --no-plc",
- file=sys.stderr)
- return 2
- jsonl_dir = os.path.dirname(os.path.abspath(args.jsonl))
- try:
- rows = load_jsonl(args.jsonl)
- base_rows = load_jsonl(args.baseline) if args.baseline else []
- want_states = parse_states(args.expect_states) if args.expect_states else []
- except (OSError, ValueError) as exc:
- print("读不动输入: %s" % exc, file=sys.stderr)
- return 2
- if not rows:
- print("导出文件里一帧都没有: %s" % args.jsonl, file=sys.stderr)
- return 2
- images = pick_images_dir(args.images, jsonl_dir, rows)
- if args.baseline:
- base_images = pick_images_dir(args.baseline_images,
- os.path.dirname(os.path.abspath(args.baseline)), base_rows)
- else:
- base_images = images
- rep = Report(args.limit)
- print("回放断言: %s(%d 帧)" % (args.jsonl, len(rows)))
- for row in rows:
- check_one_row(row, rep)
- check_sequence(rows, rep)
- pixel_frames = 0 if args.no_pixels else check_pixels(rows, images, rep)
- if args.baseline:
- print("与基线对拍: %s(容差 %.3f / 允许差异 %d 帧)"
- % (args.baseline, args.conf_tol, args.max_diff))
- stats = compare_baseline(rows, base_rows, args.conf_tol, args.max_diff, rep)
- print(" 逐帧比对 %d 帧;差异:状态 %d / 本帧结论 %d / 投票结论 %d / 置信度 %d / 证据 %d /"
- " 像素 %d / 缺帧 %d"
- % (stats["compared"], stats["state"], stats["edge_state"], stats["vote_state"],
- stats["conf"], stats["ev"], stats["pixels"], stats["missing"]))
- if not args.no_pixels and base_images:
- # 基线自己也要站得住:基线图被人改过 / 拷坏过时,上面的"差异"会冤枉新结果
- base_checked = check_pixels(base_rows, base_images, rep)
- print(" 基线像素逐字节校验帧数: %d" % base_checked)
- if want_states:
- check_expect_states(rows, want_states, args.min_accuracy, rep, args.state_field)
- print(" 像素逐字节校验帧数: %d" % pixel_frames)
- lines = ["===================== 汇总 =====================",
- "通过断言 %d 项" % rep.passed]
- for item in rep.warns:
- lines.append("[WARN] %s" % item)
- for item in rep.fails:
- lines.append("[FAIL] %s" % item)
- lines.append("结论: %s(FAIL %d / WARN %d)"
- % ("PASS" if not rep.fails else "FAIL", len(rep.fails), len(rep.warns)))
- text = "\n".join(lines)
- print(text)
- if args.report:
- os.makedirs(os.path.dirname(os.path.abspath(args.report)), exist_ok=True)
- with open(args.report, "w", encoding="utf-8") as fh:
- fh.write(text + "\n")
- print("报告已写入: %s" % args.report)
- return 1 if rep.fails else 0
- if __name__ == "__main__":
- sys.exit(main())
|