evidence_drill.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
  1. """P0-4 证据恢复演练:只读检查 JSONL 段与事件文件,不修改现场证据。
  2. 用法::
  3. python scripts/evidence_drill.py runs/drill/evidence
  4. 退出码 0 = 通过;1 = 有坏行/frame_id 回退/事件视频不可读。
  5. 放在 ``scripts/`` 而不是 ``build/``:``build/`` 在 ``.gitignore`` 里,
  6. 而 ``tests/test_evidence_drill.py`` 要 import 本模块——脚本不进交付,
  7. 交付版本的单测就是红的。
  8. """
  9. from __future__ import annotations
  10. import argparse
  11. import glob
  12. import json
  13. import os
  14. import sys
  15. def _force_utf8() -> None:
  16. """Windows 默认 GBK 控制台打印中文/符号会崩(UnicodeEncodeError),统一切 UTF-8。"""
  17. for stream in (sys.stdout, sys.stderr):
  18. try:
  19. stream.reconfigure(encoding="utf-8", errors="replace")
  20. except Exception: # pragma: no cover - 老 Python / 被重定向的流
  21. pass
  22. def check_jsonl(directory: str) -> dict:
  23. files = sorted(
  24. glob.glob(os.path.join(directory, "frames*.jsonl")),
  25. key=lambda path: os.path.getmtime(path),
  26. )
  27. total = 0
  28. bad = 0
  29. regressions = 0
  30. last_id = -1
  31. current_session = None
  32. sessions = 0
  33. first_ts = None
  34. last_ts = None
  35. for path in files:
  36. # utf-8-sig:现场用 Windows 工具另存过的片段可能带 BOM,不能当成坏行
  37. with open(path, "r", encoding="utf-8-sig", errors="replace") as fh:
  38. for line in fh:
  39. line = line.strip()
  40. if not line:
  41. continue
  42. total += 1
  43. try:
  44. row = json.loads(line)
  45. except json.JSONDecodeError:
  46. bad += 1
  47. continue
  48. session = str(row.get("session", ""))
  49. if session != current_session:
  50. current_session = session
  51. sessions += 1
  52. last_id = -1
  53. frame_id = int(row.get("frame_id", -1))
  54. if frame_id < last_id:
  55. regressions += 1
  56. last_id = max(last_id, frame_id)
  57. ts = float(row.get("ts", 0.0))
  58. first_ts = ts if first_ts is None else min(first_ts, ts)
  59. last_ts = ts if last_ts is None else max(last_ts, ts)
  60. return {
  61. "segments": len(files),
  62. "records": total,
  63. "sessions": sessions,
  64. "bad_lines": bad,
  65. "frame_id_regressions": regressions,
  66. "last_frame_id": last_id,
  67. "span_s": round((last_ts - first_ts), 3) if first_ts is not None and last_ts is not None else 0.0,
  68. }
  69. def check_events(directory: str) -> dict:
  70. metas = sorted(glob.glob(os.path.join(directory, "event-*.json")))
  71. clips = sorted(glob.glob(os.path.join(directory, "event-*.mp4")))
  72. unreadable = 0
  73. try:
  74. import cv2 # type: ignore
  75. except ImportError:
  76. cv2 = None
  77. if cv2 is not None:
  78. for path in clips:
  79. cap = cv2.VideoCapture(path)
  80. ok = cap.isOpened()
  81. frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) if ok else 0
  82. cap.release()
  83. if not ok or frames <= 0:
  84. unreadable += 1
  85. return {"event_meta": len(metas), "event_clips": len(clips), "unreadable_clips": unreadable}
  86. def main(argv=None) -> int:
  87. _force_utf8()
  88. parser = argparse.ArgumentParser(description="证据链恢复演练(只读)")
  89. parser.add_argument("directory", help="evidence 目录")
  90. args = parser.parse_args(argv)
  91. if not os.path.isdir(args.directory):
  92. print("目录不存在:%s" % args.directory)
  93. return 1
  94. summary = check_jsonl(args.directory)
  95. summary.update(check_events(args.directory))
  96. summary["ok"] = bool(
  97. summary["records"] > 0
  98. and summary["bad_lines"] == 0
  99. and summary["frame_id_regressions"] == 0
  100. and summary["unreadable_clips"] == 0
  101. )
  102. print(json.dumps(summary, ensure_ascii=False, indent=2))
  103. return 0 if summary["ok"] else 1
  104. if __name__ == "__main__":
  105. sys.exit(main())