ocr: 卷面答案不当标准答案;算式自算判分;按坐标从上到下排序
- QuestionSplitOCR 的 Answer 区是「卷面上写的」,可能正是孩子写的答案: 只能当参考(page_answer),不能拿去判对错 - 纯算式(a op b =)自己算一遍再判 calc,口算仍然机器判 - 题干按 Coord.LeftTop.Y 排序,题号自上而下 - tencent_ocr 加命令行自检:python -m backend.tencent_ocr <图片> - 单测 115 例 + 冒烟 39 项全过
This commit is contained in:
+112
-11
@@ -186,6 +186,38 @@ def _pick_answer(text: str) -> str:
|
||||
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+)?)\s*([+\-*/×÷xX])\s*(-?\d+(?:\.\d+)?)\s*=")
|
||||
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)
|
||||
|
||||
|
||||
def _guess_type(stem: str, options: list[str], answer: str) -> str:
|
||||
if len(options) >= 2:
|
||||
return "choice"
|
||||
@@ -216,30 +248,93 @@ def parse(resp: dict) -> list[dict]:
|
||||
results.extend(one.get("ResultList") or [])
|
||||
except AttributeError:
|
||||
return out
|
||||
for rl in results:
|
||||
if not isinstance(rl, dict):
|
||||
continue
|
||||
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 = _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")))
|
||||
# 注意:Answer 区拿到的是「卷面上写的东西」。孩子做完的卷子上,那就是他写的答案,
|
||||
# 不是标准答案——拿它判对错会把错的判成对的。所以只当参考存着,不参与判分。
|
||||
page_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
|
||||
|
||||
derived = None
|
||||
if jt != "choice":
|
||||
derived = _derive_answer(stem)
|
||||
|
||||
if derived is not None:
|
||||
# 纯算式:自己算一遍,可以机器判
|
||||
item = {"stem": stem, "judge_type": "calc", "options": None,
|
||||
"answer": derived, "kp": None, "page_answer": page_answer or None}
|
||||
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}
|
||||
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:
|
||||
@@ -252,3 +347,9 @@ def split_questions(image_bytes: bytes, timeout: int = TIMEOUT) -> dict:
|
||||
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:]))
|
||||
|
||||
Reference in New Issue
Block a user