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
+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)