Files
cuotibiye/tests/test_ocr_http.py
T

137 lines
4.8 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 -*-
"""HTTP OCR 后端:用一个本地假服务验证「接外部 OCR」这条路。
Linux 服务器上没有 Windows OCR,部署时必须靠 OCR_HTTP_URL;这里不测真实服务,
只测协议约定与失败退回,保证换任何一家 OCR 都不会把接口打崩。
"""
import io
import json
import shutil
import uuid
import os
import sys
import tempfile
import threading
import unittest
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(Path(__file__).resolve().parent))
from _tmpdir import workdir as _workdir # noqa: E402
sys.path.insert(0, str(ROOT))
from backend import db, ocr, services # noqa: E402
LINES = [
"1.计算:36 + 47 =( )",
"2.用竖式计算:72 - 38 =( )",
]
class _Stub(BaseHTTPRequestHandler):
fail = False
def do_POST(self): # noqa: N802
n = int(self.headers.get("Content-Length") or 0)
body = json.loads(self.rfile.read(n) or b"{}")
assert body.get("image_b64"), "应该带图片 base64"
if _Stub.fail:
self.send_response(500)
self.end_headers()
self.wfile.write(b"boom")
return
payload = {"ok": True, "lang": "zh-Hans", "width": 1000, "height": 1400,
"lines": [{"text": t, "x": 0, "y": i * 40, "w": 900, "h": 32}
for i, t in enumerate(LINES)]}
raw = json.dumps(payload).encode("utf-8")
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(raw)))
self.end_headers()
self.wfile.write(raw)
def log_message(self, *a): # 静音
pass
def _png() -> bytes:
from PIL import Image
im = Image.new("RGB", (900, 300), "white")
buf = io.BytesIO()
im.save(buf, format="PNG")
return buf.getvalue()
class HttpOcrTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.srv = ThreadingHTTPServer(("127.0.0.1", 0), _Stub)
cls.port = cls.srv.server_address[1]
threading.Thread(target=cls.srv.serve_forever, daemon=True).start()
@classmethod
def tearDownClass(cls):
cls.srv.shutdown()
def setUp(self):
self._env = os.environ.get("OCR_HTTP_URL")
os.environ["OCR_HTTP_URL"] = f"http://127.0.0.1:{self.port}/ocr"
os.environ.pop("OCR_HTTP_KEY", None)
_Stub.fail = False
self.work = _workdir("ocr_http") / uuid.uuid4().hex[:8]
self.work.mkdir(parents=True, exist_ok=True)
self.img = self.work / "page.png"
self.img.write_bytes(_png())
self.conn = db.connect(str(self.work / "t.db"))
db.init_db(self.conn)
def tearDown(self):
self.conn.close()
shutil.rmtree(self.work, ignore_errors=True)
if self._env is None:
os.environ.pop("OCR_HTTP_URL", None)
else:
os.environ["OCR_HTTP_URL"] = self._env
def test_available_true(self):
self.assertTrue(ocr.available())
def test_recognize_returns_tidied_lines(self):
r = ocr.recognize(self.img)
self.assertTrue(r["ok"], r)
self.assertEqual(len(r["lines"]), 2)
self.assertIn("36 + 47", r["lines"][0]["text"])
self.assertEqual(r["width"], 1000)
def test_service_cuts_questions_from_http_ocr(self):
g = services.login(self.conn, "demo")["guardian_id"]
services.give_consent(self.conn, g, "v1")
child = services.create_child(self.conn, g, "皮皮", 2)["id"]
paper = services.create_paper_from_image(
self.conn, g, child, "math", _png(), filename="page.png", fallback_demo=False)
self.assertEqual(paper["source"], "ocr")
self.assertGreaterEqual(len(paper["questions"]), 2)
stems = " ".join(q["stem"] for q in paper["questions"])
self.assertIn("36 + 47", stems)
def test_http_error_marks_failed(self):
_Stub.fail = True
r = ocr.recognize(self.img)
self.assertFalse(r["ok"])
self.assertIn(r["error"]["code"], ("OCR_HTTP_FAILED", "OCR_READ_FAILED"))
def test_no_fallback_raises_ocr_http_failed(self):
_Stub.fail = True
g = services.login(self.conn, "demo")["guardian_id"]
services.give_consent(self.conn, g, "v1")
child = services.create_child(self.conn, g, "皮皮", 2)["id"]
with self.assertRaises(services.ApiError) as ctx:
services.create_paper_from_image(self.conn, g, child, "math", _png(),
filename="page.png", fallback_demo=False)
self.assertEqual(ctx.exception.code, "OCR_HTTP_FAILED")
if __name__ == "__main__":
unittest.main()