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
+69 -60
View File
@@ -19,7 +19,7 @@ from contextlib import contextmanager
from datetime import date, datetime, timedelta
from pathlib import Path
from . import content, cut, judging, ocr, practice, scheduler, textin, wechat
from . import content, cut, judging, ocr, practice, scheduler, tencent_ocr, wechat
from .db import TZ, add_days, connect, log_event, new_id, now, row_to_dict, rows_to_list, today
CONSENT_VERSION = "v1"
@@ -1400,15 +1400,18 @@ def sweep_uploads(conn, days: int = 90) -> int:
return cleanup_uploads(conn, days=days)
ERASE_MIN_SIDE = 1200 # 短边不到这个尺寸就不擦:擦除会把印刷字也糊掉
MIN_SIDE_WARN = 1200 # 短边不到这个尺寸,一行字就没几个像素,认错很正常
def create_paper_from_image(conn, gid: str, cid: str, subject: str, image_bytes: bytes,
filename: str = "page.jpg", fallback_demo: bool = True) -> dict:
"""真拍照:存原图 → Windows OCR → 切成题 → 入库成一张卷子。
"""真拍照:存原图 → 切题 → 入库成一张卷子。
OCR 不可用(没装中文语言包/图片糊)时,如果 fallback_demo=True 就退回内置题库,
并在返回里写清 source="demo" 与原因——不假装识别成功。
切题优先用腾讯云「试卷切题」(QuestionSplitOCR):它一次给「一题一块」,
题干/选项/答案分区都带坐标,不用我们再按题号猜。
没配凭据或调用失败时,退到本机 Windows OCR + cut.segment;
再不行(图糊、认不出)且 fallback_demo=True,才退回内置题库,
并在返回里写清 source 与原因——不假装识别成功。
"""
require_active(conn, gid)
child = get_child(conn, gid, cid)
@@ -1421,7 +1424,7 @@ def create_paper_from_image(conn, gid: str, cid: str, subject: str, image_bytes:
if len(image_bytes) > 12 * 1024 * 1024:
raise ApiError(413, "IMAGE_TOO_LARGE", "图片太大了(上限 12MB),压缩一下再传")
# 先量一下原图:后面擦除要不要做、以及「这张图到底能不能认」都看它。
# 量一下原图尺寸:只用来提示「这张图太小」,不影响切题走哪条路。
img_w = img_h = 0
try:
from PIL import Image as _Img
@@ -1434,8 +1437,8 @@ def create_paper_from_image(conn, gid: str, cid: str, subject: str, image_bytes:
# 短边不到 1200 就别指望认得多准:微信转发会把长边压到 400,
# 一行字只剩 10 来像素,任何 OCR 都救不回来。与其等它认错,不如先说清楚。
size_warn = ""
if img_w and img_h and min(img_w, img_h) < ERASE_MIN_SIDE:
size_warn = (f"这张图只有 {img_w}×{img_h}px(短边不到 {ERASE_MIN_SIDE}),"
if img_w and img_h and min(img_w, img_h) < MIN_SIDE_WARN:
size_warn = (f"这张图只有 {img_w}×{img_h}px(短边不到 {MIN_SIDE_WARN}),"
f"一行字大约 {max(6, img_h // 40)}px 高,认错字很正常。"
f"在微信里选「原图」重发,或者重新拍一次(一次拍半页),会准很多。")
@@ -1447,67 +1450,74 @@ def create_paper_from_image(conn, gid: str, cid: str, subject: str, image_bytes:
ext = ".jpg"
img_path = folder / f"{pid}{ext}"
img_path.write_bytes(image_bytes)
clean_path_obj = folder / f"{pid}_clean.jpg"
# 手写擦除(TextIn):干净页既能重印,也能让切题少被笔迹干扰。
# 图太小就别擦——这个接口在小图上会连印刷字一起抹掉,宁可不动。
erase = {"used": False, "ok": False}
clean_rel = None
if textin.available():
if img_w and img_h and min(img_w, img_h) >= ERASE_MIN_SIDE:
r = textin.erase_handwriting(image_bytes, color=True, dewarp=False)
erase = {"used": True, "ok": bool(r.get("ok")), "ms": r.get("ms")}
if r.get("ok"):
clean_rel = f"data/uploads/{cid}/{pid}_clean.jpg"
clean_path_obj.write_bytes(r["image"])
erase["bytes"] = len(r["image"])
engine = None
questions: list[dict] = []
lines_n = 0
ocr_meta: dict = {}
# ① 腾讯云试卷切题:给了「一题一块」,连题图分离都省了。
if tencent_ocr.available():
tq = tencent_ocr.split_questions(image_bytes)
ocr_meta["tencent"] = {"ok": bool(tq.get("ok")), "code": tq.get("code"),
"message": tq.get("message"), "questions": len(tq.get("questions") or []),
"request_id": tq.get("request_id")}
if tq.get("ok") and tq.get("questions"):
questions = tq["questions"]
engine = "tencent"
# ② 退到本机 OCR + 正则切题(只在腾讯不可用/失败时跑)
res: dict = {}
if not questions:
try:
res = ocr.recognize(img_path)
qual = ocr.quality(res)
questions = cut.segment(res["lines"], subject) if qual["ok"] else []
lines_n = len(res.get("lines") or [])
except Exception:
_drop_upload(img_path)
raise
if questions:
engine = "windows"
if not questions:
if not ocr_meta.get("tencent", {}).get("ok", True) and not res:
code = (ocr_meta.get("tencent") or {}).get("code") or "OCR_FAILED"
reason = (f"腾讯切题没成功:{ocr_meta.get('tencent', {}).get('message') or code};"
f"本机 OCR 也没认出题。")
elif res:
qual = ocr.quality(res)
if not qual["ok"]:
code = qual["code"]
reason = qual["message"]
if qual.get("preview"):
reason = f"{reason}(认到的字:{qual['preview']}…)"
else:
erase["reason"] = r.get("message") or r.get("code")
code = "NO_QUESTION_NUMBER"
preview = "".join(l["text"] for l in res["lines"])[:40]
reason = (f"认到了 {len(res['lines'])} 行字,但没找到题号(1. 2. ① 这种)。"
f"把卷子拍全、让题号露出来;也可以先用演示题库走一遍。(认到:{preview}…)")
else:
erase["reason"] = f"图片只有 {img_w}×{img_h},短边不到 {ERASE_MIN_SIDE},擦除会把印刷字也糊掉"
else:
erase["reason"] = "没配 TextIn 凭据"
try:
res = ocr.recognize(img_path)
qual = ocr.quality(res)
questions = cut.segment(res["lines"], subject) if qual["ok"] else []
except Exception:
# OCR 自己崩了(没装语言包、子进程超时、图读不了):原图和擦除页都还没入库,删掉再抛
_drop_upload(img_path)
_drop_upload(clean_path_obj)
raise
if not qual["ok"] or not questions:
if not qual["ok"]:
code = qual["code"]
reason = qual["message"]
if qual.get("preview"):
reason = f"{reason}(认到的字:{qual['preview']}…)"
else:
code = "NO_QUESTION_NUMBER"
preview = "".join(l["text"] for l in res["lines"])[:40]
reason = (f"认到了 {len(res['lines'])} 行字,但没找到题号(1. 2. ① 这种)。"
f"把卷子拍全、让题号露出来;也可以先用演示题库走一遍。(认到:{preview}…)")
code = "OCR_FAILED"
reason = "这次没认出题来,重拍一次(一次半页)再试。"
if not fallback_demo:
raise ApiError(422, code, (size_warn + " " + reason).strip() if size_warn else reason)
# 退回演示题库:这张图不会有任何 papers 行指向它,留在磁盘上就是孤儿
_drop_upload(img_path)
_drop_upload(clean_path_obj)
paper = create_paper(conn, gid, cid, subject, image_count=1)
paper["source"] = "demo"
paper["too_small"] = bool(size_warn)
paper["ocr"] = {"ok": bool(qual["ok"]), "lines": len(res.get("lines") or []),
"questions": 0, "reason": reason, "warn": size_warn,
paper["ocr"] = {"ok": False, "engine": None, "lines": lines_n, "questions": 0,
"reason": reason, "warn": size_warn,
"size": {"w": img_w, "h": img_h},
"preview": qual.get("preview", "")}
"tencent": ocr_meta.get("tencent")}
return paper
with tx(conn):
image_rel = f"data/uploads/{cid}/{img_path.name}"
conn.execute("INSERT INTO papers (id, child_id, subject, image_count, clean_path, image_path,"
" created_at) VALUES (?,?,?,?,?,?,?)",
(pid, cid, subject, 1, clean_rel, image_rel, now()))
(pid, cid, subject, 1, None, image_rel, now()))
for i, q in enumerate(questions, start=1):
conn.execute(
"INSERT INTO questions (id, paper_id, child_id, subject, seq, stem, answer, options,"
@@ -1516,15 +1526,16 @@ def create_paper_from_image(conn, gid: str, cid: str, subject: str, image_bytes:
json.dumps(q.get("options"), ensure_ascii=False) if q.get("options") else None,
q.get("kp"),
q.get("judge_type") or "manual", now()))
log_event(conn, "paper_ocr", cid, subject=subject, lines=len(res["lines"]), questions=len(questions))
log_event(conn, "paper_ocr", cid, subject=subject, engine=engine,
lines=lines_n, questions=len(questions))
paper = get_paper(conn, gid, cid, pid)
paper["source"] = "ocr"
# 一行字在原图里有多高,决定了这次识别能不能信:整页截图塞进 500px 时,
# 每行不到 12px,认出来的一定有错字——这时候要提醒「分两段拍」,而不是假装准确。
hs = sorted(int(l.get("h") or 0) for l in res["lines"] if l.get("h"))
warn = size_warn
hs = sorted(int(l.get("h") or 0) for l in (res.get("lines") or []) if l.get("h"))
if hs:
median_orig = hs[len(hs) // 2] * ((res.get("width") or 1) / max(res.get("ocr_width") or 1, 1))
if median_orig < 14:
@@ -1532,13 +1543,11 @@ def create_paper_from_image(conn, gid: str, cid: str, subject: str, image_bytes:
f"建议一次只拍半页(5–8 道题),字大一点再识别。")
warn = (warn + " " + line_tip).strip() if warn else line_tip
paper["erase"] = erase
if clean_rel:
paper["clean_url"] = f"/api/papers/{pid}/clean"
paper["too_small"] = bool(size_warn)
paper["ocr"] = {"ok": True, "lines": len(res["lines"]), "questions": len(questions),
"lang": res.get("lang"), "image": f"data/uploads/{cid}/{img_path.name}",
"warn": warn, "size": {"w": img_w, "h": img_h}}
paper["ocr"] = {"ok": True, "engine": engine, "lines": lines_n, "questions": len(questions),
"image": f"data/uploads/{cid}/{img_path.name}",
"warn": warn, "size": {"w": img_w, "h": img_h},
"tencent": ocr_meta.get("tencent")}
return paper