stats.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import json
  2. import logging
  3. import threading
  4. import time
  5. from frigate.config import FrigateConfig
  6. from frigate.version import VERSION
  7. logger = logging.getLogger(__name__)
  8. def stats_init(camera_metrics, detectors):
  9. stats_tracking = {
  10. 'camera_metrics': camera_metrics,
  11. 'detectors': detectors,
  12. 'started': int(time.time())
  13. }
  14. return stats_tracking
  15. def stats_snapshot(stats_tracking):
  16. camera_metrics = stats_tracking['camera_metrics']
  17. stats = {}
  18. total_detection_fps = 0
  19. for name, camera_stats in camera_metrics.items():
  20. total_detection_fps += camera_stats['detection_fps'].value
  21. stats[name] = {
  22. 'camera_fps': round(camera_stats['camera_fps'].value, 2),
  23. 'process_fps': round(camera_stats['process_fps'].value, 2),
  24. 'skipped_fps': round(camera_stats['skipped_fps'].value, 2),
  25. 'detection_fps': round(camera_stats['detection_fps'].value, 2),
  26. 'pid': camera_stats['process'].pid,
  27. 'capture_pid': camera_stats['capture_process'].pid
  28. }
  29. stats['detectors'] = {}
  30. for name, detector in stats_tracking["detectors"].items():
  31. stats['detectors'][name] = {
  32. 'inference_speed': round(detector.avg_inference_speed.value * 1000, 2),
  33. 'detection_start': detector.detection_start.value,
  34. 'pid': detector.detect_process.pid
  35. }
  36. stats['detection_fps'] = round(total_detection_fps, 2)
  37. stats['service'] = {
  38. 'uptime': (int(time.time()) - stats_tracking['started']),
  39. 'version': VERSION
  40. }
  41. return stats
  42. class StatsEmitter(threading.Thread):
  43. def __init__(self, config: FrigateConfig, stats_tracking, mqtt_client, topic_prefix, stop_event):
  44. threading.Thread.__init__(self)
  45. self.name = 'frigate_stats_emitter'
  46. self.config = config
  47. self.stats_tracking = stats_tracking
  48. self.mqtt_client = mqtt_client
  49. self.topic_prefix = topic_prefix
  50. self.stop_event = stop_event
  51. def run(self):
  52. time.sleep(10)
  53. while True:
  54. if self.stop_event.is_set():
  55. logger.info(f"Exiting watchdog...")
  56. break
  57. stats = stats_snapshot(self.stats_tracking)
  58. self.mqtt_client.publish(f"{self.topic_prefix}/stats", json.dumps(stats), retain=False)
  59. time.sleep(self.config.mqtt.stats_interval)