http.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146
  1. import os
  2. import time
  3. import cv2
  4. import numpy as np
  5. from flask import (
  6. Flask, Blueprint, jsonify, request, Response, current_app, make_response
  7. )
  8. from peewee import SqliteDatabase
  9. from playhouse.shortcuts import model_to_dict
  10. from frigate.models import Event
  11. bp = Blueprint('frigate', __name__)
  12. def create_app(frigate_config, database: SqliteDatabase, camera_metrics, detectors, detected_frames_processor):
  13. app = Flask(__name__)
  14. @app.before_request
  15. def _db_connect():
  16. database.connect()
  17. @app.teardown_request
  18. def _db_close(exc):
  19. if not database.is_closed():
  20. database.close()
  21. app.frigate_config = frigate_config
  22. app.camera_metrics = camera_metrics
  23. app.detectors = detectors
  24. app.detected_frames_processor = detected_frames_processor
  25. app.register_blueprint(bp)
  26. return app
  27. @bp.route('/')
  28. def is_healthy():
  29. return "Frigate is running. Alive and healthy!"
  30. @bp.route('/events')
  31. def events():
  32. events = Event.select()
  33. return jsonify([model_to_dict(e) for e in events])
  34. @bp.route('/debug/stats')
  35. def stats():
  36. camera_metrics = current_app.camera_metrics
  37. stats = {}
  38. total_detection_fps = 0
  39. for name, camera_stats in camera_metrics.items():
  40. total_detection_fps += camera_stats['detection_fps'].value
  41. stats[name] = {
  42. 'camera_fps': round(camera_stats['camera_fps'].value, 2),
  43. 'process_fps': round(camera_stats['process_fps'].value, 2),
  44. 'skipped_fps': round(camera_stats['skipped_fps'].value, 2),
  45. 'detection_fps': round(camera_stats['detection_fps'].value, 2),
  46. 'pid': camera_stats['process'].pid,
  47. 'capture_pid': camera_stats['capture_process'].pid
  48. }
  49. stats['detectors'] = {}
  50. for name, detector in current_app.detectors.items():
  51. stats['detectors'][name] = {
  52. 'inference_speed': round(detector.avg_inference_speed.value*1000, 2),
  53. 'detection_start': detector.detection_start.value,
  54. 'pid': detector.detect_process.pid
  55. }
  56. stats['detection_fps'] = round(total_detection_fps, 2)
  57. return jsonify(stats)
  58. @bp.route('/<camera_name>/<label>/best.jpg')
  59. def best(camera_name, label):
  60. if camera_name in current_app.frigate_config['cameras']:
  61. best_object = current_app.detected_frames_processor.get_best(camera_name, label)
  62. best_frame = best_object.get('frame')
  63. if best_frame is None:
  64. best_frame = np.zeros((720,1280,3), np.uint8)
  65. else:
  66. best_frame = cv2.cvtColor(best_frame, cv2.COLOR_YUV2BGR_I420)
  67. crop = bool(request.args.get('crop', 0, type=int))
  68. if crop:
  69. region = best_object.get('region', [0,0,300,300])
  70. best_frame = best_frame[region[1]:region[3], region[0]:region[2]]
  71. height = int(request.args.get('h', str(best_frame.shape[0])))
  72. width = int(height*best_frame.shape[1]/best_frame.shape[0])
  73. best_frame = cv2.resize(best_frame, dsize=(width, height), interpolation=cv2.INTER_AREA)
  74. ret, jpg = cv2.imencode('.jpg', best_frame)
  75. response = make_response(jpg.tobytes())
  76. response.headers['Content-Type'] = 'image/jpg'
  77. return response
  78. else:
  79. return "Camera named {} not found".format(camera_name), 404
  80. @bp.route('/<camera_name>')
  81. def mjpeg_feed(camera_name):
  82. fps = int(request.args.get('fps', '3'))
  83. height = int(request.args.get('h', '360'))
  84. if camera_name in current_app.frigate_config['cameras']:
  85. # return a multipart response
  86. return Response(imagestream(current_app.detected_frames_processor, camera_name, fps, height),
  87. mimetype='multipart/x-mixed-replace; boundary=frame')
  88. else:
  89. return "Camera named {} not found".format(camera_name), 404
  90. @bp.route('/<camera_name>/latest.jpg')
  91. def latest_frame(camera_name):
  92. if camera_name in current_app.frigate_config['cameras']:
  93. # max out at specified FPS
  94. frame = current_app.detected_frames_processor.get_current_frame(camera_name)
  95. if frame is None:
  96. frame = np.zeros((720,1280,3), np.uint8)
  97. height = int(request.args.get('h', str(frame.shape[0])))
  98. width = int(height*frame.shape[1]/frame.shape[0])
  99. frame = cv2.resize(frame, dsize=(width, height), interpolation=cv2.INTER_AREA)
  100. ret, jpg = cv2.imencode('.jpg', frame)
  101. response = make_response(jpg.tobytes())
  102. response.headers['Content-Type'] = 'image/jpg'
  103. return response
  104. else:
  105. return "Camera named {} not found".format(camera_name), 404
  106. def imagestream(detected_frames_processor, camera_name, fps, height):
  107. while True:
  108. # max out at specified FPS
  109. time.sleep(1/fps)
  110. frame = detected_frames_processor.get_current_frame(camera_name, draw=True)
  111. if frame is None:
  112. frame = np.zeros((height,int(height*16/9),3), np.uint8)
  113. width = int(height*frame.shape[1]/frame.shape[0])
  114. frame = cv2.resize(frame, dsize=(width, height), interpolation=cv2.INTER_LINEAR)
  115. ret, jpg = cv2.imencode('.jpg', frame)
  116. yield (b'--frame\r\n'
  117. b'Content-Type: image/jpeg\r\n\r\n' + jpg.tobytes() + b'\r\n\r\n')