Spaces:
Sleeping
Sleeping
refactor: only publish if frame changed + allow path to change show_stats
Browse files
app.py
CHANGED
@@ -10,9 +10,10 @@ class Session:
|
|
10 |
def __init__(self, id: str):
|
11 |
self.id = id
|
12 |
self.latest_frame: MatLike = None
|
|
|
13 |
self.measured_fps = 0
|
14 |
self.cpu_usage = 0
|
15 |
-
self.show_stats =
|
16 |
|
17 |
app = Flask(__name__)
|
18 |
PORT = int(os.environ.get("PORT", 5000))
|
@@ -83,25 +84,30 @@ def stream_mjpeg(session_id: str):
|
|
83 |
|
84 |
if session is not None:
|
85 |
while True:
|
86 |
-
if session.
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
|
|
94 |
|
95 |
@app.route("/")
|
96 |
def video_feed():
|
97 |
global sessions
|
98 |
|
99 |
session_id = request.args.get("id", "default")
|
|
|
100 |
|
101 |
if session_id not in [s.id for s in sessions]:
|
102 |
session = Session(session_id)
|
103 |
sessions.add(session)
|
104 |
threading.Thread(target=frame_processor, args=[session_id], daemon=True).start()
|
|
|
|
|
|
|
105 |
|
106 |
return Response(stream_with_context(stream_mjpeg(session_id)), mimetype="multipart/x-mixed-replace; boundary=frame")
|
107 |
|
|
|
10 |
def __init__(self, id: str):
|
11 |
self.id = id
|
12 |
self.latest_frame: MatLike = None
|
13 |
+
self.published_frame: MatLike = None
|
14 |
self.measured_fps = 0
|
15 |
self.cpu_usage = 0
|
16 |
+
self.show_stats = True
|
17 |
|
18 |
app = Flask(__name__)
|
19 |
PORT = int(os.environ.get("PORT", 5000))
|
|
|
84 |
|
85 |
if session is not None:
|
86 |
while True:
|
87 |
+
if session.published_frame is not session.latest_frame:
|
88 |
+
if session.latest_frame is None:
|
89 |
+
continue
|
90 |
+
encode_param = [int(cv2.IMWRITE_JPEG_QUALITY), 50]
|
91 |
+
ret, jpeg = cv2.imencode(".jpg", session.latest_frame, encode_param)
|
92 |
+
frame_bytes = jpeg.tobytes() if ret else None
|
93 |
+
if frame_bytes is not None:
|
94 |
+
session.published_frame = session.latest_frame
|
95 |
+
yield (b"--frame\r\n"b"Content-Type: image/jpeg\r\n\r\n" + frame_bytes + b"\r\n")
|
96 |
|
97 |
@app.route("/")
|
98 |
def video_feed():
|
99 |
global sessions
|
100 |
|
101 |
session_id = request.args.get("id", "default")
|
102 |
+
show_stats = request.args.get("show_stats", "0") == "1"
|
103 |
|
104 |
if session_id not in [s.id for s in sessions]:
|
105 |
session = Session(session_id)
|
106 |
sessions.add(session)
|
107 |
threading.Thread(target=frame_processor, args=[session_id], daemon=True).start()
|
108 |
+
else:
|
109 |
+
session = next(s for s in sessions if s.id == session_id)
|
110 |
+
session.show_stats = show_stats
|
111 |
|
112 |
return Response(stream_with_context(stream_mjpeg(session_id)), mimetype="multipart/x-mixed-replace; boundary=frame")
|
113 |
|