dataset_harness.py 24 KB

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