457 lines
16 KiB
Python
457 lines
16 KiB
Python
# -*- 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 re
|
||
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"
|
||
|
||
|
||
_LATEX_MAP = [("\\times", "×"), ("\\div", "÷"), ("\\cdot", "·"),
|
||
("\\bigcirc", "○"), ("\\leq", "≤"), ("\\geq", "≥"),
|
||
("\\neq", "≠"), ("\\pm", "±"), ("\\text", ""), ("\\,", " "),
|
||
("\\quad", " "), ("\\left", ""), ("\\right", "")]
|
||
|
||
|
||
def clean_text(text: str) -> str:
|
||
"""把 OCR 返回的 LaTeX 片段变成人能读的样子。
|
||
|
||
腾讯切题对分数/公式会给 `$\\frac{3}{4}$` 这种,前端直接显示是一串乱码。
|
||
这里做最小变换:\\frac{a}{b} → a/b,\\times → ×,去掉 $ 与多余空格。
|
||
"""
|
||
if not text:
|
||
return ""
|
||
t = str(text)
|
||
for _ in range(6): # 处理嵌套(分子分母里还有 frac)
|
||
new_t = re.sub(r"\\frac\s*\{([^{}]*)\}\s*\{([^{}]*)\}", r"\1/\2", t)
|
||
if new_t == t:
|
||
break
|
||
t = new_t
|
||
for a, b in _LATEX_MAP:
|
||
t = t.replace(a, b)
|
||
for junk in ("\\begin{matrix}", "\\end{matrix}", "\\begin{array}", "\\end{array}"):
|
||
t = t.replace(junk, " ")
|
||
t = re.sub(r"\{?\b(?:begin|end)\{[a-z*]+\}\}?", " ", t)
|
||
t = t.replace("$", "").replace("\\", "")
|
||
t = re.sub(r"[ \t]+", " ", t)
|
||
t = re.sub(r"\n{3,}", "\n\n", t)
|
||
return t.strip()
|
||
|
||
|
||
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
|
||
|
||
|
||
_EXPR = None
|
||
|
||
|
||
def _derive_answer(stem: str):
|
||
"""卷面上没印答案时,纯算式题自己算一遍——口算占大头,不能全推给孩子自评。
|
||
|
||
只在「题干里有一个完整的 a op b = ()」且不带未知数时才*猜*,
|
||
算不出来就返回 None(宁可自评,不可算错)。
|
||
"""
|
||
global _EXPR
|
||
import re
|
||
|
||
from . import judging
|
||
|
||
if _EXPR is None:
|
||
_EXPR = re.compile(
|
||
r"(?<![\d/])(-?\d+(?:\.\d+)?)\s*([+\-×÷xX*])\s*(-?\d+(?:\.\d+)?)\s*=(?![\d/])")
|
||
frac = _frac_chain_answer(stem)
|
||
if frac is not None:
|
||
return frac
|
||
|
||
m = _EXPR.search(stem or "")
|
||
if not m:
|
||
return None
|
||
a, op, b = m.group(1), m.group(2), m.group(3)
|
||
op = {"×": "*", "÷": "/", "x": "*", "X": "*"}.get(op, op)
|
||
try:
|
||
val = judging.safe_eval(f"{a}{op}{b}")
|
||
except Exception:
|
||
return None
|
||
if val is None:
|
||
return None
|
||
if isinstance(val, float) and val.is_integer():
|
||
val = int(val)
|
||
return str(val)
|
||
|
||
|
||
_OPERAND = r"\d+(?:\.\d+)?(?:/\d+(?:\.\d+)?)?"
|
||
_CHAIN = re.compile(rf"^{_OPERAND}(?:[+\-×÷xX*]{_OPERAND})+$")
|
||
_NUMHEAD = re.compile(r"^[((]?\s*\d{1,3}\s*[..、))]\s*(?!\d)")
|
||
|
||
|
||
def _frac_chain_answer(stem: str):
|
||
"""整题就是一个算式(可以带分数、多个运算符)时,自己算。
|
||
|
||
只在「去掉题号后,剩下的全是数字与运算符、且末尾是等号」时才敢算——
|
||
带一个汉字就退出,绝不在应用题上猜。
|
||
"""
|
||
from . import judging
|
||
|
||
t = clean_text(stem or "").strip()
|
||
t = _NUMHEAD.sub("", t)
|
||
t = re.sub(r"[((]\s*[))]", "", t)
|
||
t = t.strip()
|
||
if not t.endswith("="):
|
||
return None
|
||
body = t[:-1].strip()
|
||
if not body or body.count("=") > 0:
|
||
return None
|
||
if any("\u4e00" <= ch <= "\u9fff" for ch in body):
|
||
return None
|
||
body = body.replace("×", "*").replace("÷", "/").replace("x", "*").replace("X", "*")
|
||
body = re.sub(r"\s+", "", body)
|
||
if not _CHAIN.match(body):
|
||
return None
|
||
val = judging.safe_eval(body)
|
||
if val is None:
|
||
return None
|
||
return judging._fmt(val)
|
||
|
||
|
||
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 _bbox(rl: dict) -> dict | None:
|
||
"""题块的外接框(像素):优先用 rl.Coord,退到题干各段的联合框。"""
|
||
xs0, ys0, xs1, ys1 = [], [], [], []
|
||
|
||
def eat(c):
|
||
if isinstance(c, list):
|
||
for one in c:
|
||
eat(one)
|
||
return
|
||
if not isinstance(c, dict):
|
||
return
|
||
lt, rb = c.get("LeftTop") or {}, c.get("RightBottom") or {}
|
||
try:
|
||
xs0.append(float(lt["X"])); ys0.append(float(lt["Y"]))
|
||
xs1.append(float(rb["X"])); ys1.append(float(rb["Y"]))
|
||
except (KeyError, TypeError, ValueError):
|
||
pass
|
||
|
||
eat(rl.get("Coord"))
|
||
if not xs0:
|
||
for q in (rl.get("Question") or []):
|
||
eat((q or {}).get("Coord"))
|
||
if not xs0:
|
||
return None
|
||
x0, y0, x1, y1 = min(xs0), min(ys0), max(xs1), max(ys1)
|
||
return {"x": int(x0), "y": int(y0), "w": int(max(1, x1 - x0)), "h": int(max(1, y1 - y0))}
|
||
|
||
|
||
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
|
||
def _y_of(c) -> float | None:
|
||
"""Coord 可能是 [{"LeftTop": {"X":..,"Y":..}}] 或 {"LeftTop": ...}。"""
|
||
if isinstance(c, list):
|
||
c = c[0] if c else None
|
||
if isinstance(c, dict):
|
||
lt = c.get("LeftTop") or {}
|
||
try:
|
||
return float(lt.get("Y"))
|
||
except (TypeError, ValueError):
|
||
return None
|
||
return None
|
||
|
||
def _top_y(rl: dict) -> float:
|
||
"""按题干第一段的 y 排序,保证题号自上而下。"""
|
||
ys = []
|
||
for q in (rl.get("Question") or []):
|
||
y = _y_of((q or {}).get("Coord"))
|
||
if y is not None:
|
||
ys.append(y)
|
||
if not ys:
|
||
y = _y_of(rl.get("Coord"))
|
||
if y is not None:
|
||
ys.append(y)
|
||
return min(ys) if ys else 1e9
|
||
|
||
ordered = sorted([r for r in results if isinstance(r, dict)], key=_top_y)
|
||
for rl in ordered:
|
||
stem = clean_text(_join(rl.get("Question")))
|
||
if not stem:
|
||
continue
|
||
opts = [_strip_label(clean_text(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 区拿到的是「卷面上写的东西」。孩子做完的卷子上,那就是他写的答案,
|
||
# 不是标准答案——拿它判对错会把错的判成对的。所以只当参考存着,不参与判分。
|
||
page_answer = clean_text(_pick_answer(_join(rl.get("Answer"))))
|
||
jt = rl.get("GroupType") if isinstance(rl.get("GroupType"), str) else ""
|
||
if len(opts) >= 2:
|
||
jt = "choice"
|
||
|
||
derived = None
|
||
if jt != "choice":
|
||
derived = _derive_answer(stem)
|
||
|
||
box = _bbox(rl)
|
||
if derived is not None:
|
||
# 纯算式:自己算一遍,可以机器判
|
||
item = {"stem": stem, "judge_type": "calc", "options": None,
|
||
"answer": derived, "kp": None, "page_answer": page_answer or None,
|
||
"box": box}
|
||
else:
|
||
# 其余(选择/填空/问答):没有可信的标准答案 → 孩子自评,
|
||
# 但把卷面上写的答案留给孩子和家长对照。
|
||
jt = "choice" if jt == "choice" else _guess_type(stem, opts, "")
|
||
item = {"stem": stem, "judge_type": "manual", "options": opts or None,
|
||
"answer": page_answer or None, "kp": None,
|
||
"page_answer": page_answer or None,
|
||
"detected_as": jt, "box": box}
|
||
out.append(item)
|
||
return out
|
||
|
||
|
||
def _main(argv: list[str]) -> int:
|
||
"""命令行自检:python -m backend.tencent_ocr 图片 [图片...]"""
|
||
if not argv:
|
||
print("用法:python -m backend.tencent_ocr <图片路径> [更多图片]")
|
||
print(f"凭据:{mode()}({ENV_FILE})")
|
||
return 2
|
||
if not available():
|
||
print("没读到凭据:请在 data/tencent.env 写 TENCENT_SECRET_ID / TENCENT_SECRET_KEY")
|
||
return 1
|
||
print(f"凭据:{mode()} | region={region() or '(none)'} | action={action()}")
|
||
bad = 0
|
||
for p in argv:
|
||
data = Path(p).read_bytes()
|
||
t0 = time.time()
|
||
r = split_questions(data)
|
||
ms = int((time.time() - t0) * 1000)
|
||
print(f"\n== {p} {len(data)//1024}KB {ms}ms ok={r['ok']} n={len(r['questions'])}")
|
||
if not r["ok"]:
|
||
print(f" code={r['code']}\n msg={r['message']}")
|
||
bad += 1
|
||
continue
|
||
for i, q in enumerate(r["questions"], 1):
|
||
print(f" {i}. [{q['judge_type']}] ans={q['answer']} opts={q['options']}")
|
||
print(f" {q['stem'][:70]}")
|
||
return 0 if bad == 0 else 1
|
||
|
||
|
||
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": ""}
|
||
|
||
|
||
if __name__ == "__main__":
|
||
import sys
|
||
|
||
raise SystemExit(_main(sys.argv[1:]))
|