Files
cuotibiye/backend/ocr_budget.py
T

85 lines
2.2 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""调用预算:把「这个月还能调几次 OCR」变成看得见的数。
腾讯的切题接口按次计费,免费额度只有 1000 次/月。评测、重跑、家长反复传同一张卷子
都会吃额度,而且吃到不剩时才发现。这里在本地记一个月度计数:
- `data/ocr_usage.json`:{"2026-11": 137}
- `OCR_MONTHLY_LIMIT=900`(环境变量)到顶后就不再发请求,返回 `OCR_BUDGET_EXHAUSTED`
- 不设 limit 就是纯计数,不拦
"""
from __future__ import annotations
import json
import os
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
USAGE = Path(os.environ.get("OCR_USAGE_FILE") or (ROOT / "data" / "ocr_usage.json"))
def month() -> str:
return time.strftime("%Y-%m")
def _load() -> dict:
try:
return json.loads(USAGE.read_text(encoding="utf-8"))
except Exception: # noqa: BLE001
return {}
def used() -> int:
return int(_load().get(month(), 0))
def limit() -> int:
try:
return int(os.environ.get("OCR_MONTHLY_LIMIT") or 0)
except ValueError:
return 0
def remaining() -> int | None:
lim = limit()
return None if lim <= 0 else max(0, lim - used())
def exhausted() -> bool:
lim = limit()
return lim > 0 and used() >= lim
def spend(n: int = 1) -> int:
"""记一次调用。写不进磁盘也不影响主流程(最多丢一个计数)。"""
data = _load()
data[month()] = int(data.get(month(), 0)) + n
try:
USAGE.parent.mkdir(parents=True, exist_ok=True)
USAGE.write_text(json.dumps(data, ensure_ascii=False), encoding="utf-8")
except Exception: # noqa: BLE001
pass
return data[month()]
def _main(argv: list[str]) -> int:
print(f"月份:{month()}")
print(f"已用:{used()} 次")
lim = limit()
print(f"上限:{lim if lim > 0 else '未设(OCR_MONTHLY_LIMIT)'}")
if lim > 0:
print(f"剩余:{remaining()} 次")
if argv and argv[0] == "--reset":
data = _load()
data[month()] = 0
USAGE.write_text(json.dumps(data, ensure_ascii=False), encoding="utf-8")
print("已重置本月计数")
return 0
if __name__ == "__main__":
import sys
raise SystemExit(_main(sys.argv[1:]))