153 lines
5.9 KiB
Python
153 lines
5.9 KiB
Python
# -*- coding: utf-8 -*-
|
|
"""拍整页 → 切出题块 → 家长勾「哪几道错了」→ 只入库选中的。
|
|
|
|
为什么不让家长只拍一道题:他不想也不会。整页拍、我们负责切块、他用手点,
|
|
这是唯一能落到真实家庭的流程(竞品差评里「电脑怎么拍试卷」就是这个断点)。
|
|
|
|
两步:
|
|
1. detect(image) → 存草稿 + 返回题块(含像素框),前端把框画在图上让家长点;
|
|
2. import_picks(draft, picks) → 把选中的框**从原图裁出来再单独识别一次**,
|
|
单块图的字更大、也没有相邻题的干扰,题干比整页切时干净得多。
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import io
|
|
import json
|
|
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
|
|
|
|
|
|
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 detect(image_bytes: bytes, filename: str = "page.jpg") -> 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
|
|
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 recognize_block(src: Path, block: dict) -> dict:
|
|
"""把单块裁出来再识别一次;失败就退回整页那一块的文字。"""
|
|
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
|