# βββ 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)).strftime("%Y-%m-%d") | |
records.append({"date": day, "count": data.get(day, 0)}) | |
return pd.DataFrame(records) |