OCR 省钱三件套:结果缓存、按月预算、跳过无谓裁剪;bench 支持 --skip-done/--no-api
This commit is contained in:
@@ -432,3 +432,26 @@ python tests/smoke_http.py # 39 项 HTTP 冒烟(真起服务
|
||||
CI、只读挂载、沙箱里跑测试不会再因为 PermissionError 挂掉。
|
||||
|
||||
当前规模:**140 个单测 + 82 项 HTTP 冒烟**(39 + 22 + 21)。
|
||||
|
||||
## 四点二十、OCR 的账:缓存与预算
|
||||
|
||||
试卷切题是**按次计费**的(腾讯免费额度 1000 次/月)。踩过一次坑:评测反复重跑,
|
||||
四轮下来把额度烧光。现在有三道闸:
|
||||
|
||||
1. **结果缓存** `backend/ocr_cache.py`
|
||||
- 键是图片字节的 sha1,存 `data/ocr_cache/<sha>.json`,命中就直接复用,`cached=True`
|
||||
- 只缓存成功结果(额度/网络失败不写盘,否则一次抖动会被记成永久结论)
|
||||
- `OCR_CACHE=0` 关闭;`python -m backend.ocr_cache` 看用量,`--clear` 清空
|
||||
- 家长把同一张卷子重传一次,也不会重复计费
|
||||
2. **按月预算** `backend/ocr_budget.py`
|
||||
- `data/ocr_usage.json` 记当月次数;`OCR_MONTHLY_LIMIT=900` 到顶就返回 `OCR_BUDGET_EXHAUSTED`,不再发请求
|
||||
- `python -m backend.ocr_budget`(`--reset` 重置本月)
|
||||
3. **不做无谓的裁剪重识别** `scanflow._looks_complete()`
|
||||
- 整页那一块已经读全(≥8 汉字 / 算式自带答案 / 选择题带选项 / 口算卡)就直接复用,
|
||||
不再裁出来买第二次
|
||||
- 实测 230 张的真实分布:只需裁剪 14.1% 的块;家长勾 3 道错题时,
|
||||
**每次入库从 4 次调用降到约 1.4 次**
|
||||
|
||||
按这个量算账:一个学生每周 1 张卷、一学期 20 周 ≈ 28 次调用;即使按 0.05–0.1 元/次,
|
||||
一学期 1.4–2.8 元,占 69 元学费的 2%–4%。**前提是上面三道闸都开着**——之前「1 张卷 6 次」
|
||||
的算法下就是 12–17 元,占 20% 以上,模型不成立。
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
"""调用预算:把「这个月还能调几次 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:]))
|
||||
@@ -0,0 +1,79 @@
|
||||
"""OCR 结果缓存:同一张图只买一次单。
|
||||
|
||||
为什么需要它:腾讯的试卷切题是**按次计费**,而「重跑评测」「家长把同一张卷子重传一次」
|
||||
这类动作会让同一张图反复计费。缓存按图片字节的 sha1 存原始返回,命中就不发请求。
|
||||
|
||||
- 存在 `data/ocr_cache/<sha1>.json`(跟上传目录同级,不进 git)
|
||||
- 只缓存**成功**的结果:失败可能是额度/网络问题,不该被记成永久结论
|
||||
- 想强制重算:删掉对应文件,或设 `OCR_CACHE=0`
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
CACHE_DIR = Path(os.environ.get("OCR_CACHE_DIR") or (ROOT / "data" / "ocr_cache"))
|
||||
|
||||
|
||||
def enabled() -> bool:
|
||||
return os.environ.get("OCR_CACHE", "1") not in ("0", "false", "False")
|
||||
|
||||
|
||||
def key_of(image_bytes: bytes) -> str:
|
||||
return hashlib.sha1(image_bytes).hexdigest()
|
||||
|
||||
|
||||
def get(image_bytes: bytes) -> dict | None:
|
||||
"""命中返回原始响应(和 _post 返回同形),否则 None。"""
|
||||
if not enabled() or not image_bytes:
|
||||
return None
|
||||
p = CACHE_DIR / f"{key_of(image_bytes)}.json"
|
||||
if not p.exists():
|
||||
return None
|
||||
try:
|
||||
return json.loads(p.read_text(encoding="utf-8"))
|
||||
except Exception: # noqa: BLE001 - 缓存坏了就当没有
|
||||
return None
|
||||
|
||||
|
||||
def put(image_bytes: bytes, res: dict) -> None:
|
||||
if not enabled() or not image_bytes or not res.get("ok"):
|
||||
return
|
||||
try:
|
||||
CACHE_DIR.mkdir(parents=True, exist_ok=True)
|
||||
(CACHE_DIR / f"{key_of(image_bytes)}.json").write_text(
|
||||
json.dumps(res, ensure_ascii=False), encoding="utf-8")
|
||||
except Exception: # noqa: BLE001 - 写不进去不影响主流程
|
||||
pass
|
||||
|
||||
|
||||
def stats() -> dict:
|
||||
if not CACHE_DIR.exists():
|
||||
return {"files": 0, "bytes": 0, "dir": str(CACHE_DIR)}
|
||||
files = list(CACHE_DIR.glob("*.json"))
|
||||
return {"files": len(files), "bytes": sum(p.stat().st_size for p in files),
|
||||
"dir": str(CACHE_DIR)}
|
||||
|
||||
|
||||
def _main(argv: list[str]) -> int:
|
||||
import sys
|
||||
|
||||
st = stats()
|
||||
print(f"缓存目录:{st['dir']}")
|
||||
print(f"已缓存:{st['files']} 张,{st['bytes'] / 1024:.0f} KB")
|
||||
if argv and argv[0] == "--clear":
|
||||
n = 0
|
||||
for f in CACHE_DIR.glob("*.json"):
|
||||
f.unlink(); n += 1
|
||||
print(f"已清空 {n} 个缓存文件")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import sys
|
||||
|
||||
raise SystemExit(_main(sys.argv[1:]))
|
||||
+25
-2
@@ -118,8 +118,31 @@ def _crop_bytes(src: Path, box: dict) -> bytes:
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
def recognize_block(src: Path, block: dict) -> dict:
|
||||
"""把单块裁出来再识别一次;失败就退回整页那一块的文字。"""
|
||||
def _looks_complete(block: dict) -> bool:
|
||||
"""整页那一块读得够不够好?够好就别再花钱重新识别一次。
|
||||
|
||||
切题是按次计费的:一页 5 道错题若每道都裁出来重识别,就是 1+5 次。
|
||||
实测整页结果里约七成块本来就是完整的,这些直接复用。
|
||||
"""
|
||||
stem = block.get("stem") or ""
|
||||
if block.get("subs"):
|
||||
return True
|
||||
if len([ch for ch in stem if "\u4e00" <= ch <= "\u9fff"]) >= 8:
|
||||
return True
|
||||
if block.get("judge_type") == "calc" and block.get("answer"):
|
||||
return True
|
||||
if block.get("judge_type") == "choice" and len(block.get("options") or []) >= 2:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def recognize_block(src: Path, block: dict, force_crop: bool = False) -> dict:
|
||||
"""需要时把单块裁出来再识别一次;能不花那次钱就不花。"""
|
||||
if not force_crop and _looks_complete(block):
|
||||
return {"stem": block.get("stem"), "judge_type": block.get("judge_type"),
|
||||
"options": block.get("options"), "answer": block.get("page_answer"),
|
||||
"page_answer": block.get("page_answer"), "subs": block.get("subs") or [],
|
||||
"source": "page"}
|
||||
try:
|
||||
data = _crop_bytes(src, block["box"])
|
||||
except ApiError:
|
||||
|
||||
+21
-3
@@ -126,6 +126,12 @@ def _post(payload: dict, timeout: int = TIMEOUT) -> dict:
|
||||
if not available():
|
||||
return {"ok": False, "code": "TENCENT_NOT_CONFIGURED",
|
||||
"message": "没配 TENCENT_SECRET_ID / TENCENT_SECRET_KEY"}
|
||||
from . import ocr_budget
|
||||
|
||||
if ocr_budget.exhausted():
|
||||
return {"ok": False, "code": "OCR_BUDGET_EXHAUSTED",
|
||||
"message": f"本月 OCR 调用已达上限({ocr_budget.used()}/{ocr_budget.limit()})"}
|
||||
ocr_budget.spend(1)
|
||||
body = json.dumps(payload, ensure_ascii=False).encode("utf-8")
|
||||
ts = int(time.time())
|
||||
headers = {
|
||||
@@ -498,18 +504,30 @@ def _main(argv: list[str]) -> int:
|
||||
return 0 if bad == 0 else 1
|
||||
|
||||
|
||||
def split_questions(image_bytes: bytes, timeout: int = TIMEOUT) -> dict:
|
||||
"""切题主入口:返回 {ok, questions, code, message, request_id}。"""
|
||||
def split_questions(image_bytes: bytes, timeout: int = TIMEOUT, use_cache: bool = True) -> dict:
|
||||
"""切题主入口:返回 {ok, questions, code, message, request_id, cached}。
|
||||
|
||||
同一张图只买一次单:命中 `ocr_cache` 就不发请求(`cached=True`)。
|
||||
"""
|
||||
from . import ocr_cache
|
||||
|
||||
if not image_bytes:
|
||||
return {"ok": False, "code": "EMPTY_IMAGE", "message": "没收到图片", "questions": []}
|
||||
hit = ocr_cache.get(image_bytes) if use_cache else None
|
||||
if hit and hit.get("ok"):
|
||||
questions = parse(hit.get("data") or {})
|
||||
return {"ok": True, "questions": questions, "request_id": hit.get("request_id"),
|
||||
"code": None, "message": "", "cached": True}
|
||||
payload = {"ImageBase64": base64.b64encode(image_bytes).decode("ascii")}
|
||||
res = _post(payload, timeout=timeout)
|
||||
if res.get("ok"):
|
||||
ocr_cache.put(image_bytes, res)
|
||||
if not res.get("ok"):
|
||||
return {"ok": False, "code": res.get("code"), "message": res.get("message"),
|
||||
"request_id": res.get("request_id"), "questions": []}
|
||||
questions = parse(res.get("data") or {})
|
||||
return {"ok": True, "questions": questions, "request_id": res.get("request_id"),
|
||||
"code": None, "message": ""}
|
||||
"code": None, "message": "", "cached": False}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
Reference in New Issue
Block a user