store.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  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. """读取事件索引。
  53. 同一个事件会先以 pending=True(只有截图)追加一次,录完再追加一次完整版,
  54. 因此按 id 去重、**后写覆盖先写**,保证调用方拿到的是最终状态。
  55. """
  56. p = config.EVENT_DIR / sid / "events.jsonl"
  57. if not p.exists():
  58. return []
  59. out: list[dict] = []
  60. index: dict[str, int] = {}
  61. for line in p.read_text(encoding="utf-8").splitlines():
  62. line = line.strip()
  63. if not line:
  64. continue
  65. try:
  66. ev = json.loads(line)
  67. except Exception:
  68. continue
  69. eid = ev.get("id")
  70. if eid and eid in index:
  71. out[index[eid]] = ev # 同一事件:用最新一条覆盖
  72. else:
  73. if eid:
  74. index[eid] = len(out)
  75. out.append(ev)
  76. return out
  77. def delete_session(sid: str, purge_files: bool = False) -> None:
  78. p = SESSION_DIR / f"{sid}.json"
  79. if p.exists():
  80. p.unlink()
  81. if purge_files:
  82. shutil.rmtree(config.EVENT_DIR / sid, ignore_errors=True)
  83. f = config.UPLOAD_DIR / f"{sid}.mp4"
  84. if f.exists():
  85. f.unlink()
  86. # ------------------------------------------------------------------ 统计报告
  87. def _bucket(ts: float, size: int) -> str:
  88. b = int(ts // size) * size
  89. return time.strftime("%H:%M", time.localtime(b))
  90. def vehicle_report(telemetry: list[dict], crossings: list[dict],
  91. plates: list[dict], bucket_seconds: int = 300,
  92. location: str = "") -> dict:
  93. buckets: dict[str, dict] = {}
  94. for c in crossings:
  95. key = _bucket(c["time"], bucket_seconds)
  96. b = buckets.setdefault(key, {"time": key, "in": 0, "out": 0, "classes": {}})
  97. b["in" if str(c["direction"]) in ("进", "in") else "out"] += 1
  98. b["classes"][c["class"]] = b["classes"].get(c["class"], 0) + 1
  99. total_in = sum(b["in"] for b in buckets.values())
  100. total_out = sum(b["out"] for b in buckets.values())
  101. class_total: dict[str, int] = {}
  102. for c in crossings:
  103. class_total[c["class"]] = class_total.get(c["class"], 0) + 1
  104. material = [
  105. {**c, "plate": _find_plate(c, plates)}
  106. for c in crossings
  107. if c.get("is_truck")
  108. ]
  109. return {
  110. "location": location,
  111. "location_key": "" if location else "report.location_default",
  112. "bucket_seconds": bucket_seconds,
  113. "total_in": total_in,
  114. "total_out": total_out,
  115. "by_class": class_total,
  116. "buckets": [buckets[k] for k in sorted(buckets)],
  117. "material_vehicles": material,
  118. "manifest_check": _manifest_check(material),
  119. "plates": plates,
  120. }
  121. def _find_plate(crossing: dict, plates: list[dict]) -> str:
  122. best = ""
  123. best_dt = 6.0
  124. for p in plates:
  125. dt = abs(p["time"] - crossing["time"])
  126. if dt < best_dt:
  127. best, best_dt = p.get("plate", ""), dt
  128. return best
  129. def _manifest_check(material: list[dict]) -> list[dict]:
  130. out = []
  131. for m in material:
  132. out.append({
  133. "time": time.strftime("%H:%M:%S", time.localtime(m["time"])),
  134. "class": m["class"],
  135. "plate": m.get("plate", ""),
  136. "direction": m["direction"],
  137. "class_name": m.get("class_name", m["class"]),
  138. "status_key": "checked" if m.get("manifest_ok") else "pending",
  139. "status": "checked" if m.get("manifest_ok") else "pending",
  140. })
  141. return out
  142. def people_report(telemetry: list[dict], bucket_seconds: int = 300) -> dict:
  143. buckets: dict[str, dict] = {}
  144. for rec in telemetry:
  145. key = _bucket(rec["t"], bucket_seconds)
  146. b = buckets.setdefault(key, {"time": key, "samples": 0,
  147. "construction_sum": 0, "warehouse_sum": 0,
  148. "construction_max": 0, "warehouse_max": 0,
  149. "total_max": 0})
  150. rc = rec.get("regions", {}) or {}
  151. c = int(rc.get("construction", 0))
  152. w = int(rc.get("warehouse", 0))
  153. b["samples"] += 1
  154. b["construction_sum"] += c
  155. b["warehouse_sum"] += w
  156. b["construction_max"] = max(b["construction_max"], c)
  157. b["warehouse_max"] = max(b["warehouse_max"], w)
  158. b["total_max"] = max(b["total_max"], int(rec.get("people", 0)))
  159. rows = []
  160. for k in sorted(buckets):
  161. b = buckets[k]
  162. n = max(1, b["samples"])
  163. rows.append({
  164. "time": k,
  165. "samples": b["samples"],
  166. "construction_avg": round(b["construction_sum"] / n, 2),
  167. "construction_max": b["construction_max"],
  168. "warehouse_avg": round(b["warehouse_sum"] / n, 2),
  169. "warehouse_max": b["warehouse_max"],
  170. "total_max": b["total_max"],
  171. })
  172. peak = max((r["total_max"] for r in rows), default=0)
  173. return {
  174. "bucket_seconds": bucket_seconds,
  175. "buckets": rows,
  176. "peak_total": peak,
  177. "avg_construction": round(sum(r["construction_avg"] for r in rows) / max(1, len(rows)), 2),
  178. "avg_warehouse": round(sum(r["warehouse_avg"] for r in rows) / max(1, len(rows)), 2),
  179. }