storage.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  1. """P0-4 数据证据链:逐帧 JSONL、事件视频环缓、50 MB 切分、保留期清理。
  2. 现场验收要能回答三个问题:
  3. 1. 某次误判/漏判发生时,**输入画面**是什么?→ 事件环缓 + 单帧 JSONL;
  4. 2. 断电/重启后,证据是否**连续且可恢复**?→ 追加写、坏尾行修复、段文件;
  5. 3. 硬盘会不会被写满?→ 50 MB 切分 + ``retention_days`` 清理。
  6. 本模块只负责落盘,不改变判决。默认 ``evidence.enabled=false``,现场确认
  7. 磁盘/权限后再开;开启后 ``runner`` 每帧写一行 JSONL,状态变化时把环缓里
  8. 最近 N 帧导成 mp4(失败则退化为 JPG 序列)。
  9. """
  10. from __future__ import annotations
  11. import json
  12. import os
  13. import time
  14. from collections import deque
  15. from typing import Deque, Dict, List, Optional
  16. import numpy as np
  17. try: # pragma: no cover - 与取流层同一依赖
  18. import cv2
  19. except ImportError: # pragma: no cover
  20. cv2 = None # type: ignore
  21. from .config import Config
  22. __all__ = [
  23. "DEFAULT_SEGMENT_BYTES",
  24. "EventRing",
  25. "EvidenceStore",
  26. "SegmentingJsonlWriter",
  27. "purge_old_files",
  28. ]
  29. DEFAULT_SEGMENT_BYTES = 50 * 1024 * 1024
  30. def _ensure_dir(path: str) -> str:
  31. os.makedirs(path, exist_ok=True)
  32. return path
  33. def purge_old_files(directory: str, retention_days: float, now: Optional[float] = None) -> List[str]:
  34. """删除 ``directory`` 下超过保留期的普通文件;返回删除路径。"""
  35. if not directory or not os.path.isdir(directory) or retention_days <= 0:
  36. return []
  37. cutoff = float(now if now is not None else time.time()) - float(retention_days) * 86400.0
  38. removed: List[str] = []
  39. for name in os.listdir(directory):
  40. path = os.path.join(directory, name)
  41. if not os.path.isfile(path):
  42. continue
  43. try:
  44. if os.path.getmtime(path) < cutoff:
  45. os.remove(path)
  46. removed.append(path)
  47. except OSError:
  48. continue
  49. return removed
  50. class SegmentingJsonlWriter:
  51. """按大小切分的 JSONL 追加写;重启后继续写当前段,坏尾行自动补换行。"""
  52. def __init__(
  53. self,
  54. directory: str,
  55. max_bytes: int = DEFAULT_SEGMENT_BYTES,
  56. retention_days: float = 90.0,
  57. fsync_interval_s: float = 1.0,
  58. ) -> None:
  59. self.directory = _ensure_dir(directory)
  60. self.max_bytes = max(64, int(max_bytes))
  61. self.retention_days = float(retention_days)
  62. self.fsync_interval_s = max(0.0, float(fsync_interval_s))
  63. self.path = os.path.join(self.directory, "frames.jsonl")
  64. self.records = 0
  65. self.segments = 0
  66. self.session = ""
  67. self._fh = None # type: ignore[assignment]
  68. self._last_fsync = 0.0
  69. # -- 生命周期 ---------------------------------------------------------
  70. def open(self) -> "SegmentingJsonlWriter":
  71. _ensure_dir(self.directory)
  72. self.session = "%s-%d" % (time.strftime("%Y%m%d-%H%M%S"), os.getpid())
  73. self._repair_tail()
  74. self._fh = open(self.path, "a", encoding="utf-8", newline="\n")
  75. self.segments = len(self._segment_files())
  76. purge_old_files(self.directory, self.retention_days)
  77. return self
  78. def close(self) -> None:
  79. if self._fh is not None:
  80. try:
  81. self._fh.flush()
  82. os.fsync(self._fh.fileno())
  83. except OSError:
  84. pass
  85. self._fh.close()
  86. self._fh = None
  87. def _segment_files(self) -> List[str]:
  88. return sorted(
  89. os.path.join(self.directory, name)
  90. for name in os.listdir(self.directory)
  91. if name.startswith("frames-") and name.endswith(".jsonl")
  92. )
  93. def segment_files(self) -> List[str]:
  94. """按**写入顺序**返回全部分段文件(含当前正在写的 ``frames.jsonl``)。
  95. 归档段命名为 ``frames-<时间戳>-<序号>.jsonl``,字符 ``'-'``(0x2D) 小于
  96. ``'.'``(0x2E),所以按文件名排序正好是「旧归档段 → 当前段」。外部读取证据
  97. (现场复盘、脚本抽样)必须走这个函数:``os.listdir`` 的顺序在 ext4 上是
  98. 目录哈希序,跨机器/跨文件系统都不稳定,直接拼接会把记录读乱。
  99. """
  100. current = os.path.basename(self.path)
  101. names = [
  102. name
  103. for name in os.listdir(self.directory)
  104. if name.endswith(".jsonl")
  105. and (name == current or name.startswith("frames-"))
  106. ]
  107. return [os.path.join(self.directory, name) for name in sorted(names)]
  108. def _repair_tail(self) -> None:
  109. """断电时最后一行可能只写了一半;补换行,保留原始字节供排查。"""
  110. if not os.path.isfile(self.path) or os.path.getsize(self.path) == 0:
  111. return
  112. with open(self.path, "rb+") as fh:
  113. fh.seek(-1, os.SEEK_END)
  114. if fh.read(1) != b"\n":
  115. fh.write(b"\n")
  116. def _rotate(self) -> None:
  117. if self._fh is not None:
  118. self._fh.close()
  119. self._fh = None
  120. stamp = time.strftime("%Y%m%d-%H%M%S", time.localtime())
  121. target = os.path.join(self.directory, "frames-%s-%04d.jsonl" % (stamp, self.segments + 1))
  122. counter = 1
  123. while os.path.exists(target):
  124. counter += 1
  125. target = os.path.join(self.directory, "frames-%s-%04d.jsonl" % (stamp, counter))
  126. try:
  127. os.replace(self.path, target)
  128. except OSError:
  129. pass
  130. self.segments += 1
  131. self._fh = open(self.path, "a", encoding="utf-8", newline="\n")
  132. # -- 写入 -------------------------------------------------------------
  133. def write(self, record: Dict[str, object]) -> str:
  134. if self._fh is None:
  135. self.open()
  136. line = json.dumps(record, ensure_ascii=False, default=str, separators=(",", ":")) + "\n"
  137. data = line.encode("utf-8")
  138. try:
  139. size = os.path.getsize(self.path)
  140. except OSError:
  141. size = 0
  142. if size > 0 and size + len(data) > self.max_bytes:
  143. self._rotate()
  144. self._fh.write(line) # type: ignore[union-attr]
  145. self._fh.flush() # type: ignore[union-attr]
  146. self.records += 1
  147. now = time.time()
  148. if self.fsync_interval_s > 0 and (now - self._last_fsync) >= self.fsync_interval_s:
  149. self._last_fsync = now
  150. try:
  151. os.fsync(self._fh.fileno()) # type: ignore[union-attr]
  152. except OSError:
  153. pass
  154. return self.path
  155. class EventRing:
  156. """最近 N 帧的 JPEG 环缓;状态变化时导出为 mp4(或 JPG 序列)。"""
  157. def __init__(
  158. self,
  159. max_frames: int = 90,
  160. jpeg_quality: int = 85,
  161. max_side: int = 960,
  162. fps: float = 15.0,
  163. ) -> None:
  164. self.max_frames = max(1, int(max_frames))
  165. self.jpeg_quality = min(100, max(30, int(jpeg_quality)))
  166. self.max_side = max(160, int(max_side))
  167. self.fps = max(1.0, float(fps))
  168. self._frames: Deque[Dict[str, object]] = deque(maxlen=self.max_frames)
  169. def __len__(self) -> int:
  170. return len(self._frames)
  171. def clear(self) -> None:
  172. self._frames.clear()
  173. def append(self, image: np.ndarray, ts: float, frame_id: int) -> bool:
  174. if cv2 is None or image is None or getattr(image, "size", 0) == 0:
  175. return False
  176. ok, buffer = cv2.imencode(
  177. ".jpg", image, [int(cv2.IMWRITE_JPEG_QUALITY), self.jpeg_quality]
  178. )
  179. if not ok:
  180. return False
  181. self._frames.append(
  182. {"ts": float(ts), "frame_id": int(frame_id), "jpeg": buffer.tobytes()}
  183. )
  184. return True
  185. def save(
  186. self,
  187. directory: str,
  188. payload: Optional[Dict[str, object]] = None,
  189. stem: Optional[str] = None,
  190. ) -> Dict[str, object]:
  191. """把环缓存盘;返回 ``{"clip":..., "frames":..., "meta":...}``。"""
  192. _ensure_dir(directory)
  193. stem = stem or ("event-%s" % time.strftime("%Y%m%d-%H%M%S"))
  194. meta_path = os.path.join(directory, "%s.json" % stem)
  195. with open(meta_path, "w", encoding="utf-8") as fh:
  196. json.dump(payload or {}, fh, ensure_ascii=False, default=str, indent=2)
  197. saved = {"clip": "", "frames": 0, "meta": meta_path, "mode": "none"}
  198. if not self._frames:
  199. return saved
  200. first = cv2.imdecode(np.frombuffer(self._frames[0]["jpeg"], np.uint8), cv2.IMREAD_COLOR) # type: ignore[arg-type]
  201. if first is None:
  202. return saved
  203. height, width = first.shape[:2]
  204. scale = min(1.0, float(self.max_side) / float(max(width, height)))
  205. size = (max(2, int(round(width * scale))), max(2, int(round(height * scale))))
  206. clip_path = os.path.join(directory, "%s.mp4" % stem)
  207. writer = None
  208. if cv2 is not None:
  209. writer = cv2.VideoWriter(
  210. clip_path, cv2.VideoWriter_fourcc(*"mp4v"), self.fps, size
  211. )
  212. if writer is not None and writer.isOpened():
  213. for item in self._frames:
  214. frame = cv2.imdecode(np.frombuffer(item["jpeg"], np.uint8), cv2.IMREAD_COLOR) # type: ignore[arg-type]
  215. if frame is None:
  216. continue
  217. if frame.shape[1] != size[0] or frame.shape[0] != size[1]:
  218. frame = cv2.resize(frame, size, interpolation=cv2.INTER_AREA)
  219. writer.write(frame)
  220. saved["frames"] = int(saved["frames"]) + 1
  221. writer.release()
  222. saved["clip"] = clip_path
  223. saved["mode"] = "mp4"
  224. else:
  225. if writer is not None:
  226. writer.release()
  227. frame_dir = _ensure_dir(os.path.join(directory, "%s_frames" % stem))
  228. for index, item in enumerate(self._frames):
  229. frame = cv2.imdecode(np.frombuffer(item["jpeg"], np.uint8), cv2.IMREAD_COLOR) # type: ignore[arg-type]
  230. if frame is None:
  231. continue
  232. if frame.shape[1] != size[0] or frame.shape[0] != size[1]:
  233. frame = cv2.resize(frame, size, interpolation=cv2.INTER_AREA)
  234. path = os.path.join(frame_dir, "%06d.jpg" % index)
  235. cv2.imwrite(path, frame)
  236. saved["frames"] = int(saved["frames"]) + 1
  237. saved["clip"] = frame_dir
  238. saved["mode"] = "jpg"
  239. return saved
  240. class EvidenceStore:
  241. """P0-4 证据落盘门面:逐帧 JSONL + 事件环缓 + 保留期清理。"""
  242. def __init__(
  243. self,
  244. directory: str,
  245. retention_days: float = 90.0,
  246. segment_bytes: int = DEFAULT_SEGMENT_BYTES,
  247. ring_frames: int = 300,
  248. fps: float = 15.0,
  249. jpeg_quality: int = 85,
  250. max_side: int = 960,
  251. ) -> None:
  252. self.directory = _ensure_dir(directory)
  253. self.retention_days = max(0.0, float(retention_days))
  254. self.writer = SegmentingJsonlWriter(
  255. self.directory, max_bytes=segment_bytes, retention_days=self.retention_days
  256. )
  257. self.ring = EventRing(
  258. max_frames=ring_frames, jpeg_quality=jpeg_quality, max_side=max_side, fps=fps
  259. )
  260. self.events = 0
  261. self.last_event: Dict[str, object] = {}
  262. @classmethod
  263. def from_config(cls, cfg: Config) -> "EvidenceStore":
  264. run_dir = str(cfg.get_path("run.output_dir", "runs") or "runs")
  265. directory = str(cfg.get_path("evidence.dir", "") or os.path.join(run_dir, "evidence"))
  266. segment_mb = float(cfg.get_path("evidence.segment_mb", 50.0) or 50.0)
  267. return cls(
  268. directory=directory,
  269. retention_days=float(cfg.get_path("evidence.retention_days", 90.0) or 90.0),
  270. segment_bytes=int(segment_mb * 1024 * 1024),
  271. ring_frames=int(cfg.get_path("evidence.ring_frames", 300) or 300),
  272. fps=float(cfg.get_path("evidence.fps", 15.0) or 15.0),
  273. jpeg_quality=int(cfg.get_path("evidence.jpeg_quality", 85) or 85),
  274. max_side=int(cfg.get_path("evidence.max_side", 960) or 960),
  275. )
  276. def open(self) -> "EvidenceStore":
  277. self.writer.open()
  278. return self
  279. def close(self) -> None:
  280. self.writer.close()
  281. def record(
  282. self,
  283. frame,
  284. observation,
  285. decision,
  286. snapshot=None,
  287. evidence=None,
  288. health=None,
  289. event: bool = False,
  290. ) -> Dict[str, object]:
  291. """写一行逐帧记录;``event=True`` 时同时导出环缓。"""
  292. now = time.time()
  293. if not self.writer.session:
  294. self.writer.open()
  295. payload: Dict[str, object] = {
  296. "ts": round(now, 3),
  297. "session": self.writer.session,
  298. "frame_ts": round(float(getattr(frame, "ts", 0.0)), 3),
  299. "frame_id": int(getattr(frame, "frame_id", 0)),
  300. "state": int(getattr(decision, "state", 255)),
  301. "label": str(getattr(decision, "label", "unknown")),
  302. "confidence": round(float(getattr(decision, "confidence", 0.0)), 4),
  303. "stable": bool(getattr(decision, "stable", False)),
  304. "changed": bool(getattr(decision, "changed", False)),
  305. "reason": str(getattr(decision, "reason", "")),
  306. "observation": {
  307. "state": int(getattr(observation, "state", 255)),
  308. "confidence": round(float(getattr(observation, "confidence", 0.0)), 4),
  309. "reason": str(getattr(observation, "reason", "")),
  310. "detections": [
  311. box.to_dict() for box in getattr(observation, "detections", []) or []
  312. ],
  313. },
  314. }
  315. if snapshot is not None:
  316. payload["snapshot"] = snapshot.to_dict()
  317. if evidence is not None:
  318. payload["evidence"] = evidence if isinstance(evidence, dict) else evidence.to_dict()
  319. if health is not None:
  320. payload["health"] = health if isinstance(health, dict) else health.to_dict()
  321. self.writer.write(payload)
  322. self.ring.append(getattr(frame, "image", None), payload["frame_ts"], payload["frame_id"])
  323. if event:
  324. self.events += 1
  325. stem = "event-%s-%06d" % (time.strftime("%Y%m%d-%H%M%S"), self.events)
  326. self.last_event = self.ring.save(self.directory, payload=payload, stem=stem)
  327. self.last_event["stem"] = stem
  328. return payload
  329. def purge(self) -> List[str]:
  330. """删除超过保留期的段/事件文件;返回删除路径。"""
  331. return purge_old_files(self.directory, self.retention_days)