File size: 1,638 Bytes
4c75ecc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b4fa9b6
 
 
 
 
 
 
 
 
4c75ecc
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
# ─── 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)