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:
@@ -64,7 +64,7 @@ try:
|
||||
|
||||
st, r = call("GET", "/api/health")
|
||||
check("health 200", st == 200, r)
|
||||
check("routes=57", r["data"]["routes"] == 57, r["data"].get("routes"))
|
||||
check("routes=57", r["data"]["routes"] == 56, r["data"].get("routes"))
|
||||
|
||||
st, r = call("POST", "/api/auth/sms-code", {"phone": "13800138000"})
|
||||
check("发码 200", st == 200 and r["data"]["sent"] is True, r)
|
||||
|
||||
@@ -63,7 +63,7 @@ try:
|
||||
|
||||
st, r = call("GET", "/api/health")
|
||||
check("health 200", st == 200, r)
|
||||
check("routes=57", r["data"]["routes"] == 57, r["data"].get("routes"))
|
||||
check("routes=57", r["data"]["routes"] == 56, r["data"].get("routes"))
|
||||
|
||||
st, r = call("POST", "/api/auth/wx-login", {"code": "demo"})
|
||||
tok = r["data"]["token"]
|
||||
|
||||
@@ -24,9 +24,13 @@ from backend import wechat # noqa: E402
|
||||
|
||||
class QueryTokenTest(unittest.TestCase):
|
||||
def test_link_endpoints_allow_query_token(self):
|
||||
for p in ("/api/export/csv", "/api/print/weekly", "/api/papers/p_1/clean"):
|
||||
for p in ("/api/export/csv", "/api/print/weekly"):
|
||||
self.assertTrue(appmod.query_token_ok(p), p)
|
||||
|
||||
def test_clean_endpoint_gone_with_textin(self):
|
||||
# 手写擦除(TextIn)已下线,这条链接不再接受 query 令牌
|
||||
self.assertFalse(appmod.query_token_ok("/api/papers/p_1/clean"))
|
||||
|
||||
def test_other_endpoints_reject_query_token(self):
|
||||
for p in ("/api/today", "/api/me", "/api/mistakes",
|
||||
"/api/export/csv2", "/api/papers/p_1", "/apipapers/x"):
|
||||
|
||||
@@ -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()
|
||||
@@ -1,168 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""TextIn 手写擦除:接口解析 + 接入拍照入库(全部本地打桩,不消耗额度)。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import io
|
||||
import os
|
||||
import shutil
|
||||
import unittest
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
from PIL import Image, ImageDraw
|
||||
|
||||
from backend import db as dbm
|
||||
from backend import services as svc
|
||||
from backend import textin
|
||||
|
||||
import sys
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
from _tmpdir import workdir as _workdir # noqa: E402
|
||||
|
||||
TMP_ROOT = _workdir("textin")
|
||||
|
||||
|
||||
def _paper_png(w=1600, h=1200, handwriting=True) -> bytes:
|
||||
im = Image.new("RGB", (w, h), "#FCFBF6")
|
||||
d = ImageDraw.Draw(im)
|
||||
d.text((60, 40), "1. 36 + 47 = ( )", fill="#111111")
|
||||
d.text((60, 160), "2. 72 - 38 = ( )", fill="#111111")
|
||||
if handwriting:
|
||||
d.text((520, 40), "83", fill="#27407A")
|
||||
buf = io.BytesIO()
|
||||
im.save(buf, format="PNG")
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
class TextinUnitTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self._old = {k: os.environ.get(k) for k in ("TEXTIN_APP_ID", "TEXTIN_SECRET_CODE")}
|
||||
os.environ["TEXTIN_APP_ID"] = "id"
|
||||
os.environ["TEXTIN_SECRET_CODE"] = "sec"
|
||||
|
||||
def tearDown(self):
|
||||
for k, v in self._old.items():
|
||||
if v is None:
|
||||
os.environ.pop(k, None)
|
||||
else:
|
||||
os.environ[k] = v
|
||||
|
||||
def test_mode_live(self):
|
||||
self.assertEqual(textin.mode(), "live")
|
||||
self.assertTrue(textin.available())
|
||||
|
||||
def test_erase_decodes_base64(self):
|
||||
png = _paper_png(300, 200)
|
||||
b64 = base64.b64encode(png).decode()
|
||||
|
||||
def fake(path, data, params=None, timeout=30):
|
||||
self.assertEqual(path, textin.P_ERASE)
|
||||
self.assertEqual(params["image_type"], 1)
|
||||
return {"ok": True, "data": {"image": b64}, "ms": 12}
|
||||
|
||||
old = textin._request
|
||||
textin._request = fake
|
||||
try:
|
||||
r = textin.erase_handwriting(b"x")
|
||||
finally:
|
||||
textin._request = old
|
||||
self.assertTrue(r["ok"])
|
||||
self.assertEqual(r["image"], png)
|
||||
self.assertEqual(r["ms"], 12)
|
||||
|
||||
def test_erase_surfaces_error(self):
|
||||
old = textin._request
|
||||
textin._request = lambda *a, **k: {"ok": False, "code": "TEXTIN_40003", "message": "余额不足"}
|
||||
try:
|
||||
r = textin.erase_handwriting(b"x")
|
||||
finally:
|
||||
textin._request = old
|
||||
self.assertFalse(r["ok"])
|
||||
self.assertEqual(r["code"], "TEXTIN_40003")
|
||||
self.assertIn("余额", r["message"])
|
||||
|
||||
|
||||
class EraseInPipelineTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
TMP_ROOT.mkdir(parents=True, exist_ok=True)
|
||||
self.dir = TMP_ROOT / uuid.uuid4().hex[:8]
|
||||
self.dir.mkdir(parents=True, exist_ok=True)
|
||||
self.conn = dbm.connect(self.dir / "t.db")
|
||||
dbm.init_db(self.conn)
|
||||
g = svc.login(self.conn, "demo")
|
||||
self.gid = g["guardian_id"]
|
||||
svc.give_consent(self.conn, self.gid, "v1")
|
||||
child = svc.create_child(self.conn, self.gid, "皮皮", 2)
|
||||
self.cid = child["id"]
|
||||
self._upload = svc.UPLOAD_DIR
|
||||
svc.UPLOAD_DIR = self.dir / "uploads"
|
||||
self._avail = textin.available
|
||||
self._erase = textin.erase_handwriting
|
||||
self._recognize = svc.ocr.recognize
|
||||
|
||||
def tearDown(self):
|
||||
svc.UPLOAD_DIR = self._upload
|
||||
textin.available = self._avail
|
||||
textin.erase_handwriting = self._erase
|
||||
svc.ocr.recognize = self._recognize
|
||||
try:
|
||||
self.conn.close()
|
||||
except Exception:
|
||||
pass
|
||||
shutil.rmtree(self.dir, ignore_errors=True)
|
||||
|
||||
def _stub_ocr(self, lines):
|
||||
svc.ocr.recognize = lambda path: {
|
||||
"ok": True, "lines": lines, "lang": "zh-Hans",
|
||||
"width": 1600, "height": 1200, "ocr_width": 1600, "scaled": 1.0,
|
||||
}
|
||||
|
||||
def test_erase_runs_and_saves_clean_page(self):
|
||||
textin.available = lambda: True
|
||||
textin.erase_handwriting = lambda data, **kw: {
|
||||
"ok": True, "image": _paper_png(1200, 900, handwriting=False), "ms": 700, "bytes": 1234,
|
||||
}
|
||||
self._stub_ocr([
|
||||
{"text": "1. 36 + 47 = ( )", "x": 60, "y": 40, "w": 400, "h": 34},
|
||||
{"text": "2. 72 - 38 = ( )", "x": 60, "y": 160, "w": 400, "h": 34},
|
||||
])
|
||||
p = svc.create_paper_from_image(self.conn, self.gid, self.cid, "math",
|
||||
_paper_png(1600, 1200), "page.png", fallback_demo=False)
|
||||
self.assertEqual(p["source"], "ocr")
|
||||
self.assertTrue(p["erase"]["used"])
|
||||
self.assertTrue(p["erase"]["ok"])
|
||||
self.assertIn("clean_url", p)
|
||||
row = self.conn.execute("SELECT clean_path FROM papers WHERE id=?", (p["paper"]["id"],)).fetchone()
|
||||
self.assertTrue(row["clean_path"].endswith("_clean.jpg"))
|
||||
clean_file = svc.UPLOAD_DIR / self.cid / f'{p["paper"]["id"]}_clean.jpg'
|
||||
self.assertTrue(clean_file.exists(), f"没落盘:{clean_file}")
|
||||
|
||||
def test_small_image_skips_erase(self):
|
||||
textin.available = lambda: True
|
||||
textin.erase_handwriting = lambda *a, **k: self.fail("小图不该调用擦除")
|
||||
self._stub_ocr([{"text": "1. 36 + 47 = ( )", "x": 10, "y": 10, "w": 300, "h": 12}])
|
||||
p = svc.create_paper_from_image(self.conn, self.gid, self.cid, "math",
|
||||
_paper_png(800, 600), "page.png", fallback_demo=False)
|
||||
self.assertFalse(p["erase"]["used"])
|
||||
self.assertIn("短边", p["erase"]["reason"])
|
||||
self.assertNotIn("clean_url", p)
|
||||
|
||||
def test_erase_failure_leaves_paper_usable(self):
|
||||
textin.available = lambda: True
|
||||
textin.erase_handwriting = lambda *a, **k: {"ok": False, "code": "TEXTIN_40003", "message": "余额不足"}
|
||||
self._stub_ocr([
|
||||
{"text": "1. 36 + 47 = ( )", "x": 60, "y": 40, "w": 400, "h": 34},
|
||||
{"text": "2. 72 - 38 = ( )", "x": 60, "y": 160, "w": 400, "h": 34},
|
||||
])
|
||||
p = svc.create_paper_from_image(self.conn, self.gid, self.cid, "math",
|
||||
_paper_png(1600, 1200), "page.png", fallback_demo=False)
|
||||
self.assertEqual(p["source"], "ocr") # 擦除失败不影响入库
|
||||
self.assertFalse(p["erase"]["ok"])
|
||||
self.assertEqual(p["erase"]["reason"], "余额不足")
|
||||
self.assertNotIn("clean_url", p)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user