feat: 整页拍 + 点选出错题(scanflow + 工作台界面)

This commit is contained in:
dev
2026-11-18 22:38:31 +08:00
parent 8a468d5a09
commit 88a8c3432c
16 changed files with 732 additions and 9 deletions
+12
View File
@@ -267,6 +267,18 @@ questions 入库(`options` 列存 JSON 数组,接口直接返回数组)→
- 返回三级兜底:腾讯 → 本机 OCR + `cut.segment` → 演示题库(`source=demo` 并说明原因)。
- 结果里 `ocr.engine` 是 `tencent` / `windows` / `null`,出问题先看它和 `ocr.tencent.message`。
### 四点十八、拍照入库:整页拍 → 点哪几道错了
已做完的卷子整页切不干净(手写、红勾、双栏、图形),所以流程改成三步:
1. `POST /api/papers/scan/detect`:整页图 → 腾讯云 `QuestionSplitOCR` 切块 → 返回 `draft_id` + 每块的像素框 `box` 与题干。
2. 前端把框画在图上,家长点“哪几道错了”(可多选)。
3. `POST /api/papers/scan/import`:只把选中的块从原图裁出来、放大 1.6×、**重新单独识别一次** → 建卷 → 直接入库(复用 `import_mistakes` 的排期与错因)。
两个设计取舍:
- 单块重识别偶尔更差(分数区域容易被切碎),所以用“汉字数多的那份”作为题干,而不是盲信第二次。
- 一次 detect 只调一次切题接口;选中几道就再调几次(N+1 次调用,按次计费要留意)。
## 五、接口(56 条,prod 下 48 条)
> `/api/dev/*`(6 条)与 `/api/auth/sms-code`、`/api/auth/sms-login` 只在 `QINGLING_ENV` 不是
+29 -1
View File
@@ -24,7 +24,7 @@ from urllib.parse import parse_qs, urlparse
from . import db as dbm
from . import qr
from . import services as svc
from . import scanflow, services as svc
from .services import ApiError
HERE = Path(__file__).resolve().parent
@@ -265,6 +265,34 @@ def post_paper(ctx: Ctx, **kw):
int(ctx.body.get("image_count") or 1))
def _decode_image(ctx: Ctx) -> bytes:
raw = str(ctx.body.get("image_b64") or "")
if "," in raw[:80] and raw.lstrip().startswith("data:"):
raw = raw.split(",", 1)[1]
try:
return base64.b64decode(raw, validate=False)
except Exception: # noqa: BLE001
raise svc.ApiError(400, "BAD_IMAGE", "图片不是合法的 base64")
@route("POST", "/api/papers/scan/detect", auth="parent")
def post_scan_detect(ctx: Ctx, **kw):
"""整页拍 → 切块 → 返回每块的框,让家长在图上点「哪几道错了」。"""
image = _decode_image(ctx)
return scanflow.detect(image, str(ctx.body.get("filename") or "page.jpg"))
@route("POST", "/api/papers/scan/import", auth="parent")
def post_scan_import(ctx: Ctx, **kw):
"""家长勾完 → 只把选中的块裁出来单独识别并入库。"""
picks = ctx.body.get("picks") or []
if not isinstance(picks, list):
raise svc.ApiError(400, "BAD_PICKS", "picks 要是数组")
return svc.import_scan_picks(
ctx.conn, ctx.gid, str(ctx.body.get("child_id") or ""),
str(ctx.body.get("subject") or "math"), str(ctx.body.get("draft_id") or ""), picks)
@route("POST", "/api/papers/ocr", auth="parent")
def post_paper_ocr(ctx: Ctx, **kw):
"""真拍照:图片 base64 → OCR → 切题 → 入库。OCR 不可用时按参数退回演示题库。"""
+149
View File
@@ -0,0 +1,149 @@
# -*- 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"),
})
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"), "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"), "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
+66
View File
@@ -1684,3 +1684,69 @@ def dev_scan_confirm(conn, code: str) -> dict:
out = scan_confirm(conn, row["id"], code)
out["demo"] = True
return out
def import_scan_picks(conn, gid: str, cid: str, subject: str, draft_id: str,
picks: list[int]) -> dict:
"""把「家长勾中的那几块」入库。
流程是:整页拍 → 切块给家长点 → 选中的块从原图裁出来**再单独识别一次**。
单块图字更大、没有相邻题干扰,题干比整页切时干净得多。
"""
from . import scanflow
require_active(conn, gid)
child = get_child(conn, gid, cid)
if subject not in ("math", "chinese"):
raise ApiError(400, "BAD_SUBJECT", "科目只有 math / chinese")
if subject not in child["subjects"]:
raise ApiError(400, "SUBJECT_OFF", "这个科目还没开")
src, meta = scanflow.load_draft(draft_id)
blocks = meta.get("blocks") or []
chosen = []
for i in picks:
try:
i = int(i)
except (TypeError, ValueError):
continue
if 0 <= i < len(blocks):
chosen.append(blocks[i])
if not chosen:
raise ApiError(400, "NO_PICKS", "一道都没选,先点上哪几道错了")
if len(chosen) > 20:
raise ApiError(400, "TOO_MANY", "一次最多入库 20 道")
questions = [scanflow.recognize_block(src, b) for b in chosen]
pid = new_id("p")
folder = UPLOAD_DIR / cid
folder.mkdir(parents=True, exist_ok=True)
img_path = folder / f"{pid}.jpg"
img_path.write_bytes(src.read_bytes())
with tx(conn):
conn.execute("INSERT INTO papers (id, child_id, subject, image_count, clean_path, image_path,"
" created_at) VALUES (?,?,?,?,?,?,?)",
(pid, cid, subject, 1, None, f"data/uploads/{cid}/{img_path.name}", now()))
qids = []
for i, q in enumerate(questions, start=1):
qid = new_id("q")
qids.append(qid)
conn.execute(
"INSERT INTO questions (id, paper_id, child_id, subject, seq, stem, answer, options,"
" kp, judge_type, created_at) VALUES (?,?,?,?,?,?,?,?,?,?,?)",
(qid, pid, cid, q.get("subject") or subject, i, q["stem"], q.get("answer"),
json.dumps(q.get("options"), ensure_ascii=False) if q.get("options") else None,
q.get("kp"), q.get("judge_type") or "manual", now()))
# 家长点过的就是错的——直接入库(复用 import_mistakes 的排期与错因逻辑)
imported = import_mistakes(conn, gid, cid, qids)
paper = get_paper(conn, gid, cid, pid)
paper["source"] = "scan"
paper["ocr"] = {"ok": True, "engine": "tencent", "questions": len(questions),
"picked": len(chosen), "blocks": len(blocks),
"created": len(imported.get("created") or []),
"skipped": len(imported.get("skipped") or []),
"image": f"data/uploads/{cid}/{img_path.name}"}
return paper
+69 -6
View File
@@ -22,6 +22,7 @@ import hashlib
import hmac
import json
import os
import re
import time
import urllib.error
import urllib.request
@@ -164,6 +165,37 @@ def _post(payload: dict, timeout: int = TIMEOUT) -> dict:
_LETTERS = "ABCDEFGH"
_LATEX_MAP = [("\\times", "×"), ("\\div", "÷"), ("\\cdot", "·"),
("\\bigcirc", "○"), ("\\leq", "≤"), ("\\geq", "≥"),
("\\neq", "≠"), ("\\pm", "±"), ("\\text", ""), ("\\,", " "),
("\\quad", " "), ("\\left", ""), ("\\right", "")]
def clean_text(text: str) -> str:
"""把 OCR 返回的 LaTeX 片段变成人能读的样子。
腾讯切题对分数/公式会给 `$\\frac{3}{4}$` 这种,前端直接显示是一串乱码。
这里做最小变换:\\frac{a}{b} → a/b,\\times → ×,去掉 $ 与多余空格。
"""
if not text:
return ""
t = str(text)
for _ in range(6): # 处理嵌套(分子分母里还有 frac)
new_t = re.sub(r"\\frac\s*\{([^{}]*)\}\s*\{([^{}]*)\}", r"\1/\2", t)
if new_t == t:
break
t = new_t
for a, b in _LATEX_MAP:
t = t.replace(a, b)
for junk in ("\\begin{matrix}", "\\end{matrix}", "\\begin{array}", "\\end{array}"):
t = t.replace(junk, " ")
t = re.sub(r"\{?\b(?:begin|end)\{[a-z*]+\}\}?", " ", t)
t = t.replace("$", "").replace("\\", "")
t = re.sub(r"[ \t]+", " ", t)
t = re.sub(r"\n{3,}", "\n\n", t)
return t.strip()
def _strip_label(text: str) -> str:
"""把选项自带的「A.」「A、」「A.」前缀去掉,只留内容。"""
t = (text or "").strip()
@@ -201,7 +233,8 @@ def _derive_answer(stem: str):
from . import judging
if _EXPR is None:
_EXPR = re.compile(r"(-?\d+(?:\.\d+)?)\s*([+\-*/×÷xX])\s*(-?\d+(?:\.\d+)?)\s*=")
_EXPR = re.compile(
r"(?<![\d/])(-?\d+(?:\.\d+)?)\s*([+\-×÷xX*])\s*(-?\d+(?:\.\d+)?)\s*=(?![\d/])")
m = _EXPR.search(stem or "")
if not m:
return None
@@ -229,6 +262,34 @@ def _guess_type(stem: str, options: list[str], answer: str) -> str:
return "manual"
def _bbox(rl: dict) -> dict | None:
"""题块的外接框(像素):优先用 rl.Coord,退到题干各段的联合框。"""
xs0, ys0, xs1, ys1 = [], [], [], []
def eat(c):
if isinstance(c, list):
for one in c:
eat(one)
return
if not isinstance(c, dict):
return
lt, rb = c.get("LeftTop") or {}, c.get("RightBottom") or {}
try:
xs0.append(float(lt["X"])); ys0.append(float(lt["Y"]))
xs1.append(float(rb["X"])); ys1.append(float(rb["Y"]))
except (KeyError, TypeError, ValueError):
pass
eat(rl.get("Coord"))
if not xs0:
for q in (rl.get("Question") or []):
eat((q or {}).get("Coord"))
if not xs0:
return None
x0, y0, x1, y1 = min(xs0), min(ys0), max(xs1), max(ys1)
return {"x": int(x0), "y": int(y0), "w": int(max(1, x1 - x0)), "h": int(max(1, y1 - y0))}
def parse(resp: dict) -> list[dict]:
"""把 QuestionSplitOCR 的返回拆成我们的题目结构。
@@ -275,15 +336,15 @@ def parse(resp: dict) -> list[dict]:
ordered = sorted([r for r in results if isinstance(r, dict)], key=_top_y)
for rl in ordered:
stem = _join(rl.get("Question"))
stem = clean_text(_join(rl.get("Question")))
if not stem:
continue
opts = [_strip_label(o) for o in
opts = [_strip_label(clean_text(o)) for o in
(str((x or {}).get("Text") or "") for x in (rl.get("Option") or []))]
opts = [o for o in opts if o]
# 注意:Answer 区拿到的是「卷面上写的东西」。孩子做完的卷子上,那就是他写的答案,
# 不是标准答案——拿它判对错会把错的判成对的。所以只当参考存着,不参与判分。
page_answer = _pick_answer(_join(rl.get("Answer")))
page_answer = clean_text(_pick_answer(_join(rl.get("Answer"))))
jt = rl.get("GroupType") if isinstance(rl.get("GroupType"), str) else ""
if len(opts) >= 2:
jt = "choice"
@@ -292,10 +353,12 @@ def parse(resp: dict) -> list[dict]:
if jt != "choice":
derived = _derive_answer(stem)
box = _bbox(rl)
if derived is not None:
# 纯算式:自己算一遍,可以机器判
item = {"stem": stem, "judge_type": "calc", "options": None,
"answer": derived, "kp": None, "page_answer": page_answer or None}
"answer": derived, "kp": None, "page_answer": page_answer or None,
"box": box}
else:
# 其余(选择/填空/问答):没有可信的标准答案 → 孩子自评,
# 但把卷面上写的答案留给孩子和家长对照。
@@ -303,7 +366,7 @@ def parse(resp: dict) -> list[dict]:
item = {"stem": stem, "judge_type": "manual", "options": opts or None,
"answer": page_answer or None, "kp": None,
"page_answer": page_answer or None,
"detected_as": jt}
"detected_as": jt, "box": box}
out.append(item)
return out