Files
cuotibiye/tests/test_scan_flow.py
T

277 lines
13 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""整页拍 → 点选 → 入库(scanflow)的单元测试。
腾讯云不在这里真调:把它 mock 成固定返回,只验证我们自己的逻辑——
框过滤、只入库选中的块、空 picks 报错、草稿不存在报错。
"""
import json
import unittest
from pathlib import Path
from unittest import mock
from backend import db as dbm
from backend import scanflow, services as svc
from backend.services import ApiError
from ._tmpdir import workdir
# 1 张 200x300 的纯色图就够了,识别被 mock 掉
def _png_bytes(w=200, h=300):
from PIL import Image
import io
buf = io.BytesIO()
Image.new("RGB", (w, h), (250, 250, 250)).save(buf, "PNG")
return buf.getvalue(), f"t{w}.png"
def _fake_split(image, *a, **kw):
return {
"ok": True,
"questions": [
{
"stem": "1. 计算:36 + 47 =()",
"judge_type": "calc",
"detected_as": "calc",
"answer": "83",
"page_answer": None,
"options": None,
"box": {"x": 10, "y": 10, "w": 160, "h": 60},
},
{
"stem": "2. 一个长方形长 8 厘米,宽 5 厘米,面积是多少?",
"judge_type": "manual",
"detected_as": "manual",
"answer": None,
"page_answer": "40 平方厘米",
"options": None,
"box": {"x": 10, "y": 90, "w": 160, "h": 60},
},
{
# 太小,应当被丢掉
"stem": "3. 边角料",
"judge_type": "manual",
"detected_as": "manual",
"answer": None,
"page_answer": None,
"options": None,
"box": {"x": 10, "y": 160, "w": 12, "h": 12},
},
],
}
class ScanFlowTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.dir = workdir("scanflow")
cls.db = cls.dir / "scan.db"
def setUp(self):
if self.db.exists():
self.db.unlink()
self.conn = dbm.connect(self.db)
dbm.init_db(self.conn)
lg = svc.login(self.conn, "demo")
self.gid = lg["guardian_id"]
svc.give_consent(self.conn, self.gid, "v1")
self.cid = svc.create_child(self.conn, self.gid, "小满", 5)["id"]
def tearDown(self):
self.conn.close()
def _detect(self):
raw, name = _png_bytes()
with mock.patch.object(scanflow.tencent_ocr, "split_questions", _fake_split):
return scanflow.detect(raw, name)
def test_detect_drops_tiny_block(self):
d = self._detect()
self.assertEqual(len(d["blocks"]), 2, "12x12 的小框应当被过滤")
self.assertEqual(d["width"], 200)
self.assertTrue(all(b["box"]["w"] >= scanflow.MIN_BOX_SIDE for b in d["blocks"]))
meta = Path(scanflow.DRAFT_DIR) / f"{d['draft_id']}.json"
self.assertTrue(meta.exists())
def test_import_only_picked(self):
d = self._detect()
with mock.patch.object(scanflow.tencent_ocr, "split_questions", _fake_split):
paper = svc.import_scan_picks(
self.conn, self.gid, self.cid, "math", d["draft_id"], [1]
)
self.assertEqual(len(paper["questions"]), 1)
q = paper["questions"][0]
self.assertIn("长方形", q["stem"])
self.assertEqual(paper["ocr"]["picked"], 1)
# 入库即「观察中」:今天不复习,明天才进队列
rows = self.conn.execute(
"SELECT stem, status FROM mistakes WHERE child_id=?", (self.cid,)
).fetchall()
self.assertEqual(len(rows), 1)
self.assertEqual(rows[0]["status"], "observing")
self.assertIn("长方形", rows[0]["stem"])
self.assertEqual(svc.today_queue(self.conn, self.gid, self.cid)["items"], [])
def test_empty_picks_rejected(self):
d = self._detect()
with self.assertRaises(ApiError) as ctx:
svc.import_scan_picks(self.conn, self.gid, self.cid, "math", d["draft_id"], [])
self.assertEqual(ctx.exception.status, 400)
self.assertEqual(ctx.exception.code, "NO_PICKS")
def test_unknown_draft(self):
with self.assertRaises(ApiError) as ctx:
svc.import_scan_picks(self.conn, self.gid, self.cid, "math", "deadbeefdeadbeef", [0])
self.assertEqual(ctx.exception.status, 404)
self.assertEqual(ctx.exception.code, "DRAFT_NOT_FOUND")
def test_picks_out_of_range_ignored(self):
d = self._detect()
with self.assertRaises(ApiError) as ctx:
svc.import_scan_picks(self.conn, self.gid, self.cid, "math", d["draft_id"], [9, 10])
self.assertEqual(ctx.exception.code, "NO_PICKS")
def test_multi_question_block_expands(self):
"""勾一块竖式区(6 行),应当入库 6 道,不是 1 道。"""
d = self._detect()
subs = [{"stem": f"{e} =", "answer": a, "judge_type": "calc"}
for e, a in [("1.8+0.6", "2.4"), ("6.5-2.9", "3.6"), ("40×65", "2600")]]
block = d["blocks"][0]
with mock.patch.object(
scanflow, "recognize_block",
return_value={"stem": "1.8+0.6\n6.5-2.9\n40×65", "judge_type": "card",
"options": None, "answer": None, "page_answer": None,
"source": "page", "subs": subs},
):
paper = svc.import_scan_picks(
self.conn, self.gid, self.cid, "math", d["draft_id"], [block["i"]]
)
self.assertEqual(len(paper["questions"]), 3)
self.assertEqual(paper["ocr"]["picked"], 1, "调用方勾的是 1 块")
got = [r["stem"] for r in self.conn.execute(
"SELECT stem FROM mistakes WHERE child_id=? ORDER BY id", (self.cid,))]
self.assertEqual(len(got), 3)
self.assertTrue(any("40×65" in s for s in got))
def test_prepare_lists_every_sub(self):
"""入库前预览:一块三道的口算卡要摊成 3 条,且带上 block/sub 坐标。"""
d = self._detect()
subs = [{"stem": f"{e} =", "answer": a, "judge_type": "calc"}
for e, a in [("34+25", "59"), ("78-25", "53"), ("27+69", "96")]]
with mock.patch.object(scanflow, "recognize_block",
return_value={"stem": "34+25= 78-25= 27+69=", "judge_type": "card",
"options": None, "answer": None, "page_answer": None,
"source": "page", "subs": subs}):
pv = svc.prepare_scan_picks(
self.conn, self.gid, self.cid, "math", d["draft_id"], [d["blocks"][0]["i"]])
self.assertEqual(len(pv["items"]), 3)
self.assertEqual([it["sub"] for it in pv["items"]], [0, 1, 2])
self.assertTrue(all(it["block"] == d["blocks"][0]["i"] for it in pv["items"]))
# 预览只读:预览完库里还是空的
n = self.conn.execute("SELECT COUNT(*) FROM questions").fetchone()[0]
self.assertEqual(n, 0)
def test_import_only_checked_subs(self):
"""逐条勾选:5 道口算里只勾第 0、2 道,就只入库这 2 道。"""
d = self._detect()
subs = [{"stem": f"{e} =", "answer": a, "judge_type": "calc"}
for e, a in [("34+25", "59"), ("78-25", "53"), ("27+69", "96"),
("77+69", "146"), ("90-49", "41")]]
bi = d["blocks"][0]["i"]
with mock.patch.object(scanflow, "recognize_block",
return_value={"stem": "口算卡", "judge_type": "card",
"options": None, "answer": None, "page_answer": None,
"source": "page", "subs": subs}):
paper = svc.import_scan_picks(
self.conn, self.gid, self.cid, "math", d["draft_id"],
[{"i": bi, "subs": [0, 2]}])
self.assertEqual(len(paper["questions"]), 2)
got = [r["stem"] for r in self.conn.execute(
"SELECT stem FROM mistakes WHERE child_id=? ORDER BY id", (self.cid,))]
self.assertEqual(len(got), 2)
self.assertTrue(any("34+25" in s for s in got))
self.assertTrue(any("27+69" in s for s in got))
self.assertFalse(any("77+69" in s for s in got), "没勾的(读歪那条)不该入库")
def test_import_empty_sub_list_falls_back_to_nothing(self):
"""subs 全取消:这块就不该入库,不能退化成「整块都要」。"""
d = self._detect()
subs = [{"stem": "1+1 =", "answer": "2", "judge_type": "calc"},
{"stem": "2+2 =", "answer": "4", "judge_type": "calc"}]
bi = d["blocks"][0]["i"]
with mock.patch.object(scanflow, "recognize_block",
return_value={"stem": "x", "judge_type": "card", "options": None,
"answer": None, "page_answer": None,
"source": "page", "subs": subs}):
with self.assertRaises(ApiError) as ctx:
svc.import_scan_picks(self.conn, self.gid, self.cid, "math",
d["draft_id"], [{"i": bi, "subs": []}])
self.assertEqual(ctx.exception.code, "NO_PICKS")
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_rechecks_and_takes_more(self):
"""口算卡会被整块读歪(27+69 读成 77+69):勾到它时裁出来重读,题更多就信裁剪版。"""
from backend import scanflow
block = {"i": 0, "box": {"x": 1, "y": 1, "w": 300, "h": 300}, "stem": "34+25= 78-25= 77+69=",
"judge_type": "card", "options": None, "page_answer": "",
"subs": [{"stem": "34+25 =", "answer": "59"},
{"stem": "77+69 =", "answer": "146"}]}
with mock.patch("backend.scanflow._crop_bytes", return_value=b"jpg"), \
mock.patch("backend.tencent_ocr.split_questions", return_value={"ok": True, "questions": [
{"stem": "34+25=\n78-25=\n27+69=", "judge_type": "card",
"subs": [{"stem": "34+25 =", "answer": "59"},
{"stem": "78-25 =", "answer": "53"},
{"stem": "27+69 =", "answer": "96"}]}]}):
r = scanflow.recognize_block(Path("data/bench/raw/x.jpg"), block)
stems = [s["stem"] for s in r["subs"]]
self.assertEqual(r["source"], "crop_card")
self.assertIn("27+69 =", stems, "裁剪版读对的那道要进来")
self.assertIn("78-25 =", stems, "整页版吞掉的行也要补回来")
self.assertEqual(len(stems), 4, "宁多不漏:读歪的那条也留着,等逐条勾选再收拾")
def test_card_falls_back_when_crop_is_worse(self):
from backend import scanflow
block = {"i": 0, "box": {"x": 1, "y": 1, "w": 300, "h": 300}, "stem": "a",
"judge_type": "card", "options": None, "page_answer": "",
"subs": [{"stem": "1+1 =", "answer": "2"}, {"stem": "2+2 =", "answer": "4"}]}
with mock.patch("backend.scanflow._crop_bytes", return_value=b"jpg"), \
mock.patch("backend.tencent_ocr.split_questions",
return_value={"ok": False, "code": "X"}):
r = scanflow.recognize_block(Path("data/bench/raw/x.jpg"), block)
self.assertEqual(r["source"], "page")
self.assertEqual(len(r["subs"]), 2)