smoke.py 3.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. #!/usr/bin/env python3
  2. """端到端冒烟测试:上传 → 配置 → 启动 → 轮询事件 → 校验产物。"""
  3. import json
  4. import sys
  5. import time
  6. import urllib.request
  7. from pathlib import Path
  8. BASE = sys.argv[1] if len(sys.argv) > 1 else "http://127.0.0.1:8811"
  9. VIDEO = sys.argv[2] if len(sys.argv) > 2 else "/Users/wenhongquan/Documents/trae_projects/yolo/output_video.mp4"
  10. def req(method, path, data=None, ctype="application/json"):
  11. url = BASE + path
  12. body = None
  13. if data is not None:
  14. body = json.dumps(data).encode() if ctype == "application/json" else data
  15. r = urllib.request.Request(url, data=body, method=method)
  16. if data is not None:
  17. r.add_header("Content-Type", ctype)
  18. with urllib.request.urlopen(r, timeout=120) as resp:
  19. raw = resp.read()
  20. return json.loads(raw) if raw else {}
  21. def upload(path: Path):
  22. boundary = "----dccaiSmoke"
  23. buf = bytearray()
  24. buf += f"--{boundary}\r\n".encode()
  25. buf += f'Content-Disposition: form-data; name="file"; filename="{path.name}"\r\n'.encode()
  26. buf += b"Content-Type: video/mp4\r\n\r\n"
  27. buf += path.read_bytes()
  28. buf += f"\r\n--{boundary}--\r\n".encode()
  29. r = urllib.request.Request(BASE + "/api/upload", data=bytes(buf), method="POST")
  30. r.add_header("Content-Type", f"multipart/form-data; boundary={boundary}")
  31. with urllib.request.urlopen(r, timeout=300) as resp:
  32. return json.loads(resp.read())
  33. def main():
  34. cats = req("GET", "/api/categories")
  35. available = [i["id"] for g in cats["groups"] for i in g["items"] if i["available"]]
  36. print("设备:", cats["device"])
  37. print("可用检测项:", available)
  38. meta = upload(Path(VIDEO))
  39. sid = meta["id"]
  40. print(f"上传完成 sid={sid} {meta['width']}x{meta['height']} {meta['fps']}fps {meta['duration']}s")
  41. meta = req("POST", f"/api/sessions/{sid}/config",
  42. {"categories": available, "pre_seconds": 15, "post_seconds": 15,
  43. "detect_interval": int(sys.argv[3]) if len(sys.argv) > 3 else 4})
  44. print("配置完成:", meta["categories"])
  45. st = req("POST", f"/api/sessions/{sid}/start")
  46. print("启动:", st["state"])
  47. t0 = time.time()
  48. last = ""
  49. while time.time() - t0 < 240:
  50. time.sleep(3)
  51. st = req("GET", f"/api/sessions/{sid}")
  52. line = f"[{time.time()-t0:6.1f}s] {st['state']:9s} 进度 {st['progress']*100:5.1f}% 帧 {st['frame_index']}/{st.get('total_frames')} 事件 {st['event_count']}"
  53. if line != last:
  54. print(line)
  55. last = line
  56. if st["state"] in ("finished", "stopped", "error"):
  57. if st.get("error"):
  58. print("ERROR:", st["error"])
  59. break
  60. evs = req("GET", f"/api/sessions/{sid}/events")
  61. print(f"\n共 {evs['total']} 个事件:")
  62. for e in evs["events"][:20]:
  63. print(f" - [{e['level']:8s}] {e['group']}/{e['category_name']}: {e['title']} | 片段 {e.get('clip_seconds')}s | {e.get('clip')}")
  64. rep = req("GET", f"/api/sessions/{sid}/report/summary")
  65. print("\n汇总: 车辆进/出 =", rep["vehicle"]["total_in"], "/", rep["vehicle"]["total_out"],
  66. "| 人员峰值 =", rep["people"]["peak_total"],
  67. "| 事件 =", rep["events_total"])
  68. # 校验产物
  69. root = Path(__file__).resolve().parent.parent
  70. for e in evs["events"][:5]:
  71. d = root / "storage" / "events" / sid / e["id"]
  72. snap = d / "snapshot.jpg"
  73. clip = d / "clip.mp4"
  74. print(f" {e['id']}: snapshot={snap.exists() and round(snap.stat().st_size/1024)}KB "
  75. f"clip={clip.exists() and round(clip.stat().st_size/1024)}KB")
  76. print("\nSID =", sid)
  77. if __name__ == "__main__":
  78. main()