Spaces:
Sleeping
Sleeping
Create metrics_storage.py
Browse files- metrics_storage.py +63 -0
metrics_storage.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sqlite3
|
| 2 |
+
|
| 3 |
+
from constants import DATABASE_PATH
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class MetricsStorage:
|
| 7 |
+
def __init__(self, db_path=DATABASE_PATH):
|
| 8 |
+
self.db_path = db_path
|
| 9 |
+
self.setup_database()
|
| 10 |
+
|
| 11 |
+
def setup_database(self):
|
| 12 |
+
"""Initialize the SQLite database and create tables if they don't exist"""
|
| 13 |
+
with sqlite3.connect(self.db_path) as conn:
|
| 14 |
+
cursor = conn.cursor()
|
| 15 |
+
cursor.execute(
|
| 16 |
+
"""
|
| 17 |
+
CREATE TABLE IF NOT EXISTS inference_metrics (
|
| 18 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 19 |
+
inference_time REAL,
|
| 20 |
+
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
|
| 21 |
+
)
|
| 22 |
+
"""
|
| 23 |
+
)
|
| 24 |
+
conn.commit()
|
| 25 |
+
|
| 26 |
+
def add_metric(self, inference_time):
|
| 27 |
+
"""Add a new inference time measurement to the database"""
|
| 28 |
+
with sqlite3.connect(self.db_path) as conn:
|
| 29 |
+
cursor = conn.cursor()
|
| 30 |
+
cursor.execute(
|
| 31 |
+
"INSERT INTO inference_metrics (inference_time) VALUES (?)",
|
| 32 |
+
(inference_time,),
|
| 33 |
+
)
|
| 34 |
+
conn.commit()
|
| 35 |
+
|
| 36 |
+
def get_recent_metrics(self, limit=80):
|
| 37 |
+
"""Get the most recent metrics from the database"""
|
| 38 |
+
with sqlite3.connect(self.db_path) as conn:
|
| 39 |
+
cursor = conn.cursor()
|
| 40 |
+
cursor.execute(
|
| 41 |
+
"SELECT inference_time FROM inference_metrics ORDER BY timestamp DESC LIMIT ?",
|
| 42 |
+
(limit,),
|
| 43 |
+
)
|
| 44 |
+
results = cursor.fetchall()
|
| 45 |
+
return [r[0] for r in reversed(results)]
|
| 46 |
+
|
| 47 |
+
def get_total_inferences(self):
|
| 48 |
+
"""Get the total number of inferences recorded"""
|
| 49 |
+
with sqlite3.connect(self.db_path) as conn:
|
| 50 |
+
cursor = conn.cursor()
|
| 51 |
+
cursor.execute("SELECT COUNT(*) FROM inference_metrics")
|
| 52 |
+
return cursor.fetchone()[0]
|
| 53 |
+
|
| 54 |
+
def get_average_time(self, limit=80):
|
| 55 |
+
"""Get the average inference time from the most recent entries"""
|
| 56 |
+
with sqlite3.connect(self.db_path) as conn:
|
| 57 |
+
cursor = conn.cursor()
|
| 58 |
+
cursor.execute(
|
| 59 |
+
"SELECT AVG(inference_time) FROM (SELECT inference_time FROM inference_metrics ORDER BY timestamp DESC LIMIT ?)",
|
| 60 |
+
(limit,),
|
| 61 |
+
)
|
| 62 |
+
result = cursor.fetchone()[0]
|
| 63 |
+
return result if result is not None else 0
|