# -*- coding: utf-8 -*- """拍照识题的测试:OCR 文本清洗、切题、以及 OCR 不可用时的退路。 不依赖真机 OCR:验证「没装语言包 / 图糊」时行为是否诚实(要么退演示题库,要么明确报错)。 真机 OCR 的连通性用 `python -m backend.ocr_check 图片路径` 手动验(见 backend/ocr.py)。 """ from __future__ import annotations import sys import unittest from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) sys.path.insert(0, str(Path(__file__).resolve().parent)) # tests/ 自己 from _tmpdir import workdir as _workdir # noqa: E402 from backend import cut, ocr # noqa: E402 from backend import db as dbm # noqa: E402 from backend import services as svc # noqa: E402 def line(text, y=0): return {"text": text, "x": 0, "y": y, "w": 100, "h": 20} class TidyTest(unittest.TestCase): def test_cjk_spaces_removed(self): self.assertEqual(ocr.tidy("1 . 计 算 : 36 + 47 = ( )"), "1.计算:36 + 47 =()") def test_ascii_spaces_kept(self): self.assertEqual(ocr.tidy("72 - 38 = 34"), "72 - 38 = 34") def test_empty(self): self.assertEqual(ocr.tidy(" "), "") self.assertEqual(ocr.tidy(" "), "") # 全角空格 class SegmentTest(unittest.TestCase): LINES = [ line("姓名:皮皮 班级:二年级三班", 0), line("1 . 计 算 : 36 + 47 = ( )", 30), line("2 . 用 竖 式 计 算 : 72 一 38 = ( )", 80), line("3 . 一 个 长 方 形 长 8 厘 米 , 宽 5 厘 米 , 面 积 是 多 少 ?", 130), line("4 . 看 拼 音 写 词 : x i ó n g m ā o ( )", 180), ] def test_count_and_seq(self): qs = cut.segment([{**l, "text": ocr.tidy(l["text"])} for l in self.LINES], "math") self.assertEqual([q["seq"] for q in qs], [1, 2, 3, 4]) def test_drop_header(self): qs = cut.segment([{**l, "text": ocr.tidy(l["text"])} for l in self.LINES], "math") self.assertFalse(any("姓名" in q["stem"] for q in qs)) def test_answers_computed(self): qs = cut.segment([{**l, "text": ocr.tidy(l["text"])} for l in self.LINES], "math") self.assertEqual(qs[0]["answer"], "83") self.assertEqual(qs[0]["judge_type"], "calc") # OCR 把减号认成一,也要能算对,并且题干显示成减号 self.assertEqual(qs[1]["answer"], "34") self.assertIn("72-38", qs[1]["stem"]) def test_manual_for_word_problems(self): qs = cut.segment([{**l, "text": ocr.tidy(l["text"])} for l in self.LINES], "math") self.assertIsNone(qs[2]["answer"]) self.assertEqual(qs[2]["judge_type"], "manual") self.assertEqual(qs[3]["subject"], "chinese") def test_section_header_not_a_question(self): qs = cut.segment([line("一、填空"), line("1.3 + 4 =( )")], "math") self.assertEqual(len(qs), 1) self.assertEqual(qs[0]["answer"], "7") def test_no_number_no_question(self): self.assertEqual(cut.segment([line("今天作业"), line("自己抄题")], "math"), []) class FallbackTest(unittest.TestCase): def setUp(self): self.tmpdir = _workdir("shared") self.tmpdir.mkdir(exist_ok=True) self.path = self.tmpdir / f"t_ocr_{id(self)}.db" self.conn = dbm.connect(self.path) dbm.init_db(self.conn) self.login = svc.login(self.conn, "demo") self.gid = self.login["guardian_id"] svc.give_consent(self.conn, self.gid, "v1") self.child = svc.create_child(self.conn, self.gid, "小测", 3, ["math", "chinese"], "19:30") self.cid = self.child["id"] self._orig = svc.ocr.recognize def tearDown(self): svc.ocr.recognize = self._orig self.conn.close() for suffix in ("", "-wal", "-shm"): f = Path(str(self.path) + suffix) if f.exists(): try: f.unlink() except OSError: pass def test_ocr_down_falls_back_to_demo(self): svc.ocr.recognize = lambda p: {"ok": False, "lines": [], "error": {"code": "NO_ENGINE", "message": "没有语言包"}} paper = svc.create_paper_from_image(self.conn, self.gid, self.cid, "math", b"fake-jpeg", fallback_demo=True) self.assertEqual(paper["source"], "demo") self.assertEqual(paper["ocr"]["reason"], "没有语言包") self.assertTrue(paper["questions"]) def test_ocr_down_and_no_fallback_raises(self): svc.ocr.recognize = lambda p: {"ok": False, "lines": [], "error": {"code": "NO_ENGINE", "message": "没有语言包"}} with self.assertRaises(svc.ApiError) as ctx: svc.create_paper_from_image(self.conn, self.gid, self.cid, "math", b"fake-jpeg", fallback_demo=False) self.assertEqual(ctx.exception.code, "NO_ENGINE") # 把 OCR 自己的错码透出去,前端好判断 def test_ocr_ok_creates_real_questions(self): lines = [{"text": t, "x": 0, "y": i * 40, "w": 10, "h": 20} for i, t in enumerate(["1.36 + 47 =( )", "2.一个长方形长 8 厘米,宽 5 厘米,面积是多少?"])] svc.ocr.recognize = lambda p: {"ok": True, "lines": lines, "lang": "zh-Hans-CN"} paper = svc.create_paper_from_image(self.conn, self.gid, self.cid, "math", b"fake-jpeg") self.assertEqual(paper["source"], "ocr") self.assertEqual(len(paper["questions"]), 2) self.assertEqual(paper["questions"][0]["answer"], "83") self.assertEqual(paper["questions"][1]["judge_type"], "manual") def test_self_judge_moves_state(self): svc.ocr.recognize = lambda p: {"ok": True, "lines": [{"text": "1.36 + 47 =( )", "x": 0, "y": 0, "w": 1, "h": 1}], "lang": "zh-Hans-CN"} paper = svc.create_paper_from_image(self.conn, self.gid, self.cid, "math", b"fake-jpeg") qid = paper["questions"][0]["id"] imp = svc.import_mistakes(self.conn, self.gid, self.cid, [qid]) mid = imp["created"][0]["mistake_id"] r = svc.self_judge(self.conn, self.gid, self.cid, mid, True) self.assertTrue(r["correct"]) self.assertIn(r["status"], ("careless", "queued", "recalled")) with self.assertRaises(svc.ApiError): svc.self_judge(self.conn, self.gid, self.cid, mid, True) # 已离开队列 class SmallImageTest(FallbackTest): """短边 <1200 的图:先警告,别假装认得准。""" def _tiny_jpeg(self): try: import io from PIL import Image except Exception: self.skipTest("没有 PIL") buf = io.BytesIO() Image.new("RGB", (400, 520), "white").save(buf, "JPEG") return buf.getvalue() def test_small_image_sets_warn(self): svc.ocr.recognize = lambda p: {"ok": True, "width": 400, "height": 520, "ocr_width": 400, "lines": [{"text": "1.36 + 47 =( )", "x": 0, "y": 0, "w": 9, "h": 12}], "lang": "zh-Hans-CN"} paper = svc.create_paper_from_image(self.conn, self.gid, self.cid, "math", self._tiny_jpeg()) self.assertTrue(paper["too_small"]) self.assertIn("短边不到", paper["ocr"]["warn"]) self.assertEqual(paper["ocr"]["size"], {"w": 400, "h": 520}) def test_big_image_no_warn(self): svc.ocr.recognize = lambda p: {"ok": True, "width": 2000, "height": 3000, "ocr_width": 2000, "lines": [{"text": "1.36 + 47 =( )", "x": 0, "y": 0, "w": 9, "h": 40}], "lang": "zh-Hans-CN"} try: import io from PIL import Image buf = io.BytesIO() Image.new("RGB", (1600, 2000), "white").save(buf, "JPEG") data = buf.getvalue() except Exception: self.skipTest("没有 PIL") paper = svc.create_paper_from_image(self.conn, self.gid, self.cid, "math", data) self.assertFalse(paper["too_small"]) self.assertEqual(paper["ocr"]["warn"], "") def test_demo_fallback_keeps_warn(self): svc.ocr.recognize = lambda p: {"ok": False, "lines": [], "error": {"code": "OCR_NOISY", "message": "糊"}} paper = svc.create_paper_from_image(self.conn, self.gid, self.cid, "math", self._tiny_jpeg(), fallback_demo=True) self.assertEqual(paper["source"], "demo") self.assertTrue(paper["too_small"]) self.assertIn("短边不到", paper["ocr"]["warn"]) if __name__ == "__main__": unittest.main()