检测侧:补扫没救回漏检,改成勾中口算卡时裁剪重读(312->321/330)
- scanflow._gap_bands/_gap_blocks:找出没被框盖住但有字的条带,裁出来补切一次 (OCR_GAP_SCAN=0 可关,一页最多 2 条);实测在 3 张漏检图上救回 0 道, 因为那 3 道不是空条带,而是框在、内容读歪(27+69 读成 77+69) - recognize_block 增加 crop_card 分支:勾中口算卡时裁出来重读,两版小题求并集 (宁多不漏;整页版吞行、裁剪版丢题,谁也说不全) - bench/verify_effect.py:同一份整页结果内比 page 与 page∪crop, 不跨调用比——腾讯切题两次调用本身就不完全一致 - bench/run.py --gap / --verify-cards;gold_expr.py --results - tests/test_gap_scan.py 5 例;卡片重读 2 例;179 单测 + 4 套冒烟全绿
This commit is contained in:
@@ -41,3 +41,7 @@ data/uploads/
|
|||||||
data/ocr_cache/
|
data/ocr_cache/
|
||||||
data/bench/results.before.jsonl
|
data/bench/results.before.jsonl
|
||||||
data/bench/results.prev.jsonl
|
data/bench/results.prev.jsonl
|
||||||
|
|
||||||
|
# 评测的中间结果(可重跑)
|
||||||
|
data/bench/results.gap.jsonl
|
||||||
|
data/bench/results.verified.jsonl
|
||||||
|
|||||||
@@ -475,3 +475,30 @@ python tests/smoke_http.py # 39 项 HTTP 冒烟(真起服务
|
|||||||
按这个量算账:一个学生每周 1 张卷、一学期 20 周 ≈ 28 次调用;即使按 0.05–0.1 元/次,
|
按这个量算账:一个学生每周 1 张卷、一学期 20 周 ≈ 28 次调用;即使按 0.05–0.1 元/次,
|
||||||
一学期 1.4–2.8 元,占 69 元学费的 2%–4%。**前提是上面三道闸都开着**——之前「1 张卷 6 次」
|
一学期 1.4–2.8 元,占 69 元学费的 2%–4%。**前提是上面三道闸都开着**——之前「1 张卷 6 次」
|
||||||
的算法下就是 12–17 元,占 20% 以上,模型不成立。
|
的算法下就是 12–17 元,占 20% 以上,模型不成立。
|
||||||
|
|
||||||
|
## 四点二十二、切题漏了怎么办:补扫与卡片重读
|
||||||
|
|
||||||
|
金标 330 道时还剩 12 道没认出来,一开始以为是「整块没被切出来」,做了补扫才发现**不是**。
|
||||||
|
|
||||||
|
**补扫**(`scanflow._gap_bands / _gap_blocks`,`OCR_GAP_SCAN=0` 可关)
|
||||||
|
- 找出「没有框盖住、但确实有字」的横向条带:灰度二值化后按行求墨迹比例
|
||||||
|
(`bw.resize((1,sh), BOX)` 一次拿到每行均值),先做行距桥接再找连续段,
|
||||||
|
高度 ≥90px、墨迹在 0.4%–55% 之间才算,一页最多补 2 条
|
||||||
|
- 每条带裁出来再切一次,坐标平移回整页,按题干去重、按中心点排除与已有框重叠的
|
||||||
|
- **实测在 3 张漏检图上救回 0 道**:那 3 道根本不在空条带里,而是
|
||||||
|
「框在、框里的内容读歪了」——`27+69` 被读成 `77+69`,`4/5-2/5` 被整行吞掉。
|
||||||
|
补扫留着(真有空条带时它有用),但它不是这次的解药。
|
||||||
|
|
||||||
|
**卡片重读**(`scanflow.recognize_block` 里 `crop_card` 分支)
|
||||||
|
- 口算卡最容易整块读歪。家长**勾到这一块**时,把它裁出来重读一次(1 次调用),
|
||||||
|
两版小题求并集:整页版吞行、裁剪版丢题,谁也说不全
|
||||||
|
- 只在入库时发生,不勾就不花钱;代价是「读歪的那条也在」(宁多不漏,漏掉的那道孩子永远看不到)
|
||||||
|
- 同一份整页结果内实测:**312 → 321 / 330(96.4%→97.3%)**,
|
||||||
|
`bench/verify_effect.py` 可复现(它只比 `page` 与 `page∪crop`,不跨调用比,
|
||||||
|
因为腾讯切题对同一张图的两次调用本身就不完全一致)
|
||||||
|
- 还剩 9 道没认出来:`5×0`、`92-(30+25)`、`4/5-2/5`,以及 fa0885 的三道竖式——
|
||||||
|
都是 OCR 真没读出来,裁剪也救不了,属于供应商能力边界
|
||||||
|
|
||||||
|
顺带记两个坑:`_LINE_NO` 少写 `(?!\d)` 会把 `1.8+0.6` 的 `1.` 当题号(算成 8.6);
|
||||||
|
`safe_eval` 曾走 `normalize`,那里的 `strip_punct` 会把括号剥掉,`34×(90-46)` 静默变成
|
||||||
|
`34*90-46`。(见四点二十一)
|
||||||
|
|||||||
+192
-1
@@ -13,6 +13,8 @@ from __future__ import annotations
|
|||||||
|
|
||||||
import io
|
import io
|
||||||
import json
|
import json
|
||||||
|
import os
|
||||||
|
import re
|
||||||
import uuid
|
import uuid
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
@@ -25,6 +27,15 @@ MIN_BOX_SIDE = 40 # 小于这个的框是标点/零碎,别给家长
|
|||||||
MAX_BLOCKS = 40
|
MAX_BLOCKS = 40
|
||||||
CROP_PAD = 18
|
CROP_PAD = 18
|
||||||
|
|
||||||
|
# 补扫:切题接口有时整块不给(竖式区、被折痕挡住的半栏),
|
||||||
|
# 这些地方在整页结果里连框都没有,家长根本点不到。
|
||||||
|
# 做法是找出「没被任何框盖住、但确实有字」的横向条带,裁出来再切一次。
|
||||||
|
GAP_MIN_H = 90 # 条带矮于这个就不值一次调用
|
||||||
|
GAP_MAX = 2 # 一页最多补扫两条,再多就是在赌
|
||||||
|
GAP_INK = 0.004 # 条带里墨迹像素占比下限(低于它基本是空白)
|
||||||
|
GAP_MAX_INK = 0.55 # 高于它更像照片/阴影,不是文字
|
||||||
|
GAP_PAD = 24
|
||||||
|
|
||||||
|
|
||||||
def _pil():
|
def _pil():
|
||||||
try:
|
try:
|
||||||
@@ -58,7 +69,148 @@ def save_draft(image_bytes: bytes, filename: str = "page.jpg") -> dict:
|
|||||||
return {"draft_id": draft_id, "width": w, "height": h}
|
return {"draft_id": draft_id, "width": w, "height": h}
|
||||||
|
|
||||||
|
|
||||||
def detect(image_bytes: bytes, filename: str = "page.jpg") -> dict:
|
def _gap_enabled() -> bool:
|
||||||
|
return os.environ.get("OCR_GAP_SCAN", "1").strip().lower() not in (
|
||||||
|
"0", "false", "no", "off")
|
||||||
|
|
||||||
|
|
||||||
|
def _ink_rows(src: Path) -> list[float]:
|
||||||
|
"""每行「有字」的比例(0–1)。在缩图上算:只关心哪一段有字,不需要精确。"""
|
||||||
|
Image, _ = _pil()
|
||||||
|
if Image is None:
|
||||||
|
return []
|
||||||
|
W = 600
|
||||||
|
try:
|
||||||
|
with Image.open(src) as im:
|
||||||
|
g = im.convert("L")
|
||||||
|
sh = max(1, int(round(g.height * W / max(1, g.width))))
|
||||||
|
g = g.resize((W, sh), Image.BILINEAR)
|
||||||
|
# 二值化后按行取均值:BOX 缩放就是求平均,比逐像素 Python 循环快两个数量级
|
||||||
|
bw = g.point(lambda v: 0 if v < 150 else 255)
|
||||||
|
means = list(bw.resize((1, sh), Image.BOX).tobytes()) # L 模式:一像素一字节
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
return []
|
||||||
|
return [(255 - v) / 255.0 for v in means]
|
||||||
|
|
||||||
|
|
||||||
|
def _gap_bands(src: Path, blocks: list[dict], w: int, h: int) -> list[tuple[int, int]]:
|
||||||
|
"""块框没盖住、但确实有字的横向条带(原图像素坐标,从上到下)。"""
|
||||||
|
ink = _ink_rows(src)
|
||||||
|
if not ink or not w or not h:
|
||||||
|
return []
|
||||||
|
n = len(ink)
|
||||||
|
covered = [False] * n
|
||||||
|
for b in blocks:
|
||||||
|
box = b.get("box") or {}
|
||||||
|
y0 = int(box.get("y", 0) * n / h)
|
||||||
|
y1 = int((box.get("y", 0) + box.get("h", 0)) * n / h) + 1
|
||||||
|
for y in range(max(0, y0), min(n, y1)):
|
||||||
|
covered[y] = True
|
||||||
|
# 一行一行看会碎:字与字、行与行之间都是白的。先把空隙桥接起来再找段。
|
||||||
|
hot = [GAP_INK <= ink[y] <= GAP_MAX_INK for y in range(n)]
|
||||||
|
span = max(2, int(0.02 * n))
|
||||||
|
dil = [False] * n
|
||||||
|
last = -10 ** 9
|
||||||
|
for y in range(n):
|
||||||
|
if hot[y]:
|
||||||
|
last = y
|
||||||
|
dil[y] = (y - last) <= span
|
||||||
|
last = 10 ** 9
|
||||||
|
for y in range(n - 1, -1, -1):
|
||||||
|
if hot[y]:
|
||||||
|
last = y
|
||||||
|
dil[y] = dil[y] or (last - y) <= span
|
||||||
|
min_rows = max(3, int(GAP_MIN_H * n / h))
|
||||||
|
bands: list[tuple[int, int]] = []
|
||||||
|
start = None
|
||||||
|
for y in range(n + 1): # 多走一步收尾
|
||||||
|
hit = (y < n and not covered[y] and dil[y])
|
||||||
|
if hit and start is None:
|
||||||
|
start = y
|
||||||
|
elif not hit and start is not None:
|
||||||
|
if y - start >= min_rows:
|
||||||
|
bands.append((start, y))
|
||||||
|
start = None
|
||||||
|
scored = [(sum(ink[a:b]), a, b) for a, b in bands if sum(ink[a:b]) > 0]
|
||||||
|
scored.sort(reverse=True)
|
||||||
|
out = []
|
||||||
|
for _total, a, b in scored[:GAP_MAX]:
|
||||||
|
out.append((max(0, int(a * h / n) - GAP_PAD), min(h, int(b * h / n) + GAP_PAD)))
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def _crop_band(src: Path, y0: int, y1: int) -> bytes | None:
|
||||||
|
Image, ImageOps = _pil()
|
||||||
|
if Image is None:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
with Image.open(src) as im:
|
||||||
|
im = im.convert("RGB")
|
||||||
|
crop = im.crop((0, y0, im.width, y1))
|
||||||
|
crop = crop.resize((int(crop.width * 1.4), int(crop.height * 1.4)),
|
||||||
|
Image.LANCZOS)
|
||||||
|
crop = ImageOps.autocontrast(crop, cutoff=1)
|
||||||
|
buf = io.BytesIO()
|
||||||
|
crop.save(buf, format="JPEG", quality=92)
|
||||||
|
return buf.getvalue()
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _norm_stem(stem: str) -> str:
|
||||||
|
return re.sub(r"[\s,.;:!?,。;:!?、()()\[\]【】]+", "", stem or "")
|
||||||
|
|
||||||
|
|
||||||
|
def _center_in(box: dict, blocks: list[dict]) -> bool:
|
||||||
|
cx = box["x"] + box["w"] / 2.0
|
||||||
|
cy = box["y"] + box["h"] / 2.0
|
||||||
|
for b in blocks:
|
||||||
|
o = b.get("box") or {}
|
||||||
|
if (o.get("x", 0) <= cx <= o.get("x", 0) + o.get("w", 0)
|
||||||
|
and o.get("y", 0) <= cy <= o.get("y", 0) + o.get("h", 0)):
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def _gap_blocks(src: Path, blocks: list[dict], w: int, h: int) -> list[dict]:
|
||||||
|
"""把漏掉的条带补切回来。每条带 = 一次切题调用(最多 GAP_MAX 次)。"""
|
||||||
|
added: list[dict] = []
|
||||||
|
seen = {_norm_stem(b.get("stem") or "") for b in blocks}
|
||||||
|
for y0, y1 in _gap_bands(src, blocks, w, h):
|
||||||
|
if len(blocks) + len(added) >= MAX_BLOCKS:
|
||||||
|
break
|
||||||
|
data = _crop_band(src, y0, y1)
|
||||||
|
if not data:
|
||||||
|
continue
|
||||||
|
r = tencent_ocr.split_questions(data)
|
||||||
|
if not r.get("ok"):
|
||||||
|
continue
|
||||||
|
for q in r.get("questions") or []:
|
||||||
|
stem = (q.get("stem") or "").strip()
|
||||||
|
key = _norm_stem(stem)
|
||||||
|
box = q.get("box")
|
||||||
|
if not stem or key in seen or not box:
|
||||||
|
continue
|
||||||
|
if box["w"] < MIN_BOX_SIDE or box["h"] < MIN_BOX_SIDE:
|
||||||
|
continue
|
||||||
|
moved = {"x": box["x"], "y": box["y"] + y0, "w": box["w"], "h": box["h"]}
|
||||||
|
if _center_in(moved, blocks) or _center_in(moved, added):
|
||||||
|
continue
|
||||||
|
seen.add(key)
|
||||||
|
added.append({
|
||||||
|
"box": moved,
|
||||||
|
"stem": stem,
|
||||||
|
"judge_type": q.get("detected_as") or q.get("judge_type"),
|
||||||
|
"options": q.get("options"),
|
||||||
|
"page_answer": q.get("page_answer"),
|
||||||
|
"subs": q.get("subs") or [],
|
||||||
|
"from_gap": True,
|
||||||
|
})
|
||||||
|
return added
|
||||||
|
|
||||||
|
|
||||||
|
def detect(image_bytes: bytes, filename: str = "page.jpg",
|
||||||
|
gap_scan: bool = True) -> dict:
|
||||||
"""整页切块。返回题块 + 草稿 id;切不出题就抛 422 让前端提示重拍。"""
|
"""整页切块。返回题块 + 草稿 id;切不出题就抛 422 让前端提示重拍。"""
|
||||||
d = save_draft(image_bytes, filename)
|
d = save_draft(image_bytes, filename)
|
||||||
res = tencent_ocr.split_questions(image_bytes)
|
res = tencent_ocr.split_questions(image_bytes)
|
||||||
@@ -81,6 +233,18 @@ def detect(image_bytes: bytes, filename: str = "page.jpg") -> dict:
|
|||||||
})
|
})
|
||||||
if len(blocks) >= MAX_BLOCKS:
|
if len(blocks) >= MAX_BLOCKS:
|
||||||
break
|
break
|
||||||
|
# 补扫:切题接口漏掉的条带(竖式区、折痕挡住的半栏)在整页结果里连框都没有,
|
||||||
|
# 家长根本点不到。补扫要花钱,所以 GAP_MAX 条封顶、可关。
|
||||||
|
if gap_scan and _gap_enabled() and blocks:
|
||||||
|
try:
|
||||||
|
for b in _gap_blocks(_img_path(d["draft_id"]), blocks,
|
||||||
|
d["width"], d["height"]):
|
||||||
|
b["i"] = len(blocks)
|
||||||
|
blocks.append(b)
|
||||||
|
if len(blocks) >= MAX_BLOCKS:
|
||||||
|
break
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
pass # 补扫失败不影响主流程
|
||||||
if not blocks:
|
if not blocks:
|
||||||
raise ApiError(422, "NO_BLOCK", "这一页没切出看得清的题块,换个角度重拍一次")
|
raise ApiError(422, "NO_BLOCK", "这一页没切出看得清的题块,换个角度重拍一次")
|
||||||
_meta_path(d["draft_id"]).write_text(
|
_meta_path(d["draft_id"]).write_text(
|
||||||
@@ -138,6 +302,33 @@ def _looks_complete(block: dict) -> bool:
|
|||||||
|
|
||||||
def recognize_block(src: Path, block: dict, force_crop: bool = False) -> dict:
|
def recognize_block(src: Path, block: dict, force_crop: bool = False) -> dict:
|
||||||
"""需要时把单块裁出来再识别一次;能不花那次钱就不花。"""
|
"""需要时把单块裁出来再识别一次;能不花那次钱就不花。"""
|
||||||
|
card = bool(block.get("subs")) or block.get("judge_type") == "card"
|
||||||
|
if card and not force_crop:
|
||||||
|
# 口算卡最容易整块读歪(实测 40ca7a52 那张把 27+69 读成 77+69)。
|
||||||
|
# 家长既然勾了这一块,就花一次调用裁出来重读:谁的题多信谁。
|
||||||
|
page_subs = block.get("subs") or []
|
||||||
|
try:
|
||||||
|
data = _crop_bytes(src, block["box"])
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
data = None
|
||||||
|
if data:
|
||||||
|
r = tencent_ocr.split_questions(data)
|
||||||
|
crop_subs = ((r.get("questions") or [{}])[0].get("subs") or []) if r.get("ok") else []
|
||||||
|
if crop_subs:
|
||||||
|
# 两次读到的题求并集:整页版常吞行或读歪一道,裁剪版也会漏。
|
||||||
|
# 宁多不漏——漏掉的那道孩子永远看不到,多出来的顶多多看一眼。
|
||||||
|
seen = {_norm_stem(s.get("stem")) for s in page_subs}
|
||||||
|
merged = list(page_subs)
|
||||||
|
for s in crop_subs:
|
||||||
|
k = _norm_stem(s.get("stem"))
|
||||||
|
if k and k not in seen:
|
||||||
|
seen.add(k)
|
||||||
|
merged.append(s)
|
||||||
|
if len(merged) > len(page_subs):
|
||||||
|
return {"stem": (r["questions"][0].get("stem") or block.get("stem")),
|
||||||
|
"judge_type": "card", "options": None,
|
||||||
|
"answer": None, "page_answer": None,
|
||||||
|
"subs": merged, "source": "crop_card"}
|
||||||
if not force_crop and _looks_complete(block):
|
if not force_crop and _looks_complete(block):
|
||||||
return {"stem": block.get("stem"), "judge_type": block.get("judge_type"),
|
return {"stem": block.get("stem"), "judge_type": block.get("judge_type"),
|
||||||
"options": block.get("options"), "answer": block.get("page_answer"),
|
"options": block.get("options"), "answer": block.get("page_answer"),
|
||||||
|
|||||||
+5
-4
@@ -74,12 +74,13 @@ python bench/gold_expr.py --append # 追加成 report.md 第五节
|
|||||||
|
|
||||||
`gold_expr.py` 会直接打印 Wilson 区间。为什么必须给区间:0 误判 + 83 道,95% 上界是 4.4%,读者没法据此相信「误判率 < 1%」;330 道时上界才落到 1.24%。反推:要把上界压到 1% 以内需要约 400 道,0.5% 以内约 800 道。同卷内的题不独立,真实区间比 Wilson 略宽——所以标 330 道也只敢说「1.5% 以内」。
|
`gold_expr.py` 会直接打印 Wilson 区间。为什么必须给区间:0 误判 + 83 道,95% 上界是 4.4%,读者没法据此相信「误判率 < 1%」;330 道时上界才落到 1.24%。反推:要把上界压到 1% 以内需要约 400 道,0.5% 以内约 800 道。同卷内的题不独立,真实区间比 Wilson 略宽——所以标 330 道也只敢说「1.5% 以内」。
|
||||||
|
|
||||||
漏检的 12 道分两类,都不是判题逻辑的错:
|
**一个必须知道的事实:腾讯切题对同一张图的两次调用并不完全一致**(分段会变),所以跨两次 API 调用比「318 → 321」会把随机性当效果。要测某项改动的增益,只能用同一份整页结果比 `page` 与 `page∪crop`:`python bench/verify_effect.py`。
|
||||||
|
|
||||||
1. **极短算式被读错或被吞**(9 道):`0+0` 读成 `6+0`、`2+4`、`5×2`、`5×0`、`9×9`、`3×9`、`7×4`、`4+5`、`2+3+4`。密集口算卡里一行里有 4–5 道,框切得碎,单道容易丢。
|
补扫(检测漏块)实测在 3 张漏检图上救回 **0 道**——那 3 道不是「没框」,而是「框在、内容读歪」:`27+69` 被读成 `77+69`,`4/5-2/5` 被整行吞掉。真正的解药是**卡片重读**(入库时把口算卡裁出来再读一次、两版求并集):同一份结果内 **312 → 321 / 330(96.4% → 97.3%)**。
|
||||||
2. **整块没被切出来**(3 道):`27+69`、`92-(30+25)`、`4/5-2/5`。
|
|
||||||
|
|
||||||
竖式区那 6 道(`1.8+0.6` 到 `49×59`)已经在 `split_multi` 里修好——之前它们是一个 manual 块,现在拆成 6 道 calc 并逐道自算。这也说明:**漏检的瓶颈已经从「没法拆」挪到「OCR 没给出这块」**,再往上要动的是检测侧(裁剪重识别),不是解析侧。
|
剩下的 9 道:`5×0`、`92-(30+25)`、`4/5-2/5`,以及 fa0885 的三道竖式(`68+27`/`80-49`/`75+17-43`)——都是 OCR 真没读出来,裁剪也救不了,属供应商能力边界。
|
||||||
|
|
||||||
|
竖式区那 6 道(`1.8+0.6` 到 `49×59`)已经在 `split_multi` 里修好——之前它们是一个 manual 块,现在拆成 6 道 calc 并逐道自算。
|
||||||
|
|
||||||
## 额度纪律(重要)
|
## 额度纪律(重要)
|
||||||
|
|
||||||
|
|||||||
+4
-1
@@ -95,6 +95,8 @@ def _wilson(k: int, n: int, z: float = 1.96) -> tuple[float, float]:
|
|||||||
def main() -> int:
|
def main() -> int:
|
||||||
ap = argparse.ArgumentParser()
|
ap = argparse.ArgumentParser()
|
||||||
ap.add_argument("--gold", default=str(GOLD))
|
ap.add_argument("--gold", default=str(GOLD))
|
||||||
|
ap.add_argument("--results", default=str(RESULTS),
|
||||||
|
help="换一份评测结果(比如开了卡片重读的 results.verified.jsonl)")
|
||||||
ap.add_argument("--miss", action="store_true", help="列出没认出来的算式")
|
ap.add_argument("--miss", action="store_true", help="列出没认出来的算式")
|
||||||
ap.add_argument("--append", action="store_true", help="把结果追加成 report.md 的一节")
|
ap.add_argument("--append", action="store_true", help="把结果追加成 report.md 的一节")
|
||||||
args = ap.parse_args()
|
args = ap.parse_args()
|
||||||
@@ -104,7 +106,8 @@ def main() -> int:
|
|||||||
print(f"没有金标文件:{gold_path}")
|
print(f"没有金标文件:{gold_path}")
|
||||||
return 1
|
return 1
|
||||||
gold = json.loads(gold_path.read_text(encoding="utf-8"))
|
gold = json.loads(gold_path.read_text(encoding="utf-8"))
|
||||||
rows = {r["id"]: r for r in (json.loads(l) for l in RESULTS.open(encoding="utf-8") if l.strip())}
|
res_path = Path(args.results)
|
||||||
|
rows = {r["id"]: r for r in (json.loads(l) for l in res_path.open(encoding="utf-8") if l.strip())}
|
||||||
|
|
||||||
total = hit = wrong = miss = 0
|
total = hit = wrong = miss = 0
|
||||||
miss_list: list[tuple[str, str]] = []
|
miss_list: list[tuple[str, str]] = []
|
||||||
|
|||||||
+15
-2
@@ -75,7 +75,7 @@ def _to_block(i: int, q: dict) -> dict:
|
|||||||
return {"i": i, "box": q.get("box"), "stem": q["stem"],
|
return {"i": i, "box": q.get("box"), "stem": q["stem"],
|
||||||
"judge_type": q.get("detected_as") or q.get("judge_type"),
|
"judge_type": q.get("detected_as") or q.get("judge_type"),
|
||||||
"options": q.get("options"), "page_answer": q.get("page_answer"),
|
"options": q.get("options"), "page_answer": q.get("page_answer"),
|
||||||
"subs": q.get("subs") or []}
|
"subs": q.get("subs") or [], "from_gap": False}
|
||||||
|
|
||||||
|
|
||||||
def main(argv=None) -> int:
|
def main(argv=None) -> int:
|
||||||
@@ -86,6 +86,10 @@ def main(argv=None) -> int:
|
|||||||
help="只用 OCR 缓存,缺的不发请求(额度用完后重算指标用)")
|
help="只用 OCR 缓存,缺的不发请求(额度用完后重算指标用)")
|
||||||
ap.add_argument("--skip-done", action="store_true",
|
ap.add_argument("--skip-done", action="store_true",
|
||||||
help="跳过 results.jsonl 里已经跑成功过的图(省额度)")
|
help="跳过 results.jsonl 里已经跑成功过的图(省额度)")
|
||||||
|
ap.add_argument("--gap", action="store_true",
|
||||||
|
help="开启补扫(检测漏块,每张可能多 1–2 次调用)")
|
||||||
|
ap.add_argument("--verify-cards", action="store_true",
|
||||||
|
help="口算卡裁出来重读一次(每张多 1–3 次调用)")
|
||||||
ap.add_argument("--out", default=str(RESULTS))
|
ap.add_argument("--out", default=str(RESULTS))
|
||||||
args = ap.parse_args(argv)
|
args = ap.parse_args(argv)
|
||||||
|
|
||||||
@@ -121,7 +125,16 @@ def main(argv=None) -> int:
|
|||||||
if args.no_api:
|
if args.no_api:
|
||||||
res = _detect_from_cache_only(data, fp.name)
|
res = _detect_from_cache_only(data, fp.name)
|
||||||
else:
|
else:
|
||||||
res = scanflow.detect(data, fp.name)
|
res = scanflow.detect(data, fp.name, gap_scan=args.gap)
|
||||||
|
if args.verify_cards and not args.no_api:
|
||||||
|
# 口算卡在整页结果里偶尔会读歪(27+69 → 77+69):
|
||||||
|
# 裁出这一块再读一次,题更多就信裁剪版(与入库时的逻辑一致)
|
||||||
|
src = scanflow._img_path(res["draft_id"])
|
||||||
|
for b in res.get("blocks") or []:
|
||||||
|
if b.get("subs"):
|
||||||
|
fixed = scanflow.recognize_block(src, b)
|
||||||
|
if fixed.get("source") == "crop_card":
|
||||||
|
b["subs"] = fixed["subs"]
|
||||||
ok, code, blocks = True, "", res.get("blocks") or []
|
ok, code, blocks = True, "", res.get("blocks") or []
|
||||||
except Exception as e: # noqa: BLE001
|
except Exception as e: # noqa: BLE001
|
||||||
ok, code, blocks = False, getattr(e, "code", type(e).__name__), []
|
ok, code, blocks = False, getattr(e, "code", type(e).__name__), []
|
||||||
|
|||||||
@@ -0,0 +1,84 @@
|
|||||||
|
"""一次性对照:同一份整页结果下,「卡片重读」能多救回几道金标。
|
||||||
|
|
||||||
|
为什么要写这个:腾讯切题对同一张图的两次调用并不完全一致(分段会变),
|
||||||
|
跨两次调用比「318 → 321」会把随机性当成效果。这里只比同一份结果内的
|
||||||
|
page 与 page∪crop 两个并集。
|
||||||
|
"""
|
||||||
|
import io
|
||||||
|
import json
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||||
|
|
||||||
|
from backend import scanflow # noqa: E402
|
||||||
|
from bench.gold_expr import _norm_expr, _same # noqa: E402
|
||||||
|
|
||||||
|
GOLD = Path("bench/gold.json")
|
||||||
|
RAW = Path("data/bench/raw")
|
||||||
|
|
||||||
|
|
||||||
|
def _pairs(blocks):
|
||||||
|
out = []
|
||||||
|
for b in blocks:
|
||||||
|
if b.get("subs"):
|
||||||
|
out.extend((_norm_expr(s.get("stem")), str(s.get("answer") or "")) for s in b["subs"])
|
||||||
|
elif b.get("stem"):
|
||||||
|
out.append((_norm_expr(b.get("stem")), str(b.get("answer") or "")))
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def score(exprs, pairs):
|
||||||
|
hit = 0
|
||||||
|
for e in exprs:
|
||||||
|
want = _norm_expr(e["t"])
|
||||||
|
truth = str(e.get("a") or "").strip()
|
||||||
|
exact = [p for p in pairs if p[0] == want]
|
||||||
|
pref = [p for p in pairs if p[0].startswith(want) and p[0] != want]
|
||||||
|
got = (exact or pref or [(None, None)])[0][1]
|
||||||
|
if got and truth and (got.strip() == truth or _same(got, truth)):
|
||||||
|
hit += 1
|
||||||
|
return hit
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
gold = json.loads(GOLD.read_text(encoding="utf-8"))
|
||||||
|
total = page_hit = merged_hit = crop_hit = 0
|
||||||
|
for iid, spec in gold.items():
|
||||||
|
if iid.startswith("_") or not isinstance(spec, dict):
|
||||||
|
continue
|
||||||
|
fp = RAW / f"{iid}.jpg"
|
||||||
|
if not fp.exists():
|
||||||
|
continue
|
||||||
|
det = scanflow.detect(fp.read_bytes(), fp.name, gap_scan=False)
|
||||||
|
src = scanflow._img_path(det["draft_id"])
|
||||||
|
exprs = spec["exprs"]
|
||||||
|
total += len(exprs)
|
||||||
|
a = score(exprs, _pairs(det["blocks"]))
|
||||||
|
page_hit += a
|
||||||
|
merged, prefer = [], []
|
||||||
|
for b in det["blocks"]:
|
||||||
|
if b.get("subs"):
|
||||||
|
m = scanflow.recognize_block(src, b) # 并集版
|
||||||
|
merged.append(m)
|
||||||
|
crop_only = [s for s in m["subs"]
|
||||||
|
if s not in (b.get("subs") or [])]
|
||||||
|
# 「裁剪版更多就整版换掉」的对照
|
||||||
|
if len(m["subs"]) > len(b.get("subs") or []):
|
||||||
|
prefer.append({**b, "subs": m["subs"]})
|
||||||
|
else:
|
||||||
|
prefer.append(b)
|
||||||
|
else:
|
||||||
|
merged.append(b)
|
||||||
|
prefer.append(b)
|
||||||
|
bb = score(exprs, _pairs(merged))
|
||||||
|
cc = score(exprs, _pairs(prefer))
|
||||||
|
merged_hit += bb
|
||||||
|
crop_hit += cc
|
||||||
|
if bb != a or cc != a:
|
||||||
|
print(f"{iid} 整页 {a} / 并集 {bb} / 整版换 {cc}")
|
||||||
|
print(f"合计 {total} 道:整页 {page_hit},并集 {merged_hit},整版换 {crop_hit}")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
+1
-1
@@ -1 +1 @@
|
|||||||
{"2026-11": 59}
|
{"2026-11": 101}
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
"""补扫(gap scan)的单元测试。
|
||||||
|
|
||||||
|
要验的是:切题接口整块漏掉的那一条(竖式区、被折痕挡住的半栏)能被找回来,
|
||||||
|
而且不能重复、不能越补越多、关掉就真的不花那次钱。
|
||||||
|
"""
|
||||||
|
import io
|
||||||
|
import os
|
||||||
|
import unittest
|
||||||
|
from unittest import mock
|
||||||
|
|
||||||
|
from PIL import Image, ImageDraw
|
||||||
|
|
||||||
|
from backend import scanflow
|
||||||
|
|
||||||
|
from ._tmpdir import workdir
|
||||||
|
|
||||||
|
|
||||||
|
def _page(w=400, h=800, band=(500, 700)):
|
||||||
|
"""白纸上画一条"像文字"的带(短笔画,墨迹约占三成),带外留白。"""
|
||||||
|
im = Image.new("RGB", (w, h), (255, 255, 255))
|
||||||
|
dr = ImageDraw.Draw(im)
|
||||||
|
if band:
|
||||||
|
y0, y1 = band
|
||||||
|
for y in range(y0, y1, 20):
|
||||||
|
for x in range(20, w - 40, 40):
|
||||||
|
dr.rectangle((x, y, x + 18, y + 7), fill=(30, 30, 30))
|
||||||
|
buf = io.BytesIO()
|
||||||
|
im.save(buf, "JPEG", quality=90)
|
||||||
|
return buf.getvalue()
|
||||||
|
|
||||||
|
|
||||||
|
def _q(stem, box, judge_type="manual", answer=None):
|
||||||
|
return {"stem": stem, "judge_type": judge_type, "detected_as": judge_type,
|
||||||
|
"answer": answer, "page_answer": None, "options": None,
|
||||||
|
"box": box, "subs": []}
|
||||||
|
|
||||||
|
|
||||||
|
class GapScanTest(unittest.TestCase):
|
||||||
|
@classmethod
|
||||||
|
def setUpClass(cls):
|
||||||
|
cls.dir = workdir("gapscan")
|
||||||
|
|
||||||
|
def _calls(self, second):
|
||||||
|
"""第一次调用返回整页结果(只有一块),之后的调用返回补扫结果。"""
|
||||||
|
first = {"ok": True, "questions": [
|
||||||
|
_q("1. 计算:36+47=()", {"x": 20, "y": 40, "w": 300, "h": 60}, "calc", "83"),
|
||||||
|
]}
|
||||||
|
return mock.Mock(side_effect=[first, second, second])
|
||||||
|
|
||||||
|
def test_recovers_missed_band(self):
|
||||||
|
second = {"ok": True, "questions": [
|
||||||
|
_q("1.8+0.6=\n6.5-2.9=", {"x": 20, "y": 5, "w": 200, "h": 120}, "manual"),
|
||||||
|
]}
|
||||||
|
m = self._calls(second)
|
||||||
|
with mock.patch.object(scanflow.tencent_ocr, "split_questions", m):
|
||||||
|
d = scanflow.detect(_page(), "p.jpg")
|
||||||
|
self.assertEqual(len(d["blocks"]), 2, "漏掉的条带应当被补回来")
|
||||||
|
added = d["blocks"][1]
|
||||||
|
self.assertTrue(added.get("from_gap"))
|
||||||
|
# 坐标要平移回整页:补扫裁的是 y≈476 以下
|
||||||
|
self.assertGreater(added["box"]["y"], 400)
|
||||||
|
|
||||||
|
def test_no_duplicate_when_same_stem(self):
|
||||||
|
second = {"ok": True, "questions": [
|
||||||
|
_q("1. 计算:36+47=()", {"x": 20, "y": 5, "w": 200, "h": 60}, "calc", "83"),
|
||||||
|
]}
|
||||||
|
m = self._calls(second)
|
||||||
|
with mock.patch.object(scanflow.tencent_ocr, "split_questions", m):
|
||||||
|
d = scanflow.detect(_page(), "p.jpg")
|
||||||
|
self.assertEqual(len(d["blocks"]), 1, "同一道题不能进两次")
|
||||||
|
self.assertEqual(m.call_count, 2, "仍然会补扫一次,只是结果被去重")
|
||||||
|
|
||||||
|
def test_blank_page_no_extra_call(self):
|
||||||
|
m = self._calls({"ok": True, "questions": []})
|
||||||
|
with mock.patch.object(scanflow.tencent_ocr, "split_questions", m):
|
||||||
|
d = scanflow.detect(_page(band=None), "p.jpg")
|
||||||
|
self.assertEqual(len(d["blocks"]), 1)
|
||||||
|
self.assertEqual(m.call_count, 1, "页面没有未覆盖的墨迹,不该再调用")
|
||||||
|
|
||||||
|
def test_env_switch_off(self):
|
||||||
|
m = self._calls({"ok": True, "questions": []})
|
||||||
|
with mock.patch.dict(os.environ, {"OCR_GAP_SCAN": "0"}), \
|
||||||
|
mock.patch.object(scanflow.tencent_ocr, "split_questions", m):
|
||||||
|
d = scanflow.detect(_page(), "p.jpg")
|
||||||
|
self.assertEqual(len(d["blocks"]), 1)
|
||||||
|
self.assertEqual(m.call_count, 1, "关掉开关就一次都不补")
|
||||||
|
|
||||||
|
def test_gap_capped(self):
|
||||||
|
many = {"ok": True, "questions": [
|
||||||
|
_q(f"第{i}行算式", {"x": 20, "y": 5 + i * 40, "w": 200, "h": 30}, "calc", "1")
|
||||||
|
for i in range(10)
|
||||||
|
]}
|
||||||
|
m = self._calls(many)
|
||||||
|
with mock.patch.object(scanflow.tencent_ocr, "split_questions", m):
|
||||||
|
d = scanflow.detect(_page(band=(200, 760)), "p.jpg")
|
||||||
|
# GAP_MAX=2 条带 → 最多 2 次补扫 + 1 次整页
|
||||||
|
self.assertLessEqual(m.call_count, 1 + scanflow.GAP_MAX)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
+29
-6
@@ -186,13 +186,36 @@ class NoWastefulCropTest(unittest.TestCase):
|
|||||||
sp.assert_called_once()
|
sp.assert_called_once()
|
||||||
self.assertEqual(r["source"], "crop")
|
self.assertEqual(r["source"], "crop")
|
||||||
|
|
||||||
def test_card_block_skips_crop(self):
|
def test_card_block_rechecks_and_takes_more(self):
|
||||||
|
"""口算卡会被整块读歪(27+69 读成 77+69):勾到它时裁出来重读,题更多就信裁剪版。"""
|
||||||
from backend import scanflow
|
from backend import scanflow
|
||||||
|
|
||||||
block = {"i": 0, "box": {"x": 1, "y": 1, "w": 300, "h": 300}, "stem": "10-6= 7+8=",
|
block = {"i": 0, "box": {"x": 1, "y": 1, "w": 300, "h": 300}, "stem": "34+25= 78-25= 77+69=",
|
||||||
"judge_type": "card", "options": None, "page_answer": "",
|
"judge_type": "card", "options": None, "page_answer": "",
|
||||||
"subs": [{"stem": "10-6 =", "answer": "4"}]}
|
"subs": [{"stem": "34+25 =", "answer": "59"},
|
||||||
with mock.patch("backend.tencent_ocr.split_questions") as sp:
|
{"stem": "77+69 =", "answer": "146"}]}
|
||||||
|
with mock.patch("backend.scanflow._crop_bytes", return_value=b"jpg"), \
|
||||||
|
mock.patch("backend.tencent_ocr.split_questions", return_value={"ok": True, "questions": [
|
||||||
|
{"stem": "34+25=\n78-25=\n27+69=", "judge_type": "card",
|
||||||
|
"subs": [{"stem": "34+25 =", "answer": "59"},
|
||||||
|
{"stem": "78-25 =", "answer": "53"},
|
||||||
|
{"stem": "27+69 =", "answer": "96"}]}]}):
|
||||||
r = scanflow.recognize_block(Path("data/bench/raw/x.jpg"), block)
|
r = scanflow.recognize_block(Path("data/bench/raw/x.jpg"), block)
|
||||||
sp.assert_not_called()
|
stems = [s["stem"] for s in r["subs"]]
|
||||||
self.assertEqual(len(r["subs"]), 1)
|
self.assertEqual(r["source"], "crop_card")
|
||||||
|
self.assertIn("27+69 =", stems, "裁剪版读对的那道要进来")
|
||||||
|
self.assertIn("78-25 =", stems, "整页版吞掉的行也要补回来")
|
||||||
|
self.assertEqual(len(stems), 4, "宁多不漏:读歪的那条也留着,等逐条勾选再收拾")
|
||||||
|
|
||||||
|
def test_card_falls_back_when_crop_is_worse(self):
|
||||||
|
from backend import scanflow
|
||||||
|
|
||||||
|
block = {"i": 0, "box": {"x": 1, "y": 1, "w": 300, "h": 300}, "stem": "a",
|
||||||
|
"judge_type": "card", "options": None, "page_answer": "",
|
||||||
|
"subs": [{"stem": "1+1 =", "answer": "2"}, {"stem": "2+2 =", "answer": "4"}]}
|
||||||
|
with mock.patch("backend.scanflow._crop_bytes", return_value=b"jpg"), \
|
||||||
|
mock.patch("backend.tencent_ocr.split_questions",
|
||||||
|
return_value={"ok": False, "code": "X"}):
|
||||||
|
r = scanflow.recognize_block(Path("data/bench/raw/x.jpg"), block)
|
||||||
|
self.assertEqual(r["source"], "page")
|
||||||
|
self.assertEqual(len(r["subs"]), 2)
|
||||||
|
|||||||
Reference in New Issue
Block a user