diff --git a/metrics.py b/metrics.py new file mode 100644 index 0000000..4be4b2f --- /dev/null +++ b/metrics.py @@ -0,0 +1,23 @@ +import threading +from prometheus_client import Counter, start_http_server + +_lock = threading.Lock() +_registry = None +_metrics = None + +def get_metrics(): + global _metrics + with _lock: + if _metrics is None: + start_http_server(9110) + _metrics = { + "people_in": Counter( + "people_in_count", + "Number of people who entered", + ), + "people_out": Counter( + "people_out_count", + "Number of people who exited", + ), + } + return _metrics diff --git a/streamlit_app.py b/streamlit_app.py index 9723cb3..f2afa7f 100644 --- a/streamlit_app.py +++ b/streamlit_app.py @@ -6,18 +6,9 @@ from utils.zones import draw_count_line_horizontal, draw_count_line_vertical import tempfile import time -from prometheus_client import Gauge, start_http_server +from metrics import get_metrics -# Nur einmal beim ersten Start starten -if "prom" not in st.session_state: - # Starte Prometheus-Metrik-Server (z. B. auf Port 9100) - start_http_server(9100) - - # Metriken definieren - st.session_state.prom = { - 'people_in': Gauge("people_in_count", "Number of people who entered"), - 'people_out': Gauge("people_out_count", "Number of people who exited"), - } +metrics = get_metrics() st.set_page_config(layout="wide", page_title="People Counter") @@ -33,7 +24,7 @@ if start_button and STREAM_URL: stframe = st.empty() model = YOLO("yolo_weights/yolo11n.pt") - counter = Counter(line_orientation) + counter = Counter(line_orientation, metrics) cap = cv2.VideoCapture(STREAM_URL) @@ -62,8 +53,6 @@ if start_button and STREAM_URL: for box, track_id in zip(boxes.xywh.cpu(), boxes.id.cpu()) ] counter.update(tracks, line_position) - st.session_state.prom['people_in'].set(counter.in_count) - st.session_state.prom['people_out'].set(counter.out_count) if line_orientation == 'horizontal': draw_count_line_horizontal(frame, line_position) diff --git a/utils/counter.py b/utils/counter.py index f0544a9..39b56e9 100644 --- a/utils/counter.py +++ b/utils/counter.py @@ -1,9 +1,10 @@ class Counter: - def __init__(self, line_orientation): + def __init__(self, line_orientation, metrics): self.in_count = 0 self.out_count = 0 self.track_memory = {} self.line_orientation = line_orientation + self.metrics = metrics def update(self, tracks, line_position): for track in tracks: @@ -27,5 +28,7 @@ class Counter: if prev < line_position <= center: self.in_count += 1 + self.metrics["people_in"].inc() elif prev > line_position >= center: self.out_count += 1 + self.metrics["people_out"].inc()