dataset_harness.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633
  1. """数据集回归 harness(**C++ 生产路径**):把一个图片/视频测试集跑成“本帧候选 / 发布值”表 + 安全断言。
  2. 为什么要这个脚本
  3. ----------------
  4. `docs/evidence/test_2026-11-20/测试报告.md` 那几张表是用一套**临时 harness**(`%TEMP%` 里的
  5. PGM chunk + 逐个 `portcv_run`)跑出来的,harness 本身没进仓 —— 于是“报告里的数字”无法复现,
  6. 任何判据改动都没有门禁。这里把它固化成脚本,并且**必须走 C++ `edge-v2`**:
  7. * Python 参考实现(`portcv/logic/evidence_v2.py`)在广角/远景素材上与 C++ 结论不同
  8. (实拍 `video2`:Python 抽样帧多为 `255 weak_evidence`,C++ 是 `2 deck_edge`),
  9. 用 Python 量会得出错误结论;
  10. * 现场跑的是 C++,验收看的也是 C++ 发给 PLC 的 `state`。
  11. 两遍口径(与测试报告一致)
  12. --------------------------
  13. * **本帧候选**:`evidence_v2.require_commit=false` + 单帧 → `edge_state`
  14. (算法本身把这一帧判成什么,用来评估结构可分性);
  15. * **发布值**:`evidence_v2.require_commit=true` + 同一张图重复 `--repeats` 帧(默认 20)
  16. → 寄存器口径 `state`(含 commit / 投票 / 发布门,PLC 实际采信的就是它)。
  17. 安全断言(`--labels` 给了人工判读才生效;违反 → 退出码 1)
  18. --------------------------------------------------------
  19. * `boxed`(平车坐箱 / 敞车坐箱):发布值**不得**为 `3`(载车被判空车 = 最危险的误判);
  20. * `empty`(空敞车 / 空平车):发布值**不得**为 `2` / `1`(空车被判成载车);
  21. * `working`(吊具高悬 / 夹箱的作业帧):发布值必须是 `0`(不判)。
  22. 数据域(`labels.json` 的 `domain`;`--domain field,near,web` 可过滤)
  23. -------------------------------------------------------------------
  24. * `field`:现场实拍(部署机位 / 司机视角)——**只有这一域的命中率能当现场精度**;
  25. * `near`:近距前视素材,非现场工况片段,仅作回归参照;
  26. * `web`:网上图库(广角 / 远景),与部署机位的拍摄角度、距离都不同 ——
  27. 它的数字只能回答"会不会出现危险误报",**不能**当召回率/准确率;
  28. * 报告按域分开统计;一批里没有 `field` 样本时,脚本会打醒目警告。
  29. 用法
  30. ----
  31. ::
  32. # 39 张 web_cc + 4 张对照集(人工判读见 labels.json)
  33. python scripts/dataset_harness.py --images <图片目录...> \
  34. --labels docs/evidence/test_2026-11-20/labels.json --out runs/harness
  35. # 只跑发布值(快一半)
  36. python scripts/dataset_harness.py --images <目录> --no-single
  37. # 换配置(真机模板 / view=high)
  38. python scripts/dataset_harness.py --images <目录> --config configs/edge-v2-rtsp.json
  39. 视频请先用 ``scripts/extract_frames.py`` 抽成 PGM 目录(本脚本只吃图片,避免把解码差异
  40. 混进判据口径)。
  41. 为什么所有中间产物都落在系统临时目录:C++ `main()` 的 `argv` 在 Windows 上是 ANSI 编码,
  42. 仓库路径含中文(`…\\正面吊\\…`)会被传坏。脚本把配置/PGM/dump 全部写到**纯 ASCII** 的
  43. `%TEMP%/portcv_harness`,只把结论写回 `--out`(Python 侧自己写文件,无编码问题)。
  44. """
  45. from __future__ import annotations
  46. import argparse
  47. import json
  48. import os
  49. import re
  50. import shutil
  51. import subprocess
  52. import sys
  53. import tempfile
  54. import time
  55. ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  56. STATE_LABEL = {0: "0 不在车上", 1: "1 敞车", 2: "2 平车", 3: "3 空车", 255: "255 弃权"}
  57. #: 数据域:**现场**实拍 / 近距前视素材(非现场工况) / 网上图库(广角、远景)
  58. #:
  59. #: 为什么必须分开统计:`web_cc` 那 39 张是网上找的图库照片,拍摄角度与距离
  60. #: 和部署机位(相机固定在车身左前方、近距、箱底与车面在画面中部)不是一回事 ——
  61. #: 它们的数字只能回答"会不会把载车判成空车"这类**安全方向**问题,**不能**当
  62. #: 现场精度(召回/准确率)。没有 `field` 样本时,报告里的命中率一律不作数。
  63. DOMAINS = ("field", "near", "web", "unknown")
  64. #: 人工判读标签 → 期望状态(`expect` 在 labels.json 里可逐条覆盖)
  65. LABEL_EXPECT = {
  66. "boxed_flatbed": 2,
  67. "boxed_gondola": 1,
  68. "empty_gondola": 3,
  69. "empty_flatbed": 3,
  70. "working": 0,
  71. }
  72. IMAGE_EXT = (".jpg", ".jpeg", ".png", ".bmp", ".pgm")
  73. #: 断言:标签 → 发布值禁集(None = 无禁集)
  74. GATE_FORBID = {
  75. "boxed_flatbed": {3},
  76. "boxed_gondola": {3},
  77. "empty_gondola": {1, 2},
  78. "empty_flatbed": {1, 2},
  79. "working": {1, 2, 3},
  80. }
  81. def find_exe(explicit: str = "") -> str:
  82. """找 `portcv_run`:显式参数 > 环境变量 > 本仓构建产物 > PATH。"""
  83. if explicit:
  84. return explicit
  85. env = os.environ.get("PORTCV_RUN", "")
  86. if env:
  87. return env
  88. for rel in (
  89. os.path.join("build-cmake", "windows-zig-release", "portcv_run.exe"),
  90. os.path.join("build-cmake", "windows-zig-release", "portcv_run"),
  91. os.path.join("build", "portcv_run"),
  92. os.path.join("build", "portcv_run.exe"),
  93. ):
  94. path = os.path.join(ROOT, rel)
  95. if os.path.exists(path):
  96. return path
  97. found = shutil.which("portcv_run")
  98. if found:
  99. return found
  100. raise SystemExit(
  101. "找不到 portcv_run:用 --exe 指定,或先构建(docs/deployment.md §2)。"
  102. )
  103. def collect_images(dirs: list[str]) -> list[str]:
  104. """递归收集图片;按路径排序(同一目录内即文件名序)。"""
  105. out: list[str] = []
  106. for base in dirs:
  107. if os.path.isfile(base):
  108. out.append(base)
  109. continue
  110. for cur, _sub, files in os.walk(base):
  111. for name in sorted(files):
  112. if name.lower().endswith(IMAGE_EXT):
  113. out.append(os.path.join(cur, name))
  114. return sorted(out)
  115. def image_to_pgm(src: str, dst: str) -> tuple[int, int]:
  116. """图片 → PGM(**灰度解码**,与取流口径一致:`IMREAD_GRAYSCALE`)。
  117. 路径可能含中文(仓库在 `…\\正面吊\\…`),OpenCV 的 `imread` 在 Windows 上按 ANSI
  118. 打开文件会失败 —— 所以统一 `np.fromfile` + `imdecode`(与 `portcv/io/capture.py`
  119. 同一手法,`docs/route_v2.md` §7.1 记录的「JPEG 经 BGR→gray 差 ±1 灰阶」也在这里避开)。
  120. """
  121. import cv2 # 局部导入:只跑网关/查表时不需要 cv2
  122. import numpy as np
  123. with open(src, "rb") as handle:
  124. buf = np.frombuffer(handle.read(), dtype=np.uint8)
  125. gray = cv2.imdecode(buf, cv2.IMREAD_GRAYSCALE)
  126. if gray is None:
  127. raise RuntimeError("解不开这张图(损坏或格式不支持):%s" % src)
  128. height, width = gray.shape[:2]
  129. with open(dst, "wb") as handle:
  130. handle.write(b"P5\n")
  131. handle.write(("%d %d\n" % (width, height)).encode("ascii"))
  132. handle.write(b"255\n")
  133. handle.write(np.ascontiguousarray(gray).tobytes())
  134. return width, height
  135. def prepare_configs(base_config: str, work: str, chunk: str, repeats: int,
  136. fps: float) -> tuple[str, str]:
  137. """把模板配置改写成两份(single / stable),全部指向 ASCII 临时目录。
  138. * `source.type=images` + `source.uri=<chunk>`:离线回放,零依赖;
  139. * `run.max_fps`:默认沿用模板(15 fps)。**不要调太快**:`decision.min_dwell_s`(0.2 s)
  140. 要求落位驻留,20 帧同图若跑成 83 ms,投票永远不会发布(本 harness 早期就踩过这个坑);
  141. * `evidence_v2.require_commit`:single=false(看算法本身怎么判)/ stable=true(看发布值);
  142. * `run.output_dir` / `calibration.record` 指到临时目录:仓储路径含中文,C++ 侧打不开。
  143. """
  144. with open(base_config, encoding="utf-8-sig") as handle:
  145. cfg = json.load(handle)
  146. cfg.setdefault("run", {})["max_fps"] = float(fps) if fps > 0.0 else float(
  147. cfg.get("run", {}).get("max_fps", 15.0))
  148. cfg["run"]["output_dir"] = os.path.join(work, "output")
  149. cfg["run"]["preview"] = False
  150. cfg["run"]["save_on_change"] = False
  151. cfg.setdefault("source", {})["type"] = "images"
  152. cfg["source"]["uri"] = chunk
  153. cfg["source"]["loop"] = False
  154. cfg.pop("_note", None)
  155. calib = cfg.setdefault("calibration", {})
  156. calib["record"] = ""
  157. calib["stale"] = False
  158. paths = []
  159. for name, require_commit in (("single", False), ("stable", True)):
  160. one = json.loads(json.dumps(cfg))
  161. one.setdefault("evidence_v2", {})["require_commit"] = bool(require_commit)
  162. path = os.path.join(work, "cfg_%s.json" % name)
  163. with open(path, "w", encoding="utf-8") as handle:
  164. json.dump(one, handle, ensure_ascii=False, indent=2)
  165. handle.write("\n")
  166. paths.append(path)
  167. return paths[0], paths[1]
  168. def read_dump(path: str) -> list[dict]:
  169. rows: list[dict] = []
  170. if not os.path.exists(path):
  171. return rows
  172. with open(path, encoding="utf-8-sig") as handle:
  173. for line in handle:
  174. line = line.strip()
  175. if line:
  176. rows.append(json.loads(line))
  177. return rows
  178. def run_once(exe: str, config: str, chunk: str, frames: int, dump: str,
  179. timeout: float) -> tuple[int, str, list[dict]]:
  180. """跑一次 `portcv_run`(images 源),返回 (退出码, 日志尾部, dump 行)。"""
  181. if os.path.exists(dump):
  182. os.remove(dump)
  183. cmd = [exe, "-c", config, "--source-type", "images", "--source-uri", chunk,
  184. "--max-frames", str(frames), "--dump-frames", dump,
  185. "--dump-dir", os.path.join(os.path.dirname(dump), "pgm"), "--no-plc"]
  186. try:
  187. proc = subprocess.run(cmd, cwd=ROOT, timeout=timeout,
  188. stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
  189. log = proc.stdout.decode("utf-8", "replace")
  190. code = proc.returncode
  191. except subprocess.TimeoutExpired as exc:
  192. log = (exc.stdout or b"").decode("utf-8", "replace") if exc.stdout else ""
  193. return 124, log[-400:], read_dump(dump)
  194. return code, log[-400:], read_dump(dump)
  195. def short_reason(row: dict) -> str:
  196. """从 dump 行里抠出“判据一句话”(v2 的 reason 就是现场可读诊断)。"""
  197. reason = str(row.get("reason") or "").strip()
  198. text = reason or str(row.get("summary") or "").strip()
  199. text = re.sub(r"^v2:(ok|abstain)\s*", "", text)
  200. return text.replace(" ", " ")
  201. def load_labels(path: str) -> dict[str, dict]:
  202. """读人工判读表:``{"NX70_001.jpg": {"label": "empty_flatbed", "expect": 3}}``。"""
  203. if not path:
  204. return {}
  205. with open(path, encoding="utf-8-sig") as handle:
  206. raw = json.load(handle)
  207. out: dict[str, dict] = {}
  208. for name, item in raw.items():
  209. if name.startswith("_"):
  210. continue # `_note` / `_source` 这类说明键
  211. if isinstance(item, str):
  212. item = {"label": item}
  213. entry = dict(item)
  214. label = str(entry.get("label", "")).strip()
  215. if label not in LABEL_EXPECT:
  216. raise SystemExit("labels.json 里 %s 的 label 不认识:%r(可选:%s)"
  217. % (name, label, ", ".join(sorted(LABEL_EXPECT))))
  218. entry["label"] = label
  219. domain = str(entry.get("domain", "unknown")).strip().lower() or "unknown"
  220. if domain not in DOMAINS:
  221. raise SystemExit("labels.json 里 %s 的 domain 不认识:%r(可选:%s)"
  222. % (name, domain, ", ".join(DOMAINS)))
  223. entry["domain"] = domain
  224. if "expect" not in entry:
  225. entry["expect"] = LABEL_EXPECT[label]
  226. out[os.path.basename(name)] = entry
  227. return out
  228. def parse_args(argv=None) -> argparse.Namespace:
  229. parser = argparse.ArgumentParser(
  230. description="数据集回归 harness(C++ edge-v2):本帧候选 / 发布值 + 安全断言")
  231. parser.add_argument("--images", nargs="+", required=True,
  232. help="图片目录(递归)或图片文件")
  233. parser.add_argument("--config", default=os.path.join("configs", "edge-v2-front.json"),
  234. help="配置模板(相对仓库根或绝对路径)")
  235. parser.add_argument("--labels", default="",
  236. help="人工判读 JSON(见 docs/evidence/test_2026-11-20/labels.json)")
  237. parser.add_argument("--domain", default="",
  238. help="只跑指定数据域(逗号分隔:field,near,web;空 = 全部)。"
  239. "**没有 field 样本时,命中率不得当现场精度**")
  240. parser.add_argument("--exe", default="", help="portcv_run 路径(缺省自动找)")
  241. parser.add_argument("--out", default=os.path.join("runs", "harness"),
  242. help="结论输出目录(默认 runs/harness,已 gitignore)")
  243. parser.add_argument("--repeats", type=int, default=20,
  244. help="发布值口径:同一张图重复多少帧(现场 harness 约定 20)")
  245. parser.add_argument("--fps", type=float, default=0.0,
  246. help="覆盖 run.max_fps(默认 0 = 沿用模板;"
  247. "注意别调太快:decision.min_dwell_s 要求落位驻留,"
  248. "20 帧必须跨够 0.2 s 才会发布)")
  249. parser.add_argument("--timeout", type=float, default=300.0, help="单次 portcv_run 超时(秒)")
  250. parser.add_argument("--limit", type=int, default=0, help="只跑前 N 张(0 = 全部)")
  251. parser.add_argument("--no-single", action="store_true", help="跳过“本帧候选”这一遍(快一半)")
  252. parser.add_argument("--no-gate", action="store_true", help="断言失败也返回 0(只出表)")
  253. parser.add_argument("--baseline-violations", default="",
  254. help="已知违例基线 JSON:只卡“**不许新增**违例”(改判据的日常门禁);"
  255. "不给则任何违例都返回 1(发版/验收口径)")
  256. parser.add_argument("--keep-work", action="store_true", help="保留临时工作目录")
  257. return parser.parse_args(argv)
  258. def verdict(publish: int, expect: int) -> str:
  259. """发布值 vs 人工真值:命中 / 弃权(发 0 = 不判)/ 误判。"""
  260. if publish == expect:
  261. return "命中"
  262. if publish == 0:
  263. return "弃权"
  264. return "误判"
  265. def main(argv=None) -> int:
  266. args = parse_args(argv)
  267. exe = find_exe(args.exe)
  268. config = args.config if os.path.isabs(args.config) else os.path.join(ROOT, args.config)
  269. if not os.path.exists(config):
  270. print("找不到配置模板: %s" % config, file=sys.stderr)
  271. return 2
  272. if args.repeats < 1:
  273. print("--repeats 至少 1", file=sys.stderr)
  274. return 2
  275. images = collect_images(args.images)
  276. if not images:
  277. print("没有找到图片:%s" % " ".join(args.images), file=sys.stderr)
  278. return 2
  279. if args.limit > 0:
  280. images = images[:args.limit]
  281. labels = load_labels(args.labels)
  282. if args.domain:
  283. wanted = {item.strip().lower() for item in args.domain.split(",") if item.strip()}
  284. bad = wanted - set(DOMAINS)
  285. if bad:
  286. print("--domain 里有不认识的值:%s(可选:%s)"
  287. % (sorted(bad), ", ".join(DOMAINS)), file=sys.stderr)
  288. return 2
  289. total = len(images)
  290. images = [path for path in images
  291. if labels.get(os.path.basename(path), {}).get("domain", "unknown") in wanted]
  292. print("域过滤 : %s → %d/%d 张" % ("+".join(sorted(wanted)), len(images), total))
  293. if not images:
  294. print("该数据域下没有样本", file=sys.stderr)
  295. return 2
  296. work = os.path.join(tempfile.gettempdir(), "portcv_harness")
  297. chunk = os.path.join(work, "chunk")
  298. if os.path.isdir(work):
  299. shutil.rmtree(work, ignore_errors=True)
  300. os.makedirs(chunk, exist_ok=True)
  301. cfg_single, cfg_stable = prepare_configs(config, work, chunk, args.repeats, args.fps)
  302. out_dir = args.out if os.path.isabs(args.out) else os.path.join(ROOT, args.out)
  303. os.makedirs(out_dir, exist_ok=True)
  304. print("可执行 : %s" % exe)
  305. print("配置模板 : %s" % os.path.relpath(config, ROOT))
  306. print("图片 : %d 张(人工判读 %d 条)" % (len(images), len(labels)))
  307. print("口径 : 本帧候选 = require_commit=false 单帧 / 发布值 = require_commit=true"
  308. " + 同图 %d 帧" % args.repeats)
  309. print("")
  310. rows: list[dict] = []
  311. started = time.time()
  312. for index, src in enumerate(images, 1):
  313. name = os.path.basename(src)
  314. label = labels.get(name, {})
  315. for old in os.listdir(chunk):
  316. os.remove(os.path.join(chunk, old))
  317. try:
  318. width, height = image_to_pgm(src, os.path.join(chunk, "frame_000000.pgm"))
  319. except RuntimeError as exc:
  320. print("[%d/%d] %s 跳过:%s" % (index, len(images), name, exc), file=sys.stderr)
  321. continue
  322. for copy in range(1, args.repeats):
  323. shutil.copyfile(os.path.join(chunk, "frame_000000.pgm"),
  324. os.path.join(chunk, "frame_%06d.pgm" % copy))
  325. row: dict = {
  326. "index": index,
  327. "file": name,
  328. "size": [width, height],
  329. "domain": label.get("domain", "unknown"),
  330. "label": label.get("label", ""),
  331. "expect": label.get("expect"),
  332. "note": label.get("note", ""),
  333. }
  334. if not args.no_single:
  335. code, log, dump = run_once(
  336. exe, cfg_single, chunk, 1,
  337. os.path.join(work, "dump_single.jsonl"), args.timeout)
  338. if code != 0 or not dump:
  339. row["candidate"] = None
  340. row["candidate_reason"] = ""
  341. row["candidate_error"] = "rc=%d %s" % (code, log.strip()[-120:])
  342. else:
  343. row["candidate"] = int(dump[-1].get("edge_state", -1))
  344. row["candidate_reason"] = short_reason(dump[-1])
  345. code, log, dump = run_once(
  346. exe, cfg_stable, chunk, args.repeats,
  347. os.path.join(work, "dump_stable.jsonl"), args.timeout)
  348. if code != 0 or not dump:
  349. row["publish"] = None
  350. row["publish_reason"] = ""
  351. row["publish_error"] = "rc=%d %s" % (code, log.strip()[-120:])
  352. else:
  353. last = dump[-1]
  354. row["publish"] = int(last.get("state", -1))
  355. row["publish_edge"] = int(last.get("edge_state", -1))
  356. row["publish_reason"] = short_reason(last)
  357. row["stable_flag"] = bool(int(last.get("flags", 0)) & 0x0001)
  358. row["frames"] = len(dump)
  359. if row.get("expect") is not None and row.get("publish") is not None:
  360. row["verdict"] = verdict(int(row["publish"]), int(row["expect"]))
  361. rows.append(row)
  362. print("[%d/%d] %-20s 人工=%-11s 候选=%-9s 发布=%-9s %s"
  363. % (index, len(images), name,
  364. row.get("label") or "-",
  365. "-" if row.get("candidate") is None
  366. else STATE_LABEL.get(int(row["candidate"]), str(row["candidate"])),
  367. "-" if row.get("publish") is None
  368. else STATE_LABEL.get(int(row["publish"]), str(row["publish"])),
  369. row.get("verdict", "")), file=sys.stderr)
  370. elapsed = time.time() - started
  371. report = render_report(rows, exe, config, args)
  372. md_path = os.path.join(out_dir, "dataset_harness.md")
  373. json_path = os.path.join(out_dir, "dataset_harness.json")
  374. with open(md_path, "w", encoding="utf-8") as handle:
  375. handle.write(report["markdown"])
  376. with open(json_path, "w", encoding="utf-8") as handle:
  377. json.dump(report["summary"], handle, ensure_ascii=False, indent=2)
  378. handle.write("\n")
  379. print("")
  380. print(report["markdown"])
  381. print("耗时 : %.1f s / %d 张(%.2f s 每张)"
  382. % (elapsed, len(rows), elapsed / max(1, len(rows))))
  383. print("结论 : %s" % md_path)
  384. print("小结 JSON : %s" % json_path)
  385. if not args.keep_work:
  386. shutil.rmtree(work, ignore_errors=True)
  387. if args.baseline_violations and report["fixed_violations"]:
  388. print("提示:%d 条违例已修复(%s)—— 请把它们从基线里删掉"
  389. % (len(report["fixed_violations"]), "、".join(report["fixed_violations"])))
  390. gate_items = report["new_violations"] if args.baseline_violations else report["violations"]
  391. if gate_items and not args.no_gate:
  392. print("", file=sys.stderr)
  393. print("安全断言失败 %d 条%s:" % (
  394. len(gate_items), "(基线对比口径:只卡新增)" if args.baseline_violations else ""),
  395. file=sys.stderr)
  396. for item in gate_items:
  397. print(" - %s" % item, file=sys.stderr)
  398. return 1
  399. return 0
  400. def load_baseline(path: str) -> set[str]:
  401. """读「已知违例基线」:``{"violations": ["test1.png:3", ...]}``(键 = 文件名:发布值)。
  402. 语义是**禁止变差**:基线里的违例允许存在(它们已被记录、有整改项),
  403. **新增**一条就 FAIL;某条被修好了会提示更新基线(不算失败)。
  404. """
  405. if not path:
  406. return set()
  407. with open(path, encoding="utf-8-sig") as handle:
  408. data = json.load(handle)
  409. items = data.get("violations", data if isinstance(data, list) else [])
  410. return {str(item).strip() for item in items if str(item).strip()}
  411. def render_report(rows: list[dict], exe: str, config: str,
  412. args: argparse.Namespace) -> dict:
  413. """出 Markdown 表 + 小结 JSON + 断言清单。"""
  414. lines: list[str] = []
  415. lines.append("# 数据集回归 harness(C++ `edge-v2`)")
  416. lines.append("")
  417. lines.append("- 可执行:`%s`" % os.path.basename(exe))
  418. lines.append("- 配置模板:`%s`" % os.path.relpath(config, ROOT))
  419. lines.append("- 口径:本帧候选 = `require_commit=false` 单帧;发布值 = `require_commit=true`"
  420. " + 同图 %d 帧" % args.repeats)
  421. lines.append("- 状态码:`0` 不在车上/其他;`1` 敞车;`2` 平车;`3` 空车;`255` 内部弃权")
  422. domains = sorted({row.get("domain", "unknown") for row in rows})
  423. lines.append("- 数据域:%s(`field` 现场实拍 / `near` 近距前视素材 / `web` 网上图库"
  424. "——**只有 `field` 的命中率能当现场精度**)" % "/".join(domains))
  425. lines.append("")
  426. lines.append("| # | 文件 | 域 | 人工判读 | 期望 | 本帧候选 | 发布值 | 结论 | 判据 |")
  427. lines.append("|---|---|---|---|---|---|---|---|---|")
  428. for row in rows:
  429. candidate = row.get("candidate")
  430. publish = row.get("publish")
  431. lines.append("| %d | `%s` | %s | %s | %s | %s | %s | %s | %s |" % (
  432. row["index"], row["file"], row.get("domain", "unknown"),
  433. row.get("label") or "-",
  434. "-" if row.get("expect") is None else row["expect"],
  435. "-" if candidate is None else candidate,
  436. "-" if publish is None else STATE_LABEL.get(publish, publish),
  437. row.get("verdict", "-"), (row.get("publish_reason") or "-"),
  438. ))
  439. lines.append("")
  440. by_label: dict[str, dict[str, int]] = {}
  441. for row in rows:
  442. label = row.get("label") or "unlabeled"
  443. bucket = by_label.setdefault(
  444. label, {"total": 0, "命中": 0, "弃权": 0, "误判": 0, "未判定": 0})
  445. bucket["total"] += 1
  446. bucket[row.get("verdict", "未判定")] += 1
  447. lines.append("| 人工判读 | 张数 | 命中 | 弃权 | 误判 |")
  448. lines.append("|---|---|---|---|---|")
  449. for label in sorted(by_label):
  450. bucket = by_label[label]
  451. lines.append("| %s | %d | %d | %d | %d |" % (
  452. label, bucket["total"], bucket["命中"], bucket["弃权"], bucket["误判"]))
  453. if by_label:
  454. lines.append("| **合计** | **%d** | **%d** | **%d** | **%d** |" % (
  455. sum(b["total"] for b in by_label.values()),
  456. sum(b["命中"] for b in by_label.values()),
  457. sum(b["弃权"] for b in by_label.values()),
  458. sum(b["误判"] for b in by_label.values())))
  459. lines.append("")
  460. by_domain: dict[str, dict[str, int]] = {}
  461. for row in rows:
  462. domain = row.get("domain", "unknown")
  463. bucket = by_domain.setdefault(
  464. domain, {"total": 0, "命中": 0, "弃权": 0, "误判": 0, "未判定": 0})
  465. bucket["total"] += 1
  466. bucket[row.get("verdict", "未判定")] += 1
  467. lines.append("| 数据域 | 张数 | 命中 | 弃权 | 误判 | 读法 |")
  468. lines.append("|---|---|---|---|---|---|")
  469. reading = {
  470. "field": "**唯一可作现场精度**(张数太少时仍不足以下结论)",
  471. "near": "近距前视,仅作回归参照",
  472. "web": "网上图库(广角/远景),**只看安全方向,不当精度**",
  473. "unknown": "未标域,不作数",
  474. }
  475. for domain in sorted(by_domain):
  476. bucket = by_domain[domain]
  477. lines.append("| %s | %d | %d | %d | %d | %s |" % (
  478. domain, bucket["total"], bucket["命中"], bucket["弃权"], bucket["误判"],
  479. reading.get(domain, "—")))
  480. lines.append("")
  481. if not by_domain.get("field", {}).get("total"):
  482. lines.append("> ⚠ **本批没有 `field`(现场实拍)样本**:命中/召回率**不得**作为现场精度引用;"
  483. "这批数据只能用于「会不会把载车判成空车」这类安全方向的回归。")
  484. lines.append("")
  485. violations: list[str] = []
  486. keys: list[str] = []
  487. for row in rows:
  488. label = row.get("label") or ""
  489. publish = row.get("publish")
  490. if publish is None:
  491. continue
  492. forbid = GATE_FORBID.get(label)
  493. if forbid and publish in forbid:
  494. keys.append("%s:%d" % (row["file"], int(publish)))
  495. violations.append(
  496. "`%s`(%s)发布 %s,禁止出现 %s —— %s"
  497. % (row["file"], label, STATE_LABEL.get(publish, publish),
  498. "/".join(str(v) for v in sorted(forbid)),
  499. row.get("publish_reason") or "-"))
  500. baseline_path = str(getattr(args, "baseline_violations", "") or "")
  501. new_violations: list[str] = []
  502. fixed_violations: list[str] = []
  503. if baseline_path:
  504. baseline = load_baseline(baseline_path)
  505. current = set(keys)
  506. new_violations = sorted(current - baseline)
  507. fixed_violations = sorted(baseline - current)
  508. lines.append("## 安全断言(与基线对比:禁止变差)")
  509. lines.append("")
  510. lines.append("| 项 | 数量 |")
  511. lines.append("|---|---|")
  512. lines.append("| 基线(%s) | %d |" % (os.path.basename(baseline_path), len(baseline)))
  513. lines.append("| 本次 | %d |" % len(current))
  514. lines.append("| **新增(门禁)** | **%d** |" % len(new_violations))
  515. lines.append("| 已修复(请同步基线) | %d |" % len(fixed_violations))
  516. lines.append("")
  517. if new_violations:
  518. lines.append("**新增违例(必须修掉或写进基线并说明理由)**")
  519. lines.append("")
  520. for key in new_violations:
  521. lines.append("* `%s`" % key)
  522. lines.append("")
  523. if fixed_violations:
  524. lines.append("**已修复(把这几条从基线里删掉)**:" +
  525. "、".join("`%s`" % key for key in fixed_violations))
  526. lines.append("")
  527. if violations:
  528. lines.append("## 安全断言失败明细(%d)" % len(violations))
  529. lines.append("")
  530. for item in violations:
  531. lines.append("* %s" % item)
  532. else:
  533. lines.append("## 安全断言")
  534. lines.append("")
  535. lines.append("全部通过:载车未判 `3`、空车未判 `1/2`、作业帧未判车型。")
  536. lines.append("")
  537. summary = {
  538. "config": os.path.relpath(config, ROOT),
  539. "exe": os.path.basename(exe),
  540. "repeats": args.repeats,
  541. "samples": len(rows),
  542. "by_label": by_label,
  543. "by_domain": by_domain,
  544. "violations": violations,
  545. "violation_keys": sorted(keys),
  546. "baseline": os.path.basename(baseline_path) if baseline_path else "",
  547. "new_violations": new_violations,
  548. "fixed_violations": fixed_violations,
  549. "rows": rows,
  550. }
  551. return {"markdown": "\n".join(lines), "summary": summary, "violations": violations,
  552. "new_violations": new_violations, "fixed_violations": fixed_violations}
  553. if __name__ == "__main__":
  554. raise SystemExit(main())