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:
Binary file not shown.
|
After Width: | Height: | Size: 94 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 399 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 1.6 MiB |
+112
-11
@@ -186,6 +186,38 @@ def _pick_answer(text: str) -> str:
|
|||||||
return t
|
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:
|
def _guess_type(stem: str, options: list[str], answer: str) -> str:
|
||||||
if len(options) >= 2:
|
if len(options) >= 2:
|
||||||
return "choice"
|
return "choice"
|
||||||
@@ -216,30 +248,93 @@ def parse(resp: dict) -> list[dict]:
|
|||||||
results.extend(one.get("ResultList") or [])
|
results.extend(one.get("ResultList") or [])
|
||||||
except AttributeError:
|
except AttributeError:
|
||||||
return out
|
return out
|
||||||
for rl in results:
|
def _y_of(c) -> float | None:
|
||||||
if not isinstance(rl, dict):
|
"""Coord 可能是 [{"LeftTop": {"X":..,"Y":..}}] 或 {"LeftTop": ...}。"""
|
||||||
continue
|
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"))
|
stem = _join(rl.get("Question"))
|
||||||
if not stem:
|
if not stem:
|
||||||
continue
|
continue
|
||||||
opts = [_strip_label(o) for o in
|
opts = [_strip_label(o) for o in
|
||||||
(str((x or {}).get("Text") or "") for x in (rl.get("Option") or []))]
|
(str((x or {}).get("Text") or "") for x in (rl.get("Option") or []))]
|
||||||
opts = [o for o in opts if o]
|
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 ""
|
jt = rl.get("GroupType") if isinstance(rl.get("GroupType"), str) else ""
|
||||||
if len(opts) >= 2:
|
if len(opts) >= 2:
|
||||||
jt = "choice"
|
jt = "choice"
|
||||||
elif jt not in ("calc", "text"):
|
|
||||||
jt = _guess_type(stem, opts, answer)
|
derived = None
|
||||||
item = {"stem": stem, "judge_type": jt, "options": opts or None,
|
if jt != "choice":
|
||||||
"answer": answer or None, "kp": None}
|
derived = _derive_answer(stem)
|
||||||
if jt == "choice" and answer:
|
|
||||||
letter = answer.strip().upper()[:1]
|
if derived is not None:
|
||||||
item["answer"] = letter if letter in _LETTERS[:len(opts)] else 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)
|
out.append(item)
|
||||||
return out
|
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:
|
def split_questions(image_bytes: bytes, timeout: int = TIMEOUT) -> dict:
|
||||||
"""切题主入口:返回 {ok, questions, code, message, request_id}。"""
|
"""切题主入口:返回 {ok, questions, code, message, request_id}。"""
|
||||||
if not image_bytes:
|
if not image_bytes:
|
||||||
@@ -252,3 +347,9 @@ def split_questions(image_bytes: bytes, timeout: int = TIMEOUT) -> dict:
|
|||||||
questions = parse(res.get("data") or {})
|
questions = parse(res.get("data") or {})
|
||||||
return {"ok": True, "questions": questions, "request_id": res.get("request_id"),
|
return {"ok": True, "questions": questions, "request_id": res.get("request_id"),
|
||||||
"code": None, "message": ""}
|
"code": None, "message": ""}
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
import sys
|
||||||
|
|
||||||
|
raise SystemExit(_main(sys.argv[1:]))
|
||||||
|
|||||||
Binary file not shown.
|
After Width: | Height: | Size: 110 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 560 KiB |
@@ -35,7 +35,10 @@ class ParseTest(unittest.TestCase):
|
|||||||
qs = tq.parse(resp)
|
qs = tq.parse(resp)
|
||||||
self.assertEqual(len(qs), 1)
|
self.assertEqual(len(qs), 1)
|
||||||
q = qs[0]
|
q = qs[0]
|
||||||
self.assertEqual(q["judge_type"], "choice")
|
# 卷面上的答案可能是孩子写的,不能拿来判分 → manual + 参考答案
|
||||||
|
self.assertEqual(q["judge_type"], "manual")
|
||||||
|
self.assertEqual(q["detected_as"], "choice")
|
||||||
|
self.assertEqual(q["page_answer"], "B")
|
||||||
self.assertEqual(q["answer"], "B")
|
self.assertEqual(q["answer"], "B")
|
||||||
self.assertEqual(q["options"], ["快乐(lè)", "音乐(yuè)", "长大(cháng)", "银行(háng)"])
|
self.assertEqual(q["options"], ["快乐(lè)", "音乐(yuè)", "长大(cháng)", "银行(háng)"])
|
||||||
self.assertIn("读音", q["stem"])
|
self.assertIn("读音", q["stem"])
|
||||||
@@ -58,6 +61,7 @@ class ParseTest(unittest.TestCase):
|
|||||||
q = tq.parse(resp)[0]
|
q = tq.parse(resp)[0]
|
||||||
self.assertEqual(q["judge_type"], "manual")
|
self.assertEqual(q["judge_type"], "manual")
|
||||||
self.assertIsNone(q["answer"])
|
self.assertIsNone(q["answer"])
|
||||||
|
self.assertIsNone(q["page_answer"])
|
||||||
|
|
||||||
def test_multi_part_stem_joined_in_index_order(self):
|
def test_multi_part_stem_joined_in_index_order(self):
|
||||||
resp = fake_resp([{
|
resp = fake_resp([{
|
||||||
@@ -76,8 +80,16 @@ class ParseTest(unittest.TestCase):
|
|||||||
"Answer": [{"Text": "答案:D"}],
|
"Answer": [{"Text": "答案:D"}],
|
||||||
}])
|
}])
|
||||||
q = tq.parse(resp)[0]
|
q = tq.parse(resp)[0]
|
||||||
self.assertEqual(q["judge_type"], "choice")
|
self.assertEqual(q["judge_type"], "manual")
|
||||||
self.assertIsNone(q["answer"]) # D 不在 A/B 里,不能瞎认
|
self.assertEqual(q["detected_as"], "choice")
|
||||||
|
self.assertEqual(q["page_answer"], "D") # 原样保留,但不参与判分
|
||||||
|
|
||||||
|
def test_calc_derived_when_no_answer_printed(self):
|
||||||
|
resp = fake_resp([{"Question": [{"Text": "1.计算:2.5x4=()"}], "Answer": []}])
|
||||||
|
q = tq.parse(resp)[0]
|
||||||
|
self.assertEqual(q["judge_type"], "calc")
|
||||||
|
self.assertEqual(q["answer"], "10") # 自己算出来的,可以机器判
|
||||||
|
self.assertIsNone(q["page_answer"])
|
||||||
|
|
||||||
def test_empty_or_bad_payload(self):
|
def test_empty_or_bad_payload(self):
|
||||||
self.assertEqual(tq.parse({}), [])
|
self.assertEqual(tq.parse({}), [])
|
||||||
|
|||||||
Reference in New Issue
Block a user