refactor: 抽出 core/(clock store text numeric),小学版与初中版共用归一化与数值解析
This commit is contained in:
@@ -0,0 +1,41 @@
|
||||
# core —— 两个产品共用的纯函数
|
||||
|
||||
这里只放**与业务无关**的纯函数:给定输入就有确定输出,不读数据库、不知道「错题」「毕业」「家长」这些概念。
|
||||
|
||||
一旦某个函数需要知道业务(比如「连续对两次该怎么改状态」),它就**不该**放在这里——留在各自的 `backend/`(小学版)或 `junior/`(初中版)。
|
||||
|
||||
## 有什么
|
||||
|
||||
| 文件 | 内容 | 谁在用 |
|
||||
|---|---|---|
|
||||
| `clock.py` | `now()` / `today()` / `add_days()` / `new_id()`,统一 +08:00 | 两个版本的 db 与 services |
|
||||
| `store.py` | `open_db()`(`isolation_level=None`)、`row_to_dict()` / `rows_to_list()`、`ensure_columns()`(老库补列) | 两个版本的 db |
|
||||
| `text.py` | `halfwidth()` 全角转半角、`squeeze()` 去空白、`strip_punct()` / `strip_units()` / `strip_tail()`、`has_chinese()` | 两个版本的 judging |
|
||||
| `numeric.py` | `eval_exact()` 用 `Fraction` 精确算四则、`to_qty()` 认 `3/4` `1又1/2` `0.75`、`fmt_qty()` 输出 `3/10` | 两个版本的 judging |
|
||||
|
||||
## 为什么只有这几样
|
||||
|
||||
`backend/judging.py` 与 `junior/judging.py` 之前是复制粘贴:同一段 `normalize`、同一个 `safe_eval`、同一套分数解析,改一处要改两处,一不留神就漂。所以真正共享的只有**归一化与数值**这两层。
|
||||
|
||||
**有意不抽的**:
|
||||
|
||||
- `normalize()` 本身。小学版连标点一起去掉(`83。` 与 `83` 视为同一个答案);初中版保留标点(语文默写要逐字比)。策略不同,只共享零件。
|
||||
- 单位表。小学是元/角/分/米/厘米;初中是 m/s、kg/m³、Ω、℃。放一起会互相污染。
|
||||
- `log_event()`。两个表的列名不同(`child_id` vs `student_id`),而且各自要记的事件也不同。
|
||||
- 调度器(`scheduler.py`)。小学版是「连对两次 + 讲清」,初中版是「连对两次 + 变式 + 讲清」,状态机不同。
|
||||
- `services.py`。业务本来就该分开。
|
||||
|
||||
## 加东西的判断标准
|
||||
|
||||
问三个问题,都是「是」才放进来:
|
||||
|
||||
1. 两个产品都会用、且用法完全一样?
|
||||
2. 不依赖任何业务概念(不许出现 mistake / guardian / graduated)?
|
||||
3. 单独写测试就能验证(不需要建库、不需要起服务)?
|
||||
|
||||
改完记得跑两边的测试:
|
||||
|
||||
```powershell
|
||||
python -m unittest tests.test_backend tests.test_ocr tests.test_choice tests.test_scan tests.test_kp tests.test_ocr_http tests.test_hardening tests.test_scan_flow tests.test_frac tests.test_junior
|
||||
python tests/smoke_http.py; python tests/smoke_junior.py
|
||||
```
|
||||
@@ -0,0 +1,6 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""两个产品共用的小工具(小学版 backend、初中版 junior)。
|
||||
|
||||
只放「与业务无关、纯函数」的东西:时间、ID、sqlite 连接、文本归一化、数值解析。
|
||||
一旦某个函数需要知道「错题」「毕业」这些概念,它就不该放在这里。
|
||||
"""
|
||||
@@ -0,0 +1,25 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""时间与 ID:两个产品都用东八区,都只用「人可读的 ISO 秒」存时间。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
|
||||
TZ = timezone(timedelta(hours=8))
|
||||
|
||||
|
||||
def now() -> str:
|
||||
return datetime.now(TZ).isoformat(timespec="seconds")
|
||||
|
||||
|
||||
def today() -> str:
|
||||
return datetime.now(TZ).date().isoformat()
|
||||
|
||||
|
||||
def add_days(days: int, base: str | None = None) -> str:
|
||||
d = date.fromisoformat(base) if base else date.fromisoformat(today())
|
||||
return (d + timedelta(days=days)).isoformat()
|
||||
|
||||
|
||||
def new_id(prefix: str) -> str:
|
||||
return f"{prefix}_{uuid.uuid4().hex[:12]}"
|
||||
+103
@@ -0,0 +1,103 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""数值解析:用 Fraction 精确算,避免 0.1 + 0.2 这种浮点噪声把「对的」判成「错的」。
|
||||
|
||||
两个产品都用它:
|
||||
- 小学版包一层 try/except 返回 None(拒答);
|
||||
- 初中版让异常往外抛(自己转成「不判」)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import ast
|
||||
import re
|
||||
from fractions import Fraction
|
||||
|
||||
_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)
|
||||
|
||||
_MIXED = re.compile(r"^(-?\d+)(?:又| )(\d+)\s*/\s*(\d+)$")
|
||||
_FRAC = re.compile(r"^(-?\d+)\s*/\s*(\d+)$")
|
||||
_DEC = re.compile(r"^-?\d+(?:\.\d+)?$")
|
||||
|
||||
|
||||
def eval_exact(expr: str) -> Fraction:
|
||||
"""只允许数字与四则运算,返回精确分数。不认识的输入抛 ValueError。"""
|
||||
expr = re.sub(r"[^0-9+\-*/%().]", "", expr or "")
|
||||
if not expr or len(expr) > 64:
|
||||
raise ValueError("empty or too long")
|
||||
tree = ast.parse(expr, mode="eval")
|
||||
for node in ast.walk(tree):
|
||||
if not isinstance(node, _ALLOWED):
|
||||
raise ValueError(f"bad node {type(node).__name__}")
|
||||
if isinstance(node, ast.Constant) and (
|
||||
isinstance(node.value, bool) or not isinstance(node.value, (int, float))
|
||||
):
|
||||
raise ValueError("bad constant")
|
||||
value = _eval(tree.body)
|
||||
if value is None:
|
||||
raise ValueError("bad expression")
|
||||
return value
|
||||
|
||||
|
||||
def _eval(node) -> Fraction | None:
|
||||
if isinstance(node, ast.Expression):
|
||||
return _eval(node.body)
|
||||
if isinstance(node, ast.Constant):
|
||||
v = node.value
|
||||
return Fraction(str(v)) if isinstance(v, float) else Fraction(v)
|
||||
if isinstance(node, ast.UnaryOp):
|
||||
v = _eval(node.operand)
|
||||
return None if v is None else (-v if isinstance(node.op, ast.USub) else v)
|
||||
if isinstance(node, ast.BinOp):
|
||||
a, b = _eval(node.left), _eval(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
|
||||
|
||||
|
||||
def to_qty(text: str) -> Fraction | None:
|
||||
"""把「3/4」「1又1/2」「0.75」「-3/4」「2/8」读成一个精确数。"""
|
||||
from .text import halfwidth, squeeze
|
||||
|
||||
raw = re.sub(r"\s+", " ", halfwidth(text).strip())
|
||||
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 = squeeze(raw)
|
||||
m = _FRAC.match(s)
|
||||
if m:
|
||||
den = int(m.group(2))
|
||||
return None if den == 0 else Fraction(int(m.group(1)), den)
|
||||
if _DEC.match(s):
|
||||
return Fraction(s)
|
||||
return None
|
||||
|
||||
|
||||
def fmt_qty(x) -> str:
|
||||
"""3/10 而不是 0.3;整数不带小数点。"""
|
||||
if isinstance(x, Fraction):
|
||||
if x.denominator == 1:
|
||||
return str(x.numerator)
|
||||
return f"{x.numerator}/{x.denominator}"
|
||||
try:
|
||||
return str(int(x)) if abs(float(x) - round(float(x))) < 1e-9 else f"{float(x):g}"
|
||||
except (TypeError, ValueError):
|
||||
return str(x)
|
||||
@@ -0,0 +1,49 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""sqlite 的公共部分:连库、行转字典、补列(老库升级用)。
|
||||
|
||||
刻意不碰「建表」:两个产品的表结构不一样,SCHEMA 留在各自包里。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlite3
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def open_db(path: str | Path, *, timeout: float = 15,
|
||||
check_same_thread: bool = False) -> sqlite3.Connection:
|
||||
"""打开一个「自己管事务」的库:isolation_level=None。
|
||||
|
||||
两个产品都在 services 里显式 BEGIN/COMMIT(tx()),如果这里再开自动事务,
|
||||
会撞上 `sqlite3.OperationalError: cannot start a transaction within a transaction`。
|
||||
"""
|
||||
p = Path(path)
|
||||
p.parent.mkdir(parents=True, exist_ok=True)
|
||||
conn = sqlite3.connect(str(p), timeout=timeout,
|
||||
check_same_thread=check_same_thread,
|
||||
isolation_level=None)
|
||||
conn.row_factory = sqlite3.Row
|
||||
conn.execute("PRAGMA foreign_keys=ON")
|
||||
return conn
|
||||
|
||||
|
||||
def row_to_dict(row) -> dict | None:
|
||||
return dict(row) if row is not None else None
|
||||
|
||||
|
||||
def rows_to_list(rows) -> list[dict]:
|
||||
return [dict(r) for r in rows]
|
||||
|
||||
|
||||
def ensure_columns(conn: sqlite3.Connection, table: str, cols: dict[str, str]) -> list[str]:
|
||||
"""给老库补列:`CREATE TABLE IF NOT EXISTS` 不会改已存在的表。
|
||||
|
||||
:param cols: {列名: 类型},例如 {"kp": "TEXT"}
|
||||
:return: 真正补上的列名
|
||||
"""
|
||||
have = {r["name"] for r in conn.execute(f"PRAGMA table_info({table})").fetchall()}
|
||||
added = []
|
||||
for name, ctype in cols.items():
|
||||
if name not in have:
|
||||
conn.execute(f"ALTER TABLE {table} ADD COLUMN {name} {ctype}")
|
||||
added.append(name)
|
||||
return added
|
||||
@@ -0,0 +1,56 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""文本归一化的小零件。
|
||||
|
||||
注意:两个产品的「归一化」策略不一样(小学版连标点一起去掉,初中版保留标点),
|
||||
所以这里只提供零件,不提供一揽子 normalize——策略留在各自的包里。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
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 = "。,、;:?!“”‘’()《》〈〉【】…—~·.,;:?!\"'()[]{}<>"
|
||||
|
||||
# 答案末尾常见单位(小学口径)
|
||||
UNITS = ("平方厘米", "平方米", "立方厘米", "元", "角", "分", "厘米", "分米", "毫米",
|
||||
"千米", "千克", "平方", "米", "克", "吨", "个", "只", "本", "支", "块",
|
||||
"岁", "人", "天", "时", "秒", "度")
|
||||
|
||||
|
||||
def halfwidth(s: str) -> str:
|
||||
"""全角转半角(不删空格、不去标点)。"""
|
||||
return unicodedata.normalize("NFKC", str(s or "")).translate(FW)
|
||||
|
||||
|
||||
def squeeze(s: str) -> str:
|
||||
"""去掉所有空白。"""
|
||||
return re.sub(r"\s+", "", s or "")
|
||||
|
||||
|
||||
def strip_punct(s: str) -> str:
|
||||
return (s or "").strip(PUNCT)
|
||||
|
||||
|
||||
def strip_units(s: str) -> str:
|
||||
"""去掉答案末尾的单位(只去掉一个,避免把「平方米」拆两次)。"""
|
||||
for u in UNITS:
|
||||
if s.endswith(u):
|
||||
return s[: -len(u)]
|
||||
return s
|
||||
|
||||
|
||||
def strip_tail(s: str) -> str:
|
||||
"""去掉句末标点(初中版用:保留句中逗号冒号)。"""
|
||||
return re.sub(r"[。.!!??;;]+$", "", s or "")
|
||||
|
||||
|
||||
def has_chinese(s: str) -> bool:
|
||||
return any("\u4e00" <= ch <= "\u9fff" for ch in (s or ""))
|
||||
Reference in New Issue
Block a user