Spaces:
Running
Running
File size: 12,404 Bytes
a229747 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 | import os
import sqlite3
import threading
import uuid
from datetime import datetime, timedelta, timezone
from typing import Any, Dict, List, Optional, Tuple
from config import CFG
_WRITE_LOCK = threading.Lock()
def _logs_dir() -> str:
path = os.path.join("logs")
os.makedirs(path, exist_ok=True)
return path
def _default_db_path() -> str:
return os.path.join(_logs_dir(), "api_requests.db")
def _connect(db_path: Optional[str] = None) -> sqlite3.Connection:
conn = sqlite3.connect(db_path or _default_db_path(), timeout=30, check_same_thread=False)
conn.row_factory = sqlite3.Row
conn.execute("PRAGMA journal_mode=WAL;")
conn.execute("PRAGMA synchronous=NORMAL;")
conn.execute("PRAGMA foreign_keys=ON;")
return conn
def _now_iso() -> str:
return datetime.now(timezone.utc).isoformat()
def _today_ymd() -> str:
return datetime.now(timezone.utc).date().isoformat()
def init_db(db_path: Optional[str] = None) -> None:
with _WRITE_LOCK:
conn = _connect(db_path=db_path)
try:
conn.execute(
"""
CREATE TABLE IF NOT EXISTS requests (
id INTEGER PRIMARY KEY AUTOINCREMENT,
request_id TEXT UNIQUE NOT NULL,
timestamp TEXT NOT NULL,
model_name TEXT NOT NULL,
input_text TEXT NOT NULL,
input_length INTEGER,
predicted_label TEXT NOT NULL,
predicted_label_id INTEGER NOT NULL,
confidence REAL NOT NULL,
is_low_confidence INTEGER NOT NULL DEFAULT 0,
latency_ms REAL NOT NULL,
is_batch INTEGER NOT NULL DEFAULT 0
);
"""
)
conn.execute(
"""
CREATE TABLE IF NOT EXISTS model_stats (
model_name TEXT NOT NULL,
date TEXT NOT NULL,
total_requests INTEGER DEFAULT 0,
avg_confidence REAL DEFAULT 0.0,
avg_latency_ms REAL DEFAULT 0.0,
low_conf_count INTEGER DEFAULT 0,
PRIMARY KEY (model_name, date)
);
"""
)
conn.execute(
"""
CREATE TABLE IF NOT EXISTS low_confidence_flags (
id INTEGER PRIMARY KEY AUTOINCREMENT,
request_id TEXT NOT NULL,
timestamp TEXT NOT NULL,
input_text TEXT NOT NULL,
predicted_label TEXT NOT NULL,
confidence REAL NOT NULL,
reviewed INTEGER NOT NULL DEFAULT 0,
review_note TEXT,
FOREIGN KEY (request_id) REFERENCES requests(request_id)
);
"""
)
conn.execute(
"CREATE INDEX IF NOT EXISTS idx_requests_timestamp ON requests(timestamp);"
)
conn.execute(
"CREATE INDEX IF NOT EXISTS idx_requests_model ON requests(model_name);"
)
conn.execute(
"CREATE INDEX IF NOT EXISTS idx_flags_reviewed ON low_confidence_flags(reviewed);"
)
conn.commit()
finally:
conn.close()
def new_request_id() -> str:
return str(uuid.uuid4())
def log_request(
request_id: str,
model_name: str,
input_text: str,
predicted_label: str,
predicted_label_id: int,
confidence: float,
latency_ms: float,
is_batch: bool,
db_path: Optional[str] = None,
) -> None:
ts = _now_iso()
original_len = len(input_text)
stored_text = input_text[:500]
is_low = 1 if float(confidence) < float(CFG.low_confidence_threshold) else 0
batch_int = 1 if is_batch else 0
with _WRITE_LOCK:
conn = _connect(db_path=db_path)
try:
conn.execute(
"""
INSERT INTO requests (
request_id, timestamp, model_name, input_text, input_length,
predicted_label, predicted_label_id, confidence, is_low_confidence,
latency_ms, is_batch
)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);
""",
(
request_id,
ts,
model_name,
stored_text,
original_len,
predicted_label,
int(predicted_label_id),
float(confidence),
int(is_low),
float(latency_ms),
int(batch_int),
),
)
if is_low:
conn.execute(
"""
INSERT INTO low_confidence_flags (
request_id, timestamp, input_text, predicted_label, confidence, reviewed, review_note
)
VALUES (?, ?, ?, ?, ?, 0, NULL);
""",
(request_id, ts, stored_text, predicted_label, float(confidence)),
)
date = _today_ymd()
row = conn.execute(
"""
SELECT total_requests, avg_confidence, avg_latency_ms, low_conf_count
FROM model_stats
WHERE model_name=? AND date=?;
""",
(model_name, date),
).fetchone()
if row is None:
conn.execute(
"""
INSERT INTO model_stats (
model_name, date, total_requests, avg_confidence, avg_latency_ms, low_conf_count
)
VALUES (?, ?, 1, ?, ?, ?);
""",
(model_name, date, float(confidence), float(latency_ms), int(is_low)),
)
else:
n = int(row["total_requests"])
new_n = n + 1
new_avg_conf = (float(row["avg_confidence"]) * n + float(confidence)) / new_n
new_avg_lat = (float(row["avg_latency_ms"]) * n + float(latency_ms)) / new_n
new_low = int(row["low_conf_count"]) + int(is_low)
conn.execute(
"""
UPDATE model_stats
SET total_requests=?, avg_confidence=?, avg_latency_ms=?, low_conf_count=?
WHERE model_name=? AND date=?;
""",
(new_n, new_avg_conf, new_avg_lat, new_low, model_name, date),
)
conn.commit()
finally:
conn.close()
def get_request_history(
db_path: Optional[str] = None, limit: int = 100, offset: int = 0
) -> List[Dict[str, Any]]:
conn = _connect(db_path=db_path)
try:
rows = conn.execute(
"""
SELECT *
FROM requests
ORDER BY id DESC
LIMIT ? OFFSET ?;
""",
(int(limit), int(offset)),
).fetchall()
return [dict(r) for r in rows]
finally:
conn.close()
def get_low_confidence_flags(
db_path: Optional[str] = None, reviewed: bool = False, limit: int = 50
) -> List[Dict[str, Any]]:
conn = _connect(db_path=db_path)
try:
rows = conn.execute(
"""
SELECT *
FROM low_confidence_flags
WHERE reviewed=?
ORDER BY id DESC
LIMIT ?;
""",
(1 if reviewed else 0, int(limit)),
).fetchall()
return [dict(r) for r in rows]
finally:
conn.close()
def mark_reviewed(request_id: str, note: Optional[str] = None, db_path: Optional[str] = None) -> None:
with _WRITE_LOCK:
conn = _connect(db_path=db_path)
try:
conn.execute(
"""
UPDATE low_confidence_flags
SET reviewed=1, review_note=?
WHERE request_id=?;
""",
(note, request_id),
)
conn.commit()
finally:
conn.close()
def get_model_leaderboard(db_path: Optional[str] = None) -> List[Tuple[str, int, float, float]]:
conn = _connect(db_path=db_path)
try:
rows = conn.execute(
"""
SELECT
model_name,
COUNT(*) AS total_requests,
AVG(confidence) AS avg_confidence,
AVG(latency_ms) AS avg_latency_ms
FROM requests
GROUP BY model_name
ORDER BY total_requests DESC;
"""
).fetchall()
return [
(
str(r["model_name"]),
int(r["total_requests"]),
float(r["avg_confidence"] or 0.0),
float(r["avg_latency_ms"] or 0.0),
)
for r in rows
]
finally:
conn.close()
def get_summary(
db_path: Optional[str] = None, model_name: Optional[str] = None, days: int = 7
) -> Dict[str, Any]:
conn = _connect(db_path=db_path)
try:
start_ts = (datetime.now(timezone.utc) - timedelta(days=int(days))).isoformat()
params: List[Any] = [start_ts]
where = "WHERE timestamp >= ?"
if model_name:
where += " AND model_name = ?"
params.append(model_name)
row = conn.execute(
f"""
SELECT
COUNT(*) AS total_requests,
AVG(confidence) AS avg_confidence,
AVG(latency_ms) AS avg_latency_ms,
SUM(is_low_confidence) AS low_confidence_count
FROM requests
{where};
""",
tuple(params),
).fetchone()
total_requests = int(row["total_requests"] or 0)
avg_confidence = float(row["avg_confidence"] or 0.0)
avg_latency_ms = float(row["avg_latency_ms"] or 0.0)
low_conf_count = int(row["low_confidence_count"] or 0)
rate = (low_conf_count / total_requests) * 100.0 if total_requests > 0 else 0.0
params2: List[Any] = list(params)
where2 = where
models = conn.execute(
f"""
SELECT DISTINCT model_name
FROM requests
{where2}
ORDER BY model_name;
""",
tuple(params2),
).fetchall()
models_used = [str(r["model_name"]) for r in models]
label_rows = conn.execute(
f"""
SELECT predicted_label, COUNT(*) AS c
FROM requests
{where2}
GROUP BY predicted_label;
""",
tuple(params2),
).fetchall()
predictions_by_label = {str(r["predicted_label"]): int(r["c"]) for r in label_rows}
return {
"period_days": int(days),
"total_requests": total_requests,
"models_used": models_used,
"avg_confidence": round(avg_confidence, 3),
"avg_latency_ms": round(avg_latency_ms, 2),
"low_confidence_count": low_conf_count,
"low_confidence_rate": f"{rate:.2f}%",
"predictions_by_label": predictions_by_label,
}
finally:
conn.close()
def export_low_confidence_to_folder(
output_dir: str = os.path.join("logs", "low_confidence_review"),
) -> Dict[str, Any]:
os.makedirs(output_dir, exist_ok=True)
flags = get_low_confidence_flags(reviewed=False, limit=10_000)
exported = 0
for f in flags:
request_id = str(f["request_id"])
ts = str(f["timestamp"]).replace(":", "-")
filename = f"{ts}_{request_id}.txt"
path = os.path.join(output_dir, filename)
if os.path.exists(path):
continue
content = "\n".join(
[
f"request_id: {request_id}",
f"timestamp: {f['timestamp']}",
f"predicted_label: {f['predicted_label']}",
f"confidence: {float(f['confidence']):.4f}",
"",
str(f["input_text"]),
]
)
with open(path, "w", encoding="utf-8") as out:
out.write(content)
exported += 1
return {"exported": exported, "folder": output_dir}
|