ocr: 用腾讯云 QuestionSplitOCR 替换 TextIn 擦除

- 新增 backend/tencent_ocr.py(TC3 签名 + 结果解析,零依赖)
- create_paper_from_image 改为 腾讯 -> 本机 OCR+正则 -> 演示题库 三级兜底
- 删掉 TextIn 客户端、擦除页路由 /api/papers/{pid}/clean 与相关测试
- 新增 tests/test_tencent_ocr.py(13 例,全打桩);单测 114 例、冒烟 39 项全过
This commit is contained in:
dsh
2026-11-18 20:57:45 +08:00
parent 05347e04f8
commit c1cce198fd
12 changed files with 515 additions and 417 deletions
+171
View File
@@ -0,0 +1,171 @@
# -*- coding: utf-8 -*-
"""腾讯云「试卷切题」的解析与调用(全部打桩,不花钱、不联网)。"""
import unittest
from pathlib import Path
import sys
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))
from tests._tmpdir import workdir # noqa: E402
from backend import tencent_ocr as tq # noqa: E402
WORK = workdir("tencent")
def fake_resp(items):
"""造一份 QuestionSplitOCR 的 Response。"""
return {"QuestionInfo": [{"ResultList": items}], "RequestId": "req-1"}
class ParseTest(unittest.TestCase):
def test_choice_question(self):
resp = fake_resp([{
"Question": [{"Index": 0, "Text": "下面加点字读音正确的是( )"}],
"Option": [
{"Index": 1, "Text": "A.快乐(lè)"},
{"Index": 2, "Text": "B.音乐(yuè)"},
{"Index": 3, "Text": "C.长大(cháng)"},
{"Index": 4, "Text": "D.银行(háng)"},
],
"Answer": [{"Text": "答案:B"}],
"GroupType": "multiple-choice",
}])
qs = tq.parse(resp)
self.assertEqual(len(qs), 1)
q = qs[0]
self.assertEqual(q["judge_type"], "choice")
self.assertEqual(q["answer"], "B")
self.assertEqual(q["options"], ["快乐(lè)", "音乐(yuè)", "长大(cháng)", "银行(háng)"])
self.assertIn("读音", q["stem"])
def test_calc_question(self):
resp = fake_resp([{
"Question": [{"Index": 0, "Text": "1.计算:36 + 47 ="}],
"Answer": [{"Text": "83"}],
}])
q = tq.parse(resp)[0]
self.assertEqual(q["judge_type"], "calc")
self.assertEqual(q["answer"], "83")
self.assertIsNone(q["options"])
def test_manual_when_no_answer(self):
resp = fake_resp([{
"Question": [{"Index": 0, "Text": "4.用一个成语形容秋天的景色。"}],
"Answer": [],
}])
q = tq.parse(resp)[0]
self.assertEqual(q["judge_type"], "manual")
self.assertIsNone(q["answer"])
def test_multi_part_stem_joined_in_index_order(self):
resp = fake_resp([{
"Question": [{"Index": 1, "Text": "(2)再算十位。"},
{"Index": 0, "Text": "(1)先算个位;"}],
"Answer": [{"Text": "答案:4"}],
}])
q = tq.parse(resp)[0]
self.assertTrue(q["stem"].startswith("(1)先算个位;"), q["stem"])
self.assertEqual(q["answer"], "4")
def test_choice_answer_outside_options_dropped(self):
resp = fake_resp([{
"Question": [{"Index": 0, "Text": "选一个"}],
"Option": [{"Text": "A.甲"}, {"Text": "B.乙"}],
"Answer": [{"Text": "答案:D"}],
}])
q = tq.parse(resp)[0]
self.assertEqual(q["judge_type"], "choice")
self.assertIsNone(q["answer"]) # D 不在 A/B 里,不能瞎认
def test_empty_or_bad_payload(self):
self.assertEqual(tq.parse({}), [])
self.assertEqual(tq.parse({"QuestionInfo": None}), [])
self.assertEqual(tq.parse({"QuestionInfo": [{"ResultList": [{"Question": []}]}]}), [])
class SignTest(unittest.TestCase):
def setUp(self):
self._id, self._key = tq.secret_id, tq.secret_key
tq.secret_id = lambda: "AKIDEXAMPLE"
tq.secret_key = lambda: "SECRETEXAMPLE"
def tearDown(self):
tq.secret_id, tq.secret_key = self._id, self._key
def test_signature_shape_and_determinism(self):
body = b'{"ImageBase64":"abc"}'
a = tq._sign(body, 1700000000)
b = tq._sign(body, 1700000000)
self.assertEqual(a, b)
self.assertTrue(a.startswith("TC3-HMAC-SHA256 Credential=AKIDEXAMPLE/2023-11-14/ocr/tc3_request"))
self.assertIn("SignedHeaders=content-type;host", a)
self.assertIn("Signature=", a)
def test_signature_changes_with_body(self):
self.assertNotEqual(tq._sign(b'{"a":1}', 1700000000), tq._sign(b'{"a":2}', 1700000000))
class SplitTest(unittest.TestCase):
def setUp(self):
self._post = tq._post
self._avail = tq.available
tq.available = lambda: True
def tearDown(self):
tq._post = self._post
tq.available = self._avail
def test_split_ok(self):
tq._post = lambda payload, timeout=25: {
"ok": True, "request_id": "r1",
"data": fake_resp([{
"Question": [{"Text": "2.计算:72 - 38 ="}],
"Answer": [{"Text": "34"}],
}]),
}
r = tq.split_questions(b"img")
self.assertTrue(r["ok"])
self.assertEqual(r["questions"][0]["answer"], "34")
self.assertEqual(r["request_id"], "r1")
def test_split_api_error(self):
tq._post = lambda payload, timeout=25: {
"ok": False, "code": "TENCENT_FailedOperation.UnOpenError",
"message": "服务未开通", "request_id": "r2",
}
r = tq.split_questions(b"img")
self.assertFalse(r["ok"])
self.assertEqual(r["code"], "TENCENT_FailedOperation.UnOpenError")
self.assertEqual(r["questions"], [])
def test_empty_image_short_circuits(self):
called = []
tq._post = lambda payload, timeout=25: called.append(1) or {"ok": True, "data": {}}
r = tq.split_questions(b"")
self.assertFalse(r["ok"])
self.assertEqual(r["code"], "EMPTY_IMAGE")
self.assertEqual(called, [])
def test_post_without_credentials(self):
tq.available = lambda: False
r = tq._post({"x": 1})
self.assertFalse(r["ok"])
self.assertEqual(r["code"], "TENCENT_NOT_CONFIGURED")
def test_post_network_error_is_swallowed(self):
import urllib.request
self._open = urllib.request.urlopen
urllib.request.urlopen = lambda *a, **k: (_ for _ in ()).throw(OSError("no route"))
try:
r = tq._post({"x": 1})
finally:
urllib.request.urlopen = self._open
self.assertFalse(r["ok"])
self.assertEqual(r["code"], "TENCENT_UNREACHABLE")
if __name__ == "__main__":
unittest.main()