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
+23
View File
@@ -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% 以上,模型不成立。
+84
View File
@@ -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:]))
+79
View File
@@ -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
View File
@@ -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
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__":
+18
View File
@@ -71,3 +71,21 @@ python bench/gold_expr.py --append # 追加成 report.md 第五节
三个口径:**认对**(答案数值相同,`0.6` 与 `3/5` 视为相同)、**算错**(给出答案但数值不对,这才是误判)、**没认出来**(题干里压根没出现这个算式)。
当前(4 张卷、83 道):认对 96.4%、算错 0%、没认出来 3.6%。
## 额度纪律(重要)
评测的每一次 `run.py` 都是一次真实计费调用。**不要反复全量重跑**:
```bash
python bench/run.py --skip-done # 只跑还没成功过的图(日常用这个)
python bench/run.py --ids a1b2,c3d4 # 只重跑个别图
python bench/run.py --no-api # 只用缓存重算指标,不发请求
python -m backend.ocr_budget # 本月还剩多少次
python -m backend.ocr_cache # 缓存里有多少张
```
`results.jsonl` 是合并写的:中途只跑几张不会冲掉之前的结果,也不会用一次失败覆盖上次的成功记录。
已知状态:`data/bench/results.jsonl` 是**加链式求值之前**的 230 张结果;
`report.md`(和 `report/错题毕业-拍题评测-230张.md`)里的数字是加链式求值**之后**的口径。
要复现后者需要重跑那 230 张(有缓存的话不会重复计费)。
+51 -2
View File
@@ -58,10 +58,34 @@ def norm_ans(x: str) -> str:
return s.strip()
def _detect_from_cache_only(data: bytes, name: str) -> dict:
"""不联网:只有缓存命中才算数,否则抛 NO_CACHE。"""
from backend import ocr_cache, tencent_ocr
hit = ocr_cache.get(data)
if not hit:
raise RuntimeError("NO_CACHE")
res = tencent_ocr.split_questions(data, use_cache=True)
if not res.get("ok"):
raise RuntimeError(res.get("code") or "NO_CACHE")
return {"blocks": [_to_block(i, q) for i, q in enumerate(res["questions"])]}
def _to_block(i: int, q: dict) -> dict:
return {"i": i, "box": q.get("box"), "stem": q["stem"],
"judge_type": q.get("detected_as") or q.get("judge_type"),
"options": q.get("options"), "page_answer": q.get("page_answer"),
"subs": q.get("subs") or []}
def main(argv=None) -> int:
ap = argparse.ArgumentParser(description="跑评测链路")
ap.add_argument("--limit", type=int, default=0, help="最多跑多少张(0=全部)")
ap.add_argument("--ids", default="", help="只跑这些图 id(逗号分隔),结果合并进原 jsonl")
ap.add_argument("--no-api", action="store_true",
help="只用 OCR 缓存,缺的不发请求(额度用完后重算指标用)")
ap.add_argument("--skip-done", action="store_true",
help="跳过 results.jsonl 里已经跑成功过的图(省额度)")
ap.add_argument("--out", default=str(RESULTS))
args = ap.parse_args(argv)
@@ -71,19 +95,33 @@ def main(argv=None) -> int:
files = [f for f in files if f.stem in only]
if args.limit:
files = files[: args.limit]
if args.skip_done and RESULTS.exists():
done_ids = {json.loads(l)["id"] for l in RESULTS.open(encoding="utf-8") if l.strip()}
files = [f for f in files if f.stem not in done_ids]
if not files:
print("没有图片,先跑 python bench/fetch.py")
return 1
out = Path(args.out)
out.parent.mkdir(parents=True, exist_ok=True)
# 先读旧的,最后整体回写:中途 --ids / --limit 只跑几张时,别把之前的结果冲掉
merged: dict[str, dict] = {}
if out.exists():
for line in out.open(encoding="utf-8"):
if line.strip():
row = json.loads(line)
merged[row["id"]] = row
done = 0
with out.open("w", encoding="utf-8") as f:
for n, fp in enumerate(files, 1):
data = fp.read_bytes()
t0 = time.time()
try:
res = scanflow.detect(data, fp.name)
if args.no_api:
res = _detect_from_cache_only(data, fp.name)
else:
res = scanflow.detect(data, fp.name)
ok, code, blocks = True, "", res.get("blocks") or []
except Exception as e: # noqa: BLE001
ok, code, blocks = False, getattr(e, "code", type(e).__name__), []
@@ -127,7 +165,18 @@ def main(argv=None) -> int:
})
rec = {"id": fp.stem, "ok": ok, "code": code, "ms": ms,
"n_blocks": len(rows), "blocks": rows}
f.write(json.dumps(rec, ensure_ascii=False) + "\n")
# 这次失败(比如缓存没有)不要把之前跑成功的结果冲掉
prev = merged.get(fp.stem)
if not ok and prev and prev.get("ok"):
print(f" {n:3d}/{len(files)} 跳过(保留上次成功的记录){fp.stem[:12]}")
done += 1
continue
merged[fp.stem] = rec
f.seek(0)
f.truncate()
for row in merged.values():
f.write(json.dumps(row, ensure_ascii=False) + "\n")
f.flush()
done += 1
flag = "OK " if ok and rows else "空 "
print(f" {n:3d}/{len(files)} {flag}{len(rows):2d} 题 {ms:5d}ms {fp.stem[:12]}")
+1
View File
@@ -0,0 +1 @@
{"2026-11": 3}
@@ -0,0 +1 @@
{"ok": true, "data": {}}
@@ -0,0 +1 @@
{"ok": true, "data": {"QuestionInfo": [{"Angle": 0, "Height": 300, "ImageBase64": "", "OrgHeight": 300, "OrgWidth": 900, "ResultList": null, "Width": 900}], "RequestId": "757e5fcf-84c7-4ae5-a7d7-75bafb00e616"}, "request_id": "757e5fcf-84c7-4ae5-a7d7-75bafb00e616"}
@@ -0,0 +1 @@
{"ok": true, "request_id": "r1", "data": {"QuestionInfo": [{"ResultList": [{"Question": [{"Text": "2.计算:72 - 38 ="}], "Answer": [{"Text": "34"}]}]}], "RequestId": "req-1"}}
+230 -230
View File
File diff suppressed because one or more lines are too long
+1
View File
@@ -0,0 +1 @@
{"2026-11": 12}
+107
View File
@@ -0,0 +1,107 @@
"""OCR 结果缓存:同一张图不该买两次单。"""
from __future__ import annotations
import os
import shutil
import unittest
from pathlib import Path
from unittest import mock
# 必须落在工作区内:沙箱只允许写这里,写到系统临时目录会被拒
TMP = Path(__file__).resolve().parent.parent / "data" / "_ocrcache_test"
TMP.mkdir(parents=True, exist_ok=True)
os.environ["OCR_CACHE_DIR"] = str(TMP)
from backend import ocr_cache, tencent_ocr # noqa: E402
PNG = (b"\x89PNG\r\n\x1a\n" + b"0" * 64)
class OcrCacheTest(unittest.TestCase):
def setUp(self):
for p in TMP.glob("*.json"):
p.unlink()
def test_key_is_stable_per_bytes(self):
self.assertEqual(ocr_cache.key_of(b"abc"), ocr_cache.key_of(b"abc"))
self.assertNotEqual(ocr_cache.key_of(b"abc"), ocr_cache.key_of(b"abd"))
def test_get_miss_then_hit(self):
self.assertIsNone(ocr_cache.get(PNG))
ocr_cache.put(PNG, {"ok": True, "data": {"Answer": []}})
got = ocr_cache.get(PNG)
self.assertIsNotNone(got)
self.assertTrue(got["ok"])
def test_failure_is_not_cached(self):
ocr_cache.put(PNG, {"ok": False, "code": "ARREARS"})
self.assertIsNone(ocr_cache.get(PNG))
def test_switch_off(self):
ocr_cache.put(PNG, {"ok": True, "data": {}})
os.environ["OCR_CACHE"] = "0"
try:
self.assertIsNone(ocr_cache.get(PNG))
finally:
os.environ.pop("OCR_CACHE", None)
def test_split_questions_hits_cache_instead_of_network(self):
calls = []
def fake_post(payload, timeout=30):
calls.append(1)
return {"ok": True, "data": {"Answer": []}, "request_id": "r1"}
with mock.patch.object(tencent_ocr, "_post", fake_post):
a = tencent_ocr.split_questions(PNG)
b = tencent_ocr.split_questions(PNG)
self.assertEqual(len(calls), 1, "第二张同样的图不该再发请求")
self.assertFalse(a.get("cached"))
self.assertTrue(b.get("cached"))
def test_cache_disabled_bypasses_store(self):
calls = []
def fake_post(payload, timeout=30):
calls.append(1)
return {"ok": True, "data": {"Answer": []}, "request_id": "r2"}
with mock.patch.object(tencent_ocr, "_post", fake_post):
tencent_ocr.split_questions(PNG, use_cache=False)
tencent_ocr.split_questions(PNG, use_cache=False)
self.assertEqual(len(calls), 2)
if __name__ == "__main__":
unittest.main()
class BudgetTest(unittest.TestCase):
def setUp(self):
import backend.ocr_budget as b
self.b = b
self.old = b.USAGE
b.USAGE = Path("data") / "_ocr_usage_test.json"
b.USAGE.parent.mkdir(parents=True, exist_ok=True)
if b.USAGE.exists():
b.USAGE.unlink()
def tearDown(self):
import os
self.b.USAGE = self.old
os.environ.pop("OCR_MONTHLY_LIMIT", None)
def test_counts_and_needs_explicit_limit(self):
self.assertEqual(self.b.used(), 0)
self.b.spend(2)
self.assertEqual(self.b.used(), 2)
self.assertFalse(self.b.exhausted()) # 不设上限不拦
self.assertIsNone(self.b.remaining())
def test_exhausts_at_limit(self):
import os
os.environ["OCR_MONTHLY_LIMIT"] = "3"
self.b.spend(3)
self.assertTrue(self.b.exhausted())
self.assertEqual(self.b.remaining(), 0)
+42
View File
@@ -132,3 +132,45 @@ class ScanFlowTest(unittest.TestCase):
if __name__ == "__main__":
unittest.main()
class NoWastefulCropTest(unittest.TestCase):
"""整页读得够好的块,不该再花钱裁出来识别第二次。"""
def test_complete_block_skips_crop(self):
from backend import scanflow
block = {"i": 0, "box": {"x": 10, "y": 10, "w": 300, "h": 200},
"stem": "小明有 12 个苹果,给了小红 5 个,还剩多少个?",
"judge_type": "manual", "options": None, "page_answer": "", "subs": []}
with mock.patch("backend.tencent_ocr.split_questions") as sp:
r = scanflow.recognize_block(Path("data/bench/raw/x.jpg"), block)
sp.assert_not_called()
self.assertEqual(r["source"], "page")
self.assertIn("苹果", r["stem"])
def test_broken_block_still_crops(self):
from backend import scanflow
block = {"i": 0, "box": {"x": 10, "y": 10, "w": 300, "h": 200},
"stem": "1、", "judge_type": "manual", "options": None,
"page_answer": "", "subs": []}
with mock.patch("backend.scanflow._crop_bytes", return_value=b"jpg"), \
mock.patch("backend.tencent_ocr.split_questions",
return_value={"ok": True, "questions": [
{"stem": "1、6+5-10=", "judge_type": "calc", "options": None,
"answer": "1", "page_answer": "", "subs": []}]}) as sp:
r = scanflow.recognize_block(Path("data/bench/raw/x.jpg"), block)
sp.assert_called_once()
self.assertEqual(r["source"], "crop")
def test_card_block_skips_crop(self):
from backend import scanflow
block = {"i": 0, "box": {"x": 1, "y": 1, "w": 300, "h": 300}, "stem": "10-6= 7+8=",
"judge_type": "card", "options": None, "page_answer": "",
"subs": [{"stem": "10-6 =", "answer": "4"}]}
with mock.patch("backend.tencent_ocr.split_questions") as sp:
r = scanflow.recognize_block(Path("data/bench/raw/x.jpg"), block)
sp.assert_not_called()
self.assertEqual(len(r["subs"]), 1)