Files
wangtongbo 73b75bf8de 解析:竖式区按行拆成小题(split_multi),修括号算式算错的老问题
- tencent_ocr.split_multi:多行纯算式块(竖式/脱式)一行一道、逐道自算;
  只要有一行带汉字就整块放弃,应用题不受影响
- 剥题号正则加 (?!\\d),避免把 1.8+0.6 的 1. 当成题号(会算成 8.6)
- judging.safe_eval 不再走 normalize:strip_punct 会剥掉括号,
  34×(90-46) 会静默变成 34*90-46;等号改为取最后一段
- _tidy:小数题答案给 2.4 而不是 12/5
- 金标 330 道:认对 312->318/330(96.4%),误判 0(95% CI 0-1.19%),漏检 12
- tests/test_split_multi.py 9 例;172 单测 + 4 套冒烟全绿
2026-11-19 21:21:20 +08:00

589 lines
21 KiB
Python
Raw Permalink 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 -*-
"""腾讯云「试卷切题」(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"}
from . import ocr_budget
if ocr_budget.exhausted():
return {"ok": False, "code": "OCR_BUDGET_EXHAUSTED",
"message": f"本月 OCR 调用已达上限({ocr_budget.used()}/{ocr_budget.limit()})"}
ocr_budget.spend(1)
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 _chain_answer(stem: str):
"""三步以上的连算(6+5-10、82-6×7):只要整段是纯算式,就整串求值。
比逐个两数相加强的地方是优先级和结合律都对(先乘除后加减、从左到右)。
"""
from . import judging
t = clean_text(stem or "")
t = re.sub(r"^\s*\d{1,3}\s*[.、.))]\s*", "", t) # 去掉题号
t = re.sub(r"\s+", "", t)
if not t.endswith("=") or t.count("=") != 1:
return None
expr = t[:-1]
if not re.fullmatch(r"[0-9+\-×÷*/().]+", expr or ""):
return None
if len(re.findall(r"[+\-×÷*/]", expr)) < 2: # 两数运算走原来的路
return None
expr = expr.replace("×", "*").replace("÷", "/")
if expr.startswith(("+", "*", "/")) or expr.endswith(("+", "-", "*", "/")):
return None
val = judging.safe_eval(expr)
return None if val is None else judging._fmt(val)
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/])")
chain = _chain_answer(stem)
if chain is not None:
return chain
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)
_CARD = re.compile(r"(-?\d+(?:\.\d+)?(?:\s*[+\-×÷*/]\s*-?\d+(?:\.\d+)?)+)\s*=")
def split_card(stem: str) -> list[dict]:
"""口算卡:一页十几道「a op b =」。切成小题,每道自己算答案。
只在「至少 3 道、且这些算式占了题干大头」时才切——不然会把一道竖式题
(中间有多步等号)误当成卡片。
"""
from . import judging
hits = list(_CARD.finditer(stem or ""))
if len(hits) < 3:
return []
covered = sum(m.end() - m.start() for m in hits)
if covered < len(stem) * 0.45:
return []
subs = []
for m in hits:
expr = m.group(1)
val = judging.safe_eval(expr)
if val is None:
continue
ans = _tidy(expr, judging._fmt(val))
subs.append({"stem": f"{expr} =", "answer": ans, "judge_type": "calc"})
return subs if len(subs) >= 3 else []
_LINE_NO = re.compile(r"^\s*(?:第)?[\d一二三四五六七八九十]{1,3}\s*[.、))::](?!\d)\s*")
_HAS_HAN = re.compile(r"[\u4e00-\u9fff]")
def _tidy(expr: str, ans: str) -> str:
"""按算式本身的写法给答案:小数题给小数(`12/5` → `2.4`),分数题给分数。"""
s = (ans or "").strip()
if "." in (expr or "") and "/" in s and len(s.split("/")) == 2:
try:
num, den = s.split("/")
v = float(num) / float(den)
out = f"{v:g}"
return out
except (ValueError, ZeroDivisionError):
return s
return s
def split_multi(stem: str) -> list[dict]:
"""竖式 / 脱式:一块里几行纯算式,一行一道,逐行自己算。
和 split_card 的区别:卡片用「=」认边界,竖式往往**没有等号**(卷面上是让孩子竖着算),
只能按换行拆。为了不把应用题拆坏,这里有一条硬线——**任何一行只要带汉字就整块放弃**。
应用题几乎总会带汉字(「小明有 14 个」),竖式区则是一行一个纯算式。
"""
from . import judging
lines = [x.strip() for x in re.split(r"[\n\r;;]+", stem or "") if x.strip()]
if len(lines) < 2:
return []
subs = []
for raw in lines:
s = _LINE_NO.sub("", raw).strip()
s = s.strip("**").strip()
if not s or _HAS_HAN.search(s):
return [] # 有一行是文字 → 不是竖式区
s = s.replace("×", "*").replace("÷", "/").replace("x", "*").replace("X", "*")
s = s.replace("=", "=").rstrip("=").strip()
if not s or not re.fullmatch(r"[0-9+\-*/().\s]+", s):
return []
if not re.search(r"[+\-*/]", s):
return []
val = judging.safe_eval(s)
if val is None:
return []
subs.append({"stem": f"{s} =", "answer": _tidy(s, judging._fmt(val)), "judge_type": "calc"})
return subs if len(subs) >= 2 else []
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
subs = []
if jt != "choice":
subs = split_card(stem)
if not subs:
subs = split_multi(stem)
if not subs:
derived = _derive_answer(stem)
box = _bbox(rl)
if subs:
# 一块里好几道(口算卡 / 竖式区),展开成多个小题(共用同一个框)
item = {"stem": stem, "judge_type": "card", "options": None,
"answer": None, "kp": None, "page_answer": page_answer or None,
"subs": subs, "box": box}
elif derived is not None:
# 纯算式:自己算一遍,可以机器判
item = {"stem": stem, "judge_type": "calc", "options": None,
"answer": _tidy(stem, 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, use_cache: bool = True) -> dict:
"""切题主入口:返回 {ok, questions, code, message, request_id, cached}。
同一张图只买一次单:命中 `ocr_cache` 就不发请求(`cached=True`)。
"""
from . import ocr_cache
if not image_bytes:
return {"ok": False, "code": "EMPTY_IMAGE", "message": "没收到图片", "questions": []}
hit = ocr_cache.get(image_bytes) if use_cache else None
if hit and hit.get("ok"):
questions = parse(hit.get("data") or {})
return {"ok": True, "questions": questions, "request_id": hit.get("request_id"),
"code": None, "message": "", "cached": True}
payload = {"ImageBase64": base64.b64encode(image_bytes).decode("ascii")}
res = _post(payload, timeout=timeout)
if res.get("ok"):
ocr_cache.put(image_bytes, res)
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": "", "cached": False}
if __name__ == "__main__":
import sys
raise SystemExit(_main(sys.argv[1:]))