| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382 |
- """P0-4 数据证据链:逐帧 JSONL、事件视频环缓、50 MB 切分、保留期清理。
- 现场验收要能回答三个问题:
- 1. 某次误判/漏判发生时,**输入画面**是什么?→ 事件环缓 + 单帧 JSONL;
- 2. 断电/重启后,证据是否**连续且可恢复**?→ 追加写、坏尾行修复、段文件;
- 3. 硬盘会不会被写满?→ 50 MB 切分 + ``retention_days`` 清理。
- 本模块只负责落盘,不改变判决。默认 ``evidence.enabled=false``,现场确认
- 磁盘/权限后再开;开启后 ``runner`` 每帧写一行 JSONL,状态变化时把环缓里
- 最近 N 帧导成 mp4(失败则退化为 JPG 序列)。
- """
- from __future__ import annotations
- import json
- import os
- import time
- from collections import deque
- from typing import Deque, Dict, List, Optional
- import numpy as np
- try: # pragma: no cover - 与取流层同一依赖
- import cv2
- except ImportError: # pragma: no cover
- cv2 = None # type: ignore
- from .config import Config
- __all__ = [
- "DEFAULT_SEGMENT_BYTES",
- "EventRing",
- "EvidenceStore",
- "SegmentingJsonlWriter",
- "purge_old_files",
- ]
- DEFAULT_SEGMENT_BYTES = 50 * 1024 * 1024
- def _ensure_dir(path: str) -> str:
- os.makedirs(path, exist_ok=True)
- return path
- def purge_old_files(directory: str, retention_days: float, now: Optional[float] = None) -> List[str]:
- """删除 ``directory`` 下超过保留期的普通文件;返回删除路径。"""
- if not directory or not os.path.isdir(directory) or retention_days <= 0:
- return []
- cutoff = float(now if now is not None else time.time()) - float(retention_days) * 86400.0
- removed: List[str] = []
- for name in os.listdir(directory):
- path = os.path.join(directory, name)
- if not os.path.isfile(path):
- continue
- try:
- if os.path.getmtime(path) < cutoff:
- os.remove(path)
- removed.append(path)
- except OSError:
- continue
- return removed
- class SegmentingJsonlWriter:
- """按大小切分的 JSONL 追加写;重启后继续写当前段,坏尾行自动补换行。"""
- def __init__(
- self,
- directory: str,
- max_bytes: int = DEFAULT_SEGMENT_BYTES,
- retention_days: float = 90.0,
- fsync_interval_s: float = 1.0,
- ) -> None:
- self.directory = _ensure_dir(directory)
- self.max_bytes = max(64, int(max_bytes))
- self.retention_days = float(retention_days)
- self.fsync_interval_s = max(0.0, float(fsync_interval_s))
- self.path = os.path.join(self.directory, "frames.jsonl")
- self.records = 0
- self.segments = 0
- self.session = ""
- self._fh = None # type: ignore[assignment]
- self._last_fsync = 0.0
- # -- 生命周期 ---------------------------------------------------------
- def open(self) -> "SegmentingJsonlWriter":
- _ensure_dir(self.directory)
- self.session = "%s-%d" % (time.strftime("%Y%m%d-%H%M%S"), os.getpid())
- self._repair_tail()
- self._fh = open(self.path, "a", encoding="utf-8", newline="\n")
- self.segments = len(self._segment_files())
- purge_old_files(self.directory, self.retention_days)
- return self
- def close(self) -> None:
- if self._fh is not None:
- try:
- self._fh.flush()
- os.fsync(self._fh.fileno())
- except OSError:
- pass
- self._fh.close()
- self._fh = None
- def _segment_files(self) -> List[str]:
- return sorted(
- os.path.join(self.directory, name)
- for name in os.listdir(self.directory)
- if name.startswith("frames-") and name.endswith(".jsonl")
- )
- def segment_files(self) -> List[str]:
- """按**写入顺序**返回全部分段文件(含当前正在写的 ``frames.jsonl``)。
- 归档段命名为 ``frames-<时间戳>-<序号>.jsonl``,字符 ``'-'``(0x2D) 小于
- ``'.'``(0x2E),所以按文件名排序正好是「旧归档段 → 当前段」。外部读取证据
- (现场复盘、脚本抽样)必须走这个函数:``os.listdir`` 的顺序在 ext4 上是
- 目录哈希序,跨机器/跨文件系统都不稳定,直接拼接会把记录读乱。
- """
- current = os.path.basename(self.path)
- names = [
- name
- for name in os.listdir(self.directory)
- if name.endswith(".jsonl")
- and (name == current or name.startswith("frames-"))
- ]
- return [os.path.join(self.directory, name) for name in sorted(names)]
- def _repair_tail(self) -> None:
- """断电时最后一行可能只写了一半;补换行,保留原始字节供排查。"""
- if not os.path.isfile(self.path) or os.path.getsize(self.path) == 0:
- return
- with open(self.path, "rb+") as fh:
- fh.seek(-1, os.SEEK_END)
- if fh.read(1) != b"\n":
- fh.write(b"\n")
- def _rotate(self) -> None:
- if self._fh is not None:
- self._fh.close()
- self._fh = None
- stamp = time.strftime("%Y%m%d-%H%M%S", time.localtime())
- target = os.path.join(self.directory, "frames-%s-%04d.jsonl" % (stamp, self.segments + 1))
- counter = 1
- while os.path.exists(target):
- counter += 1
- target = os.path.join(self.directory, "frames-%s-%04d.jsonl" % (stamp, counter))
- try:
- os.replace(self.path, target)
- except OSError:
- pass
- self.segments += 1
- self._fh = open(self.path, "a", encoding="utf-8", newline="\n")
- # -- 写入 -------------------------------------------------------------
- def write(self, record: Dict[str, object]) -> str:
- if self._fh is None:
- self.open()
- line = json.dumps(record, ensure_ascii=False, default=str, separators=(",", ":")) + "\n"
- data = line.encode("utf-8")
- try:
- size = os.path.getsize(self.path)
- except OSError:
- size = 0
- if size > 0 and size + len(data) > self.max_bytes:
- self._rotate()
- self._fh.write(line) # type: ignore[union-attr]
- self._fh.flush() # type: ignore[union-attr]
- self.records += 1
- now = time.time()
- if self.fsync_interval_s > 0 and (now - self._last_fsync) >= self.fsync_interval_s:
- self._last_fsync = now
- try:
- os.fsync(self._fh.fileno()) # type: ignore[union-attr]
- except OSError:
- pass
- return self.path
- class EventRing:
- """最近 N 帧的 JPEG 环缓;状态变化时导出为 mp4(或 JPG 序列)。"""
- def __init__(
- self,
- max_frames: int = 90,
- jpeg_quality: int = 85,
- max_side: int = 960,
- fps: float = 15.0,
- ) -> None:
- self.max_frames = max(1, int(max_frames))
- self.jpeg_quality = min(100, max(30, int(jpeg_quality)))
- self.max_side = max(160, int(max_side))
- self.fps = max(1.0, float(fps))
- self._frames: Deque[Dict[str, object]] = deque(maxlen=self.max_frames)
- def __len__(self) -> int:
- return len(self._frames)
- def clear(self) -> None:
- self._frames.clear()
- def append(self, image: np.ndarray, ts: float, frame_id: int) -> bool:
- if cv2 is None or image is None or getattr(image, "size", 0) == 0:
- return False
- ok, buffer = cv2.imencode(
- ".jpg", image, [int(cv2.IMWRITE_JPEG_QUALITY), self.jpeg_quality]
- )
- if not ok:
- return False
- self._frames.append(
- {"ts": float(ts), "frame_id": int(frame_id), "jpeg": buffer.tobytes()}
- )
- return True
- def save(
- self,
- directory: str,
- payload: Optional[Dict[str, object]] = None,
- stem: Optional[str] = None,
- ) -> Dict[str, object]:
- """把环缓存盘;返回 ``{"clip":..., "frames":..., "meta":...}``。"""
- _ensure_dir(directory)
- stem = stem or ("event-%s" % time.strftime("%Y%m%d-%H%M%S"))
- meta_path = os.path.join(directory, "%s.json" % stem)
- with open(meta_path, "w", encoding="utf-8") as fh:
- json.dump(payload or {}, fh, ensure_ascii=False, default=str, indent=2)
- saved = {"clip": "", "frames": 0, "meta": meta_path, "mode": "none"}
- if not self._frames:
- return saved
- first = cv2.imdecode(np.frombuffer(self._frames[0]["jpeg"], np.uint8), cv2.IMREAD_COLOR) # type: ignore[arg-type]
- if first is None:
- return saved
- height, width = first.shape[:2]
- scale = min(1.0, float(self.max_side) / float(max(width, height)))
- size = (max(2, int(round(width * scale))), max(2, int(round(height * scale))))
- clip_path = os.path.join(directory, "%s.mp4" % stem)
- writer = None
- if cv2 is not None:
- writer = cv2.VideoWriter(
- clip_path, cv2.VideoWriter_fourcc(*"mp4v"), self.fps, size
- )
- if writer is not None and writer.isOpened():
- for item in self._frames:
- frame = cv2.imdecode(np.frombuffer(item["jpeg"], np.uint8), cv2.IMREAD_COLOR) # type: ignore[arg-type]
- if frame is None:
- continue
- if frame.shape[1] != size[0] or frame.shape[0] != size[1]:
- frame = cv2.resize(frame, size, interpolation=cv2.INTER_AREA)
- writer.write(frame)
- saved["frames"] = int(saved["frames"]) + 1
- writer.release()
- saved["clip"] = clip_path
- saved["mode"] = "mp4"
- else:
- if writer is not None:
- writer.release()
- frame_dir = _ensure_dir(os.path.join(directory, "%s_frames" % stem))
- for index, item in enumerate(self._frames):
- frame = cv2.imdecode(np.frombuffer(item["jpeg"], np.uint8), cv2.IMREAD_COLOR) # type: ignore[arg-type]
- if frame is None:
- continue
- if frame.shape[1] != size[0] or frame.shape[0] != size[1]:
- frame = cv2.resize(frame, size, interpolation=cv2.INTER_AREA)
- path = os.path.join(frame_dir, "%06d.jpg" % index)
- cv2.imwrite(path, frame)
- saved["frames"] = int(saved["frames"]) + 1
- saved["clip"] = frame_dir
- saved["mode"] = "jpg"
- return saved
- class EvidenceStore:
- """P0-4 证据落盘门面:逐帧 JSONL + 事件环缓 + 保留期清理。"""
- def __init__(
- self,
- directory: str,
- retention_days: float = 90.0,
- segment_bytes: int = DEFAULT_SEGMENT_BYTES,
- ring_frames: int = 300,
- fps: float = 15.0,
- jpeg_quality: int = 85,
- max_side: int = 960,
- ) -> None:
- self.directory = _ensure_dir(directory)
- self.retention_days = max(0.0, float(retention_days))
- self.writer = SegmentingJsonlWriter(
- self.directory, max_bytes=segment_bytes, retention_days=self.retention_days
- )
- self.ring = EventRing(
- max_frames=ring_frames, jpeg_quality=jpeg_quality, max_side=max_side, fps=fps
- )
- self.events = 0
- self.last_event: Dict[str, object] = {}
- @classmethod
- def from_config(cls, cfg: Config) -> "EvidenceStore":
- run_dir = str(cfg.get_path("run.output_dir", "runs") or "runs")
- directory = str(cfg.get_path("evidence.dir", "") or os.path.join(run_dir, "evidence"))
- segment_mb = float(cfg.get_path("evidence.segment_mb", 50.0) or 50.0)
- return cls(
- directory=directory,
- retention_days=float(cfg.get_path("evidence.retention_days", 90.0) or 90.0),
- segment_bytes=int(segment_mb * 1024 * 1024),
- ring_frames=int(cfg.get_path("evidence.ring_frames", 300) or 300),
- fps=float(cfg.get_path("evidence.fps", 15.0) or 15.0),
- jpeg_quality=int(cfg.get_path("evidence.jpeg_quality", 85) or 85),
- max_side=int(cfg.get_path("evidence.max_side", 960) or 960),
- )
- def open(self) -> "EvidenceStore":
- self.writer.open()
- return self
- def close(self) -> None:
- self.writer.close()
- def record(
- self,
- frame,
- observation,
- decision,
- snapshot=None,
- evidence=None,
- health=None,
- event: bool = False,
- ) -> Dict[str, object]:
- """写一行逐帧记录;``event=True`` 时同时导出环缓。"""
- now = time.time()
- if not self.writer.session:
- self.writer.open()
- payload: Dict[str, object] = {
- "ts": round(now, 3),
- "session": self.writer.session,
- "frame_ts": round(float(getattr(frame, "ts", 0.0)), 3),
- "frame_id": int(getattr(frame, "frame_id", 0)),
- "state": int(getattr(decision, "state", 255)),
- "label": str(getattr(decision, "label", "unknown")),
- "confidence": round(float(getattr(decision, "confidence", 0.0)), 4),
- "stable": bool(getattr(decision, "stable", False)),
- "changed": bool(getattr(decision, "changed", False)),
- "reason": str(getattr(decision, "reason", "")),
- "observation": {
- "state": int(getattr(observation, "state", 255)),
- "confidence": round(float(getattr(observation, "confidence", 0.0)), 4),
- "reason": str(getattr(observation, "reason", "")),
- "detections": [
- box.to_dict() for box in getattr(observation, "detections", []) or []
- ],
- },
- }
- if snapshot is not None:
- payload["snapshot"] = snapshot.to_dict()
- if evidence is not None:
- payload["evidence"] = evidence if isinstance(evidence, dict) else evidence.to_dict()
- if health is not None:
- payload["health"] = health if isinstance(health, dict) else health.to_dict()
- self.writer.write(payload)
- self.ring.append(getattr(frame, "image", None), payload["frame_ts"], payload["frame_id"])
- if event:
- self.events += 1
- stem = "event-%s-%06d" % (time.strftime("%Y%m%d-%H%M%S"), self.events)
- self.last_event = self.ring.save(self.directory, payload=payload, stem=stem)
- self.last_event["stem"] = stem
- return payload
- def purge(self) -> List[str]:
- """删除超过保留期的段/事件文件;返回删除路径。"""
- return purge_old_files(self.directory, self.retention_days)
|