"""回放评估:用 portcv evidence-v2 前视链路对 mp4 逐帧识别(L3 回放 / TP-SAFE-001 工具)。 产物(全部落在 runs/video_eval/,runs/ 已在 .gitignore 中): * .jsonl 每帧一行(候选状态 / 生产输出 / 诊断输出 / commit 证据) * _summary.json 状态分布、稳定区间、弃权原因统计 * _annot_*.jpg 每个输出状态变化点的叠加图 * _sheet.jpg 等间隔抽帧拼图 用法: python scripts/video_eval.py --video "D:\\clips\\a.mp4" --video "D:\\clips\\b.mp4" 口径:`require_commit` 取配置值(`configs/edge-v2-front.json`,生产口径), 逐帧复算与 `VisionPipeline.step` 的等价性由 `scripts/verify_equiv.py` 校验。 本脚本原在 `build/_video_eval.py`(`build/` 进 `.gitignore`,交付拿不到), 因 `docs/test_plan_gbt45163_5.md` 的 L3/TP-SAFE-001 依赖它,已迁到 `scripts/`。 """ import argparse import json import os import sys import time import cv2 import numpy as np REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, REPO) from portcv.config import load_config # noqa: E402 from portcv.logic import TemporalVoter # noqa: E402 from portcv.schema import STATE_LABELS # noqa: E402 from portcv.service.pipeline import VisionPipeline # noqa: E402 CONFIG = os.path.join(REPO, "configs", "edge-v2-front.json") def _tag(index, path): stem = os.path.splitext(os.path.basename(path))[0] ascii_part = "".join(ch for ch in stem if ch.isascii() and ch.isalnum()) return "v%d_%s" % (index + 1, ascii_part[-6:] or "clip") def _distribution(rows, key): counts = {} for row in rows: value = int(row[key]) counts[value] = counts.get(value, 0) + 1 total = max(1, len(rows)) return { str(k): { "label": STATE_LABELS.get(k, "unknown"), "frames": v, "ratio": round(v / total, 4), } for k, v in sorted(counts.items()) } def _segments(rows, key, conf_key): out = [] cur = None for row in rows: value = int(row[key]) if cur is None or cur["state"] != value: cur = { "state": value, "label": STATE_LABELS.get(value, "unknown"), "start_i": row["i"], "start_ts": row["ts"], "end_i": row["i"], "end_ts": row["ts"], "frames": 0, "conf_sum": 0.0, } out.append(cur) cur["frames"] += 1 cur["end_i"] = row["i"] cur["end_ts"] = row["ts"] cur["conf_sum"] += float(row.get(conf_key, 0.0)) for seg in out: seg["duration_s"] = round(seg["end_ts"] - seg["start_ts"], 3) seg["conf_mean"] = round(seg["conf_sum"] / max(1, seg["frames"]), 3) del seg["conf_sum"] return out def _overlay(image, lines, color=(0, 255, 255)): canvas = image.copy() cv2.rectangle(canvas, (0, 0), (canvas.shape[1], 16 + 16 * len(lines)), (0, 0, 0), -1) for n, text in enumerate(lines): cv2.putText(canvas, text, (6, 14 + 16 * n), cv2.FONT_HERSHEY_SIMPLEX, 0.42, color, 1, cv2.LINE_AA) return canvas def _sheet(frames, path, cols=4): if not frames: return thumbs = [] for _, image in frames: h, w = image.shape[:2] tw = 236 thumbs.append(cv2.resize(image, (tw, int(round(h * tw / w))), interpolation=cv2.INTER_AREA)) th = max(t.shape[0] for t in thumbs) rows = (len(thumbs) + cols - 1) // cols sheet = np.zeros((rows * (th + 18), cols * 236, 3), dtype="uint8") for n, (idx, _) in enumerate(frames): r, c = divmod(n, cols) tile = _overlay(thumbs[n], ["frame %d" % idx], (255, 255, 255)) y0 = r * (th + 18) sheet[y0:y0 + tile.shape[0], c * 236:c * 236 + tile.shape[1]] = tile cv2.imwrite(path, sheet, [int(cv2.IMWRITE_JPEG_QUALITY), 82]) def run_clip(index, path, out_dir, step, limit, sheet_n, annot_n, cfg_path, start_i=0): cfg = load_config(cfg_path) cfg.set_path("plc.enabled", False) cfg.set_path("run.save_on_change", False) cfg.set_path("run.preview", False) pipeline = VisionPipeline(cfg) pipeline.load() require_commit = bool(cfg.get_path("evidence_v2.require_commit", True)) voter_prod = TemporalVoter.from_config(cfg) voter_diag = TemporalVoter.from_config(cfg) cap = cv2.VideoCapture(path) if not cap.isOpened(): raise RuntimeError("无法打开视频: %s" % path) fps = float(cap.get(cv2.CAP_PROP_FPS) or 25.0) frames_total = int(cap.get(cv2.CAP_PROP_FRAME_COUNT) or 0) width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) tag = _tag(index, path) if start_i: cap.set(cv2.CAP_PROP_POS_FRAMES, int(start_i)) rows = [] sheet_slots = set() if frames_total and sheet_n > 0: for n in range(sheet_n): sheet_slots.add(int((n + 0.5) * frames_total / sheet_n)) sheet_frames = [] processed = 0 idx = int(start_i) started = time.perf_counter() while True: ok, image = cap.read() if not ok or image is None: break if limit and processed >= limit: break if idx % step: idx += 1 continue ts = idx / fps t0 = time.perf_counter() boxes = pipeline.detector.timed_infer(image) result = pipeline.evidence_v2.analyze( image, ts=ts, frame_id=idx, plc_arrived=False, detections=boxes, ) dec_prod = voter_prod.update( result.to_observation(ts=ts, frame_id=idx, require_commit=True)) dec_diag = voter_diag.update( result.to_observation(ts=ts, frame_id=idx, require_commit=False)) cost_ms = (time.perf_counter() - t0) * 1000.0 rows.append({ "i": idx, "ts": round(ts, 3), "cand": int(result.state), "cand_conf": round(float(result.confidence), 3), "prod": int(dec_prod.state), "prod_conf": round(float(dec_prod.confidence), 3), "prod_stable": bool(dec_prod.stable), "diag": int(dec_diag.state), "diag_conf": round(float(dec_diag.confidence), 3), "diag_stable": bool(dec_diag.stable), "committed": bool(result.committed), "commit_reason": result.commit_reason, "abstain_reason": result.abstain_reason, "view": result.view.value, "door_posts": int(result.door_posts), "gap_px": None if result.gap_px is None else round(float(result.gap_px), 1), "gap_m": None if result.gap_m is None else round(float(result.gap_m), 3), "scale_ok": bool(result.scale_ok), "motion_ok": bool(result.motion_ok), "hoist_high": bool(result.hoist_high), "stable_frames": int(result.stable_frames), "structure_frames": int(result.structure_frames), "ms": round(cost_ms, 2), }) processed += 1 if processed % 100 == 0: print("progress %s frames=%d ts=%.1f ms=%.1f" % (tag, processed, ts, cost_ms), flush=True) if idx in sheet_slots and len(sheet_frames) < sheet_n: sheet_frames.append((idx, image.copy())) idx += 1 cap.release() elapsed = time.perf_counter() - started # 关键帧:生产输出状态每次变化各存一张(最多 annot_n 张) picks = [] last_prod = None for row in rows: if last_prod is None or row["prod"] != last_prod: picks.append(row) last_prod = row["prod"] picks = picks[:annot_n] cap = cv2.VideoCapture(path) for n, row in enumerate(picks): cap.set(cv2.CAP_PROP_POS_FRAMES, row["i"]) ok, image = cap.read() if not ok or image is None: continue lines = [ "i=%d t=%.2fs cand=%d(%.2f) out=%d(%.2f)" % ( row["i"], row["ts"], row["cand"], row["cand_conf"], row["prod"], row["prod_conf"]), "commit=%s %s" % (row["committed"], row["commit_reason"]), "posts=%d gap=%s motion_ok=%s hoist=%s" % ( row["door_posts"], row["gap_px"], row["motion_ok"], row.get("hoist_high")), "abstain=%s" % (row["abstain_reason"] or "-"), ] annot = _overlay(image, [ln[:110] for ln in lines]) cv2.imwrite(os.path.join(out_dir, "%s_annot_%02d_i%04d.jpg" % (tag, n, row["i"])), annot, [int(cv2.IMWRITE_JPEG_QUALITY), 85]) cap.release() _sheet(sheet_frames, os.path.join(out_dir, "%s_sheet.jpg" % tag)) ms_values = [r["ms"] for r in rows] or [0.0] summary = { "file": os.path.basename(path), "path": path, "tag": tag, "video": { "width": width, "height": height, "fps": round(fps, 3), "frames": frames_total, "duration_s": round(frames_total / fps, 2) if frames_total else None, }, "config": os.path.relpath(cfg_path, REPO).replace("\\", "/"), "require_commit": require_commit, "view": str(cfg.get_path("evidence_v2.view", "front")), "analysed_frames": len(rows), "step": step, "elapsed_s": round(elapsed, 2), "ms_per_frame": { "mean": round(sum(ms_values) / len(ms_values), 2), "p95": round(sorted(ms_values)[int(0.95 * (len(ms_values) - 1))], 2), }, "prod_dist": _distribution(rows, "prod"), "diag_dist": _distribution(rows, "diag"), "cand_dist": _distribution(rows, "cand"), "prod_committed_frames": sum(1 for r in rows if r["prod"] in (0, 1, 2)), "commit_ok_frames": sum(1 for r in rows if r["committed"]), "prod_segments": _segments(rows, "prod", "prod_conf"), "diag_segments": _segments(rows, "diag", "diag_conf"), "abstain_reasons": {}, "commit_reasons": {}, } for bucket, key in (("abstain_reasons", "abstain_reason"), ("commit_reasons", "commit_reason")): counts = {} for row in rows: text = str(row[key] or "-").split(" ")[0] counts[text] = counts.get(text, 0) + 1 summary[bucket] = dict(sorted(counts.items(), key=lambda kv: -kv[1])[:12]) with open(os.path.join(out_dir, "%s.jsonl" % tag), "w", encoding="utf-8") as fh: for row in rows: fh.write(json.dumps(row, ensure_ascii=False) + "\n") with open(os.path.join(out_dir, "%s_summary.json" % tag), "w", encoding="utf-8") as fh: json.dump(summary, fh, ensure_ascii=False, indent=2) return summary def main(argv=None): parser = argparse.ArgumentParser(description="对 mp4 跑 evidence-v2 识别(一次性分析)") parser.add_argument("--video", action="append", required=True) parser.add_argument("--config", default=CONFIG) parser.add_argument("--out", default=os.path.join(REPO, "runs", "video_eval")) parser.add_argument("--step", type=int, default=1) parser.add_argument("--start", type=int, default=0, help="起始帧号(调试分段跑)") parser.add_argument("--limit", type=int, default=0) parser.add_argument("--sheet", type=int, default=16) parser.add_argument("--annotate", type=int, default=6) args = parser.parse_args(argv) os.makedirs(args.out, exist_ok=True) for n, path in enumerate(args.video): summary = run_clip(n, path, args.out, args.step, args.limit, args.sheet, args.annotate, args.config, args.start) print(json.dumps({ "tag": summary["tag"], "file": summary["file"], "frames": summary["analysed_frames"], "elapsed_s": summary["elapsed_s"], "ms_per_frame": summary["ms_per_frame"], "prod_dist": summary["prod_dist"], "diag_dist": summary["diag_dist"], "cand_dist": summary["cand_dist"], "commit_ok_frames": summary["commit_ok_frames"], "prod_segments": summary["prod_segments"], }, ensure_ascii=False)) return 0 if __name__ == "__main__": sys.exit(main())