204 lines
7.5 KiB
Python
204 lines
7.5 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""判题引擎(初中版):分学科、宁可不判不可判错。
|
||
|
||
五个学科各有自己的「可判」边界:
|
||
math 算式 / 数值 / 选择 —— 只允许数字与四则运算,混进别的字符就拒答
|
||
physics 数值 + 单位 —— 缺单位、单位不一致,一律拒答
|
||
chemistry 化学式 / 方程式 —— 大小写与下标归一后比对;含中文描述拒答
|
||
english 拼写 / 选择 —— 忽略大小写与句末标点
|
||
chinese 默写 / 选择 —— 逐字比对;阅读题一律 manual
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import ast
|
||
import re
|
||
import unicodedata
|
||
|
||
FW = {ord(c): ord(c) - 0xFEE0 for c in "0123456789+-×÷=()"}
|
||
FW[ord(" ")] = ord(" ")
|
||
|
||
_ALLOWED = (ast.Expression, ast.BinOp, ast.UnaryOp, ast.Constant, ast.Add, ast.Sub,
|
||
ast.Mult, ast.Div, ast.Pow, ast.Mod, ast.USub, ast.UAdd, ast.FloorDiv,
|
||
ast.Load)
|
||
|
||
_UNIT_ALIAS = {
|
||
"米": "m", "千米": "km", "厘米": "cm", "毫米": "mm",
|
||
"秒": "s", "分钟": "min", "小时": "h",
|
||
"千克": "kg", "克": "g", "牛": "N", "牛顿": "N",
|
||
"帕": "Pa", "焦": "J", "焦耳": "J", "瓦": "W", "瓦特": "W",
|
||
"伏": "V", "安": "A", "欧": "Ω", "摄氏度": "℃", "度": "℃",
|
||
"立方米": "m3", "立方厘米": "cm3", "毫升": "mL", "升": "L",
|
||
}
|
||
_UNITS = set(_UNIT_ALIAS.values()) | {"m/s", "km/h", "g/cm3", "kg/m3", "m2", "cm2", "s-1"}
|
||
|
||
|
||
def normalize(s: str) -> str:
|
||
if s is None:
|
||
return ""
|
||
s = unicodedata.normalize("NFKC", str(s)).translate(FW)
|
||
s = s.replace("×", "*").replace("÷", "/").replace("=", "=")
|
||
s = s.replace(",", ",").replace(";", ";").replace(":", ":")
|
||
return re.sub(r"\s+", "", s).strip()
|
||
|
||
|
||
def strip_tail(s: str) -> str:
|
||
return re.sub(r"[。.!!??;;]+$", "", s)
|
||
|
||
|
||
def safe_eval(expr: str):
|
||
"""只算四则运算;任何不认识的东西都抛 ValueError。"""
|
||
if not expr or len(expr) > 80:
|
||
raise ValueError("bad")
|
||
tree = ast.parse(expr, mode="eval")
|
||
for node in ast.walk(tree):
|
||
if not isinstance(node, _ALLOWED):
|
||
raise ValueError("bad node")
|
||
return eval(compile(tree, "<judge>", "eval"), {"__builtins__": {}}, {})
|
||
|
||
|
||
_CALC_OK = re.compile(r"^[0-9+\-*/().=]+$")
|
||
|
||
|
||
def judge_calc(user: str, answer: str):
|
||
u, a = normalize(user), normalize(answer)
|
||
if not _CALC_OK.match(u):
|
||
return None, "答案里有非数字符号,这次不判(交给老师或家长)"
|
||
if "=" in u:
|
||
u = u.split("=")[-1]
|
||
try:
|
||
got = safe_eval(u)
|
||
except Exception: # noqa: BLE001
|
||
return None, "算不出你的答案,这次不判"
|
||
try:
|
||
want = safe_eval(a.split("=")[-1]) if _CALC_OK.match(a) else None
|
||
except Exception: # noqa: BLE001
|
||
want = None
|
||
if want is None:
|
||
return strip_tail(u) == strip_tail(a), ""
|
||
ok = abs(float(got) - float(want)) < 1e-6
|
||
return ok, "" if ok else f"你算的是 {got:g},正确答案是 {want:g}"
|
||
|
||
|
||
def _split_value_unit(s: str):
|
||
m = re.match(r"^(-?\d+(?:\.\d+)?)([a-zA-Z/℃Ω]+|[\u4e00-\u9fa5]+)?$", s)
|
||
if not m:
|
||
return None, None
|
||
unit = m.group(2)
|
||
if unit and unit in _UNIT_ALIAS:
|
||
unit = _UNIT_ALIAS[unit]
|
||
return float(m.group(1)), unit
|
||
|
||
|
||
def judge_numeric(user: str, answer: str):
|
||
u, a = normalize(user), normalize(answer)
|
||
uv, uu = _split_value_unit(u)
|
||
if uv is None:
|
||
return None, "看不懂你的答案格式,这次不判"
|
||
av, au = _split_value_unit(a)
|
||
if au and not uu:
|
||
return None, "你只写了数字没写单位,这次不判"
|
||
if uu and au and uu != au:
|
||
return None, f"单位不一样(你写 {uu},参考答案 {au}),这次不判"
|
||
if av is None:
|
||
return None, "参考答案没解析出来,这次不判"
|
||
ok = abs(uv - av) < 1e-6
|
||
return ok, "" if ok else f"你填 {uv:g}{uu or ''},正确答案是 {av:g}{au or ''}"
|
||
|
||
|
||
def norm_formula(s: str) -> str:
|
||
"""H2O / h2o / H₂O → H2O;元素首字母大写、次字母小写。"""
|
||
s = normalize(s).replace("₂", "2").replace("₃", "3").replace("₄", "4")
|
||
s = s.replace("→", "=").replace("—>", "=")
|
||
out, prev = [], ""
|
||
for ch in s:
|
||
if ch.isalpha():
|
||
out.append(ch.upper() if (prev == "" or prev.isdigit() or prev in "+=") else ch.lower())
|
||
else:
|
||
out.append(ch)
|
||
prev = ch
|
||
return "".join(out)
|
||
|
||
|
||
def judge_chemistry(user: str, answer: str):
|
||
u, a = normalize(user), normalize(answer)
|
||
if re.search(r"[\u4e00-\u9fa5]", u) or re.search(r"[\u4e00-\u9fa5]", a):
|
||
return None, "这道题不是纯化学式,交给老师"
|
||
if not a:
|
||
return None, "参考答案为空,这次不判"
|
||
ok = norm_formula(u) == norm_formula(a)
|
||
return ok, "" if ok else "化学式没对上(注意大小写与下标)"
|
||
|
||
|
||
def judge_english(user: str, answer: str):
|
||
def norm(x):
|
||
x = unicodedata.normalize("NFKC", str(x or "")).lower()
|
||
x = re.sub(r"[,.!?;:'\"]", "", x)
|
||
return re.sub(r"\s+", " ", x).strip()
|
||
u, a = norm(user), norm(answer)
|
||
if not a:
|
||
return None, "参考答案为空,这次不判"
|
||
ok = u == a
|
||
if ok:
|
||
return True, ""
|
||
# 拼写只差一个字母:不判,避免把「大小写/标点」当成错
|
||
if len(u) == len(a):
|
||
diff = sum(1 for x, y in zip(u, a) if x != y)
|
||
if diff == 1:
|
||
return None, "只差一个字母,可能是手误,这次不判"
|
||
return False, "拼写不对"
|
||
|
||
|
||
def judge_text(user: str, answer: str):
|
||
u, a = strip_tail(normalize(user)), strip_tail(normalize(answer))
|
||
if not a:
|
||
return None, "参考答案为空,这次不判"
|
||
if u == a:
|
||
return True, ""
|
||
if len(u) == len(a):
|
||
for i, (x, y) in enumerate(zip(u, a)):
|
||
if x != y:
|
||
return False, f"第 {i + 1} 个字写错了(你写「{x}」,应是「{y}」)"
|
||
if len(u) < len(a):
|
||
return False, f"少了 {len(a) - len(u)} 个字(正确答案 {len(a)} 个字)"
|
||
return False, "和正确答案不一样"
|
||
|
||
|
||
def judge(subject: str, judge_type: str, user: str, answer: str):
|
||
"""返回 (correct, detail)。correct=None 表示拒答(不判对错)。"""
|
||
jt = (judge_type or "").strip().lower()
|
||
if jt == "manual":
|
||
return None, "这道题机器不判,留给老师"
|
||
if jt == "calc":
|
||
return judge_calc(user, answer)
|
||
if jt == "numeric":
|
||
return judge_numeric(user, answer)
|
||
if jt == "choice":
|
||
u, a = normalize(user)[:1].upper(), normalize(answer)[:1].upper()
|
||
if not a:
|
||
return None, "参考答案为空"
|
||
return (u == a), "" if u == a else f"正确答案是 {a}"
|
||
if jt == "text":
|
||
if subject == "chemistry":
|
||
return judge_chemistry(user, answer)
|
||
if subject == "english":
|
||
return judge_english(user, answer)
|
||
return judge_text(user, answer)
|
||
return None, "这类题暂不判"
|
||
|
||
|
||
def infer_type(subject: str, stem: str, answer: str) -> str:
|
||
a = normalize(answer)
|
||
if subject == "chinese" and ("阅读" in stem or "概括" in stem or "赏析" in stem):
|
||
return "manual"
|
||
if re.fullmatch(r"[A-Da-d]", a):
|
||
return "choice"
|
||
if subject == "math" and re.fullmatch(r"[0-9+\-*/().=]+", a):
|
||
return "calc"
|
||
if subject == "physics" and re.match(r"^-?\d+(\.\d+)?", a):
|
||
return "numeric"
|
||
if subject == "chemistry":
|
||
return "text"
|
||
if subject == "english":
|
||
return "text"
|
||
return "text"
|