store.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  1. """会话与事件的持久化:元数据、事件包(截图+片段+JSON)、统计报告。"""
  2. from __future__ import annotations
  3. import json
  4. import shutil
  5. import time
  6. import uuid
  7. from pathlib import Path
  8. from . import config
  9. SESSION_DIR = config.CACHE_DIR / "sessions"
  10. SESSION_DIR.mkdir(parents=True, exist_ok=True)
  11. # ------------------------------------------------------------------ 会话
  12. def save_session(meta: dict) -> None:
  13. sid = meta["id"]
  14. (SESSION_DIR / f"{sid}.json").write_text(
  15. json.dumps(meta, ensure_ascii=False, indent=2), encoding="utf-8"
  16. )
  17. def load_session(sid: str) -> dict | None:
  18. p = SESSION_DIR / f"{sid}.json"
  19. if not p.exists():
  20. return None
  21. return json.loads(p.read_text(encoding="utf-8"))
  22. def list_sessions() -> list[dict]:
  23. out = []
  24. for p in sorted(SESSION_DIR.glob("*.json"), key=lambda x: x.stat().st_mtime, reverse=True):
  25. try:
  26. out.append(json.loads(p.read_text(encoding="utf-8")))
  27. except Exception:
  28. continue
  29. return out
  30. def update_session(sid: str, **fields) -> dict | None:
  31. meta = load_session(sid)
  32. if meta is None:
  33. return None
  34. meta.update(fields)
  35. meta["updated_at"] = time.time()
  36. save_session(meta)
  37. return meta
  38. # ------------------------------------------------------------------ 事件
  39. def new_event_id() -> str:
  40. return time.strftime("%Y%m%d-%H%M%S-") + uuid.uuid4().hex[:6]
  41. def event_dir(sid: str, eid: str) -> Path:
  42. d = config.EVENT_DIR / sid / eid
  43. d.mkdir(parents=True, exist_ok=True)
  44. return d
  45. def append_event(sid: str, event: dict) -> None:
  46. """事件索引写入 {sid}/events.jsonl 便于快速读取。"""
  47. d = config.EVENT_DIR / sid
  48. d.mkdir(parents=True, exist_ok=True)
  49. with (d / "events.jsonl").open("a", encoding="utf-8") as f:
  50. f.write(json.dumps(event, ensure_ascii=False) + "\n")
  51. def list_events(sid: str) -> list[dict]:
  52. p = config.EVENT_DIR / sid / "events.jsonl"
  53. if not p.exists():
  54. return []
  55. out = []
  56. for line in p.read_text(encoding="utf-8").splitlines():
  57. line = line.strip()
  58. if not line:
  59. continue
  60. try:
  61. out.append(json.loads(line))
  62. except Exception:
  63. continue
  64. return out
  65. def delete_session(sid: str, purge_files: bool = False) -> None:
  66. p = SESSION_DIR / f"{sid}.json"
  67. if p.exists():
  68. p.unlink()
  69. if purge_files:
  70. shutil.rmtree(config.EVENT_DIR / sid, ignore_errors=True)
  71. f = config.UPLOAD_DIR / f"{sid}.mp4"
  72. if f.exists():
  73. f.unlink()
  74. # ------------------------------------------------------------------ 统计报告
  75. def _bucket(ts: float, size: int) -> str:
  76. b = int(ts // size) * size
  77. return time.strftime("%H:%M", time.localtime(b))
  78. def vehicle_report(telemetry: list[dict], crossings: list[dict],
  79. plates: list[dict], bucket_seconds: int = 300,
  80. location: str = "正门计数线") -> dict:
  81. buckets: dict[str, dict] = {}
  82. for c in crossings:
  83. key = _bucket(c["time"], bucket_seconds)
  84. b = buckets.setdefault(key, {"time": key, "in": 0, "out": 0, "classes": {}})
  85. b["in" if c["direction"] == "进" else "out"] += 1
  86. b["classes"][c["class"]] = b["classes"].get(c["class"], 0) + 1
  87. total_in = sum(b["in"] for b in buckets.values())
  88. total_out = sum(b["out"] for b in buckets.values())
  89. class_total: dict[str, int] = {}
  90. for c in crossings:
  91. class_total[c["class"]] = class_total.get(c["class"], 0) + 1
  92. material = [
  93. {**c, "plate": _find_plate(c, plates)}
  94. for c in crossings
  95. if c.get("is_truck")
  96. ]
  97. return {
  98. "location": location,
  99. "bucket_seconds": bucket_seconds,
  100. "total_in": total_in,
  101. "total_out": total_out,
  102. "by_class": class_total,
  103. "buckets": [buckets[k] for k in sorted(buckets)],
  104. "material_vehicles": material,
  105. "manifest_check": _manifest_check(material),
  106. "plates": plates,
  107. }
  108. def _find_plate(crossing: dict, plates: list[dict]) -> str:
  109. best = ""
  110. best_dt = 6.0
  111. for p in plates:
  112. dt = abs(p["time"] - crossing["time"])
  113. if dt < best_dt:
  114. best, best_dt = p.get("plate", ""), dt
  115. return best
  116. def _manifest_check(material: list[dict]) -> list[dict]:
  117. out = []
  118. for m in material:
  119. out.append({
  120. "time": time.strftime("%H:%M:%S", time.localtime(m["time"])),
  121. "class": m["class"],
  122. "plate": m.get("plate", ""),
  123. "direction": m["direction"],
  124. "status": "已核对" if m.get("manifest_ok") else "待核对(未提供申报清单)",
  125. })
  126. return out
  127. def people_report(telemetry: list[dict], bucket_seconds: int = 300) -> dict:
  128. buckets: dict[str, dict] = {}
  129. for rec in telemetry:
  130. key = _bucket(rec["t"], bucket_seconds)
  131. b = buckets.setdefault(key, {"time": key, "samples": 0,
  132. "construction_sum": 0, "warehouse_sum": 0,
  133. "construction_max": 0, "warehouse_max": 0,
  134. "total_max": 0})
  135. rc = rec.get("regions", {}) or {}
  136. c = int(rc.get("construction", 0))
  137. w = int(rc.get("warehouse", 0))
  138. b["samples"] += 1
  139. b["construction_sum"] += c
  140. b["warehouse_sum"] += w
  141. b["construction_max"] = max(b["construction_max"], c)
  142. b["warehouse_max"] = max(b["warehouse_max"], w)
  143. b["total_max"] = max(b["total_max"], int(rec.get("people", 0)))
  144. rows = []
  145. for k in sorted(buckets):
  146. b = buckets[k]
  147. n = max(1, b["samples"])
  148. rows.append({
  149. "time": k,
  150. "samples": b["samples"],
  151. "construction_avg": round(b["construction_sum"] / n, 2),
  152. "construction_max": b["construction_max"],
  153. "warehouse_avg": round(b["warehouse_sum"] / n, 2),
  154. "warehouse_max": b["warehouse_max"],
  155. "total_max": b["total_max"],
  156. })
  157. peak = max((r["total_max"] for r in rows), default=0)
  158. return {
  159. "bucket_seconds": bucket_seconds,
  160. "buckets": rows,
  161. "peak_total": peak,
  162. "avg_construction": round(sum(r["construction_avg"] for r in rows) / max(1, len(rows)), 2),
  163. "avg_warehouse": round(sum(r["warehouse_avg"] for r in rows) / max(1, len(rows)), 2),
  164. }