# -*- coding: utf-8 -*- """拍整页 → 切出题块 → 家长勾「哪几道错了」→ 只入库选中的。 为什么不让家长只拍一道题:他不想也不会。整页拍、我们负责切块、他用手点, 这是唯一能落到真实家庭的流程(竞品差评里「电脑怎么拍试卷」就是这个断点)。 两步: 1. detect(image) → 存草稿 + 返回题块(含像素框),前端把框画在图上让家长点; 2. import_picks(draft, picks) → 把选中的框**从原图裁出来再单独识别一次**, 单块图的字更大、也没有相邻题的干扰,题干比整页切时干净得多。 """ from __future__ import annotations import io import json import os import re import uuid from pathlib import Path from . import tencent_ocr from .db import new_id, now from .services import UPLOAD_DIR, ApiError DRAFT_DIR = UPLOAD_DIR / "_drafts" 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 # 补扫的条带会放大再送 OCR,返回的框是放大后的坐标,要按这个数除回去 GAP_SCALE = 1.4 def _pil(): try: from PIL import Image, ImageOps return Image, ImageOps except Exception: # noqa: BLE001 return None, None def _meta_path(draft_id: str) -> Path: return DRAFT_DIR / f"{draft_id}.json" def _img_path(draft_id: str) -> Path: return DRAFT_DIR / f"{draft_id}.jpg" def save_draft(image_bytes: bytes, filename: str = "page.jpg") -> dict: """存原图,返回草稿 id 与尺寸。""" DRAFT_DIR.mkdir(parents=True, exist_ok=True) draft_id = uuid.uuid4().hex[:16] _img_path(draft_id).write_bytes(image_bytes) w = h = 0 Image, _ = _pil() if Image is not None: try: with Image.open(io.BytesIO(image_bytes)) as im: w, h = im.size except Exception: # noqa: BLE001 pass return {"draft_id": draft_id, "width": w, "height": h} def _gap_enabled() -> bool: """补扫要不要做:默认由 detect(gap_scan=) 决定,环境变量只用来「强制关」。 补扫在真实卷子上救回过整块(看图写数、比大小),但每页多 1–2 次调用, 所以默认关闭;要开就 detect(..., gap_scan=True),线上想临时全关就设 OCR_GAP_SCAN=0。 """ v = os.environ.get("OCR_GAP_SCAN") if v is None: return True return v.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 * GAP_SCALE), int(crop.height * GAP_SCALE)), 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 # 补扫图是放大 1.4 倍再送的,坐标要除回去;再整体下移到条带在原图里的位置 bx = int(round(box["x"] / GAP_SCALE)) by = int(round(box["y"] / GAP_SCALE)) + y0 bw = int(round(box["w"] / GAP_SCALE)) bh = int(round(box["h"] / GAP_SCALE)) if by < 0 or by >= h or bx >= w: continue moved = {"x": bx, "y": by, "w": bw, "h": bh} 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 = False) -> dict: """整页切块。返回题块 + 草稿 id;切不出题就抛 422 让前端提示重拍。""" d = save_draft(image_bytes, filename) res = tencent_ocr.split_questions(image_bytes) if not res.get("ok"): raise ApiError(422, "SPLIT_FAILED", f"整页切题没成功:{res.get('message') or res.get('code')}") blocks = [] for q in res["questions"]: box = q.get("box") if not box or box["w"] < MIN_BOX_SIDE or box["h"] < MIN_BOX_SIDE: continue blocks.append({ "i": len(blocks), "box": box, "stem": q["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 [], }) 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( json.dumps({"blocks": blocks, "w": d["width"], "h": d["height"]}, ensure_ascii=False), encoding="utf-8") return {"draft_id": d["draft_id"], "width": d["width"], "height": d["height"], "blocks": blocks} def load_draft(draft_id: str) -> tuple[Path, dict]: p = _img_path(draft_id) m = _meta_path(draft_id) if not draft_id or not p.exists() or not m.exists(): raise ApiError(404, "DRAFT_NOT_FOUND", "这个草稿过期了,重新拍一次") return p, json.loads(m.read_text(encoding="utf-8")) def _crop_bytes(src: Path, box: dict) -> bytes: Image, ImageOps = _pil() if Image is None: raise ApiError(500, "PIL_MISSING", "服务端没装 Pillow,裁切不可用") with Image.open(src) as im: im = im.convert("RGB") pad = CROP_PAD x0 = max(0, box["x"] - pad) y0 = max(0, box["y"] - pad) x1 = min(im.width, box["x"] + box["w"] + pad) y1 = min(im.height, box["y"] + box["h"] + pad) crop = im.crop((x0, y0, x1, y1)) # 单块放大 1.6 倍:本来就是半页里的半行,字太小 crop = crop.resize((int(crop.width * 1.6), int(crop.height * 1.6)), Image.LANCZOS) crop = ImageOps.autocontrast(crop, cutoff=1) buf = io.BytesIO() crop.save(buf, format="JPEG", quality=92) return buf.getvalue() def _looks_complete(block: dict) -> bool: """整页那一块读得够不够好?够好就别再花钱重新识别一次。 切题是按次计费的:一页 5 道错题若每道都裁出来重识别,就是 1+5 次。 实测整页结果里约七成块本来就是完整的,这些直接复用。 """ stem = block.get("stem") or "" if block.get("subs"): return True if len([ch for ch in stem if "\u4e00" <= ch <= "\u9fff"]) >= 8: return True if block.get("judge_type") == "calc" and block.get("answer"): return True if block.get("judge_type") == "choice" and len(block.get("options") or []) >= 2: return True return False 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"), "page_answer": block.get("page_answer"), "subs": block.get("subs") or [], "source": "page"} try: data = _crop_bytes(src, block["box"]) except ApiError: raise except Exception: # noqa: BLE001 data = None if data: r = tencent_ocr.split_questions(data) if r.get("ok") and r.get("questions"): q = r["questions"][0] page_stem = block.get("stem") or "" # 单块重识别有时反而更差(分数区域容易被切碎): # 谁的汉字多、谁长,就用谁,别盲目信第二次。 if _score(q["stem"]) >= _score(page_stem) * 0.9: return {"stem": q["stem"], "judge_type": q.get("detected_as") or q["judge_type"], "options": q.get("options"), "answer": q.get("answer"), "page_answer": q.get("page_answer"), "subs": q.get("subs") or [], "source": "crop"} return {"stem": block["stem"], "judge_type": block.get("judge_type"), "options": block.get("options"), "answer": block.get("page_answer"), "page_answer": block.get("page_answer"), "subs": block.get("subs") or [], "source": "page"} def _score(stem: str) -> float: """题干好不好:汉字越多越像真题干,纯数字/符号说明切歪了。""" if not stem: return 0.0 cjk = sum(1 for ch in stem if "\u4e00" <= ch <= "\u9fff") return cjk * 2.0 + len(stem) * 0.2