# ─── analytics.py ────────────────────────────────────────────────────────────── import os import json from datetime import datetime, timedelta, timezone from filelock import FileLock # pip install filelock import pandas as pd # already available in HF images COUNTS_FILE = "/data/request_counts.json" LOCK_FILE = COUNTS_FILE + ".lock" def _load() -> dict: if not os.path.exists(COUNTS_FILE): return {} with open(COUNTS_FILE) as f: return json.load(f) def _save(data: dict): with open(COUNTS_FILE, "w") as f: json.dump(data, f) async def record_request() -> None: """Increment today's counter (UTC) atomically.""" today = datetime.now(timezone.utc).strftime("%Y-%m-%d") with FileLock(LOCK_FILE): data = _load() data[today] = data.get(today, 0) + 1 _save(data) def last_n_days_df(n: int = 30) -> pd.DataFrame: """Return a DataFrame with a row for each of the past *n* days.""" now = datetime.now(timezone.utc) with FileLock(LOCK_FILE): data = _load() records = [] for i in range(n): day = (now - timedelta(days=n - 1 - i)) day_str = day.strftime("%Y-%m-%d") # Format date for display (MMM DD) display_date = day.strftime("%b %d") records.append({ "date": display_date, "count": data.get(day_str, 0), "full_date": day_str # Keep full date for tooltip }) return pd.DataFrame(records)