Files
cuotibiye/tests/test_textin.py
T

165 lines
6.2 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.
# -*- 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
TMP_ROOT = Path(__file__).resolve().parent / "_tmp_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()