feat: 整页拍 + 点选出错题(scanflow + 工作台界面)
This commit is contained in:
File diff suppressed because one or more lines are too long
@@ -0,0 +1,66 @@
|
||||
// 验证「拍照入库」界面:登录 → 进 scan → 模拟选图 → 点选 → 截图
|
||||
import fs from "node:fs";
|
||||
import { ensureBrowser, attach, navigate, evaluate } from "./collector/cdp.mjs";
|
||||
|
||||
const BASE = "http://127.0.0.1:8000";
|
||||
const b64 = fs.readFileSync("./_scan_b64.txt", "utf8").trim();
|
||||
|
||||
const launch = await ensureBrowser({ headless: true, port: 9333, profileDir: "./data/_shot_profile", startUrl: "about:blank" });
|
||||
const { cdp } = await attach(9333);
|
||||
|
||||
try {
|
||||
await cdp.send("Emulation.setDeviceMetricsOverride", { width: 1440, height: 950, deviceScaleFactor: 1, mobile: false });
|
||||
await navigate(cdp, `${BASE}/workbench#scan`);
|
||||
await new Promise((r) => setTimeout(r, 1200));
|
||||
|
||||
// 登录(用演示账号拿 token,直接塞进 localStorage)
|
||||
const lg = await evaluate(cdp, `(async () => {
|
||||
const r = await fetch("${BASE}/api/auth/wx-login", {method:"POST", headers:{"Content-Type":"application/json"}, body: JSON.stringify({code:"demo"})});
|
||||
const j = await r.json();
|
||||
if (!j.ok) return {err: j.error};
|
||||
localStorage.setItem("ql_token", j.data.token);
|
||||
const kids = j.data.children || [];
|
||||
if (kids[0]) localStorage.setItem("ql_child", kids[0].id);
|
||||
return {n: kids.length, kid: kids[0] && kids[0].nickname};
|
||||
})()`, { awaitPromise: true });
|
||||
console.log("login:", JSON.stringify(lg));
|
||||
|
||||
await navigate(cdp, `${BASE}/workbench#scan`);
|
||||
await new Promise((r) => setTimeout(r, 1500));
|
||||
|
||||
// 造一个 File 走 onScanFile,等价于用户点「选照片」
|
||||
const split = await evaluate(cdp, `(async () => {
|
||||
const bin = atob("${b64}");
|
||||
const u8 = new Uint8Array(bin.length);
|
||||
for (let i = 0; i < bin.length; i++) u8[i] = bin.charCodeAt(i);
|
||||
const f = new File([u8], "page.jpg", {type: "image/jpeg"});
|
||||
await onScanFile(f);
|
||||
return {blocks: SCAN.blocks.length, draft: !!SCAN.draft, hint: document.getElementById("scanHint").textContent};
|
||||
})()`, { awaitPromise: true });
|
||||
console.log("detect:", JSON.stringify(split));
|
||||
|
||||
// 点选前三块里第一块,看按钮是否可用
|
||||
const probe = await evaluate(cdp, `(async () => {
|
||||
const r = await api("/api/papers/scan/detect", {method:"POST", body:{image_b64:"${b64}", filename:"p.jpg"}}).then(v=>v).catch(e=>"ERR:"+(e&&e.message));
|
||||
return typeof r === "string" ? r : {blocks: (r.blocks||[]).length};
|
||||
})()`, { awaitPromise: true });
|
||||
console.log("probe:", JSON.stringify(probe).slice(0, 300));
|
||||
const picked = await evaluate(cdp, `(() => {
|
||||
toggleBox(0);
|
||||
return {picks: SCAN.picks.slice(), btn: document.getElementById("scanImport").textContent,
|
||||
disabled: document.getElementById("scanImport").disabled,
|
||||
boxes: document.querySelectorAll(".scan-box").length,
|
||||
onCount: document.querySelectorAll(".scan-box.on").length};
|
||||
})()`, {});
|
||||
console.log("pick:", JSON.stringify(picked));
|
||||
|
||||
await evaluate(cdp, `document.querySelector(".scroll") && (document.querySelector(".scroll").scrollTop = 0);`, {});
|
||||
const shot = await cdp.send("Page.captureScreenshot", { format: "png" });
|
||||
fs.writeFileSync("./prototype/workbench/preview-scan.png", Buffer.from(shot.data, "base64"));
|
||||
console.log("shot saved");
|
||||
} catch (e) {
|
||||
console.error("FAIL", e && (e.stack || e.message));
|
||||
} finally {
|
||||
if (!launch.reused) await cdp.send("Browser.close").catch(() => {});
|
||||
cdp.close();
|
||||
}
|
||||
@@ -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
@@ -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 不可用时按参数退回演示题库。"""
|
||||
|
||||
@@ -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
|
||||
@@ -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
@@ -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
|
||||
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 1.6 MiB |
Binary file not shown.
|
After Width: | Height: | Size: 176 KiB |
@@ -153,3 +153,12 @@ prototype/workbench/index.html ← 全部代码都在这一个文件里
|
||||
成语 + 拼音 + 褒/贬/中性 + 释义 + 例句 + 易错字;
|
||||
- 只影响「知识点」页,不改判分、不改讲清验收;
|
||||
- 改表流程:改 xlsx → `python gen_idiom.py` → 刷新工作台。
|
||||
|
||||
## 九、拍照入库(整页拍 → 点选)
|
||||
|
||||
入口在左侧「拍照入库」。选一张整页卷子照片 → 后端切块 → 图上出现带编号的红框 →
|
||||
点一下真正做错的那几道(可多选)→ 「入库选中的 N 道」。
|
||||
|
||||
- 不要求家长只拍一道题:整页拍,切歪了也能靠点选绕过去。
|
||||
- 已做完的卷子也能用:卷面上的手写答案**不会**被当成标准答案,只有纯算式才由我们自算。
|
||||
- 分数/公式会被转成可读形式(`\frac{1}{4}` → `1/4`);分数四则的自动判分还没做,这类题标「你自己判」。
|
||||
|
||||
@@ -379,6 +379,27 @@ td .t{font-family:"Consolas",monospace;font-size:13.5px}
|
||||
.idm-d { margin-top: 6px; font-size: 13px; line-height: 1.65; color: #3B342C; }
|
||||
.idm-e { margin-top: 4px; font-size: 12px; color: #6E6252; }
|
||||
.idm-t { margin-top: 4px; font-size: 11.5px; color: #8A6A3E; }
|
||||
/* ---- 拍照入库 ---- */
|
||||
.scan-drop { text-align: center; padding: 34px 20px; border: 1.5px dashed #E2D3BE; border-radius: var(--r); background: #FDFAF3; }
|
||||
.sd-t { font-size: 17px; font-weight: 700; color: var(--ink); }
|
||||
.sd-s { margin-top: 8px; font-size: 13px; color: var(--muted); line-height: 1.7; max-width: 520px; margin-left: auto; margin-right: auto; }
|
||||
.scan-drop .btn { margin-top: 16px; }
|
||||
.sd-hint { display: block; margin-top: 10px; font-size: 12.5px; color: #8A6A3E; min-height: 18px; }
|
||||
.scan-head { display: flex; align-items: center; gap: 10px; margin-bottom: 12px; flex-wrap: wrap; }
|
||||
.scan-tip { margin-left: 10px; font-size: 12.5px; color: var(--muted); }
|
||||
.scan-wrap { position: relative; width: fit-content; max-width: 100%; margin: 0 auto; }
|
||||
.scan-wrap img { display: block; max-width: 100%; max-height: 62vh; border-radius: 10px; border: 1px solid var(--line); }
|
||||
.scan-layer { position: absolute; inset: 0; }
|
||||
.scan-box { position: absolute; border: 2px solid rgba(228,99,74,.55); background: rgba(228,99,74,.06); border-radius: 6px; cursor: pointer; transition: background .12s, border-color .12s; }
|
||||
.scan-box:hover { border-color: var(--brand); background: rgba(228,99,74,.12); }
|
||||
.scan-box.on { border-color: var(--brand-d); background: rgba(228,99,74,.20); box-shadow: 0 0 0 2px rgba(228,99,74,.25) inset; }
|
||||
.scan-box i { position: absolute; top: -9px; left: -9px; width: 20px; height: 20px; border-radius: 50%; background: #fff; border: 1.5px solid rgba(228,99,74,.55); color: #B4482F; font-style: normal; font-size: 11px; line-height: 17px; text-align: center; font-weight: 700; }
|
||||
.scan-box.on i { background: var(--brand); border-color: var(--brand-d); color: #fff; }
|
||||
.scan-legend { margin-top: 12px; font-size: 12px; color: var(--muted); }
|
||||
.toast { position: fixed; left: 50%; bottom: 46px; transform: translateX(-50%) translateY(12px);
|
||||
background: #2B2622; color: #fff; font-size: 13.5px; padding: 10px 18px; border-radius: 999px;
|
||||
box-shadow: 0 8px 22px rgba(0,0,0,.18); opacity: 0; pointer-events: none; transition: opacity .18s, transform .18s; z-index: 90; }
|
||||
.toast.on { opacity: 1; transform: translateX(-50%) translateY(0); }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
@@ -397,6 +418,9 @@ td .t{font-family:"Consolas",monospace;font-size:13.5px}
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7"><path d="M5 4h11l3 3v13H5z"/><path d="M8 9h8M8 13h6"/></svg>今日训练
|
||||
<span class="badge" id="navDue">5</span>
|
||||
</a>
|
||||
<a href="#scan" data-v="scan">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7"><path d="M4 8V6a2 2 0 0 1 2-2h2M20 8V6a2 2 0 0 0-2-2h-2M4 16v2a2 2 0 0 0 2 2h2M20 16v2a2 2 0 0 1-2 2h-2"/><rect x="8" y="8" width="8" height="8" rx="1.5"/></svg>拍照入库
|
||||
</a>
|
||||
<a href="#wrong" data-v="wrong">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7"><path d="M6 3h9l4 4v14H6z"/><path d="M9 12l2 2 4-4"/></svg>错题本
|
||||
</a>
|
||||
@@ -524,6 +548,36 @@ td .t{font-family:"Consolas",monospace;font-size:13.5px}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- ======== 拍照入库(整页拍 → 点哪几道错了) ======== -->
|
||||
<section class="view" id="v-scan" hidden>
|
||||
<h1>拍照入库</h1>
|
||||
<p class="sub">把整页拍下来就行,不用单独拍某一道。我们切好块,你在图上点一下「哪几道错了」。</p>
|
||||
|
||||
<div class="card" id="scanPick">
|
||||
<div class="scan-drop" id="scanDrop">
|
||||
<div class="sd-t">选一张卷子照片</div>
|
||||
<div class="sd-s">整页拍、光线均匀、字清楚。已做完的卷子也能用——手写的部分我们不当作答案。</div>
|
||||
<input type="file" id="scanFile" accept="image/*" hidden>
|
||||
<button class="btn" id="scanChoose">选照片</button>
|
||||
<span class="sd-hint" id="scanHint"></span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card" id="scanBox" hidden>
|
||||
<div class="scan-head">
|
||||
<div><b id="scanCount">切出 0 道</b><span class="scan-tip">点一下你觉得错的那几道(可多选)</span></div>
|
||||
<div class="grow"></div>
|
||||
<button class="btn line" id="scanReset">重选</button>
|
||||
<button class="btn" id="scanImport" disabled>入库选中的 0 道</button>
|
||||
</div>
|
||||
<div class="scan-wrap" id="scanWrap">
|
||||
<img id="scanImg" alt="卷子">
|
||||
<div class="scan-layer" id="scanLayer"></div>
|
||||
</div>
|
||||
<div class="scan-legend">框里有数字的是切出来的题块;红色是已选中的。看不清就重拍一张——比在这里硬认快。</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- ======== 今日训练 ======== -->
|
||||
<section class="view" id="v-train" hidden>
|
||||
<h1>今日训练</h1>
|
||||
@@ -861,6 +915,16 @@ const DEMO = {
|
||||
|
||||
const LOGIN = { code: "", timer: null, deadline: 0 };
|
||||
|
||||
let _toastTimer = null;
|
||||
function toast(msg) {
|
||||
let el = document.getElementById("toast");
|
||||
if (!el) { el = document.createElement("div"); el.id = "toast"; el.className = "toast"; document.body.appendChild(el); }
|
||||
el.textContent = String(msg || "");
|
||||
el.classList.add("on");
|
||||
clearTimeout(_toastTimer);
|
||||
_toastTimer = setTimeout(() => el.classList.remove("on"), 2600);
|
||||
}
|
||||
|
||||
function setStatus(t) { const el = document.getElementById("lgStatus"); if (el) el.textContent = t; }
|
||||
|
||||
function showLogin() {
|
||||
@@ -2028,6 +2092,137 @@ document.addEventListener("click", () => {
|
||||
if (pn) pn.classList.remove("on");
|
||||
});
|
||||
|
||||
|
||||
/* ================= 拍照入库:整页拍 → 点选 → 入库 ================= */
|
||||
const SCAN = { draft: null, blocks: [], picks: [], w: 1, h: 1, busy: false };
|
||||
|
||||
function scanEl(id) { return document.getElementById(id); }
|
||||
|
||||
function scanReset() {
|
||||
SCAN.draft = null; SCAN.blocks = []; SCAN.picks = []; SCAN.busy = false;
|
||||
scanEl("scanBox").hidden = true;
|
||||
scanEl("scanPick").hidden = false;
|
||||
scanEl("scanHint").textContent = "";
|
||||
scanEl("scanImg").removeAttribute("src");
|
||||
scanEl("scanLayer").innerHTML = "";
|
||||
}
|
||||
|
||||
function scanChoose() { scanEl("scanFile").click(); }
|
||||
|
||||
async function onScanFile(file) {
|
||||
if (!file) return;
|
||||
if (SCAN.busy) return;
|
||||
SCAN.busy = true;
|
||||
scanEl("scanHint").textContent = "正在切题…(一张图大约几秒)";
|
||||
try {
|
||||
const dataUrl = await new Promise((res, rej) => {
|
||||
const r = new FileReader();
|
||||
r.onload = () => res(String(r.result || ""));
|
||||
r.onerror = () => rej(new Error("读不出这张图"));
|
||||
r.readAsDataURL(file);
|
||||
});
|
||||
const b64 = dataUrl.includes(",") ? dataUrl.split(",")[1] : dataUrl;
|
||||
const d = await api("/api/papers/scan/detect", {
|
||||
method: "POST",
|
||||
body: { image_b64: b64, filename: file.name || "page.jpg" }
|
||||
});
|
||||
SCAN.draft = d.draft_id; SCAN.blocks = d.blocks || []; SCAN.w = d.width || 1; SCAN.h = d.height || 1;
|
||||
SCAN.picks = [];
|
||||
scanEl("scanImg").src = dataUrl;
|
||||
scanEl("scanPick").hidden = true;
|
||||
scanEl("scanBox").hidden = false;
|
||||
scanEl("scanHint").textContent = "";
|
||||
renderScanBoxes();
|
||||
updateScanCount();
|
||||
} catch (e) {
|
||||
scanEl("scanHint").textContent = (e && e.message) || "切不出来,换一张试试";
|
||||
if (window.console) console.warn(e);
|
||||
} finally {
|
||||
SCAN.busy = false;
|
||||
}
|
||||
}
|
||||
|
||||
function renderScanBoxes() {
|
||||
const layer = scanEl("scanLayer");
|
||||
layer.innerHTML = "";
|
||||
SCAN.blocks.forEach((b, i) => {
|
||||
const box = b.box || {};
|
||||
const el = document.createElement("div");
|
||||
el.className = "scan-box";
|
||||
el.style.left = (100 * (box.x || 0) / SCAN.w) + "%";
|
||||
el.style.top = (100 * (box.y || 0) / SCAN.h) + "%";
|
||||
el.style.width = (100 * (box.w || 0) / SCAN.w) + "%";
|
||||
el.style.height = (100 * (box.h || 0) / SCAN.h) + "%";
|
||||
el.innerHTML = "<i>" + (i + 1) + "</i>";
|
||||
el.title = (b.stem || "").slice(0, 60);
|
||||
el.onclick = () => toggleBox(i);
|
||||
layer.appendChild(el);
|
||||
});
|
||||
}
|
||||
|
||||
function toggleBox(i) {
|
||||
const at = SCAN.picks.indexOf(i);
|
||||
if (at >= 0) SCAN.picks.splice(at, 1); else SCAN.picks.push(i);
|
||||
const nodes = scanEl("scanLayer").children;
|
||||
const el = nodes && nodes[i];
|
||||
if (el) el.classList.toggle("on", SCAN.picks.indexOf(i) >= 0);
|
||||
updateScanCount();
|
||||
}
|
||||
|
||||
function updateScanCount() {
|
||||
const n = SCAN.blocks.length;
|
||||
scanEl("scanCount").textContent = "切出 " + n + " 道";
|
||||
const btn = scanEl("scanImport");
|
||||
btn.disabled = SCAN.picks.length === 0;
|
||||
btn.textContent = "入库选中的 " + SCAN.picks.length + " 道";
|
||||
SCAN.blocks.forEach((b, i) => {
|
||||
const el = scanEl("scanLayer").children[i];
|
||||
if (el) el.classList.toggle("on", SCAN.picks.indexOf(i) >= 0);
|
||||
});
|
||||
}
|
||||
|
||||
async function onScanImport() {
|
||||
if (!SCAN.picks.length || !SCAN.draft || SCAN.busy) return;
|
||||
SCAN.busy = true;
|
||||
const btn = scanEl("scanImport");
|
||||
const old = btn.textContent;
|
||||
btn.textContent = "入库中…";
|
||||
try {
|
||||
const r = await api("/api/papers/scan/import", {
|
||||
method: "POST",
|
||||
body: { child_id: S.cid, subject: (S.kid && S.kid.subjects && S.kid.subjects[0]) || "math", draft_id: SCAN.draft, picks: SCAN.picks }
|
||||
});
|
||||
const picked = (r && r.ocr && r.ocr.picked) || SCAN.picks.length;
|
||||
toast("已入库 " + picked + " 道,明天开始复习");
|
||||
scanReset();
|
||||
await refresh();
|
||||
show("wrong");
|
||||
} catch (e) {
|
||||
toast((e && e.message) || "入库失败,再试一次");
|
||||
} finally {
|
||||
btn.textContent = old;
|
||||
SCAN.busy = false;
|
||||
}
|
||||
}
|
||||
|
||||
document.addEventListener("DOMContentLoaded", () => {
|
||||
const b = scanEl("scanChoose"); if (b) b.onclick = scanChoose;
|
||||
const f = scanEl("scanFile");
|
||||
if (f) f.onchange = () => { onScanFile(f.files && f.files[0]); f.value = ""; };
|
||||
const imp = scanEl("scanImport"); if (imp) imp.onclick = onScanImport;
|
||||
const rs = scanEl("scanReset"); if (rs) rs.onclick = scanReset;
|
||||
const dr = scanEl("scanDrop");
|
||||
if (dr) {
|
||||
dr.addEventListener("dragover", (e) => { e.preventDefault(); dr.style.background = "#FBEFE4"; });
|
||||
dr.addEventListener("dragleave", () => { dr.style.background = ""; });
|
||||
dr.addEventListener("drop", (e) => {
|
||||
e.preventDefault(); dr.style.background = "";
|
||||
const file = e.dataTransfer && e.dataTransfer.files && e.dataTransfer.files[0];
|
||||
onScanFile(file);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 335 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 335 KiB |
@@ -64,7 +64,7 @@ try:
|
||||
|
||||
st, r = call("GET", "/api/health")
|
||||
check("health 200", st == 200, r)
|
||||
check("routes=57", r["data"]["routes"] == 56, r["data"].get("routes"))
|
||||
check("routes=58", r["data"]["routes"] == 58, r["data"].get("routes"))
|
||||
|
||||
st, r = call("POST", "/api/auth/sms-code", {"phone": "13800138000"})
|
||||
check("发码 200", st == 200 and r["data"]["sent"] is True, r)
|
||||
|
||||
@@ -63,7 +63,7 @@ try:
|
||||
|
||||
st, r = call("GET", "/api/health")
|
||||
check("health 200", st == 200, r)
|
||||
check("routes=57", r["data"]["routes"] == 56, r["data"].get("routes"))
|
||||
check("routes=58", r["data"]["routes"] == 58, r["data"].get("routes"))
|
||||
|
||||
st, r = call("POST", "/api/auth/wx-login", {"code": "demo"})
|
||||
tok = r["data"]["token"]
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
"""整页拍 → 点选 → 入库(scanflow)的单元测试。
|
||||
|
||||
腾讯云不在这里真调:把它 mock 成固定返回,只验证我们自己的逻辑——
|
||||
框过滤、只入库选中的块、空 picks 报错、草稿不存在报错。
|
||||
"""
|
||||
import json
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest import mock
|
||||
|
||||
from backend import db as dbm
|
||||
from backend import scanflow, services as svc
|
||||
from backend.services import ApiError
|
||||
|
||||
from ._tmpdir import workdir
|
||||
|
||||
# 1 张 200x300 的纯色图就够了,识别被 mock 掉
|
||||
def _png_bytes(w=200, h=300):
|
||||
from PIL import Image
|
||||
import io
|
||||
buf = io.BytesIO()
|
||||
Image.new("RGB", (w, h), (250, 250, 250)).save(buf, "PNG")
|
||||
return buf.getvalue(), f"t{w}.png"
|
||||
|
||||
|
||||
def _fake_split(image, *a, **kw):
|
||||
return {
|
||||
"ok": True,
|
||||
"questions": [
|
||||
{
|
||||
"stem": "1. 计算:36 + 47 =()",
|
||||
"judge_type": "calc",
|
||||
"detected_as": "calc",
|
||||
"answer": "83",
|
||||
"page_answer": None,
|
||||
"options": None,
|
||||
"box": {"x": 10, "y": 10, "w": 160, "h": 60},
|
||||
},
|
||||
{
|
||||
"stem": "2. 一个长方形长 8 厘米,宽 5 厘米,面积是多少?",
|
||||
"judge_type": "manual",
|
||||
"detected_as": "manual",
|
||||
"answer": None,
|
||||
"page_answer": "40 平方厘米",
|
||||
"options": None,
|
||||
"box": {"x": 10, "y": 90, "w": 160, "h": 60},
|
||||
},
|
||||
{
|
||||
# 太小,应当被丢掉
|
||||
"stem": "3. 边角料",
|
||||
"judge_type": "manual",
|
||||
"detected_as": "manual",
|
||||
"answer": None,
|
||||
"page_answer": None,
|
||||
"options": None,
|
||||
"box": {"x": 10, "y": 160, "w": 12, "h": 12},
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
class ScanFlowTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.dir = workdir("scanflow")
|
||||
cls.db = cls.dir / "scan.db"
|
||||
|
||||
def setUp(self):
|
||||
if self.db.exists():
|
||||
self.db.unlink()
|
||||
self.conn = dbm.connect(self.db)
|
||||
dbm.init_db(self.conn)
|
||||
lg = svc.login(self.conn, "demo")
|
||||
self.gid = lg["guardian_id"]
|
||||
svc.give_consent(self.conn, self.gid, "v1")
|
||||
self.cid = svc.create_child(self.conn, self.gid, "小满", 5)["id"]
|
||||
|
||||
def tearDown(self):
|
||||
self.conn.close()
|
||||
|
||||
def _detect(self):
|
||||
raw, name = _png_bytes()
|
||||
with mock.patch.object(scanflow.tencent_ocr, "split_questions", _fake_split):
|
||||
return scanflow.detect(raw, name)
|
||||
|
||||
def test_detect_drops_tiny_block(self):
|
||||
d = self._detect()
|
||||
self.assertEqual(len(d["blocks"]), 2, "12x12 的小框应当被过滤")
|
||||
self.assertEqual(d["width"], 200)
|
||||
self.assertTrue(all(b["box"]["w"] >= scanflow.MIN_BOX_SIDE for b in d["blocks"]))
|
||||
meta = Path(scanflow.DRAFT_DIR) / f"{d['draft_id']}.json"
|
||||
self.assertTrue(meta.exists())
|
||||
|
||||
def test_import_only_picked(self):
|
||||
d = self._detect()
|
||||
with mock.patch.object(scanflow.tencent_ocr, "split_questions", _fake_split):
|
||||
paper = svc.import_scan_picks(
|
||||
self.conn, self.gid, self.cid, "math", d["draft_id"], [1]
|
||||
)
|
||||
self.assertEqual(len(paper["questions"]), 1)
|
||||
q = paper["questions"][0]
|
||||
self.assertIn("长方形", q["stem"])
|
||||
self.assertEqual(paper["ocr"]["picked"], 1)
|
||||
# 入库即「观察中」:今天不复习,明天才进队列
|
||||
rows = self.conn.execute(
|
||||
"SELECT stem, status FROM mistakes WHERE child_id=?", (self.cid,)
|
||||
).fetchall()
|
||||
self.assertEqual(len(rows), 1)
|
||||
self.assertEqual(rows[0]["status"], "observing")
|
||||
self.assertIn("长方形", rows[0]["stem"])
|
||||
self.assertEqual(svc.today_queue(self.conn, self.gid, self.cid)["items"], [])
|
||||
|
||||
def test_empty_picks_rejected(self):
|
||||
d = self._detect()
|
||||
with self.assertRaises(ApiError) as ctx:
|
||||
svc.import_scan_picks(self.conn, self.gid, self.cid, "math", d["draft_id"], [])
|
||||
self.assertEqual(ctx.exception.status, 400)
|
||||
self.assertEqual(ctx.exception.code, "NO_PICKS")
|
||||
|
||||
def test_unknown_draft(self):
|
||||
with self.assertRaises(ApiError) as ctx:
|
||||
svc.import_scan_picks(self.conn, self.gid, self.cid, "math", "deadbeefdeadbeef", [0])
|
||||
self.assertEqual(ctx.exception.status, 404)
|
||||
self.assertEqual(ctx.exception.code, "DRAFT_NOT_FOUND")
|
||||
|
||||
def test_picks_out_of_range_ignored(self):
|
||||
d = self._detect()
|
||||
with self.assertRaises(ApiError) as ctx:
|
||||
svc.import_scan_picks(self.conn, self.gid, self.cid, "math", d["draft_id"], [9, 10])
|
||||
self.assertEqual(ctx.exception.code, "NO_PICKS")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user