| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198 |
- """会话与事件的持久化:元数据、事件包(截图+片段+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]:
- p = config.EVENT_DIR / sid / "events.jsonl"
- if not p.exists():
- return []
- out = []
- for line in p.read_text(encoding="utf-8").splitlines():
- line = line.strip()
- if not line:
- continue
- try:
- out.append(json.loads(line))
- except Exception:
- continue
- 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 c["direction"] == "进" 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,
- "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"],
- "status": "已核对" if m.get("manifest_ok") else "待核对(未提供申报清单)",
- })
- 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),
- }
|