feat: 分数四则精确判分(Fraction)+ 分数解析三步

This commit is contained in:
dev
2026-11-18 22:51:20 +08:00
parent 3e90bfb07a
commit f85adf2af0
8 changed files with 267 additions and 9 deletions
+8
View File
@@ -279,6 +279,14 @@ questions 入库(`options` 列存 JSON 数组,接口直接返回数组)→
- 单块重识别偶尔更差(分数区域容易被切碎),所以用“汉字数多的那份”作为题干,而不是盲信第二次。 - 单块重识别偶尔更差(分数区域容易被切碎),所以用“汉字数多的那份”作为题干,而不是盲信第二次。
- 一次 detect 只调一次切题接口;选中几道就再调几次(N+1 次调用,按次计费要留意)。 - 一次 detect 只调一次切题接口;选中几道就再调几次(N+1 次调用,按次计费要留意)。
### 四点十九、分数:精确算,不算错
- 判分用 `Fraction`:`0.75` 与 `3/4` 是同一个答案,`2/8` 与 `1/4` 也算对;分母为 0 直接拒答。
- 认这几种写法:`3/4`、`1又1/2`、`1 1/2`、`0.75`、`-3/4`。
- 切题时只有「整题就是一个算式、末尾是等号、一个汉字都没有」才自己算答案(`_frac_chain_answer`),
带应用题文字的一律不猜;`2.5×4` 这种开头的小数**不会**被当成题号吃掉。
- 解析(工作台)对分数四则单独出三步:分子乘分子 / 分母乘分母 / 约分;除法则先颠倒再乘。
## 五、接口(56 条,prod 下 48 条) ## 五、接口(56 条,prod 下 48 条)
> `/api/dev/*`(6 条)与 `/api/auth/sms-code`、`/api/auth/sms-login` 只在 `QINGLING_ENV` 不是 > `/api/dev/*`(6 条)与 `/api/auth/sms-code`、`/api/auth/sms-login` 只在 `QINGLING_ENV` 不是
+87 -9
View File
@@ -11,6 +11,7 @@ from __future__ import annotations
import ast import ast
import re import re
import unicodedata import unicodedata
from fractions import Fraction
FW = str.maketrans({ FW = str.maketrans({
"0": "0", "1": "1", "2": "2", "3": "3", "4": "4", "5": "5", "0": "0", "1": "1", "2": "2", "3": "3", "4": "4", "5": "5",
@@ -58,25 +59,95 @@ def safe_eval(expr: str) -> float | None:
if isinstance(node, ast.Constant) and not isinstance(node.value, (int, float)): if isinstance(node, ast.Constant) and not isinstance(node.value, (int, float)):
return None return None
try: try:
value = eval(compile(tree, "<calc>", "eval"), {"__builtins__": {}}, {}) # noqa: S307 value = _eval_fraction(tree.body)
except Exception: except Exception:
return None return None
if isinstance(value, complex): if value is None:
return None return None
return float(value) return value
def _num(text: str | None) -> float | None: 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) s = normalize_answer(text)
m = re.fullmatch(r"-?\d+(?:\.\d+)?", s) if not s:
if m: return None
return float(s) q = to_qty(s)
if q is not None:
return q
return safe_eval(s) 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: def _dirty(text: str | None) -> bool:
"""算式里混进了非数字字符(认不出的笔画、字母、问号)→ 不判。""" """算式里混进了非数字字符(认不出的笔画、字母、问号)→ 不判。"""
raw = unicodedata.normalize("NFKC", str(text or "")).translate(FW) raw = unicodedata.normalize("NFKC", str(text or "")).translate(FW)
raw = raw.replace("又", "")
return bool(re.search(r"[^0-9+\-*/%().=\s]", raw)) return bool(re.search(r"[^0-9+\-*/%().=\s]", raw))
@@ -88,11 +159,18 @@ def judge_calc(expected: str | None, given: str | None, tol: float = 1e-6):
g = _num(given) g = _num(given)
if e is None or g is None: if e is None or g is None:
return None, "算式无法解析,已拒答" return None, "算式无法解析,已拒答"
ok = abs(e - g) <= tol 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)}" return ok, "数值一致" if ok else f"应为 {_fmt(e)},你写的是 {_fmt(g)}"
def _fmt(x: float) -> str: 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}" return str(int(x)) if abs(x - round(x)) < 1e-9 else f"{x:g}"
+38
View File
@@ -235,6 +235,10 @@ def _derive_answer(stem: str):
if _EXPR is None: if _EXPR is None:
_EXPR = re.compile( _EXPR = re.compile(
r"(?<![\d/])(-?\d+(?:\.\d+)?)\s*([+\-×÷xX*])\s*(-?\d+(?:\.\d+)?)\s*=(?![\d/])") r"(?<![\d/])(-?\d+(?:\.\d+)?)\s*([+\-×÷xX*])\s*(-?\d+(?:\.\d+)?)\s*=(?![\d/])")
frac = _frac_chain_answer(stem)
if frac is not None:
return frac
m = _EXPR.search(stem or "") m = _EXPR.search(stem or "")
if not m: if not m:
return None return None
@@ -251,6 +255,40 @@ def _derive_answer(stem: str):
return str(val) return str(val)
_OPERAND = r"\d+(?:\.\d+)?(?:/\d+(?:\.\d+)?)?"
_CHAIN = re.compile(rf"^{_OPERAND}(?:[+\-×÷xX*]{_OPERAND})+$")
_NUMHEAD = re.compile(r"^[((]?\s*\d{1,3}\s*[..、))]\s*(?!\d)")
def _frac_chain_answer(stem: str):
"""整题就是一个算式(可以带分数、多个运算符)时,自己算。
只在「去掉题号后,剩下的全是数字与运算符、且末尾是等号」时才敢算——
带一个汉字就退出,绝不在应用题上猜。
"""
from . import judging
t = clean_text(stem or "").strip()
t = _NUMHEAD.sub("", t)
t = re.sub(r"[((]\s*[))]", "", t)
t = t.strip()
if not t.endswith("="):
return None
body = t[:-1].strip()
if not body or body.count("=") > 0:
return None
if any("\u4e00" <= ch <= "\u9fff" for ch in body):
return None
body = body.replace("×", "*").replace("÷", "/").replace("x", "*").replace("X", "*")
body = re.sub(r"\s+", "", body)
if not _CHAIN.match(body):
return None
val = judging.safe_eval(body)
if val is None:
return None
return judging._fmt(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"
+5
View File
@@ -162,3 +162,8 @@ prototype/workbench/index.html ← 全部代码都在这一个文件里
- 不要求家长只拍一道题:整页拍,切歪了也能靠点选绕过去。 - 不要求家长只拍一道题:整页拍,切歪了也能靠点选绕过去。
- 已做完的卷子也能用:卷面上的手写答案**不会**被当成标准答案,只有纯算式才由我们自算。 - 已做完的卷子也能用:卷面上的手写答案**不会**被当成标准答案,只有纯算式才由我们自算。
- 分数/公式会被转成可读形式(`\frac{1}{4}` → `1/4`);分数四则的自动判分还没做,这类题标「你自己判」。 - 分数/公式会被转成可读形式(`\frac{1}{4}` → `1/4`);分数四则的自动判分还没做,这类题标「你自己判」。
## 十、分数题
- 解析:`1/4×3/5` 这类会走分数专线(分子乘分子 / 分母乘分母 / 约分),不再是「先看个位」。
- 判分:孩子写 `3/20`、`0.15`、`0.150` 都算对;写 `0.1` 会提示「应为 3/20,你写的是 1/10」。
+56
View File
@@ -1423,9 +1423,65 @@ function decimals(x) {
* 以前这里写死「先看个位…满十进一」,所以「2.5 × 4」也会显示加减法的步骤—— * 以前这里写死「先看个位…满十进一」,所以「2.5 × 4」也会显示加减法的步骤——
* 错的不是排版,是内容:孩子照着念会被教错。 * 错的不是排版,是内容:孩子照着念会被教错。
*/ */
function gcd(a, b) { a = Math.abs(a); b = Math.abs(b); while (b) { const t = a % b; a = b; b = t; } return a || 1; }
/* 分数四则:小学五年级的主战场,单独一套说法 */
function fracPlan(body) {
const m = body.match(/(\d+)\s*\/\s*(\d+)\s*([×xX*÷/++\--])\s*(\d+)\s*\/\s*(\d+)/);
if (!m) return null;
const n1 = Number(m[1]), d1 = Number(m[2]), n2 = Number(m[4]), d2 = Number(m[5]);
const op = m[3].replace(/[xX*]/g, "×").replace(/[\/÷]/g, "÷").replace(/+/g, "+").replace(/-/g, "-");
if (!d1 || !d2) return null;
const base = `分母不能是 0;算完记得看能不能约分。`;
if (op === "×") {
const pn = n1 * n2, pd = d1 * d2, g = gcd(pn, pd);
return {
know: "分数乘法",
idea: "分数乘分数,分子乘分子、分母乘分母,能约分的先约分更省事。",
steps: [
`分子乘分子:${n1} × ${n2} = ${pn}。`,
`分母乘分母:${d1} × ${d2} = ${pd}。`,
g > 1 ? `都得 ${pn}/${pd},分子分母同时除以 ${g},约成 ${pn / g}/${pd / g}。` : `分子分母没有公因数,答案就是 ${pn}/${pd}。`,
],
traps: `① 把分母也相乘后忘了约分;② 分子分母交叉约分时约错边;③ ${base}`,
};
}
if (op === "÷") {
const pn = n1 * d2, pd = d1 * n2, g = gcd(pn, pd);
return {
know: "分数除法",
idea: "除以一个分数,等于乘它的倒数——把第二个分数上下颠倒,再按乘法算。",
steps: [
`把 ${n2}/${d2} 颠倒成 ${d2}/${n2},除号变乘号。`,
`分子乘分子、分母乘分母:${n1} × ${d2} = ${pn},${d1} × ${n2} = ${pd}。`,
g > 1 ? `约分:${pn}/${pd} → ${pn / g}/${pd / g}。` : `答案就是 ${pn}/${pd}。`,
],
traps: `① 只颠倒了被除数;② 忘了把除号改成乘号;③ 除数为 0 不可能,但要检查分母。`,
};
}
if (op === "+" || op === "-") {
const pd = d1 * d2, a1 = n1 * d2, a2 = n2 * d1;
const top = op === "+" ? a1 + a2 : a1 - a2;
const g = gcd(top, pd);
return {
know: `分数${op === "+" ? "加" : "减"}法`,
idea: "分母不同要先通分:把两个分数变成同分母,再只加减分子。",
steps: [
`通分:公分母取 ${d1} × ${d2} = ${pd}。`,
`${n1}/${d1} 变成 ${a1}/${pd},${n2}/${d2} 变成 ${a2}/${pd}。`,
`分子${op === "+" ? "相加" : "相减"}:${a1} ${op} ${a2} = ${top},得 ${top}/${pd}${g > 1 ? `,约成 ${top / g}/${pd / g}` : ""}。`,
],
traps: `① 分母直接相加;② 通分后忘了改分子;③ 结果没约分。`,
};
}
return null;
}
function calcPlan(q) { function calcPlan(q) {
const raw = String(q.stem || ""); const raw = String(q.stem || "");
const body = raw.split("=")[0].trim(); const body = raw.split("=")[0].trim();
const fp = fracPlan(body);
if (fp) return fp;
const m = body.match(/(-?\d+(?:\.\d+)?)\s*([++\--×xX*÷/])\s*(-?\d+(?:\.\d+)?)/); const m = body.match(/(-?\d+(?:\.\d+)?)\s*([++\--×xX*÷/])\s*(-?\d+(?:\.\d+)?)/);
if (!m) return null; if (!m) return null;
const a = m[1]; const a = m[1];
Binary file not shown.

After

Width:  |  Height:  |  Size: 117 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 117 KiB

+73
View File
@@ -0,0 +1,73 @@
"""分数判分:小学五年级的核心缺口,这一组是它的护栏。
原则没变——宁可不算,不可算错:
- 只有「整题就是一个算式」时我们才自己算,带一个汉字就不算;
- 判分用 Fraction 精确比较,0.75 与 3/4 视为同一个答案。
"""
import unittest
from backend import judging
from backend.tencent_ocr import _frac_chain_answer as chain
class FractionCompareTest(unittest.TestCase):
def test_equivalent_forms(self):
ok, _ = judging.judge_calc("3/4", "0.75")
self.assertTrue(ok)
ok, _ = judging.judge_calc("0.75", "3/4")
self.assertTrue(ok)
ok, _ = judging.judge_calc("2/8", "1/4")
self.assertTrue(ok, "约分后相等也算对")
def test_mixed_number(self):
ok, msg = judging.judge_calc("1又1/2", "1.5")
self.assertTrue(ok, msg)
def test_wrong_answer_message(self):
ok, msg = judging.judge_calc("3/4", "2/3")
self.assertFalse(ok)
self.assertIn("3/4", msg)
self.assertIn("2/3", msg)
def test_zero_denominator_refused(self):
self.assertIsNone(judging.to_qty("3/0"))
ok, _ = judging.judge_calc("3/4", "3/0")
self.assertIsNone(ok, "分母为 0 应当拒答,而不是判错")
def test_decimal_and_int_still_work(self):
self.assertTrue(judging.judge_calc("83", "83")[0])
self.assertTrue(judging.judge_calc("2.5", "2.50")[0])
class FractionArithmeticTest(unittest.TestCase):
def test_exact_fraction_result(self):
val = judging.safe_eval("3/4*2/5")
self.assertEqual(judging._fmt(val), "3/10")
def test_integer_stays_integer(self):
self.assertEqual(judging._fmt(judging.safe_eval("36+47")), "83")
def test_divide_by_zero(self):
self.assertIsNone(judging.safe_eval("3/0"))
class ChainAnswerTest(unittest.TestCase):
def test_pure_fraction_expression(self):
self.assertEqual(chain("1/4×3/5="), "3/20")
self.assertEqual(chain("3. 3/4×2/5="), "3/10")
def test_decimal_not_eaten_as_numbering(self):
# 「2.5×4」曾把开头的 2. 当题号,剩下 5×4 算出 20
self.assertEqual(chain("2.5×4=( )"), "10")
def test_chinese_text_never_derived(self):
self.assertIsNone(chain("2.5/8吨的4/7是()吨"))
self.assertIsNone(chain("1. 计算:36 + 47 =()"))
def test_two_equals_rejected(self):
# 孩子已经写了答案的卷面:「1/4×3/5=1×3/4×5=3/20」不能拿来当题
self.assertIsNone(chain("1/4×3/5=1×3/4×5=3/20"))
if __name__ == "__main__":
unittest.main()