Files

80 lines
2.5 KiB
Python

"""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:]))