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:
@@ -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": ""}
|
||||
Reference in New Issue
Block a user