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
+2 -2
View File
@@ -26,13 +26,13 @@ data/wx.env
# 部署
deploy/.env
backup/
data/textin.env
data/tencent.env
# DSH harness artifacts
.dsh-vision-router/
data/shot-profile/
# 用户上传的卷子照片:绝不进仓库
# �û��ϴ��ľ�����Ƭ���������ֿ�
data/uploads/
+11 -17
View File
@@ -256,23 +256,18 @@ questions 入库(`options` 列存 JSON 数组,接口直接返回数组)→
**完全一致(21×21 diff = 0,连掩码选择都一样)**。不做的事:不做中文/字节模式、不做纠错等级 M/Q/H、
不做多版本自动升级——登录码只用得上这一小片。
## 四点十四、手写擦除(TextIn)
## 四点十四、拍照切题(腾讯云 QuestionSplitOCR)
拍照入库前,可以先把孩子的笔迹擦掉,得到一张**干净的空白卷**:既能重新打印,也能让切题少被笔迹干扰。
- 接口:`POST https://ocr.tencentcloudapi.com`,`Action=QuestionSplitOCR`、`Version=2018-11-19`,
签名 TC3-HMAC-SHA256(`backend/tencent_ocr.py` 里自己算,零依赖)。
- 凭据放 `data/tencent.env`(`TENCENT_SECRET_ID` / `TENCENT_SECRET_KEY`,可选 `TENCENT_REGION`,
**已 gitignore**)。`tencent_ocr.available()` 为真才会走这条;否则退本机 Windows OCR + 正则切题。
- 为什么换掉原来的「TextIn 手写擦除」:那个只擦手写、切题还得按题号猜;
QuestionSplitOCR 一次给「一题一块」(题干/选项/答案分区 + 坐标),题图分离也一起解决。
- 返回三级兜底:腾讯 → 本机 OCR + `cut.segment` → 演示题库(`source=demo` 并说明原因)。
- 结果里 `ocr.engine` 是 `tencent` / `windows` / `null`,出问题先看它和 `ocr.tencent.message`。
- 接口:`POST https://api.textin.com/ai/service/v1/handwritten_erase`,请求头 `x-ti-app-id` / `x-ti-secret-code`,
body 直接是图片二进制,返回 `result.image`(base64 jpg)。
- 凭据放 `data/textin.env`(`TEXTIN_APP_ID` / `TEXTIN_SECRET_CODE`,**已 gitignore**),
代码在 `backend/textin.py`,`mode()` 为 `live` 时才会调用。
- 何时擦:**短边 ≥ 1200px** 才擦(`services.ERASE_MIN_SIDE`)。小图擦完会连印刷字一起糊掉,宁可不动,
返回里会写 `erase.reason` 说明跳过的原因。
- 擦完存哪:`data/uploads/{child_id}/{paper_id}_clean.jpg`,`papers.clean_path` 记相对路径,
`GET /api/papers/{pid}/clean?token=` 取图(token 可放 query,方便新标签页直接打开)。
- 失败不影响入库:擦除失败只写 `paper.erase = {ok:false, reason}`,照常 OCR 切题。
- 已知限制:按次计费,余额不足时接口返回 `40003 余额不足`;对**低分辨率截图**(如 387×516 放大后)
会把字抹花——这种情况会直接跳过。
## 五、接口(57 条,prod 下 49 条)
## 五、接口(56 条,prod 下 48 条)
> `/api/dev/*`(6 条)与 `/api/auth/sms-code`、`/api/auth/sms-login` 只在 `QINGLING_ENV` 不是
> `prod` 时注册。生产环境里它们直接 404,连「存在」都不暴露。
@@ -377,7 +372,6 @@ python tests/smoke_http.py # 39 项 HTTP 冒烟(真起服务
- `create_paper_from_image` 会返回 `too_small: true`,并在 `ocr.warn` 里写清尺寸与建议;
- 小程序在**选图之后、上传之前**就用 `wx.getImageInfo` 量一遍,太小的图弹窗提示「选原图 / 重拍」,也可以硬着头皮继续上传;
- 太小的图不做 TextIn 擦除(会把印刷字一起糊掉)。
不这么做的话,用户看到的是「没认出题」,但我们真正该说的是「你这张图只有 400×520,一行字 13px」。
@@ -408,7 +402,7 @@ python tests/smoke_http.py # 39 项 HTTP 冒烟(真起服务
三条规则,都是被真实审查意见逼出来的:
1. **令牌只允许出现在三个链接接口的 query 里** —— `/api/export/csv`、`/api/print/weekly`、
`/api/papers/{pid}/clean`。别的接口一律走 `Authorization: Bearer`,因为反代的 access log
别的接口一律走 `Authorization: Bearer`,因为反代的 access log
会把 URL 原样记下来,令牌进了日志就等于泄漏。规则在 `app.py` 的 `QUERY_TOKEN_PATHS`。
2. **订阅额度发成功才扣** —— 一次性订阅是用户点一次才给一条,先扣后发、发失败就成了
「付了没拿到」。现在 `_peek_grant()` 只看不扣,`send_subscribe` 成功后才 `_mark_grant_used()`;
-15
View File
@@ -46,7 +46,6 @@ MAX_BODY = 16 * 1024 * 1024 # 与 Caddy 的 request_body max_size 对
QUERY_TOKEN_PATHS = (
re.compile(r"^/api/export/csv$"),
re.compile(r"^/api/print/weekly$"),
re.compile(r"^/api/papers/[^/]+/clean$"),
)
@@ -283,20 +282,6 @@ def post_paper_ocr(ctx: Ctx, **kw):
fallback_demo=bool(ctx.body.get("fallback_demo", True)))
@route("GET", r"/api/papers/(?P<pid>[^/]+)/clean", auth="parent")
def paper_clean(ctx: Ctx, pid: str, **kw):
"""擦除手写后的干净页(token 可放 query,方便新标签页直接打开)。"""
row = ctx.conn.execute("SELECT child_id, clean_path FROM papers WHERE id=?", (pid,)).fetchone()
if not row or not row["clean_path"]:
raise ApiError(404, "NO_CLEAN", "这张卷子没有擦除后的干净页")
svc.get_child(ctx.conn, ctx.gid, row["child_id"])
fp = ROOT / row["clean_path"]
if not fp.exists():
raise ApiError(404, "NO_CLEAN", "干净页文件不在了")
# TextIn 擦除出来的是 .jpg,别一律当 png 发
return ("png" if fp.suffix.lower() == ".png" else "jpg", fp.read_bytes())
@route("GET", r"/api/papers/(?P<pid>[^/]+)", auth="parent")
def get_paper(ctx: Ctx, pid: str, **kw):
return svc.get_paper(ctx.conn, ctx.gid, ctx.q("child_id"), pid)
+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
+254
View File
@@ -0,0 +1,254 @@
# -*- coding: utf-8 -*-
"""腾讯云「试卷切题」(QuestionSplitOCR)——拍照识题的唯一引擎。
为什么换成它:
- 上一版用 TextIn 只做「手写擦除」,切题还得靠我们自己按题号猜;
- 腾讯这个接口一次给出「一题一块」:题干、选项、答案分区,都带坐标,
切题不再靠正则猜题号,题图分离的问题也一起解决了。
零依赖:urllib + hashlib + hmac 自己算 TC3-HMAC-SHA256 签名。
凭据读环境变量,或 data/tencent.env(已 gitignore):
TENCENT_SECRET_ID=...
TENCENT_SECRET_KEY=...
TENCENT_REGION=ap-guangzhou # 可不填
TENCENT_OCR_ACTION=QuestionSplitOCR # 默认就是这个
文档:https://cloud.tencent.com/document/product/866/115930
"""
from __future__ import annotations
import base64
import hashlib
import hmac
import json
import os
import time
import urllib.error
import urllib.request
from datetime import datetime, timezone
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
ENV_FILE = ROOT / "data" / "tencent.env"
HOST = "ocr.tencentcloudapi.com"
SERVICE = "ocr"
VERSION = "2018-11-19"
ACTION = "QuestionSplitOCR"
TIMEOUT = 25
_ENV_LOADED = False
def _load_env() -> None:
"""把 data/tencent.env 读进环境变量(不覆盖已有值)。"""
global _ENV_LOADED
if _ENV_LOADED:
return
_ENV_LOADED = True
if not ENV_FILE.exists():
return
try:
for raw in ENV_FILE.read_text(encoding="utf-8-sig").splitlines():
line = raw.strip()
if not line or line.startswith("#") or "=" not in line:
continue
k, v = line.split("=", 1)
k, v = k.strip(), v.strip().strip('"').strip("'")
if k and k not in os.environ:
os.environ[k] = v
except OSError:
pass
def _cred(name: str, default: str = "") -> str:
_load_env()
return (os.environ.get(name) or default).strip()
def secret_id() -> str:
return _cred("TENCENT_SECRET_ID")
def secret_key() -> str:
return _cred("TENCENT_SECRET_KEY")
def region() -> str:
return _cred("TENCENT_REGION")
def action() -> str:
return _cred("TENCENT_OCR_ACTION", ACTION) or ACTION
def available() -> bool:
return bool(secret_id() and secret_key())
def mode() -> str:
return "live" if available() else "none"
# ------------------------------------------------------------------ 签名
def _hmac(key: bytes, msg: str) -> bytes:
return hmac.new(key, msg.encode("utf-8"), hashlib.sha256).digest()
def _sha256_hex(data: bytes) -> str:
return hashlib.sha256(data).hexdigest()
def _sign(payload: bytes, timestamp: int) -> str:
"""TC3-HMAC-SHA256,返回 Authorization 头的值。"""
date = datetime.fromtimestamp(timestamp, tz=timezone.utc).strftime("%Y-%m-%d")
signed_headers = "content-type;host"
canonical_headers = ("content-type:application/json; charset=utf-8\n"
f"host:{HOST}\n")
canonical_request = "\n".join([
"POST", "/", "", canonical_headers, signed_headers, _sha256_hex(payload),
])
scope = f"{date}/{SERVICE}/tc3_request"
string_to_sign = "\n".join([
"TC3-HMAC-SHA256", str(timestamp), scope, _sha256_hex(canonical_request.encode("utf-8")),
])
k_date = _hmac(("TC3" + secret_key()).encode("utf-8"), date)
k_service = _hmac(k_date, SERVICE)
k_signing = _hmac(k_service, "tc3_request")
signature = hmac.new(k_signing, string_to_sign.encode("utf-8"), hashlib.sha256).hexdigest()
return (f"TC3-HMAC-SHA256 Credential={secret_id()}/{scope}, "
f"SignedHeaders={signed_headers}, Signature={signature}")
def _post(payload: dict, timeout: int = TIMEOUT) -> dict:
"""发一次请求;永远返回 dict,不抛异常(网络错误也包成 ok=False)。"""
if not available():
return {"ok": False, "code": "TENCENT_NOT_CONFIGURED",
"message": "没配 TENCENT_SECRET_ID / TENCENT_SECRET_KEY"}
body = json.dumps(payload, ensure_ascii=False).encode("utf-8")
ts = int(time.time())
headers = {
"Content-Type": "application/json; charset=utf-8",
"Host": HOST,
"X-TC-Action": action(),
"X-TC-Version": VERSION,
"X-TC-Timestamp": str(ts),
"Authorization": _sign(body, ts),
}
if region():
headers["X-TC-Region"] = region()
req = urllib.request.Request(f"https://{HOST}", data=body, method="POST", headers=headers)
try:
with urllib.request.urlopen(req, timeout=timeout) as resp:
raw = resp.read()
except urllib.error.HTTPError as e: # 4xx/5xx 也带 body
raw = e.read() or b""
if not raw:
return {"ok": False, "code": f"HTTP_{e.code}", "message": str(e)}
except Exception as e: # 网络不通、超时、DNS
return {"ok": False, "code": "TENCENT_UNREACHABLE",
"message": f"{type(e).__name__}: {e}"}
try:
data = json.loads(raw.decode("utf-8"))
except Exception:
return {"ok": False, "code": "TENCENT_BAD_JSON", "message": "返回不是 JSON"}
resp = data.get("Response") or {}
if resp.get("Error"):
err = resp["Error"]
return {"ok": False, "code": f"TENCENT_{err.get('Code') or 'ERROR'}",
"message": err.get("Message") or "", "request_id": resp.get("RequestId")}
return {"ok": True, "data": resp, "request_id": resp.get("RequestId")}
# ------------------------------------------------------------------ 解析
_LETTERS = "ABCDEFGH"
def _strip_label(text: str) -> str:
"""把选项自带的「A.」「A、」「A.」前缀去掉,只留内容。"""
t = (text or "").strip()
if len(t) >= 2 and t[0].upper() in _LETTERS and t[1] in "..、,,::))":
return t[2:].strip()
return t
def _join(items, key: str = "Text") -> str:
rows = sorted(items or [], key=lambda x: (x.get("Index") if isinstance(x, dict) else 0) or 0)
return "".join(str((r or {}).get(key) or "") for r in rows).strip()
def _pick_answer(text: str) -> str:
t = (text or "").strip()
for pre in ("答案:", "答案:", "正确答案:", "正确答案:", "答:"):
if t.startswith(pre):
t = t[len(pre):].strip()
t = t.strip("。. ")
return t
def _guess_type(stem: str, options: list[str], answer: str) -> str:
if len(options) >= 2:
return "choice"
if answer:
a = answer.strip()
if len(a) <= 12 and any(ch.isdigit() for ch in a):
return "calc"
return "text"
return "manual"
def parse(resp: dict) -> list[dict]:
"""把 QuestionSplitOCR 的返回拆成我们的题目结构。
结构(简化):
QuestionInfo[0].ResultList[i] = {
"Question": [{"Index":0,"Text":"..."}], # 题干(可能分几段)
"Option": [{"Index":1,"Text":"A.…"}],
"Answer": [{"Text":"…"}],
"Parse": [...], "Figure": [...],
}
"""
out: list[dict] = []
try:
info = (resp.get("QuestionInfo") or [])
results = []
for one in info:
results.extend(one.get("ResultList") or [])
except AttributeError:
return out
for rl in results:
if not isinstance(rl, dict):
continue
stem = _join(rl.get("Question"))
if not stem:
continue
opts = [_strip_label(o) for o in
(str((x or {}).get("Text") or "") for x in (rl.get("Option") or []))]
opts = [o for o in opts if o]
answer = _pick_answer(_join(rl.get("Answer")))
jt = rl.get("GroupType") if isinstance(rl.get("GroupType"), str) else ""
if len(opts) >= 2:
jt = "choice"
elif jt not in ("calc", "text"):
jt = _guess_type(stem, opts, answer)
item = {"stem": stem, "judge_type": jt, "options": opts or None,
"answer": answer or None, "kp": None}
if jt == "choice" and answer:
letter = answer.strip().upper()[:1]
item["answer"] = letter if letter in _LETTERS[:len(opts)] else None
out.append(item)
return out
def split_questions(image_bytes: bytes, timeout: int = TIMEOUT) -> dict:
"""切题主入口:返回 {ok, questions, code, message, request_id}。"""
if not image_bytes:
return {"ok": False, "code": "EMPTY_IMAGE", "message": "没收到图片", "questions": []}
payload = {"ImageBase64": base64.b64encode(image_bytes).decode("ascii")}
res = _post(payload, timeout=timeout)
if not res.get("ok"):
return {"ok": False, "code": res.get("code"), "message": res.get("message"),
"request_id": res.get("request_id"), "questions": []}
questions = parse(res.get("data") or {})
return {"ok": True, "questions": questions, "request_id": res.get("request_id"),
"code": None, "message": ""}
-151
View File
@@ -1,151 +0,0 @@
"""TextIn 云服务(手写擦除 / 通用识别)。
为什么单开一个模块:
- 本机 OCR 走 Windows.Media.Ocr,只能认字、不能"擦",而且部署到 Linux 上就没有了;
- TextIn 的手写擦除正好补上产品里缺的一环:把卷子上孩子的笔迹擦掉,得到一张干净的空白卷,
既能重新打印,也能让"切题"少被手写干扰。
零依赖:urllib + json,凭据从环境变量或 data/textin.env 读。
"""
from __future__ import annotations
import base64
import json
import os
import urllib.error
import urllib.parse
import urllib.request
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
ENV_FILE = ROOT / "data" / "textin.env"
BASE = "https://api.textin.com"
# 手写擦除:返回 result.image(base64 的 jpg)
P_ERASE = "/ai/service/v1/handwritten_erase"
# 通用文字识别(版面上带坐标,可辅助切题)
P_OCR = "/ai/service/v1/general_ocr"
def _load_env() -> None:
"""把 data/textin.env 里的键读进环境变量(不覆盖已有的)。"""
if not ENV_FILE.exists():
return
try:
text = ENV_FILE.read_text(encoding="utf-8-sig")
except OSError:
return
for line in text.splitlines():
line = line.strip()
if not line or line.startswith("#") or "=" not in line:
continue
k, v = line.split("=", 1)
k, v = k.strip(), v.strip()
if k and v and not os.environ.get(k):
os.environ[k] = v
_load_env()
def app_id() -> str:
return os.environ.get("TEXTIN_APP_ID", "").strip()
def secret() -> str:
return os.environ.get("TEXTIN_SECRET_CODE", "").strip()
def mode() -> str:
"""live / none。"""
return "live" if (app_id() and secret()) else "none"
def available() -> bool:
return mode() == "live"
def _request(path: str, data: bytes, params: dict | None = None, timeout: int = 30) -> dict:
"""返回 {ok, data|error, code, message}。永不抛异常。"""
if not available():
return {"ok": False, "code": "TEXTIN_NOT_CONFIGURED", "message": "没配 TEXTIN_APP_ID / TEXTIN_SECRET_CODE"}
url = BASE + path
if params:
q = "&".join(f"{k}={urllib.parse.quote(str(v))}" for k, v in params.items())
url = f"{url}?{q}"
req = urllib.request.Request(
url,
data=data,
method="POST",
headers={
"x-ti-app-id": app_id(),
"x-ti-secret-code": secret(),
"Content-Type": "application/octet-stream",
},
)
try:
with urllib.request.urlopen(req, timeout=timeout) as r:
raw = r.read()
except urllib.error.HTTPError as e:
return {"ok": False, "code": f"HTTP_{e.code}", "message": f"HTTP {e.code}"}
except Exception as e: # noqa: BLE001
return {"ok": False, "code": "TEXTIN_UNREACHABLE", "message": f"{type(e).__name__}: {e}"}
try:
payload = json.loads(raw.decode("utf-8", "replace"))
except ValueError:
return {"ok": False, "code": "TEXTIN_BAD_JSON", "message": "返回不是 JSON"}
code = payload.get("code")
if code != 200:
msg = payload.get("message") or payload.get("msg") or ""
return {"ok": False, "code": f"TEXTIN_{code}", "message": msg, "request_id": payload.get("x_request_id")}
return {"ok": True, "data": payload.get("result") or {}, "ms": payload.get("duration"),
"request_id": payload.get("x_request_id")}
def erase_handwriting(image: bytes, *, color: bool = True, dewarp: bool = True,
crop: bool = False, timeout: int = 40) -> dict:
"""擦掉手写笔迹,返回 {ok, image(bytes), ms, message}。
color=True 保留红色批改以外的原卷色彩(试卷上老师的红钩会尽量保留);
传 False 得到黑白图,打印更省墨。
"""
params = {
"image_type": 1 if color else 0,
"dewarp": 1 if dewarp else 0,
"crop": 1 if crop else 0,
"binarization": 1,
}
r = _request(P_ERASE, image, params, timeout=timeout)
if not r["ok"]:
return {"ok": False, "code": r["code"], "message": r["message"]}
b64 = (r["data"] or {}).get("image") or ""
if not b64:
return {"ok": False, "code": "TEXTIN_NO_IMAGE", "message": "接口成功但没返回图"}
try:
out = base64.b64decode(b64)
except Exception as e: # noqa: BLE001
return {"ok": False, "code": "TEXTIN_BAD_BASE64", "message": str(e)}
return {"ok": True, "image": out, "ms": r.get("ms"), "bytes": len(out)}
def general_ocr(image: bytes, timeout: int = 30) -> dict:
"""通用识别:返回 [{text, x, y, w, h}],形状对齐 ocr.recognize() 用的 lines。"""
r = _request(P_OCR, image, {"straighten": 0}, timeout=timeout)
if not r["ok"]:
return {"ok": False, "code": r["code"], "message": r["message"], "lines": []}
res = r["data"] or {}
lines = []
for item in (res.get("lines") or []):
pos = item.get("pos") or []
xs = [p[0] for p in pos if isinstance(p, (list, tuple)) and p]
ys = [p[1] for p in pos if isinstance(p, (list, tuple)) and len(p) > 1]
if not xs or not ys:
continue
lines.append({
"text": (item.get("text") or "").strip(),
"x": int(min(xs)), "y": int(min(ys)),
"w": int(max(xs) - min(xs)), "h": int(max(ys) - min(ys)),
})
lines.sort(key=lambda l: (l["y"], l["x"]))
return {"ok": True, "lines": [l for l in lines if l["text"]], "ms": r.get("ms")}
+1 -1
View File
@@ -112,7 +112,7 @@ SQLite 用 `.backup`,不要 `cp`(WAL 下可能拷到半截)。上传的卷
## 五、上线前检查清单
- [ ] `api/health` 返回 `version=1.2.0`;`routes` 在 prod 下是 49(dev 下 57,多出的 8 条是 6 个 `/api/dev/*` 与 2 个短信登录接口)
- [ ] `api/health` 返回 `version=1.2.0`;`routes` 在 prod 下是 49(dev 下 56,多出的 8 条是 6 个 `/api/dev/*` 与 2 个短信登录接口)
- [ ] 手机号登录能收到验证码(**现在还是 dev 模式直接回显,必须接短信服务商**)
- [ ] 小程序 `code2session` 能换到真 openid
- [ ] 拍照识题返回 `source=ocr`
+1 -1
View File
@@ -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)
+1 -1
View File
@@ -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"]
+5 -1
View File
@@ -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"):
+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()
-168
View File
@@ -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()