检测侧:补扫没救回漏检,改成勾中口算卡时裁剪重读(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:
2026-11-19 21:35:10 +08:00
parent 55e44ec1f5
commit 9f8ef886f0
10 changed files with 462 additions and 15 deletions
+27
View File
@@ -475,3 +475,30 @@ python tests/smoke_http.py # 39 项 HTTP 冒烟(真起服务
按这个量算账:一个学生每周 1 张卷、一学期 20 周 ≈ 28 次调用;即使按 0.05–0.1 元/次,
一学期 1.4–2.8 元,占 69 元学费的 2%–4%。**前提是上面三道闸都开着**——之前「1 张卷 6 次」
的算法下就是 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
View File
@@ -13,6 +13,8 @@ from __future__ import annotations
import io
import json
import os
import re
import uuid
from pathlib import Path
@@ -25,6 +27,15 @@ MIN_BOX_SIDE = 40 # 小于这个的框是标点/零碎,别给家长
MAX_BLOCKS = 40
CROP_PAD = 18
# 补扫:切题接口有时整块不给(竖式区、被折痕挡住的半栏),
# 这些地方在整页结果里连框都没有,家长根本点不到。
# 做法是找出「没被任何框盖住、但确实有字」的横向条带,裁出来再切一次。
GAP_MIN_H = 90 # 条带矮于这个就不值一次调用
GAP_MAX = 2 # 一页最多补扫两条,再多就是在赌
GAP_INK = 0.004 # 条带里墨迹像素占比下限(低于它基本是空白)
GAP_MAX_INK = 0.55 # 高于它更像照片/阴影,不是文字
GAP_PAD = 24
def _pil():
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}
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 让前端提示重拍。"""
d = save_draft(image_bytes, filename)
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:
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:
raise ApiError(422, "NO_BLOCK", "这一页没切出看得清的题块,换个角度重拍一次")
_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:
"""需要时把单块裁出来再识别一次;能不花那次钱就不花。"""
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):
return {"stem": block.get("stem"), "judge_type": block.get("judge_type"),
"options": block.get("options"), "answer": block.get("page_answer"),