Files
cuotibiye/backend/judging.py
T

167 lines
5.8 KiB
Python
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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 -*-
"""判题引擎(A 类:封闭答案)。
只做「可判性 A」的题:口算、竖式结果、看拼音写词、听写、选择、默写。
B 类(应用题)只判最终结果;C 类不判,调用方应传 judge_type='manual'。
原则:宁可不判,不可判错——算不出来就返回 None(拒答),交给人工。
"""
from __future__ import annotations
import ast
import re
import unicodedata
FW = str.maketrans({
"0": "0", "1": "1", "2": "2", "3": "3", "4": "4", "5": "5",
"6": "6", "7": "7", "8": "8", "9": "9",
"+": "+", "-": "-", "×": "*", "÷": "/", "=": "=", "(": "(", ")": ")",
".": ".", " ": " ",
})
PUNCT = "。,、;:?!“”‘’()《》〈〉【】…—~·.,;:?!\"'()[]{}<>"
def normalize(text: str | None) -> str:
if text is None:
return ""
s = unicodedata.normalize("NFKC", str(text)).translate(FW)
s = s.strip()
s = re.sub(r"\s+", "", s)
return s.strip(PUNCT)
def normalize_answer(text: str | None) -> str:
"""去掉末尾的「=」与单位、括号,用于比较。"""
s = normalize(text)
s = s.rstrip("=")
s = re.sub(r"(元|角|分|米|厘米|分米|毫米|千米|克|千克|吨|个|只|本|支|块|岁|人|天|时|分|秒|度|平方厘米|平方米|立方厘米)$", "", s)
return s
_ALLOWED = (ast.Expression, ast.BinOp, ast.UnaryOp, ast.Constant,
ast.Add, ast.Sub, ast.Mult, ast.Div, ast.Mod, ast.USub, ast.UAdd, ast.Pow)
def safe_eval(expr: str) -> float | None:
"""只允许数字与四则运算,其余一律拒答。"""
expr = normalize(expr).replace("=", "")
expr = re.sub(r"[^0-9+\-*/%().]", "", expr)
if not expr or len(expr) > 64:
return None
try:
tree = ast.parse(expr, mode="eval")
except SyntaxError:
return None
for node in ast.walk(tree):
if not isinstance(node, _ALLOWED):
return None
if isinstance(node, ast.Constant) and not isinstance(node.value, (int, float)):
return None
try:
value = eval(compile(tree, "<calc>", "eval"), {"__builtins__": {}}, {}) # noqa: S307
except Exception:
return None
if isinstance(value, complex):
return None
return float(value)
def _num(text: str | None) -> float | None:
s = normalize_answer(text)
m = re.fullmatch(r"-?\d+(?:\.\d+)?", s)
if m:
return float(s)
return safe_eval(s)
def _dirty(text: str | None) -> bool:
"""算式里混进了非数字字符(认不出的笔画、字母、问号)→ 不判。"""
raw = unicodedata.normalize("NFKC", str(text or "")).translate(FW)
return bool(re.search(r"[^0-9+\-*/%().=\s]", raw))
def judge_calc(expected: str | None, given: str | None, tol: float = 1e-6):
"""口算/竖式:比对数值。算不出给 None(拒答)。"""
if _dirty(expected) or _dirty(given):
return None, "写得看不清,已拒答"
e = _num(expected)
g = _num(given)
if e is None or g is None:
return None, "算式无法解析,已拒答"
ok = abs(e - g) <= tol
return ok, "数值一致" if ok else f"应为 {_fmt(e)},你写的是 {_fmt(g)}"
def _fmt(x: float) -> str:
return str(int(x)) if abs(x - round(x)) < 1e-9 else f"{x:g}"
def judge_text(expected: str | None, given: str | None):
"""听写/看拼音写词/默写:归一化后逐字比对。"""
e = normalize_answer(expected)
g = normalize_answer(given)
if not e:
return None, "没有标准答案,已拒答"
if not g:
return False, "没有写答案"
if e == g:
return True, "完全正确"
# 逐字定位,给出「第几个字错」
diff = next((i for i, (a, b) in enumerate(zip(e, g)) if a != b), min(len(e), len(g)))
if len(g) < len(e):
return False, f"少了第 {diff + 1} 个字"
if len(g) > len(e):
return False, f"多了字(第 {diff + 1} 个字开始)"
return False, f"第 {diff + 1} 个字写错:应为「{e[diff]}」,你写的是「{g[diff]}」"
def _letter(s: str | None) -> str:
"""从「B」「b」「选B」「B. 11」里取出选项字母。"""
t = normalize(s or "").upper()
m = re.search(r"[A-D]", t)
return m.group(0) if m else ""
def judge_choice(expected: str | None, given: str | None):
e = _letter(expected)
if e:
g = _letter(given)
if not g:
return False, "没有选选项"
if e == g:
return True, "选对了"
return False, f"应选 {e},你选了 {g}"
# 老数据里答案存的是「选项文本」而不是字母(选字填空),比对字面即可
et = normalize_answer(expected)
gt = normalize_answer(given)
if not et:
return None, "没有标准答案,已拒答"
if not gt:
return False, "没有作答"
if et == gt:
return True, "选对了"
return False, f"应选「{et}」"
def judge(judge_type: str, expected: str | None, given: str | None):
"""统一入口。返回 (correct: bool|None, detail: str)。None = 拒答/需人工。"""
if judge_type == "calc":
return judge_calc(expected, given)
if judge_type == "choice":
return judge_choice(expected, given)
if judge_type == "text":
return judge_text(expected, given)
return None, "这类题机器不判,留给家长/老师"
def infer_judge_type(stem: str, subject: str) -> str:
"""没有题库时,按题干猜题型(真实环境应来自切题+题型分类)。"""
s = normalize(stem)
if re.search(r"\d\s*[+\-*/×÷]\s*\d", s) or re.fullmatch(r"[\d\s+\-*/()=.]+", s):
return "calc"
if subject == "chinese" and ("(" in stem and ")" in stem):
return "choice"
if subject == "chinese":
return "text"
return "manual"