File size: 4,698 Bytes
17f4503
 
 
 
9c56a9c
17f4503
 
 
 
 
 
 
 
 
9c56a9c
17f4503
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9c56a9c
17f4503
9c56a9c
 
 
 
 
 
 
 
 
17f4503
 
 
 
 
 
 
9c56a9c
 
 
 
 
 
17f4503
 
9c56a9c
 
 
 
17f4503
 
 
 
 
 
 
9c56a9c
 
 
 
 
 
 
 
17f4503
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9c56a9c
17f4503
 
 
 
 
 
 
 
 
 
9c56a9c
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
"""
Counting what each student does per day: questions, uploads, pages read by Sarvam Vision, AI tokens,
flashcard reviews, ratings. Used for the admin page, cost estimates, streaks, and the monthly budget.

One row per user per day in the usage_daily table (one column per counter).
"""
import datetime as dt
import logging
import threading
import time
from zoneinfo import ZoneInfo

from fastapi import HTTPException

from backend import db, settings

logger = logging.getLogger(__name__)

COUNTERS = (
    "questions",
    "uploads",
    "pages_read",
    "upload_failures",
    "study_requests",
    "reviews",
    "prompt_tokens",
    "completion_tokens",
    "ratings_up",
    "ratings_down",
)

_lock = threading.Lock()
_month_cost: dict[str, float] = {}  # "YYYY-MM" -> estimated cost so far (filled lazily from the database)


def tz() -> ZoneInfo:
    try:
        return ZoneInfo(settings.APP_TIMEZONE)
    except Exception:
        return ZoneInfo("UTC")


def today(now: float | None = None) -> dt.date:
    return dt.datetime.fromtimestamp(now if now is not None else time.time(), tz()).date()


def day_num(day: dt.date) -> int:
    return day.year * 10000 + day.month * 100 + day.day


def prices_set() -> bool:
    return any(
        (settings.AI_PRICE_PER_PAGE, settings.AI_PRICE_PER_1K_INPUT_TOKENS, settings.AI_PRICE_PER_1K_OUTPUT_TOKENS)
    )


def cost_of(counts: dict) -> float:
    return (
        float(counts.get("pages_read") or 0) * settings.AI_PRICE_PER_PAGE
        + float(counts.get("prompt_tokens") or 0) / 1000 * settings.AI_PRICE_PER_1K_INPUT_TOKENS
        + float(counts.get("completion_tokens") or 0) / 1000 * settings.AI_PRICE_PER_1K_OUTPUT_TOKENS
    )


def record(user_id: str, **increments: int) -> None:
    """Add to today's counters for a user. Never raises: counting must not break the request."""
    increments = {k: int(v) for k, v in increments.items() if k in COUNTERS and v}
    if not user_id or not increments:
        return
    day = today()
    month = f"{day.year:04d}-{day.month:02d}"
    cols = ", ".join(increments)  # names come from COUNTERS only
    try:
        db.execute(
            f"INSERT INTO usage_daily (user_id, day, {cols}) VALUES (:u, :day, "
            + ", ".join(f":{k}" for k in increments)
            + ") ON CONFLICT (user_id, day) DO UPDATE SET "
            + ", ".join(f"{k} = usage_daily.{k} + EXCLUDED.{k}" for k in increments),
            u=user_id,
            day=day,
            **increments,
        )
        with _lock:
            if month in _month_cost:
                _month_cost[month] += cost_of(increments)
    except Exception:
        logger.warning("Usage counting failed for %s", user_id, exc_info=True)


def _public(row: dict) -> dict:
    day = row["day"]
    return {**{k: int(row[k]) for k in COUNTERS}, "user_id": row["user_id"], "day": day.isoformat(),
            "day_num": day_num(day), "month": f"{day.year:04d}-{day.month:02d}"}


def records_since(start: dt.date, user_id: str | None = None) -> list[dict]:
    if user_id:
        found = db.rows("SELECT * FROM usage_daily WHERE day >= :d AND user_id = :u", d=start, u=user_id)
    else:
        found = db.rows("SELECT * FROM usage_daily WHERE day >= :d", d=start)
    return [_public(r) for r in found]


def month_cost(now: float | None = None) -> float:
    day = today(now)
    month = f"{day.year:04d}-{day.month:02d}"
    with _lock:
        if month not in _month_cost:
            first = day.replace(day=1)
            sums = db.one(
                "SELECT " + ", ".join(f"coalesce(sum({k}), 0) AS {k}" for k in COUNTERS)
                + " FROM usage_daily WHERE day >= :first AND day <= :day",
                first=first,
                day=day,
            )
            _month_cost[month] = cost_of(sums or {})
        return _month_cost[month]


def check_budget() -> None:
    """Pause paid AI work (HTTP 503) once this month's estimated cost reaches AI_MONTHLY_BUDGET."""
    if settings.AI_MONTHLY_BUDGET <= 0 or not prices_set():
        return
    try:
        spent = month_cost()
    except Exception:
        logger.warning("Budget check failed; allowing the request", exc_info=True)
        return
    if spent >= settings.AI_MONTHLY_BUDGET:
        raise HTTPException(
            status_code=503,
            detail="Study AI has used this month's AI budget, so reading files, answers and study "
            "tools are paused until next month. Your notes and flashcard reviews still work.",
        )


def reset_cache() -> None:
    with _lock:
        _month_cost.clear()


def delete_user(user_id: str) -> None:
    db.execute("DELETE FROM usage_daily WHERE user_id = :u", u=user_id)