224 lines
10 KiB
Python
224 lines
10 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""把 OCR 出来的行,切成「一道一道题」。
|
||
|
||
真实世界的卷子没有统一格式,所以这里只做三件事,宁少不多:
|
||
1. 按题号切(1. / 1、 / (1) / ①),没题号的行并到上一题;
|
||
2. 丢掉页眉页脚(姓名、班级、得分、第 X 页、分数括号);
|
||
3. 能算的把答案算出来(36+47=( )→ 83),算不出的标 manual,让人自己判。
|
||
|
||
切不准的代价比切错小:切少了用户手动补,切错了用户取消勾选。
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import re
|
||
|
||
from . import judging
|
||
|
||
NUM_HEAD = re.compile(r"^[((【\[]?\s*(\d{1,3})\s*[..、·・•。))\]】]\s*")
|
||
CIRCLED = re.compile(r"^([①-⑳])\s*")
|
||
SECTION = re.compile(r"^[一二三四五六七八九十]{1,2}\s*[、..]\s*")
|
||
DROP = re.compile(r"(姓\s*名|班\s*级|学\s*号|得\s*分|第\s*\d+\s*页|共\s*\d+\s*页|密\s*封|装\s*订)")
|
||
EXPR = re.compile(r"([0-9][0-9\s+\-*/().]*?)\s*=\s*(?:[((]\s*[))]?|$)")
|
||
TAIL = re.compile(r"([0-9][0-9\s]*[+\-*/][0-9\s]*[0-9])\s*$")
|
||
PURE = re.compile(r"^[\d\s+\-*/().]+$")
|
||
|
||
FACT = re.compile(r"\d{1,4}\s*[+\-*/×÷]\s*\d{1,4}\s*=\s*(?:[((]\s*[))]?)?")
|
||
CIRCLED_MAP = {chr(0x2460 + i): i + 1 for i in range(20)}
|
||
|
||
# 选项:单独一行「A.10」「B、11」「(C)12」,或同一行里连着四个
|
||
OPT_LINE = re.compile(r"^[((]?\s*([A-Da-d])\s*[..、,,))::]\s*(.+)$")
|
||
# 选项之间没有空格时(「A.快乐B.音乐C.长大D.银行」),靠字母 + 顿号硬切
|
||
OPT_NOSPACE = re.compile(r"([A-Da-d])\s*[..、]\s*([^A-Da-d]{1,40}?)(?=[A-Da-d]\s*[..、]|$)")
|
||
# 单独一行的答案:「83」「34」「40 厘米」——只在题干以「=」「( )」「___」收尾时才认
|
||
ANS_LINE = re.compile(r"^[\d\s.,.,]+?(?:厘米|米|元|角|分|个|只|岁|千克|克|平方厘米|平方米)?$")
|
||
|
||
|
||
def _opts_nospace(text: str) -> list[tuple[str, str]]:
|
||
"""无空格选项:至少要 3 个才敢切,避免把英文单词里的字母当选项。"""
|
||
hits = [(k.upper(), v.strip().rstrip("。")) for k, v in OPT_NOSPACE.findall(text)]
|
||
return hits if len(hits) >= 3 else []
|
||
|
||
|
||
def _looks_answer(text: str, cur: dict | None) -> bool:
|
||
if cur is None:
|
||
return False
|
||
t = text.strip()
|
||
if not t or len(t) > 12 or not ANS_LINE.match(t):
|
||
return False
|
||
tail = "".join(cur.get("parts") or [])[-8:]
|
||
return any(m in tail for m in ("=", "(", "(", "_", "_"))
|
||
|
||
|
||
OPT_INLINE = re.compile(r"[((]?\s*([A-Da-d])\s*[..、,,))::]\s*([^\sA-Da-d].*?)(?=\s+[((]?\s*[A-Da-d]\s*[..、,,))::]|$)")
|
||
ANS_MARK = re.compile(r"[((]\s*([A-Da-d])\s*[))]|答案\s*[::]?\s*([A-Da-d])|故选\s*([A-Da-d])")
|
||
|
||
|
||
def _fix_math(text: str) -> str:
|
||
"""OCR 常把减号认成一,把乘号认成 x,只在算式上下文里修。"""
|
||
t = text.replace("×", "*").replace("÷", "/")
|
||
# 数字 一 数字 → 数字 - 数字
|
||
t = re.sub(r"(?<=\d)\s*一\s*(?=\d)", "-", t)
|
||
t = re.sub(r"(?<=\d)\s*[xX]\s*(?=\d)", "*", t)
|
||
return t
|
||
|
||
|
||
def _calc_answer(stem: str) -> str | None:
|
||
t = _fix_math(stem)
|
||
m = EXPR.search(t) or TAIL.search(t)
|
||
if not m:
|
||
return None
|
||
expr = m.group(1).strip()
|
||
if not PURE.match(expr):
|
||
return None
|
||
try:
|
||
val = judging.safe_eval(expr)
|
||
except Exception: # noqa: BLE001
|
||
return None
|
||
if val is None:
|
||
return None
|
||
if isinstance(val, float) and abs(val - round(val)) < 1e-9:
|
||
val = int(round(val))
|
||
return str(val)
|
||
|
||
|
||
def _guess_subject(stem: str, default: str) -> str:
|
||
s = stem
|
||
if re.search(r"(看拼音|写词|组词|拼音|笔顺|偏旁|生字|读一读|默写|造句|反义词|近义词)", s):
|
||
return "chinese"
|
||
if re.search(r"[0-9]\s*[+\-*/×÷]\s*[0-9]", _fix_math(s)) or re.search(r"(计算|竖式|面积|周长|多少|应用题)", s):
|
||
return "math"
|
||
if re.search(r"[a-zA-Z]{2,}\s*[āáǎàēéěèīíǐìōóǒòūúǔùǖǘǚǜ]", s):
|
||
return "chinese"
|
||
return default
|
||
|
||
|
||
def segment(lines: list[dict], subject: str = "math", max_questions: int = 30) -> list[dict]:
|
||
"""lines 来自 ocr.recognize(已按 y 排序)。返回题目列表。"""
|
||
items: list[dict] = []
|
||
cur = None
|
||
auto = 0
|
||
for ln in lines:
|
||
text = (ln.get("text") or "").strip()
|
||
if not text:
|
||
continue
|
||
if DROP.search(text) and len(text) <= 24:
|
||
continue
|
||
if SECTION.match(text):
|
||
# 大题标题(一、填空)不单独成题,也不并入上一题
|
||
cur = None
|
||
continue
|
||
head = NUM_HEAD.match(text)
|
||
if head:
|
||
auto += 1
|
||
cur = {"seq": int(head.group(1)) if head.group(1) else auto,
|
||
"parts": [text[head.end():].strip()], "y": ln.get("y") or 0, "opts": {}}
|
||
items.append(cur)
|
||
continue
|
||
cir = CIRCLED.match(text)
|
||
if cir:
|
||
auto += 1
|
||
num = CIRCLED_MAP.get(cir.group(1), auto)
|
||
cur = {"seq": num, "parts": [text[cir.end():].strip()], "y": ln.get("y") or 0, "opts": {}}
|
||
items.append(cur)
|
||
continue
|
||
if cur is not None:
|
||
inline = OPT_INLINE.findall(text) or _opts_nospace(text)
|
||
if len(inline) >= 2: # 「A.6×6 B.8×4 C.9×4 D.5×9」一行四个
|
||
for k, v in inline:
|
||
cur["opts"].setdefault(k.upper(), v.strip().rstrip("。"))
|
||
continue
|
||
if _looks_answer(text, cur): # 「36 + 47 =」下一行的「83」是答案,不是题干
|
||
cur.setdefault("ans", text.strip())
|
||
continue
|
||
opt = OPT_LINE.match(text)
|
||
# 「A.10」这种单独一行的选项,挂到当前题上,不并进题干
|
||
if opt and len(text) <= 60:
|
||
# 「A.快乐B.音乐C.长大D.银行」——OPT_LINE 只看见第一个 A,
|
||
# 先把整行按字母切开;切不动才当成单个选项
|
||
many = _opts_nospace(text)
|
||
if len(many) >= 2:
|
||
for k, v in many:
|
||
cur["opts"].setdefault(k, v)
|
||
else:
|
||
cur["opts"][opt.group(1).upper()] = opt.group(2).strip()
|
||
else:
|
||
cur["parts"].append(text)
|
||
# 第一个题号之前的导语(卷子标题、说明)直接丢
|
||
|
||
out = []
|
||
for it in items:
|
||
stem = " ".join(p for p in it["parts"] if p).strip()
|
||
stem = re.sub(r"\s{2,}", " ", stem)
|
||
# 只修「数字 一 数字」这种被认错的减号,中文里的「一」不动
|
||
stem = re.sub(r"(?<=\d)\s*一\s*(?=\d)", "-", stem)
|
||
opts = dict(it.get("opts") or {})
|
||
# 选项全挤在题干里:「…( ) A.10 B.11 C.12 D.13」
|
||
if len(opts) < 2:
|
||
inline = list(OPT_INLINE.finditer(stem))
|
||
if len(inline) < 2:
|
||
for k, v in _opts_nospace(stem):
|
||
opts.setdefault(k, v)
|
||
if len(opts) >= 3:
|
||
cut_at = stem.find("A" + ".")
|
||
if cut_at < 0:
|
||
cut_at = min([stem.find(f"{k}.") for k in ("A", "B", "C", "D") if stem.find(f"{k}.") >= 0] or [-1])
|
||
if cut_at > 0:
|
||
stem = stem[:cut_at].strip() or stem
|
||
inline = []
|
||
if len(inline) >= 2:
|
||
for k, v in OPT_INLINE.findall(stem):
|
||
opts.setdefault(k.upper(), v.strip().rstrip("。"))
|
||
stem = stem[:inline[0].start()].strip() or stem
|
||
if len(stem) < 2:
|
||
continue
|
||
subj = _guess_subject(stem, subject)
|
||
options = [opts[k] for k in ("A", "B", "C", "D") if k in opts] or None
|
||
calc = _calc_answer(stem)
|
||
if options:
|
||
# 有选项就是选择题:先看算出来的值能不能对上某个选项(口算选择题最常见),
|
||
# 再看题干里有没有标答案;都没有就让孩子自己判。
|
||
answer = None
|
||
if calc is not None:
|
||
for idx, text in enumerate(options):
|
||
if re.fullmatch(rf"[^\d]*{re.escape(calc)}[^\d]*", text):
|
||
answer = "ABCD"[idx]
|
||
break
|
||
if answer is None:
|
||
m = ANS_MARK.search(stem)
|
||
letter = next((g for g in (m.groups() if m else ()) if g), None)
|
||
answer = letter.upper() if letter else None
|
||
jt = "choice" if answer else "manual"
|
||
elif calc:
|
||
answer, jt = calc, "calc"
|
||
elif it.get("ans"):
|
||
# 题干里没有算式,但下一行单独写了答案(「83」):这题仍然可判
|
||
guess = it["ans"].strip()
|
||
answer, jt = (guess, "calc") if re.fullmatch(r"[\d.]+", guess) else (None, "manual")
|
||
else:
|
||
# 没有标准答案的一律 manual:机器不判,孩子自己判对错
|
||
answer, jt = None, "manual"
|
||
out.append({"seq": it["seq"], "stem": stem, "answer": answer,
|
||
"judge_type": jt, "subject": subj, "options": options})
|
||
if len(out) >= max_questions:
|
||
break
|
||
if out:
|
||
return out
|
||
# 一整页都是口算题卡、没有题号:按「算式=」来切,一行里有两道就切两道。
|
||
# 但要有足够的密度才认——否则一张糊图里零星几个数字会被切成「题目」。
|
||
facts = []
|
||
for ln in lines:
|
||
text = (ln.get("text") or "").strip()
|
||
if not text or (DROP.search(text) and len(text) <= 24):
|
||
continue
|
||
text = _fix_math(text) # 「72一38」先修成「72-38」,否则口算题一行都认不出
|
||
facts.extend(m.group(0).strip() for m in FACT.finditer(text))
|
||
all_text = "".join((l.get("text") or "") for l in lines)
|
||
digits = sum(ch.isdigit() for ch in all_text)
|
||
if len(facts) >= 4 and all_text and digits / len(all_text) >= 0.25:
|
||
for i, stem in enumerate(facts[:max_questions], 1):
|
||
answer = _calc_answer(stem)
|
||
out.append({"seq": i, "stem": stem, "answer": answer,
|
||
"judge_type": "calc" if answer else "manual",
|
||
"subject": _guess_subject(stem, subject), "options": None})
|
||
return out
|