245 lines
8.2 KiB
Python
245 lines
8.2 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""判题引擎(A 类:封闭答案)。
|
||
|
||
只做「可判性 A」的题:口算、竖式结果、看拼音写词、听写、选择、默写。
|
||
B 类(应用题)只判最终结果;C 类不判,调用方应传 judge_type='manual'。
|
||
|
||
原则:宁可不判,不可判错——算不出来就返回 None(拒答),交给人工。
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import ast
|
||
import re
|
||
import unicodedata
|
||
from fractions import Fraction
|
||
|
||
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_fraction(tree.body)
|
||
except Exception:
|
||
return None
|
||
if value is None:
|
||
return None
|
||
return value
|
||
|
||
|
||
def _eval_fraction(node):
|
||
"""用 Fraction 求值:3/4*2/5 要得 3/10,不能变成 0.30000000000000004。"""
|
||
if isinstance(node, ast.Expression):
|
||
return _eval_fraction(node.body)
|
||
if isinstance(node, ast.Constant):
|
||
v = node.value
|
||
if isinstance(v, bool) or not isinstance(v, (int, float)):
|
||
return None
|
||
return Fraction(str(v)) if isinstance(v, float) else Fraction(v)
|
||
if isinstance(node, ast.UnaryOp):
|
||
v = _eval_fraction(node.operand)
|
||
if v is None:
|
||
return None
|
||
return -v if isinstance(node.op, ast.USub) else v
|
||
if isinstance(node, ast.BinOp):
|
||
a = _eval_fraction(node.left)
|
||
b = _eval_fraction(node.right)
|
||
if a is None or b is None:
|
||
return None
|
||
if isinstance(node.op, ast.Add):
|
||
return a + b
|
||
if isinstance(node.op, ast.Sub):
|
||
return a - b
|
||
if isinstance(node.op, ast.Mult):
|
||
return a * b
|
||
if isinstance(node.op, ast.Div):
|
||
return None if b == 0 else a / b
|
||
if isinstance(node.op, ast.Mod):
|
||
return None if b == 0 else a % b
|
||
if isinstance(node.op, ast.Pow):
|
||
if b.denominator != 1 or abs(b) > 8:
|
||
return None
|
||
return a ** int(b)
|
||
return None
|
||
return None
|
||
|
||
|
||
_MIXED = re.compile(r"^(-?\d+)(?:又|\s)(\d+)\s*/\s*(\d+)$")
|
||
_FRAC = re.compile(r"^(-?\d+)\s*/\s*(\d+)$")
|
||
|
||
|
||
def _num(text: str | None):
|
||
"""把答案读成一个数(可能是 Fraction)。读不出返回 None。"""
|
||
s = normalize_answer(text)
|
||
if not s:
|
||
return None
|
||
q = to_qty(s)
|
||
if q is not None:
|
||
return q
|
||
return safe_eval(s)
|
||
|
||
|
||
def to_qty(text: str | None):
|
||
"""支持 3/4、1又1/2、0.75、-3/4、2/8 这几种写法。"""
|
||
raw = unicodedata.normalize("NFKC", str(text or "")).translate(FW).strip()
|
||
raw = re.sub(r"\s+", " ", raw)
|
||
m = _MIXED.match(raw)
|
||
if m:
|
||
whole, num, den = int(m.group(1)), int(m.group(2)), int(m.group(3))
|
||
if den == 0:
|
||
return None
|
||
sign = -1 if whole < 0 else 1
|
||
return sign * (abs(whole) + Fraction(num, den))
|
||
s = normalize(text)
|
||
if not s:
|
||
return None
|
||
m = _FRAC.match(s)
|
||
if m:
|
||
den = int(m.group(2))
|
||
if den == 0:
|
||
return None
|
||
return Fraction(int(m.group(1)), den)
|
||
if re.fullmatch(r"-?\d+(?:\.\d+)?", s):
|
||
return Fraction(s)
|
||
return None
|
||
|
||
|
||
def _dirty(text: str | None) -> bool:
|
||
"""算式里混进了非数字字符(认不出的笔画、字母、问号)→ 不判。"""
|
||
raw = unicodedata.normalize("NFKC", str(text or "")).translate(FW)
|
||
raw = raw.replace("又", "")
|
||
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, "算式无法解析,已拒答"
|
||
if isinstance(e, Fraction) and isinstance(g, Fraction):
|
||
ok = e == g
|
||
else:
|
||
ok = abs(float(e) - float(g)) <= tol
|
||
return ok, "数值一致" if ok else f"应为 {_fmt(e)},你写的是 {_fmt(g)}"
|
||
|
||
|
||
def _fmt(x) -> str:
|
||
if isinstance(x, Fraction):
|
||
if x.denominator == 1:
|
||
return str(x.numerator)
|
||
return f"{x.numerator}/{x.denominator}"
|
||
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"
|