"""数据集回归 harness(**C++ 生产路径**):把一个图片/视频测试集跑成“本帧候选 / 发布值”表 + 安全断言。 为什么要这个脚本 ---------------- `docs/evidence/test_2026-11-20/测试报告.md` 那几张表是用一套**临时 harness**(`%TEMP%` 里的 PGM chunk + 逐个 `portcv_run`)跑出来的,harness 本身没进仓 —— 于是“报告里的数字”无法复现, 任何判据改动都没有门禁。这里把它固化成脚本,并且**必须走 C++ `edge-v2`**: * Python 参考实现(`portcv/logic/evidence_v2.py`)在广角/远景素材上与 C++ 结论不同 (实拍 `video2`:Python 抽样帧多为 `255 weak_evidence`,C++ 是 `2 deck_edge`), 用 Python 量会得出错误结论; * 现场跑的是 C++,验收看的也是 C++ 发给 PLC 的 `state`。 两遍口径(与测试报告一致) -------------------------- * **本帧候选**:`evidence_v2.require_commit=false` + 单帧 → `edge_state` (算法本身把这一帧判成什么,用来评估结构可分性); * **发布值**:`evidence_v2.require_commit=true` + 同一张图重复 `--repeats` 帧(默认 20) → 寄存器口径 `state`(含 commit / 投票 / 发布门,PLC 实际采信的就是它)。 安全断言(`--labels` 给了人工判读才生效;违反 → 退出码 1) -------------------------------------------------------- * `boxed`(平车坐箱 / 敞车坐箱):发布值**不得**为 `3`(载车被判空车 = 最危险的误判); * `empty`(空敞车 / 空平车):发布值**不得**为 `2` / `1`(空车被判成载车); * `working`(吊具高悬 / 夹箱的作业帧):发布值必须是 `0`(不判)。 数据域(`labels.json` 的 `domain`;`--domain field,near,web` 可过滤) ------------------------------------------------------------------- * `field`:现场实拍(部署机位 / 司机视角)——**只有这一域的命中率能当现场精度**; * `near`:近距前视素材,非现场工况片段,仅作回归参照; * `web`:网上图库(广角 / 远景),与部署机位的拍摄角度、距离都不同 —— 它的数字只能回答"会不会出现危险误报",**不能**当召回率/准确率; * 报告按域分开统计;一批里没有 `field` 样本时,脚本会打醒目警告。 用法 ---- :: # 39 张 web_cc + 4 张对照集(人工判读见 labels.json) python scripts/dataset_harness.py --images <图片目录...> \ --labels docs/evidence/test_2026-11-20/labels.json --out runs/harness # 只跑发布值(快一半) python scripts/dataset_harness.py --images <目录> --no-single # 换配置(真机模板 / view=high) python scripts/dataset_harness.py --images <目录> --config configs/edge-v2-rtsp.json 视频请先用 ``scripts/extract_frames.py`` 抽成 PGM 目录(本脚本只吃图片,避免把解码差异 混进判据口径)。 为什么所有中间产物都落在系统临时目录:C++ `main()` 的 `argv` 在 Windows 上是 ANSI 编码, 仓库路径含中文(`…\\正面吊\\…`)会被传坏。脚本把配置/PGM/dump 全部写到**纯 ASCII** 的 `%TEMP%/portcv_harness`,只把结论写回 `--out`(Python 侧自己写文件,无编码问题)。 """ from __future__ import annotations import argparse import json import os import re import shutil import subprocess import sys import tempfile import time ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATE_LABEL = {0: "0 不在车上", 1: "1 敞车", 2: "2 平车", 3: "3 空车", 255: "255 弃权"} #: 数据域:**现场**实拍 / 近距前视素材(非现场工况) / 网上图库(广角、远景) #: #: 为什么必须分开统计:`web_cc` 那 39 张是网上找的图库照片,拍摄角度与距离 #: 和部署机位(相机固定在车身左前方、近距、箱底与车面在画面中部)不是一回事 —— #: 它们的数字只能回答"会不会把载车判成空车"这类**安全方向**问题,**不能**当 #: 现场精度(召回/准确率)。没有 `field` 样本时,报告里的命中率一律不作数。 DOMAINS = ("field", "near", "web", "unknown") #: 人工判读标签 → 期望状态(`expect` 在 labels.json 里可逐条覆盖) LABEL_EXPECT = { "boxed_flatbed": 2, "boxed_gondola": 1, "empty_gondola": 3, "empty_flatbed": 3, "working": 0, } IMAGE_EXT = (".jpg", ".jpeg", ".png", ".bmp", ".pgm") #: 断言:标签 → 发布值禁集(None = 无禁集) GATE_FORBID = { "boxed_flatbed": {3}, "boxed_gondola": {3}, "empty_gondola": {1, 2}, "empty_flatbed": {1, 2}, "working": {1, 2, 3}, } def find_exe(explicit: str = "") -> str: """找 `portcv_run`:显式参数 > 环境变量 > 本仓构建产物 > PATH。""" if explicit: return explicit env = os.environ.get("PORTCV_RUN", "") if env: return env for rel in ( os.path.join("build-cmake", "windows-zig-release", "portcv_run.exe"), os.path.join("build-cmake", "windows-zig-release", "portcv_run"), os.path.join("build", "portcv_run"), os.path.join("build", "portcv_run.exe"), ): path = os.path.join(ROOT, rel) if os.path.exists(path): return path found = shutil.which("portcv_run") if found: return found raise SystemExit( "找不到 portcv_run:用 --exe 指定,或先构建(docs/deployment.md §2)。" ) def collect_images(dirs: list[str]) -> list[str]: """递归收集图片;按路径排序(同一目录内即文件名序)。""" out: list[str] = [] for base in dirs: if os.path.isfile(base): out.append(base) continue for cur, _sub, files in os.walk(base): for name in sorted(files): if name.lower().endswith(IMAGE_EXT): out.append(os.path.join(cur, name)) return sorted(out) def image_to_pgm(src: str, dst: str) -> tuple[int, int]: """图片 → PGM(**灰度解码**,与取流口径一致:`IMREAD_GRAYSCALE`)。 路径可能含中文(仓库在 `…\\正面吊\\…`),OpenCV 的 `imread` 在 Windows 上按 ANSI 打开文件会失败 —— 所以统一 `np.fromfile` + `imdecode`(与 `portcv/io/capture.py` 同一手法,`docs/route_v2.md` §7.1 记录的「JPEG 经 BGR→gray 差 ±1 灰阶」也在这里避开)。 """ import cv2 # 局部导入:只跑网关/查表时不需要 cv2 import numpy as np with open(src, "rb") as handle: buf = np.frombuffer(handle.read(), dtype=np.uint8) gray = cv2.imdecode(buf, cv2.IMREAD_GRAYSCALE) if gray is None: raise RuntimeError("解不开这张图(损坏或格式不支持):%s" % src) height, width = gray.shape[:2] with open(dst, "wb") as handle: handle.write(b"P5\n") handle.write(("%d %d\n" % (width, height)).encode("ascii")) handle.write(b"255\n") handle.write(np.ascontiguousarray(gray).tobytes()) return width, height def prepare_configs(base_config: str, work: str, chunk: str, repeats: int, fps: float) -> tuple[str, str]: """把模板配置改写成两份(single / stable),全部指向 ASCII 临时目录。 * `source.type=images` + `source.uri=`:离线回放,零依赖; * `run.max_fps`:默认沿用模板(15 fps)。**不要调太快**:`decision.min_dwell_s`(0.2 s) 要求落位驻留,20 帧同图若跑成 83 ms,投票永远不会发布(本 harness 早期就踩过这个坑); * `evidence_v2.require_commit`:single=false(看算法本身怎么判)/ stable=true(看发布值); * `run.output_dir` / `calibration.record` 指到临时目录:仓储路径含中文,C++ 侧打不开。 """ with open(base_config, encoding="utf-8-sig") as handle: cfg = json.load(handle) cfg.setdefault("run", {})["max_fps"] = float(fps) if fps > 0.0 else float( cfg.get("run", {}).get("max_fps", 15.0)) cfg["run"]["output_dir"] = os.path.join(work, "output") cfg["run"]["preview"] = False cfg["run"]["save_on_change"] = False cfg.setdefault("source", {})["type"] = "images" cfg["source"]["uri"] = chunk cfg["source"]["loop"] = False cfg.pop("_note", None) calib = cfg.setdefault("calibration", {}) calib["record"] = "" calib["stale"] = False paths = [] for name, require_commit in (("single", False), ("stable", True)): one = json.loads(json.dumps(cfg)) one.setdefault("evidence_v2", {})["require_commit"] = bool(require_commit) path = os.path.join(work, "cfg_%s.json" % name) with open(path, "w", encoding="utf-8") as handle: json.dump(one, handle, ensure_ascii=False, indent=2) handle.write("\n") paths.append(path) return paths[0], paths[1] def read_dump(path: str) -> list[dict]: rows: list[dict] = [] if not os.path.exists(path): return rows with open(path, encoding="utf-8-sig") as handle: for line in handle: line = line.strip() if line: rows.append(json.loads(line)) return rows def run_once(exe: str, config: str, chunk: str, frames: int, dump: str, timeout: float) -> tuple[int, str, list[dict]]: """跑一次 `portcv_run`(images 源),返回 (退出码, 日志尾部, dump 行)。""" if os.path.exists(dump): os.remove(dump) cmd = [exe, "-c", config, "--source-type", "images", "--source-uri", chunk, "--max-frames", str(frames), "--dump-frames", dump, "--dump-dir", os.path.join(os.path.dirname(dump), "pgm"), "--no-plc"] try: proc = subprocess.run(cmd, cwd=ROOT, timeout=timeout, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) log = proc.stdout.decode("utf-8", "replace") code = proc.returncode except subprocess.TimeoutExpired as exc: log = (exc.stdout or b"").decode("utf-8", "replace") if exc.stdout else "" return 124, log[-400:], read_dump(dump) return code, log[-400:], read_dump(dump) def short_reason(row: dict) -> str: """从 dump 行里抠出“判据一句话”(v2 的 reason 就是现场可读诊断)。""" reason = str(row.get("reason") or "").strip() text = reason or str(row.get("summary") or "").strip() text = re.sub(r"^v2:(ok|abstain)\s*", "", text) return text.replace(" ", " ") def load_labels(path: str) -> dict[str, dict]: """读人工判读表:``{"NX70_001.jpg": {"label": "empty_flatbed", "expect": 3}}``。""" if not path: return {} with open(path, encoding="utf-8-sig") as handle: raw = json.load(handle) out: dict[str, dict] = {} for name, item in raw.items(): if name.startswith("_"): continue # `_note` / `_source` 这类说明键 if isinstance(item, str): item = {"label": item} entry = dict(item) label = str(entry.get("label", "")).strip() if label not in LABEL_EXPECT: raise SystemExit("labels.json 里 %s 的 label 不认识:%r(可选:%s)" % (name, label, ", ".join(sorted(LABEL_EXPECT)))) entry["label"] = label domain = str(entry.get("domain", "unknown")).strip().lower() or "unknown" if domain not in DOMAINS: raise SystemExit("labels.json 里 %s 的 domain 不认识:%r(可选:%s)" % (name, domain, ", ".join(DOMAINS))) entry["domain"] = domain if "expect" not in entry: entry["expect"] = LABEL_EXPECT[label] out[os.path.basename(name)] = entry return out def parse_args(argv=None) -> argparse.Namespace: parser = argparse.ArgumentParser( description="数据集回归 harness(C++ edge-v2):本帧候选 / 发布值 + 安全断言") parser.add_argument("--images", nargs="+", required=True, help="图片目录(递归)或图片文件") parser.add_argument("--config", default=os.path.join("configs", "edge-v2-front.json"), help="配置模板(相对仓库根或绝对路径)") parser.add_argument("--labels", default="", help="人工判读 JSON(见 docs/evidence/test_2026-11-20/labels.json)") parser.add_argument("--domain", default="", help="只跑指定数据域(逗号分隔:field,near,web;空 = 全部)。" "**没有 field 样本时,命中率不得当现场精度**") parser.add_argument("--exe", default="", help="portcv_run 路径(缺省自动找)") parser.add_argument("--out", default=os.path.join("runs", "harness"), help="结论输出目录(默认 runs/harness,已 gitignore)") parser.add_argument("--repeats", type=int, default=20, help="发布值口径:同一张图重复多少帧(现场 harness 约定 20)") parser.add_argument("--fps", type=float, default=0.0, help="覆盖 run.max_fps(默认 0 = 沿用模板;" "注意别调太快:decision.min_dwell_s 要求落位驻留," "20 帧必须跨够 0.2 s 才会发布)") parser.add_argument("--timeout", type=float, default=300.0, help="单次 portcv_run 超时(秒)") parser.add_argument("--limit", type=int, default=0, help="只跑前 N 张(0 = 全部)") parser.add_argument("--no-single", action="store_true", help="跳过“本帧候选”这一遍(快一半)") parser.add_argument("--no-gate", action="store_true", help="断言失败也返回 0(只出表)") parser.add_argument("--keep-work", action="store_true", help="保留临时工作目录") return parser.parse_args(argv) def verdict(publish: int, expect: int) -> str: """发布值 vs 人工真值:命中 / 弃权(发 0 = 不判)/ 误判。""" if publish == expect: return "命中" if publish == 0: return "弃权" return "误判" def main(argv=None) -> int: args = parse_args(argv) exe = find_exe(args.exe) config = args.config if os.path.isabs(args.config) else os.path.join(ROOT, args.config) if not os.path.exists(config): print("找不到配置模板: %s" % config, file=sys.stderr) return 2 if args.repeats < 1: print("--repeats 至少 1", file=sys.stderr) return 2 images = collect_images(args.images) if not images: print("没有找到图片:%s" % " ".join(args.images), file=sys.stderr) return 2 if args.limit > 0: images = images[:args.limit] labels = load_labels(args.labels) if args.domain: wanted = {item.strip().lower() for item in args.domain.split(",") if item.strip()} bad = wanted - set(DOMAINS) if bad: print("--domain 里有不认识的值:%s(可选:%s)" % (sorted(bad), ", ".join(DOMAINS)), file=sys.stderr) return 2 total = len(images) images = [path for path in images if labels.get(os.path.basename(path), {}).get("domain", "unknown") in wanted] print("域过滤 : %s → %d/%d 张" % ("+".join(sorted(wanted)), len(images), total)) if not images: print("该数据域下没有样本", file=sys.stderr) return 2 work = os.path.join(tempfile.gettempdir(), "portcv_harness") chunk = os.path.join(work, "chunk") if os.path.isdir(work): shutil.rmtree(work, ignore_errors=True) os.makedirs(chunk, exist_ok=True) cfg_single, cfg_stable = prepare_configs(config, work, chunk, args.repeats, args.fps) out_dir = args.out if os.path.isabs(args.out) else os.path.join(ROOT, args.out) os.makedirs(out_dir, exist_ok=True) print("可执行 : %s" % exe) print("配置模板 : %s" % os.path.relpath(config, ROOT)) print("图片 : %d 张(人工判读 %d 条)" % (len(images), len(labels))) print("口径 : 本帧候选 = require_commit=false 单帧 / 发布值 = require_commit=true" " + 同图 %d 帧" % args.repeats) print("") rows: list[dict] = [] started = time.time() for index, src in enumerate(images, 1): name = os.path.basename(src) label = labels.get(name, {}) for old in os.listdir(chunk): os.remove(os.path.join(chunk, old)) try: width, height = image_to_pgm(src, os.path.join(chunk, "frame_000000.pgm")) except RuntimeError as exc: print("[%d/%d] %s 跳过:%s" % (index, len(images), name, exc), file=sys.stderr) continue for copy in range(1, args.repeats): shutil.copyfile(os.path.join(chunk, "frame_000000.pgm"), os.path.join(chunk, "frame_%06d.pgm" % copy)) row: dict = { "index": index, "file": name, "size": [width, height], "domain": label.get("domain", "unknown"), "label": label.get("label", ""), "expect": label.get("expect"), "note": label.get("note", ""), } if not args.no_single: code, log, dump = run_once( exe, cfg_single, chunk, 1, os.path.join(work, "dump_single.jsonl"), args.timeout) if code != 0 or not dump: row["candidate"] = None row["candidate_reason"] = "" row["candidate_error"] = "rc=%d %s" % (code, log.strip()[-120:]) else: row["candidate"] = int(dump[-1].get("edge_state", -1)) row["candidate_reason"] = short_reason(dump[-1]) code, log, dump = run_once( exe, cfg_stable, chunk, args.repeats, os.path.join(work, "dump_stable.jsonl"), args.timeout) if code != 0 or not dump: row["publish"] = None row["publish_reason"] = "" row["publish_error"] = "rc=%d %s" % (code, log.strip()[-120:]) else: last = dump[-1] row["publish"] = int(last.get("state", -1)) row["publish_edge"] = int(last.get("edge_state", -1)) row["publish_reason"] = short_reason(last) row["stable_flag"] = bool(int(last.get("flags", 0)) & 0x0001) row["frames"] = len(dump) if row.get("expect") is not None and row.get("publish") is not None: row["verdict"] = verdict(int(row["publish"]), int(row["expect"])) rows.append(row) print("[%d/%d] %-20s 人工=%-11s 候选=%-9s 发布=%-9s %s" % (index, len(images), name, row.get("label") or "-", "-" if row.get("candidate") is None else STATE_LABEL.get(int(row["candidate"]), str(row["candidate"])), "-" if row.get("publish") is None else STATE_LABEL.get(int(row["publish"]), str(row["publish"])), row.get("verdict", "")), file=sys.stderr) elapsed = time.time() - started report = render_report(rows, exe, config, args) md_path = os.path.join(out_dir, "dataset_harness.md") json_path = os.path.join(out_dir, "dataset_harness.json") with open(md_path, "w", encoding="utf-8") as handle: handle.write(report["markdown"]) with open(json_path, "w", encoding="utf-8") as handle: json.dump(report["summary"], handle, ensure_ascii=False, indent=2) handle.write("\n") print("") print(report["markdown"]) print("耗时 : %.1f s / %d 张(%.2f s 每张)" % (elapsed, len(rows), elapsed / max(1, len(rows)))) print("结论 : %s" % md_path) print("小结 JSON : %s" % json_path) if not args.keep_work: shutil.rmtree(work, ignore_errors=True) if report["violations"] and not args.no_gate: print("", file=sys.stderr) print("安全断言失败 %d 条:" % len(report["violations"]), file=sys.stderr) for item in report["violations"]: print(" - %s" % item, file=sys.stderr) return 1 return 0 def render_report(rows: list[dict], exe: str, config: str, args: argparse.Namespace) -> dict: """出 Markdown 表 + 小结 JSON + 断言清单。""" lines: list[str] = [] lines.append("# 数据集回归 harness(C++ `edge-v2`)") lines.append("") lines.append("- 可执行:`%s`" % os.path.basename(exe)) lines.append("- 配置模板:`%s`" % os.path.relpath(config, ROOT)) lines.append("- 口径:本帧候选 = `require_commit=false` 单帧;发布值 = `require_commit=true`" " + 同图 %d 帧" % args.repeats) lines.append("- 状态码:`0` 不在车上/其他;`1` 敞车;`2` 平车;`3` 空车;`255` 内部弃权") domains = sorted({row.get("domain", "unknown") for row in rows}) lines.append("- 数据域:%s(`field` 现场实拍 / `near` 近距前视素材 / `web` 网上图库" "——**只有 `field` 的命中率能当现场精度**)" % "/".join(domains)) lines.append("") lines.append("| # | 文件 | 域 | 人工判读 | 期望 | 本帧候选 | 发布值 | 结论 | 判据 |") lines.append("|---|---|---|---|---|---|---|---|---|") for row in rows: candidate = row.get("candidate") publish = row.get("publish") lines.append("| %d | `%s` | %s | %s | %s | %s | %s | %s | %s |" % ( row["index"], row["file"], row.get("domain", "unknown"), row.get("label") or "-", "-" if row.get("expect") is None else row["expect"], "-" if candidate is None else candidate, "-" if publish is None else STATE_LABEL.get(publish, publish), row.get("verdict", "-"), (row.get("publish_reason") or "-"), )) lines.append("") by_label: dict[str, dict[str, int]] = {} for row in rows: label = row.get("label") or "unlabeled" bucket = by_label.setdefault( label, {"total": 0, "命中": 0, "弃权": 0, "误判": 0, "未判定": 0}) bucket["total"] += 1 bucket[row.get("verdict", "未判定")] += 1 lines.append("| 人工判读 | 张数 | 命中 | 弃权 | 误判 |") lines.append("|---|---|---|---|---|") for label in sorted(by_label): bucket = by_label[label] lines.append("| %s | %d | %d | %d | %d |" % ( label, bucket["total"], bucket["命中"], bucket["弃权"], bucket["误判"])) if by_label: lines.append("| **合计** | **%d** | **%d** | **%d** | **%d** |" % ( sum(b["total"] for b in by_label.values()), sum(b["命中"] for b in by_label.values()), sum(b["弃权"] for b in by_label.values()), sum(b["误判"] for b in by_label.values()))) lines.append("") by_domain: dict[str, dict[str, int]] = {} for row in rows: domain = row.get("domain", "unknown") bucket = by_domain.setdefault( domain, {"total": 0, "命中": 0, "弃权": 0, "误判": 0, "未判定": 0}) bucket["total"] += 1 bucket[row.get("verdict", "未判定")] += 1 lines.append("| 数据域 | 张数 | 命中 | 弃权 | 误判 | 读法 |") lines.append("|---|---|---|---|---|---|") reading = { "field": "**唯一可作现场精度**(张数太少时仍不足以下结论)", "near": "近距前视,仅作回归参照", "web": "网上图库(广角/远景),**只看安全方向,不当精度**", "unknown": "未标域,不作数", } for domain in sorted(by_domain): bucket = by_domain[domain] lines.append("| %s | %d | %d | %d | %d | %s |" % ( domain, bucket["total"], bucket["命中"], bucket["弃权"], bucket["误判"], reading.get(domain, "—"))) lines.append("") if not by_domain.get("field", {}).get("total"): lines.append("> ⚠ **本批没有 `field`(现场实拍)样本**:命中/召回率**不得**作为现场精度引用;" "这批数据只能用于「会不会把载车判成空车」这类安全方向的回归。") lines.append("") violations: list[str] = [] for row in rows: label = row.get("label") or "" publish = row.get("publish") if publish is None: continue forbid = GATE_FORBID.get(label) if forbid and publish in forbid: violations.append( "`%s`(%s)发布 %s,禁止出现 %s —— %s" % (row["file"], label, STATE_LABEL.get(publish, publish), "/".join(str(v) for v in sorted(forbid)), row.get("publish_reason") or "-")) if violations: lines.append("## 安全断言失败(%d)" % len(violations)) lines.append("") for item in violations: lines.append("* %s" % item) else: lines.append("## 安全断言") lines.append("") lines.append("全部通过:载车未判 `3`、空车未判 `1/2`、作业帧未判车型。") lines.append("") summary = { "config": os.path.relpath(config, ROOT), "exe": os.path.basename(exe), "repeats": args.repeats, "samples": len(rows), "by_label": by_label, "by_domain": by_domain, "violations": violations, "rows": rows, } return {"markdown": "\n".join(lines), "summary": summary, "violations": violations} if __name__ == "__main__": raise SystemExit(main())