OCR 省钱三件套:结果缓存、按月预算、跳过无谓裁剪;bench 支持 --skip-done/--no-api

This commit is contained in:
2026-11-19 16:33:15 +08:00
parent ba7c35d538
commit df196fd8d9
15 changed files with 685 additions and 237 deletions
+21 -3
View File
@@ -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__":