"""会话与事件的持久化:元数据、事件包(截图+片段+JSON)、统计报告。""" from __future__ import annotations import json import shutil import time import uuid from pathlib import Path from . import config SESSION_DIR = config.CACHE_DIR / "sessions" SESSION_DIR.mkdir(parents=True, exist_ok=True) # ------------------------------------------------------------------ 会话 def save_session(meta: dict) -> None: sid = meta["id"] (SESSION_DIR / f"{sid}.json").write_text( json.dumps(meta, ensure_ascii=False, indent=2), encoding="utf-8" ) def load_session(sid: str) -> dict | None: p = SESSION_DIR / f"{sid}.json" if not p.exists(): return None return json.loads(p.read_text(encoding="utf-8")) def list_sessions() -> list[dict]: out = [] for p in sorted(SESSION_DIR.glob("*.json"), key=lambda x: x.stat().st_mtime, reverse=True): try: out.append(json.loads(p.read_text(encoding="utf-8"))) except Exception: continue return out def update_session(sid: str, **fields) -> dict | None: meta = load_session(sid) if meta is None: return None meta.update(fields) meta["updated_at"] = time.time() save_session(meta) return meta # ------------------------------------------------------------------ 事件 def new_event_id() -> str: return time.strftime("%Y%m%d-%H%M%S-") + uuid.uuid4().hex[:6] def event_dir(sid: str, eid: str) -> Path: d = config.EVENT_DIR / sid / eid d.mkdir(parents=True, exist_ok=True) return d def append_event(sid: str, event: dict) -> None: """事件索引写入 {sid}/events.jsonl 便于快速读取。""" d = config.EVENT_DIR / sid d.mkdir(parents=True, exist_ok=True) with (d / "events.jsonl").open("a", encoding="utf-8") as f: f.write(json.dumps(event, ensure_ascii=False) + "\n") def list_events(sid: str) -> list[dict]: """读取事件索引。 同一个事件会先以 pending=True(只有截图)追加一次,录完再追加一次完整版, 因此按 id 去重、**后写覆盖先写**,保证调用方拿到的是最终状态。 """ p = config.EVENT_DIR / sid / "events.jsonl" if not p.exists(): return [] out: list[dict] = [] index: dict[str, int] = {} for line in p.read_text(encoding="utf-8").splitlines(): line = line.strip() if not line: continue try: ev = json.loads(line) except Exception: continue eid = ev.get("id") if eid and eid in index: out[index[eid]] = ev # 同一事件:用最新一条覆盖 else: if eid: index[eid] = len(out) out.append(ev) return out def delete_session(sid: str, purge_files: bool = False) -> None: p = SESSION_DIR / f"{sid}.json" if p.exists(): p.unlink() if purge_files: shutil.rmtree(config.EVENT_DIR / sid, ignore_errors=True) f = config.UPLOAD_DIR / f"{sid}.mp4" if f.exists(): f.unlink() # ------------------------------------------------------------------ 统计报告 def _bucket(ts: float, size: int) -> str: b = int(ts // size) * size return time.strftime("%H:%M", time.localtime(b)) def vehicle_report(telemetry: list[dict], crossings: list[dict], plates: list[dict], bucket_seconds: int = 300, location: str = "") -> dict: buckets: dict[str, dict] = {} for c in crossings: key = _bucket(c["time"], bucket_seconds) b = buckets.setdefault(key, {"time": key, "in": 0, "out": 0, "classes": {}}) b["in" if str(c["direction"]) in ("进", "in") else "out"] += 1 b["classes"][c["class"]] = b["classes"].get(c["class"], 0) + 1 total_in = sum(b["in"] for b in buckets.values()) total_out = sum(b["out"] for b in buckets.values()) class_total: dict[str, int] = {} for c in crossings: class_total[c["class"]] = class_total.get(c["class"], 0) + 1 material = [ {**c, "plate": _find_plate(c, plates)} for c in crossings if c.get("is_truck") ] return { "location": location, "location_key": "" if location else "report.location_default", "bucket_seconds": bucket_seconds, "total_in": total_in, "total_out": total_out, "by_class": class_total, "buckets": [buckets[k] for k in sorted(buckets)], "material_vehicles": material, "manifest_check": _manifest_check(material), "plates": plates, } def _find_plate(crossing: dict, plates: list[dict]) -> str: best = "" best_dt = 6.0 for p in plates: dt = abs(p["time"] - crossing["time"]) if dt < best_dt: best, best_dt = p.get("plate", ""), dt return best def _manifest_check(material: list[dict]) -> list[dict]: out = [] for m in material: out.append({ "time": time.strftime("%H:%M:%S", time.localtime(m["time"])), "class": m["class"], "plate": m.get("plate", ""), "direction": m["direction"], "class_name": m.get("class_name", m["class"]), "status_key": "checked" if m.get("manifest_ok") else "pending", "status": "checked" if m.get("manifest_ok") else "pending", }) return out def people_report(telemetry: list[dict], bucket_seconds: int = 300) -> dict: buckets: dict[str, dict] = {} for rec in telemetry: key = _bucket(rec["t"], bucket_seconds) b = buckets.setdefault(key, {"time": key, "samples": 0, "construction_sum": 0, "warehouse_sum": 0, "construction_max": 0, "warehouse_max": 0, "total_max": 0}) rc = rec.get("regions", {}) or {} c = int(rc.get("construction", 0)) w = int(rc.get("warehouse", 0)) b["samples"] += 1 b["construction_sum"] += c b["warehouse_sum"] += w b["construction_max"] = max(b["construction_max"], c) b["warehouse_max"] = max(b["warehouse_max"], w) b["total_max"] = max(b["total_max"], int(rec.get("people", 0))) rows = [] for k in sorted(buckets): b = buckets[k] n = max(1, b["samples"]) rows.append({ "time": k, "samples": b["samples"], "construction_avg": round(b["construction_sum"] / n, 2), "construction_max": b["construction_max"], "warehouse_avg": round(b["warehouse_sum"] / n, 2), "warehouse_max": b["warehouse_max"], "total_max": b["total_max"], }) peak = max((r["total_max"] for r in rows), default=0) return { "bucket_seconds": bucket_seconds, "buckets": rows, "peak_total": peak, "avg_construction": round(sum(r["construction_avg"] for r in rows) / max(1, len(rows)), 2), "avg_warehouse": round(sum(r["warehouse_avg"] for r in rows) / max(1, len(rows)), 2), }