| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122 |
- """P0-4 证据恢复演练:只读检查 JSONL 段与事件文件,不修改现场证据。
- 用法::
- python scripts/evidence_drill.py runs/drill/evidence
- 退出码 0 = 通过;1 = 有坏行/frame_id 回退/事件视频不可读。
- 放在 ``scripts/`` 而不是 ``build/``:``build/`` 在 ``.gitignore`` 里,
- 而 ``tests/test_evidence_drill.py`` 要 import 本模块——脚本不进交付,
- 交付版本的单测就是红的。
- """
- from __future__ import annotations
- import argparse
- import glob
- import json
- import os
- import sys
- def _force_utf8() -> None:
- """Windows 默认 GBK 控制台打印中文/符号会崩(UnicodeEncodeError),统一切 UTF-8。"""
- for stream in (sys.stdout, sys.stderr):
- try:
- stream.reconfigure(encoding="utf-8", errors="replace")
- except Exception: # pragma: no cover - 老 Python / 被重定向的流
- pass
- def check_jsonl(directory: str) -> dict:
- files = sorted(
- glob.glob(os.path.join(directory, "frames*.jsonl")),
- key=lambda path: os.path.getmtime(path),
- )
- total = 0
- bad = 0
- regressions = 0
- last_id = -1
- current_session = None
- sessions = 0
- first_ts = None
- last_ts = None
- for path in files:
- # utf-8-sig:现场用 Windows 工具另存过的片段可能带 BOM,不能当成坏行
- with open(path, "r", encoding="utf-8-sig", errors="replace") as fh:
- for line in fh:
- line = line.strip()
- if not line:
- continue
- total += 1
- try:
- row = json.loads(line)
- except json.JSONDecodeError:
- bad += 1
- continue
- session = str(row.get("session", ""))
- if session != current_session:
- current_session = session
- sessions += 1
- last_id = -1
- frame_id = int(row.get("frame_id", -1))
- if frame_id < last_id:
- regressions += 1
- last_id = max(last_id, frame_id)
- ts = float(row.get("ts", 0.0))
- first_ts = ts if first_ts is None else min(first_ts, ts)
- last_ts = ts if last_ts is None else max(last_ts, ts)
- return {
- "segments": len(files),
- "records": total,
- "sessions": sessions,
- "bad_lines": bad,
- "frame_id_regressions": regressions,
- "last_frame_id": last_id,
- "span_s": round((last_ts - first_ts), 3) if first_ts is not None and last_ts is not None else 0.0,
- }
- def check_events(directory: str) -> dict:
- metas = sorted(glob.glob(os.path.join(directory, "event-*.json")))
- clips = sorted(glob.glob(os.path.join(directory, "event-*.mp4")))
- unreadable = 0
- try:
- import cv2 # type: ignore
- except ImportError:
- cv2 = None
- if cv2 is not None:
- for path in clips:
- cap = cv2.VideoCapture(path)
- ok = cap.isOpened()
- frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) if ok else 0
- cap.release()
- if not ok or frames <= 0:
- unreadable += 1
- return {"event_meta": len(metas), "event_clips": len(clips), "unreadable_clips": unreadable}
- def main(argv=None) -> int:
- _force_utf8()
- parser = argparse.ArgumentParser(description="证据链恢复演练(只读)")
- parser.add_argument("directory", help="evidence 目录")
- args = parser.parse_args(argv)
- if not os.path.isdir(args.directory):
- print("目录不存在:%s" % args.directory)
- return 1
- summary = check_jsonl(args.directory)
- summary.update(check_events(args.directory))
- summary["ok"] = bool(
- summary["records"] > 0
- and summary["bad_lines"] == 0
- and summary["frame_id_regressions"] == 0
- and summary["unreadable_clips"] == 0
- )
- print(json.dumps(summary, ensure_ascii=False, indent=2))
- return 0 if summary["ok"] else 1
- if __name__ == "__main__":
- sys.exit(main())
|