Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
87278b51e8 | ||
|
|
b470d189fc | ||
|
|
dfc9656eb2 | ||
|
|
5fcbe086fd | ||
|
|
53699b4e42 | ||
|
|
2f81e07b7d | ||
|
|
c4e26051e3 | ||
|
|
59e82b922a | ||
|
|
8a93058855 | ||
|
|
bde4170423 | ||
|
|
d6462b9ce2 | ||
|
|
c4f5df3343 | ||
|
|
aa068cef6f | ||
|
|
ab05221105 | ||
|
|
ef201ffacc | ||
|
|
11a7f18b31 |
@@ -45,3 +45,7 @@ data/bench/results.prev.jsonl
|
||||
# 评测的中间结果(可重跑)
|
||||
data/bench/results.gap.jsonl
|
||||
data/bench/results.verified.jsonl
|
||||
|
||||
# test artifacts (tests may only write inside the workspace)
|
||||
data/_ocrcache_test/
|
||||
data/_ocr_usage_test.json
|
||||
|
||||
@@ -4,11 +4,13 @@
|
||||
|
||||
| 想做什么 | 从这里进 |
|
||||
|---|---|
|
||||
| **第一次了解这个项目** | `docs/项目总览.md`(Word 版:`report/错题毕业-项目总览.docx`;PDF 版同名 `.pdf`)—— 需求、竞品、优势、现状、缺口,一页纸讲清 |
|
||||
| 找某份文档 | `docs/README.md`(按「你想知道什么」排的索引) |
|
||||
| 跑起来看效果 | `python -m backend.app --port 8000` → <http://127.0.0.1:8000/workbench>(扫码或输 8 位码,也可「先看演示」) |
|
||||
| 看后端接口 | <http://127.0.0.1:8000/docs>(自动生成);控制台 <http://127.0.0.1:8000/> |
|
||||
| 读需求与设计 | `report/错题毕业-小学版-PRD.docx`、`report/错题毕业-产品方案书.pdf` |
|
||||
| 部署上线 | `deploy/README.md`(Docker + Caddy + 备份 + 上线检查清单) |
|
||||
| 小程序 | `miniprogram/README.md`(3 tab:首页 / 排题 / 我的) |
|
||||
| 小程序 | `miniprogram/README.md`(3 tab:首页 / 拍题 / 我的) |
|
||||
| 看数据从哪来 | `data/out/report.md`(1,097 条竞品差评 + 554 条小红书评论的归因) |
|
||||
|
||||
代码在哪:`backend/`(接口与业务)、`core/`(两个产品共用的纯函数:时间/连接/文本/数值)、`prototype/workbench/`(工作台单文件)、`miniprogram/`(小程序)、`deploy/`(部署)。
|
||||
@@ -314,3 +316,48 @@ data/
|
||||
`deploy/` 里有三种跑法(Docker Compose / systemd / 本机),以及 Caddy 反代、备份脚本、上线检查清单。先看 [deploy/README.md](deploy/README.md)。
|
||||
|
||||
注意两条平台限制:Linux 服务器上没有 Windows OCR,拍照识题要配 `OCR_HTTP_URL`;手机号登录的短信服务商还没接(现在验证码直接回显,只适合本机)。
|
||||
|
||||
## 本地怎么跑(三步)
|
||||
|
||||
### 一、起后端
|
||||
|
||||
```powershell
|
||||
cd D:\gitee\errortopic
|
||||
python -m backend.app --port 8000 # 只给本机用
|
||||
python -m backend.app --host 0.0.0.0 --port 8000 # 手机也想连(同一个 Wi-Fi)
|
||||
```
|
||||
|
||||
启动后:
|
||||
|
||||
- 工作台 <http://127.0.0.1:8000/workbench>
|
||||
- 接口控制台 <http://127.0.0.1:8000/>(列出 60 条路由)
|
||||
- 接口文档 <http://127.0.0.1:8000/docs>
|
||||
|
||||
### 二、登录(dev 模式不用微信)
|
||||
|
||||
打开工作台会显示 8 位登录码。`wx_mode` 是 `dev` 时,码下面有一个
|
||||
**「模拟确认」**按钮——点它等于手机扫码确认,直接进工作台,数据写
|
||||
`data/app.db`。
|
||||
|
||||
不想连后端也能看界面:直接双击打开 `prototype/workbench/index.html`,
|
||||
点「先看演示」,用的是内置演示数据(不含拍照入库,那个必须后端)。
|
||||
|
||||
### 三、手机上试
|
||||
|
||||
同一 Wi-Fi 下用手机浏览器打开 `http://<电脑局域网 IP>:8000/workbench`
|
||||
(Windows 上用 `ipconfig` 看 WLAN 的 IPv4)。底部会变成 6 个 tab 的导航,
|
||||
今日训练 / 错题本 / 周报三屏都能用。
|
||||
|
||||
## 本地怎么验
|
||||
|
||||
```powershell
|
||||
python tools/run_tests.py # 239 个单测
|
||||
python tests\smoke_http.py # 41 项接口冒烟
|
||||
python tests\smoke_manual.py # 22 项手工链路
|
||||
python tests\smoke_login.py # 21 项登录
|
||||
python tests\smoke_junior.py # 29 项初中版
|
||||
```
|
||||
|
||||
拍照入库会真调腾讯云切题(**一张照片 1 次调用**,勾到口算卡再裁一次,命中
|
||||
缓存就不花钱)。本月用量看 `data/ocr_usage.json`,免费额度 1000 次/月,
|
||||
`OCR_MONTHLY_LIMIT` 到顶会自动停手。
|
||||
|
||||
@@ -1,164 +0,0 @@
|
||||
"""把知识点编号(kp)打通:题库标注 → 表结构 → 入库 → 接口 → 解析查表。
|
||||
|
||||
分三步:
|
||||
1. content.py 末尾给 72 道题标上 M/C 编号(显式列表,不改题干);
|
||||
2. db.py 的 questions / mistakes 加 kp 列,老库用 _migrate 补;
|
||||
3. services.py 的 4 处 INSERT 带上 kp,attempt 返回 kp,前端按 kp 查模板。
|
||||
"""
|
||||
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parent
|
||||
CONTENT = ROOT / "backend" / "content.py"
|
||||
DB = ROOT / "backend" / "db.py"
|
||||
SERVICES = ROOT / "backend" / "services.py"
|
||||
|
||||
# ── 72 道题的知识点编号(按 grade 顺序,对应 content.py 里的列表)────────────
|
||||
MATH_KP = {
|
||||
1: ["M003", "M004", "M003", "M004", "M007", "M004"],
|
||||
2: ["M019", "M020", "M022", "M023", "M022", "M020"],
|
||||
3: ["M037", "M038", "M039", "M040", "M051", "M027"],
|
||||
4: ["M039", "M060", "M062", "M055", "", "M038"],
|
||||
5: ["M077", "M078", "M082", "M081", "M096", "M064"],
|
||||
6: ["M087", "M110", "M114", "M105", "M110", "M103"],
|
||||
}
|
||||
CHINESE_KP = {
|
||||
1: ["C011", "C011", "C014", "C015", "C008", ""],
|
||||
2: ["C030", "C027", "C032", "C030", "C038", "C030"],
|
||||
3: ["C046", "C052", "C049", "C046", "", "C046"],
|
||||
4: ["C070", "C070", "C075", "C073", "", "C038"],
|
||||
5: ["C090", "C090", "C093", "C073", "C059", "C038"],
|
||||
6: ["C108", "C108", "C111", "C073", "C113", "C119"],
|
||||
}
|
||||
|
||||
BLOCK_HEAD = "\n# ---------------------------------------------------------------- 知识点编号\n"
|
||||
|
||||
|
||||
def patch_content():
|
||||
s = CONTENT.read_text(encoding="utf-8")
|
||||
if "MATH_KP" in s:
|
||||
print("content.py 已标注,跳过")
|
||||
return
|
||||
lines = [BLOCK_HEAD]
|
||||
lines.append("# 每道题对应《知识点对照表》里的一个编号;空字符串表示这个概念还没进表,\n")
|
||||
lines.append("# 解析时退回通用三步(宁可讲得浅,也不套错模板)。\n")
|
||||
lines.append("MATH_KP = {\n")
|
||||
for g, codes in MATH_KP.items():
|
||||
lines.append(f" {g}: {codes!r},\n")
|
||||
lines.append("}\nCHINESE_KP = {\n")
|
||||
for g, codes in CHINESE_KP.items():
|
||||
lines.append(f" {g}: {codes!r},\n")
|
||||
lines.append("}\n\n")
|
||||
lines.append("for _g, _codes in MATH_KP.items():\n")
|
||||
lines.append(" for _q, _kp in zip(MATH[_g], _codes):\n")
|
||||
lines.append(' _q["kp"] = _kp or None\n')
|
||||
lines.append("for _g, _codes in CHINESE_KP.items():\n")
|
||||
lines.append(" for _q, _kp in zip(CHINESE[_g], _codes):\n")
|
||||
lines.append(' _q["kp"] = _kp or None\n')
|
||||
s = s.rstrip("\n") + "\n" + "".join(lines)
|
||||
CONTENT.write_text(s, encoding="utf-8", newline="\n")
|
||||
print("content.py 已加 72 道题的 kp")
|
||||
|
||||
|
||||
def patch_db():
|
||||
s = DB.read_text(encoding="utf-8")
|
||||
if '"kp"' in s:
|
||||
print("db.py 已有 kp,跳过")
|
||||
return
|
||||
# 1) 建表语句加列
|
||||
s = s.replace(''' options TEXT,
|
||||
judge_type TEXT NOT NULL DEFAULT 'calc'
|
||||
)''', ''' options TEXT,
|
||||
kp TEXT,
|
||||
judge_type TEXT NOT NULL DEFAULT 'calc'
|
||||
)''', 1)
|
||||
# 2) 迁移:老库补列
|
||||
s = s.replace(''' want = {"questions": ["options"], "mistakes": ["options"]}''',
|
||||
''' want = {"questions": ["options", "kp"], "mistakes": ["options", "kp"]}''', 1)
|
||||
DB.write_text(s, encoding="utf-8", newline="\n")
|
||||
print("db.py 已加 kp 列与迁移")
|
||||
|
||||
|
||||
def patch_services():
|
||||
s = SERVICES.read_text(encoding="utf-8")
|
||||
n = 0
|
||||
|
||||
# ① create_paper
|
||||
old = ''' "INSERT INTO questions (id, paper_id, child_id, subject, seq, stem, answer, options,"
|
||||
" judge_type, created_at) VALUES (?,?,?,?,?,?,?,?,?,?)",
|
||||
(new_id("q"), pid, cid, subject, i, q["stem"], q["answer"],
|
||||
json.dumps(q.get("options"), ensure_ascii=False) if q.get("options") else None,
|
||||
q.get("judge_type") or judging.infer_judge_type(q["stem"], subject), now()))'''
|
||||
new = ''' "INSERT INTO questions (id, paper_id, child_id, subject, seq, stem, answer, options,"
|
||||
" kp, judge_type, created_at) VALUES (?,?,?,?,?,?,?,?,?,?,?)",
|
||||
(new_id("q"), pid, cid, subject, i, q["stem"], q["answer"],
|
||||
json.dumps(q.get("options"), ensure_ascii=False) if q.get("options") else None,
|
||||
q.get("kp"),
|
||||
q.get("judge_type") or judging.infer_judge_type(q["stem"], subject), now()))'''
|
||||
assert old in s, "create_paper insert 未匹配"
|
||||
s = s.replace(old, new, 1)
|
||||
n += 1
|
||||
|
||||
# ② create_paper_from_image
|
||||
old = ''' "INSERT INTO questions (id, paper_id, child_id, subject, seq, stem, answer, options,"
|
||||
" judge_type, created_at) VALUES (?,?,?,?,?,?,?,?,?,?)",
|
||||
(new_id("q"), 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("judge_type") or "manual", now()))'''
|
||||
new = ''' "INSERT INTO questions (id, paper_id, child_id, subject, seq, stem, answer, options,"
|
||||
" kp, judge_type, created_at) VALUES (?,?,?,?,?,?,?,?,?,?,?)",
|
||||
(new_id("q"), 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()))'''
|
||||
assert old in s, "create_paper_from_image insert 未匹配"
|
||||
s = s.replace(old, new, 1)
|
||||
n += 1
|
||||
|
||||
# ③ add_manual_mistake
|
||||
old = ''' "INSERT INTO questions (id, paper_id, child_id, subject, seq, stem, answer, options,"
|
||||
" judge_type, verdict, wrong_code, created_at) VALUES (?,?,?,?,1,?,?,?,?,'wrong',?,?)",
|
||||
(qid, pid, cid, subject, stem, ans,
|
||||
json.dumps(opts, ensure_ascii=False) if opts else None, jt, wrong_code, now()))'''
|
||||
new = ''' "INSERT INTO questions (id, paper_id, child_id, subject, seq, stem, answer, options,"
|
||||
" kp, judge_type, verdict, wrong_code, created_at)"
|
||||
" VALUES (?,?,?,?,1,?,?,?,?,?,'wrong',?,?)",
|
||||
(qid, pid, cid, subject, stem, ans,
|
||||
json.dumps(opts, ensure_ascii=False) if opts else None, kp, jt, wrong_code, now()))'''
|
||||
assert old in s, "add_manual_mistake insert 未匹配"
|
||||
s = s.replace(old, new, 1)
|
||||
n += 1
|
||||
|
||||
# ④ mistakes 入库
|
||||
old = ''' "INSERT INTO mistakes (id, child_id, question_id, subject, stem, answer, options, judge_type,"
|
||||
" wrong_count, wrong_code, status, stage, interval_days, next_due, created_at)"
|
||||
" VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
|
||||
(mid, cid, qid, q["subject"], q["stem"], q["answer"], q["options"], q["judge_type"],'''
|
||||
new = ''' "INSERT INTO mistakes (id, child_id, question_id, subject, stem, answer, options, kp,"
|
||||
" judge_type, wrong_count, wrong_code, status, stage, interval_days, next_due, created_at)"
|
||||
" VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
|
||||
(mid, cid, qid, q["subject"], q["stem"], q["answer"], q["options"], q["kp"], q["judge_type"],'''
|
||||
assert old in s, "mistakes insert 未匹配"
|
||||
s = s.replace(old, new, 1)
|
||||
n += 1
|
||||
|
||||
# ⑤ 手输题允许带 kp
|
||||
s = s.replace(''' options: list[str] | None = None, wrong_code: str = "E4",
|
||||
source: str = "manual") -> dict:''',
|
||||
''' options: list[str] | None = None, wrong_code: str = "E4",
|
||||
source: str = "manual", kp: str | None = None) -> dict:''', 1)
|
||||
|
||||
# ⑥ attempt 把 kp 一起下发(前端据此查解析模板)
|
||||
s = s.replace(''' "judge_type": mdict.get("judge_type"),''',
|
||||
''' "judge_type": mdict.get("judge_type"),
|
||||
"kp": mdict.get("kp"),''', 1)
|
||||
|
||||
SERVICES.write_text(s, encoding="utf-8", newline="\n")
|
||||
print(f"services.py 已改 {n} 处 INSERT + attempt 返回 kp")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
patch_content()
|
||||
patch_db()
|
||||
patch_services()
|
||||
@@ -484,7 +484,7 @@ python tests/smoke_http.py # 39 项 HTTP 冒烟(真起服务
|
||||
|
||||
金标 330 道时还剩 12 道没认出来,一开始以为是「整块没被切出来」,做了补扫才发现**不是**。
|
||||
|
||||
**补扫**(`scanflow._gap_bands / _gap_blocks`,`OCR_GAP_SCAN=0` 可关)
|
||||
**补扫**(`scanflow._gap_bands / _gap_blocks`,默认关:`detect(gap_scan=True)` 才做,`OCR_GAP_SCAN=0` 强制关)
|
||||
- 找出「没有框盖住、但确实有字」的横向条带:灰度二值化后按行求墨迹比例
|
||||
(`bw.resize((1,sh), BOX)` 一次拿到每行均值),先做行距桥接再找连续段,
|
||||
高度 ≥90px、墨迹在 0.4%–55% 之间才算,一页最多补 2 条
|
||||
@@ -492,6 +492,13 @@ python tests/smoke_http.py # 39 项 HTTP 冒烟(真起服务
|
||||
- **实测在 3 张漏检图上救回 0 道**:那 3 道根本不在空条带里,而是
|
||||
「框在、框里的内容读歪了」——`27+69` 被读成 `77+69`,`4/5-2/5` 被整行吞掉。
|
||||
补扫留着(真有空条带时它有用),但它不是这次的解药。
|
||||
- **默认关**:每页多 1–2 次调用,而金标口径上救回 0 道;线上要开就
|
||||
`scanflow.detect(image, name, gap_scan=True)`。它在「看图写数、比大小」这种
|
||||
整块没有文字框的区域确实有用(一张卷上能多出 3 块可点区域)。
|
||||
- **踩过一个坐标 bug**:补扫条带是**放大 1.4 倍**再送去识别的,早先 `_gap_blocks`
|
||||
只做 `y + y0` 平移、没把框除以 1.4,于是小程序里出现 `y=1448 / 页高 1260` 的框,
|
||||
点在页面外面。现在用 `GAP_SCALE = 1.4`,裁切和还原用同一个常量,并把完全落在
|
||||
页外的框丢掉。凡是「裁一块出去识别、再把坐标搬回来」的代码都要成对检查缩放。
|
||||
|
||||
**卡片重读**(`scanflow.recognize_block` 里 `crop_card` 分支)
|
||||
- 口算卡最容易整块读歪。家长**勾到这一块**时,把它裁出来重读一次(1 次调用),
|
||||
@@ -532,7 +539,7 @@ python tests/smoke_http.py # 39 项 HTTP 冒烟(真起服务
|
||||
但如果孩子讲不清的原因是**前置知识缺了**(「两位数乘两位数」讲不清,其实是「表内乘法」不熟),
|
||||
再讲十遍这道题也不会过——闭环就在这里空转。
|
||||
|
||||
数据在 `data/kp_graph.json`:小学数学 1–3 年级,39 个知识点、60 条边,
|
||||
数据在 `data/kp_graph.json`:小学数学 1–6 年级,80 个知识点、106 条边(1–3 年级已核对过教材顺序,4–6 年级是草稿、待老师逐条审),
|
||||
每条边写 `strength`(hard/soft)与一句人话 `reason`。id 直接复用工作台
|
||||
`kpt.json` 的编号,前端不用再维护一张名字表。
|
||||
|
||||
@@ -550,7 +557,7 @@ python tests/smoke_http.py # 39 项 HTTP 冒烟(真起服务
|
||||
|
||||
三条边界,写在这里免得以后越做越大:
|
||||
|
||||
1. 只做小学 1–3 年级数学。语文的「知识点」不是树,硬连只会连出假因果。
|
||||
1. 只做小学数学。语文的「知识点」不是树,硬连只会连出假因果。
|
||||
2. 只做「退一层」,不做自适应诊断。错了的边只影响**建议**,不影响判分和毕业,
|
||||
所以不需要教师逐条审核就能上线。
|
||||
3. 不给空建议:没有知识点、或没有 hard 前置(比如 `M001` 10 以内数的认识),
|
||||
@@ -559,3 +566,119 @@ python tests/smoke_http.py # 39 项 HTTP 冒烟(真起服务
|
||||
`tests/test_kp_graph.py` 14 例:图自检(无未知 id、无环、前置年级不更高)、
|
||||
每条边有理由、规模在 30–60 点 / 40–90 边、`M041` 退到 `M039`、
|
||||
根节点不给建议、讲清失败时接口带 `retreat`、没有 kp 时不带。
|
||||
|
||||
### 四点二十五、知识点归类:认得出才归,认不出留空
|
||||
|
||||
拍照入库的题,切题接口不给知识点,于是「学情分析」里这一半题是隐形的——
|
||||
家长看到的是「数学最弱」,但说不出弱在哪一块。`backend/kp_match.py` 就是补这一手:
|
||||
一张规则表(32 条),按题干认出知识点,认出来才写 `kp`。
|
||||
|
||||
三条原则写在文件头,也是这次实现里反复权衡的地方:
|
||||
|
||||
1. **认不出就不给**。错的归类比没有归类更坏——它会让家长把时间花在错的地方。
|
||||
实测 `data/app.db` 39 道题里补上 12 道,剩下 3 道(病句、文学常识、句子排序)
|
||||
`kpt.json` 里根本没有对应点,就让它空着。
|
||||
2. **规则按「具体 → 笼统」排,顺序本身就是逻辑**。小数乘法必须排在整数乘法前,
|
||||
否则 `2.5 × 4` 会被「×」那条先抓走;只出现 `a/b` 的分数必须排在「吨/千克」前,
|
||||
否则「一批货物重 20 吨,它的 7/10 是多少」会被「吨」抢走归到质量单位。
|
||||
`tests/test_kp_match.py` 里 `test_decimal_beats_integer` 与
|
||||
`test_fraction_beats_unit` 就是钉这两个顺序的。
|
||||
3. **名字要能在模板里解析到 id**。规则写的是知识点**名字**,由 `resolve()` 反查
|
||||
`kpt.json` 的键;模板改名不会崩,只是那条规则失效。`rules_ok()` 返回解析不到的
|
||||
名字,`test_every_candidate_resolves` 把它当中断条件——候选名写错会当场红。
|
||||
|
||||
接在两个地方:`import_scan_picks()` 展开完口算卡之后逐题补,
|
||||
`add_manual_mistake()` 手输时顺手补(都只在 `kp` 为空时写,不覆盖已有的)。
|
||||
|
||||
历史库用一次性脚本补:
|
||||
|
||||
```powershell
|
||||
python tools/backfill_kp.py # 只看会补哪些
|
||||
python tools/backfill_kp.py --apply # 真写
|
||||
```
|
||||
|
||||
`tests/test_kp_match.py` 19 例:规则自检、小数/分数/单位/拼音/量词/近义词/
|
||||
标点/成语各命中一条、空题干与无关题干返回 `None`。
|
||||
|
||||
### 四点二十六、入库前逐条勾选:`/api/papers/scan/prepare`
|
||||
|
||||
`POST /api/papers/scan/prepare`(`{draft_id, picks, child_id, subject}`)只读不写:
|
||||
把勾中的块各 `recognize_block` 一遍,返回 `items: [{block, sub, stem, answer, …}]`。
|
||||
`sub` 是 `None` 表示这块本来就一道题,数字表示它是这块里的第几道(口算卡下标)。
|
||||
|
||||
`import_scan_picks` 的 `picks` 因此支持两种写法:`3`(整块)与
|
||||
`{"i": 3, "subs": [0, 2]}`(只要这块的第 0、2 道)。三种边界都在测试里:
|
||||
|
||||
- `subs: []` —— 这块里的小题全取消,等于不入库,不能退化成「整块都要」;
|
||||
- `subs` 下标越界 —— 跳过,不猜;
|
||||
- 预览是空的 —— 400 `NO_PICKS`。
|
||||
|
||||
为什么要有它:切题把 `27+69` 读成 `77+69` 这种错,机器判断不了对错,但家长一眼
|
||||
就能看出来。与其让家长事后去错题本里删,不如入库前摊开给他看。
|
||||
|
||||
调用成本:预览与正式入库调的是同一个 `recognize_block`,裁剪图按 sha1 命中
|
||||
`data/ocr_cache/`,所以预览这一遍**不额外花钱**(除非把 `OCR_CACHE=0` 关了)。
|
||||
|
||||
### 四点二十七、小狮落库:跨设备一致
|
||||
|
||||
`children` 表加了两列:`pet_stage`(0/1/2/3,按已毕业数 12 / 40 / 100 分档)和 `pet_fed_at`(最后喂食日期)。
|
||||
|
||||
- `services._pet_sync(conn, cid)` 现算:`graduated` = 已毕业数,`left_today` = 今天到期且未毕业的题数。
|
||||
- `fed_today` 的条件是 **`left_today == 0` 且今天真有一道题做过**——不是打卡,也不是打开页面就算。
|
||||
新号没有做题记录时不给「喂过」,否则白送一次。
|
||||
- 只有 `stage` 变了、或今天第一次喂,才 `UPDATE`;`GET /api/children` 不会天天写库。
|
||||
- `get_child()` / `list_children()` / `attempt()` 的返回体都带 `pet: {stage, fed_at, fed_today, graduated, left_today}`,
|
||||
前端优先用服务端的 `stage`(演示模式才本地算)。
|
||||
|
||||
### 四点二十八、语音讲一遍:录音 + 三项自评
|
||||
|
||||
`POST /api/mistakes/<mid>/explain` 现在多认一种 `channel: "audio"`:
|
||||
|
||||
```json
|
||||
{"channel": "audio", "audio_b64": "...", "audio_ext": "webm",
|
||||
"checks": {"wrong_reason": 1, "key_steps": 1, "next_time": 0}}
|
||||
```
|
||||
|
||||
- 音频落 `data/uploads/audio/{mid}_{ts}.{ext}`,单条上限 **8MB**,扩展名白名单
|
||||
`webm/mp3/m4a/aac/wav/ogg`(`services.AUDIO_EXTS`)。
|
||||
- **不转写、不判语义**:判「说没讲清」靠三项勾选(`services.EXPLAIN_CHECKS`),
|
||||
勾全了才 `passed`。理由写在 `prototype/workbench/README.md` 十六:
|
||||
机器判语义现在的误差比家长亲耳听大,先解决「不打字也能提交」。
|
||||
- 返回体多两个字段:`audio`(相对 `data/uploads` 的路径,前端可回放)、
|
||||
`checks`(本次勾选,0/1)。
|
||||
- 没过一样会带 `ask_stuck_at` 与 `retreat`,和打字那条路完全一致。
|
||||
|
||||
|
||||
### 四点二十九、变式自校验与严档(`variant_pending`)
|
||||
|
||||
`practice.verify(item) -> (ok, reason)`:变式必须能算、答案和题干一致、选择题答案在选项里,
|
||||
否则从 `similar()` 的结果里剔掉(宁缺勿错)。
|
||||
|
||||
严档(`children.strict_variant=1`)下的状态机:
|
||||
|
||||
| 发生什么 | 结果 |
|
||||
| --- | --- |
|
||||
| 原题做对 | `variant_pending`,`next_due` 当天,界面提示「换一道」 |
|
||||
| 变式做对 | `passed_once`,按第 1 档间隔排下一次 |
|
||||
| 变式做错 | `queued`,间隔归零,`wrong_count+1`,错因 `E2` |
|
||||
|
||||
`attempt(..., is_variant=True)` 只在 `status == "variant_pending"` 时接受,
|
||||
否则 409 `NOT_VARIANT_PENDING`;反过来 `variant_pending` 下不带 `variant` 会 409 `NEED_VARIANT`。
|
||||
`is_due()` 也认 `variant_pending`,所以上次没验完的变式今天还会排回来。
|
||||
|
||||
接口:`POST /api/children/<cid>/settings {"strict_variant": 1|0}`。
|
||||
|
||||
### 四点三十、连错三次也退一层(W8)
|
||||
|
||||
原来只有「讲清失败」才给退一层建议。但同一道题连错三次,说明缺的往往是前置——
|
||||
再排一次同题只是重复挫败。现在 `attempt()` 在 `wrong_count >= 3` 且答错时返回:
|
||||
|
||||
```json
|
||||
"retreat": {"kp": "M041", "name": "两位数乘两位数",
|
||||
"step": {"id": "M039", "name": "多位数乘一位数", "grade": 2},
|
||||
"reason": "两位数乘两位数就是两次多位数乘一位数再相加",
|
||||
"tip": "这道题讲不清,可能不是这道题的问题——先退到「多位数乘一位数」,做对两道再回来讲。"}
|
||||
```
|
||||
|
||||
前端在「再想想」那块把这条建议摊开,不再只是重复「明天再来一次」。
|
||||
注意:建题时 `wrong_count` 已经是 1(错三次才入库),所以第二次做错就会触发。
|
||||
|
||||
@@ -23,7 +23,7 @@ from pathlib import Path
|
||||
from urllib.parse import parse_qs, urlparse
|
||||
|
||||
from . import db as dbm
|
||||
from . import kp_graph, qr
|
||||
from . import kp_graph, ocr_budget, qr, tencent_ocr
|
||||
from . import scanflow, services as svc
|
||||
from .services import ApiError
|
||||
|
||||
@@ -103,8 +103,21 @@ def health(ctx: Ctx, **kw):
|
||||
svc.sweep_uploads(ctx.conn) # 上传目录按 90 天清,内部自己限每天一次
|
||||
except Exception:
|
||||
pass
|
||||
# 上线自查用:OCR 凭据配没配、这个月还剩多少次、缓存开没开。
|
||||
# 故意不暴露密钥本身,只说「有没有」。
|
||||
try:
|
||||
ocr_state = {
|
||||
"configured": tencent_ocr.available(),
|
||||
"mode": tencent_ocr.mode(),
|
||||
"cache": os.environ.get("OCR_CACHE", "") not in ("0", "false", "no", "off"),
|
||||
"used": ocr_budget.used(),
|
||||
"limit": ocr_budget.limit() or None,
|
||||
"remaining": ocr_budget.remaining(),
|
||||
}
|
||||
except Exception:
|
||||
ocr_state = {"configured": None}
|
||||
return {"ok": True, "service": "qingling-primary", "version": "1.2.0", "time": dbm.now(),
|
||||
"wx_mode": svc.wechat.mode(), "routes": len(ROUTES)}
|
||||
"wx_mode": svc.wechat.mode(), "routes": len(ROUTES), "ocr": ocr_state}
|
||||
|
||||
|
||||
@route("POST", "/api/auth/wx-login", auth="none")
|
||||
@@ -282,6 +295,17 @@ def post_scan_detect(ctx: Ctx, **kw):
|
||||
return scanflow.detect(image, str(ctx.body.get("filename") or "page.jpg"))
|
||||
|
||||
|
||||
@route("POST", "/api/papers/scan/prepare", auth="parent")
|
||||
def post_scan_prepare(ctx: Ctx, **kw):
|
||||
"""入库前预览:勾中的块里到底有哪几道(口算卡一块十几道,要逐条勾)。"""
|
||||
picks = ctx.body.get("picks") or []
|
||||
if not isinstance(picks, list):
|
||||
raise svc.ApiError(400, "BAD_PICKS", "picks 要是数组")
|
||||
return svc.prepare_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/scan/import", auth="parent")
|
||||
def post_scan_import(ctx: Ctx, **kw):
|
||||
"""家长勾完 → 只把选中的块裁出来单独识别并入库。"""
|
||||
@@ -358,7 +382,8 @@ def _child_id(ctx: Ctx) -> str:
|
||||
def post_attempt(ctx: Ctx, mid: str, **kw):
|
||||
return svc.attempt(ctx.conn, ctx.gid, _child_id(ctx), mid,
|
||||
str(ctx.body.get("answer") or ""),
|
||||
ctx.body.get("cost_ms"))
|
||||
ctx.body.get("cost_ms"),
|
||||
is_variant=bool(ctx.body.get("variant")))
|
||||
|
||||
|
||||
@route("POST", r"/api/mistakes/(?P<mid>[^/]+)/self-judge", auth="child_ok")
|
||||
@@ -385,7 +410,23 @@ def get_similar(ctx: Ctx, mid: str, **kw):
|
||||
def post_explain(ctx: Ctx, mid: str, **kw):
|
||||
return svc.explain(ctx.conn, ctx.gid, _child_id(ctx), mid,
|
||||
str(ctx.body.get("channel") or "ai_voice"),
|
||||
str(ctx.body.get("text") or ""))
|
||||
str(ctx.body.get("text") or ""),
|
||||
checks=ctx.body.get("checks") or None,
|
||||
audio_b64=ctx.body.get("audio_b64") or None,
|
||||
audio_ext=ctx.body.get("audio_ext") or None)
|
||||
|
||||
|
||||
@route("POST", r"/api/children/(?P<cid>[^/]+)/settings", auth="parent")
|
||||
def post_settings(ctx: Ctx, cid: str, **kw):
|
||||
"""严档开关:打开后第二次要做对一道没见过的变式。"""
|
||||
return svc.set_settings(ctx.conn, ctx.gid, cid, ctx.body.get("strict_variant"))
|
||||
|
||||
|
||||
@route("POST", r"/api/mistakes/(?P<mid>[^/]+)/stuck", auth="child_ok")
|
||||
def post_stuck(ctx: Ctx, mid: str, **kw):
|
||||
"""讲清失败后记「卡在哪」:read / plan / calc / check。"""
|
||||
return svc.set_stuck_at(ctx.conn, ctx.gid, _child_id(ctx), mid,
|
||||
ctx.body.get("stuck_at"))
|
||||
|
||||
|
||||
@route("GET", r"/api/kp-graph/(?P<kp>[^/]+)", auth="none")
|
||||
|
||||
@@ -46,7 +46,9 @@ CREATE TABLE IF NOT EXISTS children (
|
||||
grade INTEGER NOT NULL CHECK (grade BETWEEN 1 AND 6),
|
||||
remind_at TEXT NOT NULL DEFAULT '19:30',
|
||||
created_at TEXT NOT NULL,
|
||||
deleted_at TEXT
|
||||
deleted_at TEXT,
|
||||
pet_stage INTEGER NOT NULL DEFAULT 0,
|
||||
pet_fed_at TEXT
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS child_subjects (
|
||||
@@ -101,6 +103,7 @@ CREATE TABLE IF NOT EXISTS mistakes (
|
||||
next_due TEXT,
|
||||
explain_fails INTEGER NOT NULL DEFAULT 0,
|
||||
unstable_count INTEGER NOT NULL DEFAULT 0,
|
||||
stuck_at TEXT, -- 讲清失败时记的卡点:read/plan/calc/check
|
||||
created_at TEXT NOT NULL,
|
||||
graduated_at TEXT
|
||||
);
|
||||
@@ -274,9 +277,13 @@ def _migrate(conn: sqlite3.Connection) -> None:
|
||||
want = {
|
||||
"questions": {"options": "TEXT", "kp": "TEXT"},
|
||||
"mistakes": {"options": "TEXT", "kp": "TEXT",
|
||||
"unstable_count": "INTEGER NOT NULL DEFAULT 0"},
|
||||
"unstable_count": "INTEGER NOT NULL DEFAULT 0",
|
||||
"stuck_at": "TEXT"},
|
||||
"guardians": {"phone": "TEXT"},
|
||||
"papers": {"clean_path": "TEXT", "image_path": "TEXT"},
|
||||
# 小狮的形态与「今天喂过没有」要跨设备一致,所以落库(原来只在浏览器算出来)
|
||||
"children": {"pet_stage": "INTEGER NOT NULL DEFAULT 0", "pet_fed_at": "TEXT",
|
||||
"strict_variant": "INTEGER NOT NULL DEFAULT 0"},
|
||||
}
|
||||
for table, cols in want.items():
|
||||
ensure_columns(conn, table, cols)
|
||||
|
||||
@@ -25,8 +25,12 @@ GRAPH_PATH = Path(__file__).resolve().parent.parent / "data" / "kp_graph.json"
|
||||
|
||||
@lru_cache(maxsize=1)
|
||||
def _load() -> tuple[dict, dict]:
|
||||
raw = json.loads(GRAPH_PATH.read_text(encoding="utf-8"))
|
||||
topics = {t["id"]: t for t in raw["topics"]}
|
||||
"""读图。文件缺了/坏了就当没有图——「退一层」只是建议,不能因为少个数据文件让讲一遍 500。"""
|
||||
try:
|
||||
raw = json.loads(GRAPH_PATH.read_text(encoding="utf-8"))
|
||||
topics = {t["id"]: t for t in raw["topics"]}
|
||||
except (OSError, ValueError, KeyError):
|
||||
return {}, {}
|
||||
parents: dict[str, list[dict]] = {}
|
||||
for e in raw["edges"]:
|
||||
parents.setdefault(e["topicId"], []).append({
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
"""按题干把一道题归到 kpt.json 里的知识点。
|
||||
|
||||
为什么要它:拍照入库的题没有知识点,学情分析就看不见它们——「哪块最弱」
|
||||
永远是空话。这里用一张规则表,把常见的题干形态映射到知识点名,再由名字
|
||||
反查 id(`kpt.json` 的键)。
|
||||
|
||||
三条原则:
|
||||
1. 只认能认出来的。认不出来就返回 None,**不硬猜**——错的归类比没有归类更坏,
|
||||
会让学情分析把家长的时间花在错的地方。
|
||||
2. 规则按「具体 → 笼统」排。第一条命中的就用,所以小数乘法要排在整数乘法前面。
|
||||
3. 名字要能在 kpt.json 里解析到 id;解析不到就跳过这条规则(模板改名不会崩)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
from functools import lru_cache
|
||||
from pathlib import Path
|
||||
|
||||
KPT_PATH = Path(__file__).resolve().parent.parent / "prototype" / "workbench" / "kpt.json"
|
||||
|
||||
|
||||
# (正则, 候选知识点名(按优先级), 说明)
|
||||
# 候选名既可以是 `n`(名称),也可以是 `k`(主题),解析时两种都认。
|
||||
RULES: list[tuple[str, tuple[str, ...], str]] = [
|
||||
# ---------- 数学:先认带小数/分数的,再认整数 ----------
|
||||
(r"分数|\d+\s*/\s*\d+\s*[+\-×÷]", ("分数加减法", "分数四则混合运算", "分数的意义与性质"), "分数运算"),
|
||||
# 只出现 a/b(没有运算符)也算分数:得排在小数、整数、单位之前,
|
||||
# 否则「一批货物重 20 吨,它的 7/10 是多少」会被「吨」抢走归到质量单位。
|
||||
(r"\d+\s*/\s*\d+", ("分数的意义与性质", "分数的初步认识"), "分数"),
|
||||
(r"\d+\.\d+\s*×|\d+\.\d+\s*\*", ("小数乘法", "小数的意义与性质"), "小数乘法"),
|
||||
(r"\d+\.\d+\s*÷|\d+\.\d+\s*/", ("小数除法", "小数的意义与性质"), "小数除法"),
|
||||
(r"\d+\.\d+\s*[+\-]", ("小数加减法", "小数的意义与性质"), "小数加减"),
|
||||
(r"×|\*", ("多位数乘一位数", "表内乘法", "乘加乘减"), "乘法"),
|
||||
(r"÷|(?<!\d)/(?!\d)|除以", ("除数是一位数的除法", "表内除法", "有余数除法"), "除法"),
|
||||
(r"[+\-]", ("万以内加减法", "100以内进位加法", "100以内不退位减法",
|
||||
"20以内进位加法", "20以内退位减法", "10以内加减法"), "加减法"),
|
||||
(r"面积", ("长方形正方形面积", "面积与面积单位"), "面积"),
|
||||
(r"周长", ("长方形正方形周长", "圆的周长"), "周长"),
|
||||
(r"时分秒|几点|时针|分针|经过.*分", ("时分秒", "24时计时法"), "时间"),
|
||||
(r"年月日|平年|闰年|季度", ("年月日",), "年月日"),
|
||||
(r"元角分|人民币|几元", ("认识人民币",), "人民币"),
|
||||
(r"千克|克|吨", ("质量单位(克、千克、吨)",), "质量单位"),
|
||||
(r"厘米|毫米|分米|米长|米宽", ("长度单位(厘米、米)",), "长度单位"),
|
||||
(r"平均分|平均分成|每份", ("表内除法", "分数的初步认识"), "平均分"),
|
||||
(r"倍|是.*的几倍", ("乘加乘减", "表内乘法"), "倍数"),
|
||||
# ---------- 语文 ----------
|
||||
(r"看拼音写词|看拼音写词语|读拼音写词", ("会写字(上册100字)", "会写字(上册250字)"), "拼音写词"),
|
||||
(r"同音字|选字填空|读音相同", ("同音字辨析",), "同音字"),
|
||||
(r"形近字|字形相近", ("形近字辨析", "形近字(30组)"), "形近字"),
|
||||
(r"多音字", ("多音字(常见20个)", "多音字(30个)"), "多音字"),
|
||||
(r"反义词", ("反义词", "近反义词辨析"), "反义词"),
|
||||
(r"近义词", ("近义词", "近反义词辨析"), "近义词"),
|
||||
(r"量词|一(\s*)", ("量词", "量词扩展"), "量词"),
|
||||
(r"标点|逗号|句号|问号|感叹号|顿号|引号|分号", ("标点(逗号、句号、问号、感叹号)", "标点(顿号、冒号、引号)", "分号用法"), "标点"),
|
||||
(r"成语", ("成语(初步,20个)", "成语积累(50个)", "成语运用(60个)"), "成语"),
|
||||
(r"把字句|被字句", ("把字句(初步)", "把字句与被字句转换"), "句式转换"),
|
||||
(r"改为陈述句|反问句|改成陈述句", ("反问句与陈述句转换",), "反问句改写"),
|
||||
(r"比喻|拟人|排比|夸张", ("比喻与拟人判断", "比喻句判断", "修辞(排比、夸张)"), "修辞"),
|
||||
(r"古诗|默写|背诵|课文内容填空", ("古诗背诵(10首)", "古诗文默写(15首)", "按课文内容填空"), "背诵默写"),
|
||||
(r"的、地、得|词语搭配", ("词语搭配(的、地、得)",), "词语搭配"),
|
||||
(r"偏旁|部首", ("偏旁部首(常见20个)",), "偏旁部首"),
|
||||
(r"笔顺|笔画|独体字", ("独体字书写", "会写字(上册100字)"), "写字笔顺"),
|
||||
(r"关联词|因为.*所以|虽然.*但是", ("关联词(因为…所以…)",), "关联词"),
|
||||
]
|
||||
|
||||
|
||||
@lru_cache(maxsize=1)
|
||||
def _templates() -> dict:
|
||||
try:
|
||||
return json.loads(KPT_PATH.read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError):
|
||||
return {}
|
||||
|
||||
|
||||
@lru_cache(maxsize=1)
|
||||
def _index() -> tuple[dict[str, str], dict[str, str]]:
|
||||
"""返回 (按名称精确索引, 按名称包含索引)。值都是 kpt 的键。"""
|
||||
exact: dict[str, str] = {}
|
||||
loose: dict[str, str] = {}
|
||||
for kid, v in _templates().items():
|
||||
for label in (v.get("n"), v.get("k")):
|
||||
if not label:
|
||||
continue
|
||||
exact.setdefault(label, kid)
|
||||
for label in (v.get("n"), v.get("k")):
|
||||
if label:
|
||||
loose.setdefault(label, kid)
|
||||
return exact, loose
|
||||
|
||||
|
||||
def resolve(name: str) -> str | None:
|
||||
"""把知识点名(或主题名)解析成 kpt 的键;解析不到返回 None。"""
|
||||
exact, _ = _index()
|
||||
if name in exact:
|
||||
return exact[name]
|
||||
return None
|
||||
|
||||
|
||||
def _first_id(names: tuple[str, ...]) -> str | None:
|
||||
for name in names:
|
||||
kid = resolve(name)
|
||||
if kid:
|
||||
return kid
|
||||
return None
|
||||
|
||||
|
||||
def classify(subject: str | None, stem: str | None) -> str | None:
|
||||
"""按题干猜知识点,返回 kpt 的键(如 M041);认不出来返回 None。"""
|
||||
text = (stem or "").strip()
|
||||
if not text:
|
||||
return None
|
||||
for pattern, names, _why in RULES:
|
||||
if not re.search(pattern, text):
|
||||
continue
|
||||
kid = _first_id(names)
|
||||
if kid:
|
||||
return kid
|
||||
return None
|
||||
|
||||
|
||||
def name_of(kp: str | None) -> str:
|
||||
"""给日志/测试用:把 kp 换成「主题/名称」。"""
|
||||
tpl = _templates().get(kp or "")
|
||||
if not tpl:
|
||||
return ""
|
||||
return f"{tpl.get('k', '')}/{tpl.get('n', '')}"
|
||||
|
||||
|
||||
def rules_ok() -> list[str]:
|
||||
"""自检:返回解析不到的候选名(模板改名时能提前发现)。"""
|
||||
bad = []
|
||||
for _pattern, names, _why in RULES:
|
||||
for name in names:
|
||||
if resolve(name) is None:
|
||||
bad.append(name)
|
||||
return bad
|
||||
|
||||
|
||||
if __name__ == "__main__": # 手工试一下:python -m backend.kp_match "36 + 47 ="
|
||||
import sys
|
||||
|
||||
if len(sys.argv) > 1:
|
||||
for arg in sys.argv[1:]:
|
||||
kp = classify(None, arg)
|
||||
print(f"{arg} -> {kp} {name_of(kp)}")
|
||||
else:
|
||||
print("规则里解析不到的名字:", rules_ok() or "无")
|
||||
@@ -88,6 +88,41 @@ def _math_variants(stem: str, n: int) -> list[dict]:
|
||||
return results
|
||||
|
||||
|
||||
def verify(item: dict) -> tuple[bool, str]:
|
||||
"""一道变式能不能给孩子做:能算出唯一答案,且答案就是它自己给的那个。
|
||||
|
||||
出错的变式比不做更糟——孩子按对的做反而被判错,一次就毁掉信任。
|
||||
"""
|
||||
stem = str(item.get("stem") or "").strip()
|
||||
answer = str(item.get("answer") or "").strip()
|
||||
jt = item.get("judge_type")
|
||||
if not stem:
|
||||
return False, "题干是空的"
|
||||
if not answer:
|
||||
return False, "没有答案"
|
||||
if jt == "calc":
|
||||
# 「36 + 24 =」末尾那个等号要先去掉:safe_eval 会把 = 右边当答案取值
|
||||
expr = stem.rstrip("==").strip()
|
||||
got = judging.safe_eval(expr)
|
||||
if got is None:
|
||||
return False, "算不出来"
|
||||
want = judging.to_qty(answer)
|
||||
if want is None:
|
||||
return False, "答案不是数"
|
||||
if abs(float(got) - float(want)) > 1e-6:
|
||||
return False, "答案和题干对不上"
|
||||
return True, ""
|
||||
if jt == "choice":
|
||||
opts = item.get("options") or {}
|
||||
if isinstance(opts, dict) and len(opts) >= 2:
|
||||
letters = {k.strip().upper() for k in opts}
|
||||
if answer.strip().upper() not in letters:
|
||||
return False, "答案不在选项里"
|
||||
return True, ""
|
||||
# 填空/问答:答案非空就放;判分靠孩子自评,不假装能验
|
||||
return True, ""
|
||||
|
||||
|
||||
def similar(stem: str, answer: str, judge_type: str, subject: str, grade: int, n: int = 3) -> list[dict]:
|
||||
"""返回 n 道同类题;每道都带确定答案。"""
|
||||
items: list[dict] = []
|
||||
@@ -104,6 +139,8 @@ def similar(stem: str, answer: str, judge_type: str, subject: str, grade: int, n
|
||||
continue
|
||||
items.append({"stem": q["stem"], "answer": q["answer"], "judge_type": q["judge_type"],
|
||||
"options": q.get("options"), "tag": "同知识点变式"})
|
||||
# 自校验:算不出答案、答案和题干对不上、选择题选项不干净 —— 一律不给
|
||||
items = [it for it in items if verify(it)[0]]
|
||||
for it in items:
|
||||
it.setdefault("subject", subject)
|
||||
it.setdefault("tag", "同类变式")
|
||||
|
||||
@@ -35,6 +35,8 @@ GAP_MAX = 2 # 一页最多补扫两条,再多就是在赌
|
||||
GAP_INK = 0.004 # 条带里墨迹像素占比下限(低于它基本是空白)
|
||||
GAP_MAX_INK = 0.55 # 高于它更像照片/阴影,不是文字
|
||||
GAP_PAD = 24
|
||||
# 补扫的条带会放大再送 OCR,返回的框是放大后的坐标,要按这个数除回去
|
||||
GAP_SCALE = 1.4
|
||||
|
||||
|
||||
def _pil():
|
||||
@@ -70,8 +72,15 @@ def save_draft(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")
|
||||
"""补扫要不要做:默认由 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]:
|
||||
@@ -147,7 +156,7 @@ def _crop_band(src: Path, y0: int, y1: int) -> bytes | None:
|
||||
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)),
|
||||
crop = crop.resize((int(crop.width * GAP_SCALE), int(crop.height * GAP_SCALE)),
|
||||
Image.LANCZOS)
|
||||
crop = ImageOps.autocontrast(crop, cutoff=1)
|
||||
buf = io.BytesIO()
|
||||
@@ -193,7 +202,14 @@ def _gap_blocks(src: Path, blocks: list[dict], w: int, h: int) -> list[dict]:
|
||||
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"]}
|
||||
# 补扫图是放大 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)
|
||||
@@ -210,7 +226,7 @@ def _gap_blocks(src: Path, blocks: list[dict], w: int, h: int) -> list[dict]:
|
||||
|
||||
|
||||
def detect(image_bytes: bytes, filename: str = "page.jpg",
|
||||
gap_scan: bool = True) -> dict:
|
||||
gap_scan: bool = False) -> dict:
|
||||
"""整页切块。返回题块 + 草稿 id;切不出题就抛 422 让前端提示重拍。"""
|
||||
d = save_draft(image_bytes, filename)
|
||||
res = tencent_ocr.split_questions(image_bytes)
|
||||
|
||||
@@ -27,6 +27,7 @@ STATUS_ZH = {
|
||||
"queued": "待复习",
|
||||
"unstable": "会但不稳",
|
||||
"passed_once": "已对 1 次",
|
||||
"variant_pending": "换一道",
|
||||
"to_explain": "待讲清",
|
||||
"graduated": "已毕业",
|
||||
"careless": "粗心小记",
|
||||
@@ -48,7 +49,8 @@ def is_due(mistake: dict, on: str | None = None) -> bool:
|
||||
观察中的题也会在次日回来「复核」一次:做对就是粗心,做错才确认没懂。
|
||||
不稳的题同样回到队列:今天错、今天对的,明天必须再做对一次才算过。
|
||||
"""
|
||||
if mistake.get("status") not in ("observing", "queued", "unstable", "passed_once"):
|
||||
if mistake.get("status") not in ("observing", "queued", "unstable", "passed_once",
|
||||
"variant_pending"):
|
||||
return False
|
||||
due = mistake.get("next_due")
|
||||
return bool(due) and due <= (on or today())
|
||||
@@ -62,12 +64,16 @@ def due_today(mistakes: list[dict], on: str | None = None, cap: int = DAILY_CAP)
|
||||
|
||||
|
||||
def on_attempt(mistake: dict, correct: bool, *, created_at: str | None = None,
|
||||
same_day_wrong: bool = False) -> dict:
|
||||
same_day_wrong: bool = False, strict: bool = False,
|
||||
is_variant: bool = False) -> dict:
|
||||
"""做了一次(重做/口答)。返回要写回 mistakes 的字段。
|
||||
|
||||
:param same_day_wrong: 这道题「今天」已经错过一次。看完解析当场再做对,
|
||||
只能说明「听完会了」,说明不了「记住了」——所以不推进档位,
|
||||
只记一道「会但不稳」,明天再从头做对一次才算第一次。
|
||||
:param strict: 严档。打开后,第一次做对不算数——先换一道**没见过**的变式
|
||||
(`variant_pending`),变式做对才算第一次连对。默认关闭。
|
||||
:param is_variant: 这一次做的是变式题(不是原题)。
|
||||
"""
|
||||
ts = created_at or now()
|
||||
stage = int(mistake.get("stage") or 0)
|
||||
@@ -93,6 +99,23 @@ def on_attempt(mistake: dict, correct: bool, *, created_at: str | None = None,
|
||||
"unstable_count": int(mistake.get("unstable_count") or 0) + 1,
|
||||
"wrong_code": mistake.get("wrong_code") or "E4",
|
||||
}
|
||||
if strict:
|
||||
if status == "variant_pending":
|
||||
# 变式做对了:这才是「换一层皮还会」,算第一次连对
|
||||
stage = max(stage, 1)
|
||||
interval = INTERVALS[min(stage - 1, len(INTERVALS) - 1)]
|
||||
return {"status": "passed_once", "stage": stage, "interval_days": interval,
|
||||
"next_due": add_days(interval, base=_date_of(ts)),
|
||||
"wrong_code": mistake.get("wrong_code") or "E4"}
|
||||
if is_variant:
|
||||
# 变式做错了:说明还是没懂,回队列(间隔归零)
|
||||
return {"status": "queued", "stage": 0, "interval_days": 1,
|
||||
"next_due": add_days(1, base=_date_of(ts)),
|
||||
"wrong_count": wrong_count + 1, "wrong_code": "E2"}
|
||||
# 原题做对但还没验过变式:今天就给一道,别等到明天
|
||||
return {"status": "variant_pending", "stage": 0, "interval_days": 0,
|
||||
"next_due": _date_of(ts), "wrong_code": mistake.get("wrong_code") or "E4"}
|
||||
|
||||
stage += 1
|
||||
interval = INTERVALS[min(stage - 1, len(INTERVALS) - 1)]
|
||||
if stage >= 2:
|
||||
|
||||
@@ -19,7 +19,7 @@ from contextlib import contextmanager
|
||||
from datetime import date, datetime, timedelta
|
||||
from pathlib import Path
|
||||
|
||||
from . import content, cut, judging, kp_graph, ocr, practice, scheduler, tencent_ocr, wechat
|
||||
from . import content, cut, judging, kp_graph, kp_match, ocr, practice, scheduler, tencent_ocr, wechat
|
||||
from .db import TZ, add_days, connect, log_event, new_id, now, row_to_dict, rows_to_list, today
|
||||
|
||||
CONSENT_VERSION = "v1"
|
||||
@@ -653,6 +653,7 @@ def list_children(conn, gid: str) -> list[dict]:
|
||||
for r in rows:
|
||||
d = dict(r)
|
||||
d["subjects"] = _subjects(conn, r["id"])
|
||||
d["pet"] = _pet_sync(conn, r["id"])
|
||||
out.append(d)
|
||||
return out
|
||||
|
||||
@@ -663,6 +664,7 @@ def get_child(conn, gid: str, cid: str) -> dict:
|
||||
_need(row, "NO_CHILD", "没有这个孩子")
|
||||
d = dict(row)
|
||||
d["subjects"] = _subjects(conn, cid)
|
||||
d["pet"] = _pet_sync(conn, cid)
|
||||
return d
|
||||
|
||||
|
||||
@@ -867,6 +869,8 @@ def add_manual_mistake(conn, gid: str, cid: str, subject: str, stem: str,
|
||||
|
||||
pid = new_id("p")
|
||||
qid = new_id("q")
|
||||
if not kp:
|
||||
kp = kp_match.classify(subject, stem) # 手输也顺手归一下,归不上留空
|
||||
with tx(conn):
|
||||
conn.execute("INSERT INTO papers (id, child_id, subject, image_count, source, created_at)"
|
||||
" VALUES (?,?,?,0,?,?)", (pid, cid, subject, source, now()))
|
||||
@@ -906,7 +910,48 @@ def today_queue(conn, gid: str, cid: str, subject: str | None = None) -> dict:
|
||||
}
|
||||
|
||||
|
||||
def attempt(conn, gid: str, cid: str, mid: str, answer_text: str, cost_ms: int | None = None) -> dict:
|
||||
PET_STAGES = (12, 40, 100) # 已毕业 12 / 40 / 100 道,形态升一级
|
||||
|
||||
|
||||
def pet_stage_of(graduated: int) -> int:
|
||||
return 3 if graduated >= PET_STAGES[2] else 2 if graduated >= PET_STAGES[1] else 1 if graduated >= PET_STAGES[0] else 0
|
||||
|
||||
|
||||
def _pet_sync(conn, cid: str) -> dict:
|
||||
"""把「已吃掉几道」和「今天喂过没有」写进 children,换设备也是同一只。
|
||||
|
||||
只在当天该做的题全部做完时算「喂过」——不是打卡,是把今天这轮跑完。
|
||||
"""
|
||||
graduated = conn.execute(
|
||||
"SELECT COUNT(*) FROM mistakes WHERE child_id=? AND status='graduated'", (cid,)).fetchone()[0]
|
||||
left = conn.execute(
|
||||
"SELECT COUNT(*) FROM mistakes WHERE child_id=? AND status IN"
|
||||
" ('observing','queued','passed_once','unstable') AND next_due<=?", (cid, today())).fetchone()[0]
|
||||
stage = pet_stage_of(graduated)
|
||||
# 「喂过」= 今天该做的题都做完了,而且今天确实动过手。
|
||||
# 光看 left==0 会把「今天没事干」也算成喂过,刚建号的孩子就白送一次。
|
||||
day = today()
|
||||
touched = conn.execute(
|
||||
"SELECT 1 FROM attempts WHERE child_id=? AND substr(created_at,1,10)=? LIMIT 1",
|
||||
(cid, day)).fetchone() is not None
|
||||
fed = left == 0 and touched
|
||||
row = conn.execute("SELECT pet_stage, pet_fed_at FROM children WHERE id=?", (cid,)).fetchone()
|
||||
cur_stage = (row["pet_stage"] if row else None) or 0
|
||||
cur_fed = row["pet_fed_at"] if row else None
|
||||
# 只在真的变了才写:get_child 会在读接口里被调用,别让 GET 变成天天 UPDATE
|
||||
if cur_stage != stage or (fed and cur_fed != day):
|
||||
if fed:
|
||||
conn.execute("UPDATE children SET pet_stage=?, pet_fed_at=? WHERE id=?", (stage, day, cid))
|
||||
cur_fed = day
|
||||
else:
|
||||
conn.execute("UPDATE children SET pet_stage=? WHERE id=?", (stage, cid))
|
||||
cur_stage = stage
|
||||
return {"stage": cur_stage, "fed_at": cur_fed, "fed_today": cur_fed == day,
|
||||
"graduated": graduated, "left_today": left}
|
||||
|
||||
|
||||
def attempt(conn, gid: str, cid: str, mid: str, answer_text: str, cost_ms: int | None = None,
|
||||
is_variant: bool = False) -> dict:
|
||||
get_child(conn, gid, cid)
|
||||
m = conn.execute("SELECT * FROM mistakes WHERE id=? AND child_id=?", (mid, cid)).fetchone()
|
||||
_need(m, "NO_MISTAKE", "没有这道错题")
|
||||
@@ -921,15 +966,26 @@ def attempt(conn, gid: str, cid: str, mid: str, answer_text: str, cost_ms: int |
|
||||
same_day_wrong = conn.execute(
|
||||
"SELECT 1 FROM attempts WHERE mistake_id=? AND is_correct=0"
|
||||
" AND substr(created_at,1,10)=? LIMIT 1", (mid, today())).fetchone() is not None
|
||||
state = scheduler.on_attempt(mdict, correct, same_day_wrong=same_day_wrong)
|
||||
# 严档:这道题现在是「等一道变式」,那这次必须做的是变式才算数
|
||||
if is_variant and mdict["status"] != "variant_pending":
|
||||
raise ApiError(409, "NOT_VARIANT_PENDING", "这道题现在不需要做变式")
|
||||
if mdict["status"] == "variant_pending" and not is_variant:
|
||||
raise ApiError(409, "NEED_VARIANT", "这道题要先做对一道变式")
|
||||
child = get_child(conn, gid, cid)
|
||||
strict = bool((child.get("strict_variant") if isinstance(child, dict) else 0) or 0)
|
||||
state = scheduler.on_attempt(mdict, correct, same_day_wrong=same_day_wrong,
|
||||
strict=strict, is_variant=is_variant)
|
||||
with tx(conn):
|
||||
conn.execute("INSERT INTO attempts (id, mistake_id, child_id, answer_text, is_correct, cost_ms, created_at)"
|
||||
" VALUES (?,?,?,?,?,?,?)",
|
||||
(new_id("a"), mid, cid, answer_text, int(correct), cost_ms, now()))
|
||||
_apply(conn, mid, state)
|
||||
log_event(conn, "attempt", cid, correct=correct, status=state["status"])
|
||||
pet = _pet_sync(conn, cid)
|
||||
return {
|
||||
"mistake_id": mid,
|
||||
"pet": pet,
|
||||
"need_variant": state["status"] == "variant_pending",
|
||||
"correct": correct,
|
||||
"detail": detail,
|
||||
# 答完才能给答案:讲解要照着它生成步骤,之前不给是为了不让孩子提前看
|
||||
@@ -946,6 +1002,9 @@ def attempt(conn, gid: str, cid: str, mid: str, answer_text: str, cost_ms: int |
|
||||
"unstable": state["status"] == "unstable",
|
||||
"unstable_hint": ("这次算「会但不稳」——明天同一道题再做对一次,才往前算。"
|
||||
if state["status"] == "unstable" else None),
|
||||
# 连错三次:不再排同一道,先退一层补前置(讲清失败那条路走 retreat,这里同源)
|
||||
"retreat": (kp_graph.retreat(mdict.get("kp"))
|
||||
if (not correct and int(state.get("wrong_count") or 0) >= 3) else None),
|
||||
}
|
||||
|
||||
|
||||
@@ -976,15 +1035,59 @@ def skip(conn, gid: str, cid: str, mid: str) -> dict:
|
||||
"note": "跳过不算错也不算对,明天再来一次;连续跳过的会进「顽固题」"}
|
||||
|
||||
|
||||
def explain(conn, gid: str, cid: str, mid: str, channel: str, text: str) -> dict:
|
||||
#: 语音讲清时,家长/孩子勾的三件事——判不了语义,就让人来判。
|
||||
EXPLAIN_CHECKS = {
|
||||
"wrong_reason": "说清了错在哪",
|
||||
"key_steps": "说出了正确的走法",
|
||||
"next_time": "说了下次怎么防",
|
||||
}
|
||||
|
||||
|
||||
def explain(conn, gid: str, cid: str, mid: str, channel: str, text: str,
|
||||
checks: dict | None = None, audio_b64: str | None = None,
|
||||
audio_ext: str | None = None) -> dict:
|
||||
get_child(conn, gid, cid)
|
||||
m = conn.execute("SELECT * FROM mistakes WHERE id=? AND child_id=?", (mid, cid)).fetchone()
|
||||
_need(m, "NO_MISTAKE", "没有这道错题")
|
||||
if channel not in ("ai_voice", "voice", "steps", "find_error", "make_question", "three_lines"):
|
||||
if channel not in ("ai_voice", "voice", "steps", "find_error", "make_question", "three_lines", "audio"):
|
||||
raise ApiError(400, "BAD_CHANNEL", "不支持的讲解方式")
|
||||
if m["status"] != "to_explain":
|
||||
raise ApiError(409, "NOT_TO_EXPLAIN", "这道题还没到「讲清」这一步(要先连对两次)")
|
||||
score = scheduler.score_explain(text, channel)
|
||||
audio_path = None
|
||||
if channel == "audio":
|
||||
# 语音:落一份音频;判分不靠关键词,靠三项勾选(说没说清,家长比关键词更准)
|
||||
if not audio_b64:
|
||||
raise ApiError(400, "NO_AUDIO", "没有收到录音")
|
||||
ext = (audio_ext or "webm").lower().lstrip(".")
|
||||
if ext not in AUDIO_EXTS:
|
||||
raise ApiError(400, "BAD_AUDIO_EXT", "不支持的音频格式")
|
||||
try:
|
||||
blob = base64.b64decode(str(audio_b64).split(",")[-1], validate=False)
|
||||
except Exception: # noqa: BLE001
|
||||
raise ApiError(400, "BAD_AUDIO", "录音不是合法的 base64")
|
||||
if not blob:
|
||||
raise ApiError(400, "NO_AUDIO", "录音是空的")
|
||||
if len(blob) > AUDIO_MAX_BYTES:
|
||||
raise ApiError(400, "AUDIO_TOO_BIG", "录音太大了(上限 8MB)")
|
||||
def _flag(v):
|
||||
try:
|
||||
return bool(int(v))
|
||||
except (TypeError, ValueError):
|
||||
return bool(v)
|
||||
hit = {k: _flag((checks or {}).get(k)) for k in EXPLAIN_CHECKS}
|
||||
# 三项都勾了才算说清;勾多少记多少,前端据此显示「差在哪一项」
|
||||
score = {
|
||||
"rubric_wrong_reason": "说清了" if hit["wrong_reason"] else "没说清错在哪",
|
||||
"rubric_key_steps": "说了" if hit["key_steps"] else "没说出正确走法",
|
||||
"rubric_next_time": "说了" if hit["next_time"] else "没说下次怎么防",
|
||||
"passed": all(hit.values()),
|
||||
}
|
||||
AUDIO_DIR.mkdir(parents=True, exist_ok=True)
|
||||
audio_path = AUDIO_DIR / f"{mid}_{int(time.time())}.{ext}"
|
||||
audio_path.write_bytes(blob)
|
||||
text = "(语音 %.1f 秒)" % (len(blob) / 16000.0)
|
||||
else:
|
||||
score = scheduler.score_explain(text, channel)
|
||||
state = scheduler.on_explain(dict(m), bool(score["passed"]))
|
||||
with tx(conn):
|
||||
conn.execute(
|
||||
@@ -1005,9 +1108,46 @@ def explain(conn, gid: str, cid: str, mid: str, channel: str, text: str) -> dict
|
||||
"status_zh": scheduler.STATUS_ZH.get(state["status"], state["status"]),
|
||||
"hint": "过了就毕业;没过就换一条路,7 天内还有机会" if not score["passed"] else "这题你不用再做了",
|
||||
"retreat": retreat,
|
||||
"ask_stuck_at": (not score["passed"]) and not m["stuck_at"],
|
||||
"audio": (str(audio_path.relative_to(UPLOAD_DIR)) if audio_path else None),
|
||||
"checks": ({k: int(v) for k, v in (checks or {}).items() if k in EXPLAIN_CHECKS}
|
||||
if channel == "audio" else None),
|
||||
}
|
||||
|
||||
|
||||
#: 讲清失败时问「刚才卡在哪」,只有四个键,不让家长打字。
|
||||
STUCK_AT = {
|
||||
"read": "题没读懂",
|
||||
"plan": "不知道从哪下手",
|
||||
"calc": "会做,算错了",
|
||||
"check": "没检查",
|
||||
}
|
||||
|
||||
|
||||
def set_settings(conn, gid: str, cid: str, strict_variant=None) -> dict:
|
||||
"""孩子级设置。目前只有一个:「严档」——第二次要做对一道没见过的变式。"""
|
||||
get_child(conn, gid, cid)
|
||||
if strict_variant is not None:
|
||||
conn.execute("UPDATE children SET strict_variant=? WHERE id=?",
|
||||
(1 if str(strict_variant) in ("1", "true", "True", "on") else 0, cid))
|
||||
row = conn.execute("SELECT strict_variant FROM children WHERE id=?", (cid,)).fetchone()
|
||||
return {"child_id": cid, "strict_variant": int((row["strict_variant"] if row else 0) or 0)}
|
||||
|
||||
|
||||
def set_stuck_at(conn, gid: str, cid: str, mid: str, value) -> dict:
|
||||
"""记一次卡点。只在讲清失败后问,入库时不问(避免每道题都弹一次)。"""
|
||||
get_child(conn, gid, cid)
|
||||
m = conn.execute("SELECT id, stuck_at FROM mistakes WHERE id=? AND child_id=?", (mid, cid)).fetchone()
|
||||
_need(m, "NO_MISTAKE", "没有这道错题")
|
||||
key = str(value or "").strip()
|
||||
if key not in STUCK_AT:
|
||||
raise ApiError(400, "BAD_STUCK_AT", "卡点只能是 read / plan / calc / check 之一")
|
||||
with tx(conn):
|
||||
conn.execute("UPDATE mistakes SET stuck_at=? WHERE id=?", (key, mid))
|
||||
log_event(conn, "stuck_at", cid, mistake_id=mid, stuck_at=key)
|
||||
return {"mistake_id": mid, "stuck_at": key, "stuck_at_zh": STUCK_AT[key]}
|
||||
|
||||
|
||||
def _apply(conn, mid: str, state: dict) -> None:
|
||||
fields = ", ".join(f"{k}=?" for k in state)
|
||||
conn.execute(f"UPDATE mistakes SET {fields} WHERE id=?", (*state.values(), mid))
|
||||
@@ -1125,7 +1265,9 @@ def weekly_sheet_html(conn, gid: str, cid: str, week_of: str | None = None) -> s
|
||||
<title>本周错题 · {_esc(child["nickname"])}</title>
|
||||
<style>
|
||||
@page {{ size: A5; margin: 12mm; }}
|
||||
body {{ font-family: "Microsoft YaHei", "PingFang SC", sans-serif; color:#24211f; font-size:12pt; }}
|
||||
body {{ font-family: "Microsoft YaHei", "PingFang SC", sans-serif; color:#24211f; font-size:12pt;
|
||||
max-width: 148mm; margin: 6mm auto; padding: 0 4mm; }}
|
||||
@media print {{ body {{ max-width: none; margin: 0; padding: 0; }} }}
|
||||
h1 {{ font-size:15pt; margin:0 0 2mm; }}
|
||||
.meta {{ color:#6b6560; font-size:9pt; margin-bottom:4mm; }}
|
||||
.q {{ margin: 0 0 5mm; page-break-inside: avoid; }}
|
||||
@@ -1373,6 +1515,9 @@ def demo_data(conn, gid: str, nickname: str = "皮皮", grade: int = 2) -> dict:
|
||||
# ---------------------------------------------------------------- 拍照识题
|
||||
|
||||
UPLOAD_DIR = Path(__file__).resolve().parent.parent / "data" / "uploads"
|
||||
AUDIO_DIR = UPLOAD_DIR / "audio"
|
||||
AUDIO_MAX_BYTES = 8 * 1024 * 1024 # 8MB,够录 2 分钟
|
||||
AUDIO_EXTS = ("webm", "mp3", "m4a", "aac", "wav", "ogg")
|
||||
|
||||
|
||||
def _drop_upload(path: Path) -> None:
|
||||
@@ -1712,12 +1857,65 @@ def dev_scan_confirm(conn, code: str) -> dict:
|
||||
return out
|
||||
|
||||
|
||||
def prepare_scan_picks(conn, gid: str, cid: str, subject: str, draft_id: str,
|
||||
picks: list) -> dict:
|
||||
"""入库前的「逐条勾选」预览:把勾中的块认一遍,列出里面的每一道小题。
|
||||
|
||||
为什么要单独一步:口算卡一块十几道,切题偶尔会把相邻的题读进来、甚至读歪
|
||||
(`27+69` 读成 `77+69`)。整块入库会把孩子没做错的题也塞进错题本,家长得
|
||||
事后一条条删。所以入库前把这几道摊开给家长看,取消掉没做错的。
|
||||
|
||||
这一步只读不写。它调的 `recognize_block` 与真正入库时同一套(裁剪图按
|
||||
sha1 命中 OCR 缓存),所以预览过一遍之后,正式入库**不会再花一次调用**。
|
||||
"""
|
||||
from . import scanflow
|
||||
|
||||
require_active(conn, gid)
|
||||
get_child(conn, gid, cid)
|
||||
src, meta = scanflow.load_draft(draft_id)
|
||||
blocks = meta.get("blocks") or []
|
||||
items = []
|
||||
for p in picks:
|
||||
try:
|
||||
i = int(p if not isinstance(p, dict) else p.get("i"))
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if not (0 <= i < len(blocks)):
|
||||
continue
|
||||
r = scanflow.recognize_block(src, blocks[i])
|
||||
subs = r.get("subs") or []
|
||||
if subs:
|
||||
for k, x in enumerate(subs):
|
||||
items.append({"block": i, "sub": k, "stem": x.get("stem") or "",
|
||||
"judge_type": "calc", "answer": x.get("answer"),
|
||||
"options": None, "source": r.get("source")})
|
||||
else:
|
||||
items.append({"block": i, "sub": None, "stem": r.get("stem") or "",
|
||||
"judge_type": r.get("judge_type"), "answer": r.get("answer"),
|
||||
"options": r.get("options"), "source": r.get("source")})
|
||||
if not items:
|
||||
raise ApiError(400, "NO_PICKS", "一道都没选,先点上哪几道错了")
|
||||
if len(items) > 60:
|
||||
items = items[:60]
|
||||
return {"draft_id": draft_id, "items": items,
|
||||
"hint": "这些是勾中的块里认出来的题。取消掉没做错的那几道,再入库。"}
|
||||
|
||||
|
||||
def import_scan_picks(conn, gid: str, cid: str, subject: str, draft_id: str,
|
||||
picks: list[int]) -> dict:
|
||||
picks: list) -> dict:
|
||||
"""把「家长勾中的那几块」入库。
|
||||
|
||||
流程是:整页拍 → 切块给家长点 → 选中的块从原图裁出来**再单独识别一次**。
|
||||
单块图字更大、没有相邻题干扰,题干比整页切时干净得多。
|
||||
|
||||
picks 每一项可以是:
|
||||
|
||||
- `3`(块序号):整块都要,块里若是口算卡就展开成全部小问;
|
||||
- `{"i": 3, "subs": [0, 2]}`:只要这块里的第 0、2 个小问——家长在
|
||||
「这块里有 8 道,取消你没做错的」那一步勾出来的结果。
|
||||
|
||||
为什么要第二种:口算卡一块十几道,切题偶尔会把相邻的题读进来(甚至读歪),
|
||||
整块入库会把没做错的题也塞进错题本。逐条勾选把最后这个决定权还给家长。
|
||||
"""
|
||||
from . import scanflow
|
||||
|
||||
@@ -1730,13 +1928,27 @@ def import_scan_picks(conn, gid: str, cid: str, subject: str, draft_id: str,
|
||||
src, meta = scanflow.load_draft(draft_id)
|
||||
blocks = meta.get("blocks") or []
|
||||
chosen = []
|
||||
for i in picks:
|
||||
for p in picks:
|
||||
subs_only = None
|
||||
if isinstance(p, dict):
|
||||
raw_i, raw_subs = p.get("i"), p.get("subs")
|
||||
if isinstance(raw_subs, list):
|
||||
sub_idx = set()
|
||||
for s in raw_subs:
|
||||
try:
|
||||
sub_idx.add(int(s))
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
subs_only = sub_idx
|
||||
p = raw_i
|
||||
try:
|
||||
i = int(i)
|
||||
i = int(p)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if 0 <= i < len(blocks):
|
||||
chosen.append(blocks[i])
|
||||
if subs_only is not None and not subs_only:
|
||||
continue # 这块里的小题全被取消 = 这块不入库
|
||||
chosen.append((blocks[i], subs_only))
|
||||
if not chosen:
|
||||
raise ApiError(400, "NO_PICKS", "一道都没选,先点上哪几道错了")
|
||||
if len(chosen) > 20:
|
||||
@@ -1744,15 +1956,25 @@ def import_scan_picks(conn, gid: str, cid: str, subject: str, draft_id: str,
|
||||
|
||||
# 口算卡(一块里十几道)先展开成多道,再往库里写
|
||||
questions = []
|
||||
for b in chosen:
|
||||
for b, subs_only in chosen:
|
||||
r = scanflow.recognize_block(src, b)
|
||||
subs = r.get("subs") or []
|
||||
if subs:
|
||||
questions.extend({"stem": x.get("stem") or "", "judge_type": "calc",
|
||||
"options": None, "answer": x.get("answer"),
|
||||
"page_answer": None, "source": r.get("source")} for x in subs)
|
||||
else:
|
||||
keep = subs_only if subs_only is not None else range(len(subs))
|
||||
for k in keep:
|
||||
if 0 <= k < len(subs):
|
||||
x = subs[k]
|
||||
questions.append({"stem": x.get("stem") or "", "judge_type": "calc",
|
||||
"options": None, "answer": x.get("answer"),
|
||||
"page_answer": None, "source": r.get("source")})
|
||||
elif subs_only is None:
|
||||
questions.append(r)
|
||||
# subs_only 给了但这块其实只有一道题:说明前端的勾选过期了,跳过不猜
|
||||
|
||||
# 切题不给知识点;这里按题干补一次,补不上就留空(学情分析宁可少,不可错)
|
||||
for q in questions:
|
||||
if not q.get("kp"):
|
||||
q["kp"] = kp_match.classify(q.get("subject") or subject, q.get("stem"))
|
||||
|
||||
pid = new_id("p")
|
||||
folder = UPLOAD_DIR / cid
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
{"2026-11": 3}
|
||||
@@ -1 +1 @@
|
||||
{"2026-11": 101}
|
||||
{"2026-11": 209}
|
||||
@@ -1,12 +1,24 @@
|
||||
# 复制成 .env 再改。这个文件里有密钥,别提交到仓库。
|
||||
SITE_DOMAIN=workbench.example.com
|
||||
|
||||
# 生产开关:prod 不注册 /api/dev/* 与 /api/auth/sms-*(短信登录整条关掉)
|
||||
QINGLING_ENV=prod
|
||||
|
||||
# 微信小程序(不填则登录走 demo 账号)
|
||||
WX_APPID=
|
||||
WX_SECRET=
|
||||
WX_TMPL_DAILY=
|
||||
WX_TMPL_EXPIRE=
|
||||
|
||||
# 部署在 Linux 时拍照识题必须走外部 OCR
|
||||
# 拍照识题:腾讯云试卷切题(主链路,必配;也可以放 data/tencent.env)
|
||||
TENCENT_SECRET_ID=
|
||||
TENCENT_SECRET_KEY=
|
||||
TENCENT_REGION=ap-guangzhou
|
||||
|
||||
# OCR 花钱的闸门(可不设)
|
||||
# OCR_MONTHLY_LIMIT=900 # 到顶直接停,不发请求;不设=只计数不拦
|
||||
# OCR_CACHE=0 # 关掉结果缓存(默认开)
|
||||
|
||||
# 本机 OCR 兜底(可选;Linux 上没有本机 OCR,要用就指一个 HTTP 服务)
|
||||
OCR_HTTP_URL=
|
||||
OCR_HTTP_KEY=
|
||||
|
||||
@@ -6,7 +6,10 @@
|
||||
|---|---|---|
|
||||
| Docker Compose(推荐) | 有 Docker 的云主机 | `cd deploy && docker compose up -d --build` |
|
||||
| systemd | 不想装 Docker 的 Linux | 见 `errortopic.service` 顶部注释 |
|
||||
| 本机 | 只是自己看效果 | `python -m backend.app --port 8000` |
|
||||
| 本机 / 内网 | 自己看效果、给同事试 | `python -m backend.app --host 0.0.0.0 --port 8000` |
|
||||
|
||||
> 上线前请先读 [第五节 检查清单](#五上线前检查清单),那里每一条都对应一次真实踩坑。
|
||||
> 当前版本 `1.2.0`,接口数:**prod 52 条 / dev 60 条**(多出的是 `/api/dev/*` 与短信登录)。
|
||||
|
||||
---
|
||||
|
||||
@@ -16,53 +19,73 @@
|
||||
# 1. 把项目放上去
|
||||
git clone <你的仓库> /opt/errortopic && cd /opt/errortopic/deploy
|
||||
|
||||
# 2. 配置
|
||||
cp .env.example .env && vi .env # 填域名、OCR、微信密钥
|
||||
# 2. 配置(见第三节「必须配的六件事」)
|
||||
cp .env.example .env && vi .env
|
||||
|
||||
# 3. 起服务
|
||||
docker compose up -d --build
|
||||
|
||||
# 4. 看是否活着
|
||||
curl -s https://你的域名/api/health
|
||||
curl -s https://你的域名/api/health # 期待 "version":"1.2.0"
|
||||
|
||||
# 5. 首次初始化(只跑一次,会写进挂卷的 data/app.db)
|
||||
# 5. 首次初始化(只跑一次,写进挂卷的 data/app.db)
|
||||
docker compose exec app python -c "from backend import db, seed; c=db.connect(); db.init_db(c); print(seed.seed(c))"
|
||||
```
|
||||
|
||||
> 第 5 步其实可省:`backend.app` 启动时会自己 `init_db`,只有想塞演示数据(皮皮/小满)才需要跑 `seed`。
|
||||
> 另外 `data/` 目录要带 `kp_graph.json`(先修图),少了它不影响判分和毕业,只是「讲不清 → 退一层」那条建议不显示。
|
||||
|
||||
站点结构:
|
||||
|
||||
- `https://你的域名/workbench` —— 家长/孩子用的工作台
|
||||
- `https://你的域名/` —— 接口控制台(联调用,上线建议用 Nginx 或 Caddy 关掉)
|
||||
- `https://你的域名/docs` —— 接口清单
|
||||
- `https://你的域名/workbench` —— 家长/孩子用的工作台(要能登录)
|
||||
- `https://你的域名/` —— 接口控制台(联调用,**上线建议关掉**)
|
||||
- `https://你的域名/docs` —— 接口清单(同样建议关)
|
||||
|
||||
`app` 只在 compose 内网监听 8000,公网只开 80/443,由 Caddy 反代并自动签证书。
|
||||
|
||||
## 二、域名与合规(国内服务器)
|
||||
|
||||
1. **ICP 备案**:域名 + 服务器在同一家云厂商,备案通过前 80/443 会被拦。
|
||||
1. **ICP 备案**:域名与服务器在同一家云厂商,备案通过前 80/443 会被拦。
|
||||
2. **DNS**:A 记录指向服务器公网 IP。
|
||||
3. **放行端口**:80/443(安全组 + 防火墙)。
|
||||
4. Caddy 自动签证书,不用管 certbot;只要 80 端口能从公网访问到。
|
||||
3. **放行端口**:80/443(安全组 + 防火墙),80 必须能从公网访问(Caddy 签证书要用)。
|
||||
4. 教育类目还需要**企业主体**——个人主体连小程序码都拿不到,这条不是技术问题。
|
||||
|
||||
## 三、必须配的四件事
|
||||
## 三、必须配的六件事
|
||||
|
||||
### 1)小程序登录(可选,不配就走 demo)
|
||||
### 1)拍照识题:腾讯切题(**必配**,否则只剩手输)
|
||||
|
||||
```
|
||||
WX_APPID=wx...
|
||||
WX_SECRET=...
|
||||
主链路是腾讯云「试卷切题 QuestionSplitOCR」。凭据两种放法,任选一种:
|
||||
|
||||
```bash
|
||||
# 放法 A:写进 data/tencent.env(容器已挂载 ../data,改完不用重启镜像)
|
||||
TENCENT_SECRET_ID=AKID...
|
||||
TENCENT_SECRET_KEY=...
|
||||
TENCENT_REGION=ap-guangzhou
|
||||
|
||||
# 放法 B:写进 deploy/.env,compose 会透传给容器(见 docker-compose.yml)
|
||||
```
|
||||
|
||||
不配时 `/api/auth/wx-login` 用 `code=demo` 的假 openid,只适合演示。
|
||||
成本闸门(都可不设):
|
||||
|
||||
### 2)拍照识题(Linux 必须配)
|
||||
```
|
||||
OCR_MONTHLY_LIMIT=900 # 每月最多调用次数,到顶直接停、不发请求;不设=只计数不拦
|
||||
OCR_CACHE=0 # 关掉结果缓存(默认开:同一张图不重复花钱)
|
||||
```
|
||||
|
||||
**Linux 上没有 Windows OCR**,`backend/ocr.py` 会走外部服务:
|
||||
- 预算计数在 `data/ocr_usage.json`,缓存文件名是图片 sha1,都在挂卷里。
|
||||
- 想查当月用量:`docker compose exec app python -m backend.ocr_budget`
|
||||
- 想清缓存重算:`docker compose exec app python -m backend.ocr_cache --clear`
|
||||
|
||||
### 2)本机 OCR 兜底(可选)
|
||||
|
||||
腾讯失败时会退到 `backend/ocr.recognize`。Windows 上有真实 OCR,**Linux 上没有**,需要指一个 HTTP OCR:
|
||||
|
||||
```
|
||||
OCR_HTTP_URL=https://你的OCR服务/ocr
|
||||
OCR_HTTP_KEY=xxx
|
||||
```
|
||||
|
||||
协议(自己包一层百度/腾讯云/自建 PaddleOCR 都行):
|
||||
响应协议:
|
||||
|
||||
```jsonc
|
||||
// 请求
|
||||
@@ -72,25 +95,34 @@ OCR_HTTP_KEY=xxx
|
||||
"lines": [{"text": "1.计算:36 + 47 =( )", "x": 0, "y": 0, "w": 900, "h": 32}]}
|
||||
```
|
||||
|
||||
没配 OCR 也不会挂:接口返回 `source="demo"`,并在 `ocr.reason` 里写原因,前端提示「没认出来,改手输或重拍」。**不要让它静默退成演示题库还告诉用户识别成功**。
|
||||
不配也不会挂:主链路走腾讯,兜底失败时接口返回 `source="demo"` 并在 `ocr.reason` 里写原因,前端提示「没认出来,改手输或重拍」。**不要让它静默退成演示题库还告诉用户识别成功。**
|
||||
|
||||
### 3)微信订阅消息
|
||||
### 3)微信登录(不配就只能演示)
|
||||
|
||||
```
|
||||
WX_TMPL_DAILY=模板ID
|
||||
WX_TMPL_EXPIRE=模板ID
|
||||
WX_APPID=wx...
|
||||
WX_SECRET=...
|
||||
```
|
||||
|
||||
个人主体只能用「一次性订阅」,额度一条、用完要用户再点一次——这是平台限制,不是实现问题。
|
||||
不配时 `/api/auth/wx-login` 用假 openid,只适合演示。
|
||||
|
||||
### 4)业务域名
|
||||
### 4)微信订阅消息
|
||||
|
||||
```
|
||||
WX_TMPL_DAILY=模板ID # 每日提醒
|
||||
WX_TMPL_EXPIRE=模板ID # 体验到期
|
||||
```
|
||||
|
||||
个人主体只能用「一次性订阅」:一次授权一条,用完要用户再点——平台限制,不是实现问题。号码池在 `data/` 里,重启不丢。
|
||||
|
||||
### 5)业务域名(小程序要用)
|
||||
|
||||
小程序后台 → 开发管理 → 开发设置:
|
||||
|
||||
- **request 合法域名**:`https://你的域名`
|
||||
- **业务域名**(`<web-view>` 要用):`https://你的域名`,需要上传校验文件到根路径
|
||||
- **业务域名**(`<web-view>` 打开工作台要用):`https://你的域名`,并上传校验文件到根路径
|
||||
|
||||
校验文件放 `backend/` 下会被 `GET /` 的路由挡住,建议在 Caddy 里加一条:
|
||||
校验文件别放 `backend/`(会被 `GET /` 挡住),放 `/srv/verify`,在 Caddyfile 里加一条:
|
||||
|
||||
```
|
||||
handle /你的校验文件名.txt {
|
||||
@@ -99,29 +131,43 @@ handle /你的校验文件名.txt {
|
||||
}
|
||||
```
|
||||
|
||||
## 四、备份
|
||||
小程序里把 `miniprogram/utils/config.js` 的 `apiBase` 改成 `https://你的域名`。
|
||||
|
||||
### 6)生产开关
|
||||
|
||||
`docker-compose.yml` 默认 `QINGLING_ENV=prod`:
|
||||
|
||||
- 不注册 `/api/dev/*` 与 `/api/auth/sms-*`(`POST /api/dev/reseed` 必须 404)
|
||||
- 短信登录整条链路关闭,线上只能扫码/微信登录
|
||||
|
||||
## 四、备份与清理
|
||||
|
||||
```bash
|
||||
chmod +x deploy/backup.sh
|
||||
deploy/backup.sh /app/data/app.db /backup
|
||||
|
||||
# crontab:每天 3:15
|
||||
15 3 * * * /opt/errortopic/deploy/backup.sh /app/data/app.db /backup >> /var/log/errortopic-backup.log 2>&1
|
||||
```
|
||||
|
||||
SQLite 用 `.backup`,不要 `cp`(WAL 下可能拷到半截)。上传的卷子照片在 `data/uploads/`,按 90 天清理策略单独处理。
|
||||
- SQLite 用 `.backup`,**不要 `cp`**(WAL 下可能拷到半截)。脚本默认留 14 份。
|
||||
- 除了 `app.db`,`data/` 下还有三样会涨:`uploads/`(卷子照片,90 天自动清理)、`_drafts/`(拍题草稿,可随时删)、`ocr_cache/`(识别结果缓存,可随时删)。
|
||||
- 整目录备份更稳:`tar czf /backup/data-$(date +%F).tgz -C /app data --exclude=data/ocr_cache`。
|
||||
- 恢复演练:停服 → 覆盖 `app.db` → 起服 → `curl /api/health` → 打开 `/workbench` 看今天 5 道还在不在。**没演练过的备份等于没有备份。**
|
||||
|
||||
## 五、上线前检查清单
|
||||
|
||||
- [ ] `api/health` 返回 `version=1.2.0`;`routes` 在 prod 下是 49(dev 下 56,多出的 8 条是 6 个 `/api/dev/*` 与 2 个短信登录接口)
|
||||
- [ ] 手机号登录能收到验证码(**现在还是 dev 模式直接回显,必须接短信服务商**)
|
||||
- [ ] 小程序 `code2session` 能换到真 openid
|
||||
- [ ] 拍照识题返回 `source=ocr`
|
||||
- [ ] `/workbench` 能在手机浏览器打开、能登录
|
||||
- [ ] 备份任务跑过一次、`/backup` 里有文件
|
||||
- [ ] 数据目录权限正确(容器用户可写)
|
||||
- [ ] 关掉或限制 `/`(接口控制台)与 `/docs`
|
||||
- [ ] `QINGLING_ENV=prod` 已生效:`POST /api/dev/reseed`、`/api/dev/issue-codes` 必须 404
|
||||
- [ ] Caddy 里 `/api/dev/*` 与 `/api/auth/sms-*` 返回 404(`curl -i https://<域名>/api/dev/reseed`)
|
||||
- [ ] `curl -s https://<域名>/api/health` 返回 `"version":"1.2.0"` 且 `routes` 里没有 `dev` 字样
|
||||
- [ ] `curl -i https://<域名>/api/dev/reseed` 返回 404
|
||||
- [ ] `curl -i https://<域名>/api/auth/sms-code` 返回 404(prod 关了短信登录)
|
||||
- [ ] 拍一张真卷,`POST /api/papers/scan/detect` 返回 `blocks` 非空(不是 `SPLIT_FAILED`)
|
||||
- [ ] 勾两题入库,`/workbench` 的错题本能看到,`kp` 不是空的
|
||||
- [ ] `/workbench` 在手机浏览器能打开、能登录、底部 tab 可用
|
||||
- [ ] 小程序能扫码登录、能拍题、能入库(真机,不是模拟器)
|
||||
- [ ] 订阅消息能收到一条(模板审核通过后)
|
||||
- [ ] 备份跑过一次,`/backup` 里有文件;按上文做过一次恢复
|
||||
- [ ] `/` 与 `/docs` 已关或加访问限制
|
||||
- [ ] `data/` 目录权限正确(容器用户可写),磁盘余量 > 5GB
|
||||
|
||||
## 六、回滚
|
||||
|
||||
@@ -133,4 +179,15 @@ sed -i 's/:1.2.0/:1.1.0/' docker-compose.yml
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
数据在挂卷里,回滚不会丢;但如果新版本改过表结构,回滚前先备份。
|
||||
数据在挂卷里,回滚不会丢;但**如果新版本改过表结构,回滚前先备份**(`db._migrate` 只加列不删列,所以通常能回,但仍要备份)。
|
||||
|
||||
## 七、内网试用(不上公网)
|
||||
|
||||
给同事/家长试用最省事的方式:
|
||||
|
||||
```bash
|
||||
python -m backend.app --host 0.0.0.0 --port 8000
|
||||
# 手机与电脑同一 Wi-Fi,访问 http://<电脑内网IP>:8000/workbench
|
||||
```
|
||||
|
||||
dev 模式会显示「模拟确认」按钮,点一下就能登录,不需要短信。**这条路径不要暴露到公网**——dev 模式可以重置数据。
|
||||
|
||||
@@ -22,9 +22,16 @@ services:
|
||||
WX_SECRET: ${WX_SECRET:-}
|
||||
WX_TMPL_DAILY: ${WX_TMPL_DAILY:-}
|
||||
WX_TMPL_EXPIRE: ${WX_TMPL_EXPIRE:-}
|
||||
# 部署在 Linux 时拍照识题必须走外部 OCR
|
||||
# 部署在 Linux 时拍照识题必须走外部 OCR(可选;主链路是下面的腾讯切题)
|
||||
OCR_HTTP_URL: ${OCR_HTTP_URL:-}
|
||||
OCR_HTTP_KEY: ${OCR_HTTP_KEY:-}
|
||||
# 拍照识题主链路:腾讯云试卷切题(也可以写进挂载的 data/tencent.env)
|
||||
TENCENT_SECRET_ID: ${TENCENT_SECRET_ID:-}
|
||||
TENCENT_SECRET_KEY: ${TENCENT_SECRET_KEY:-}
|
||||
TENCENT_REGION: ${TENCENT_REGION:-ap-guangzhou}
|
||||
# OCR 花钱的闸门:月度上限与结果缓存
|
||||
OCR_MONTHLY_LIMIT: ${OCR_MONTHLY_LIMIT:-}
|
||||
OCR_CACHE: ${OCR_CACHE:-}
|
||||
# 数据库位置(挂卷)
|
||||
QINGLING_DB: /app/data/app.db
|
||||
# 生产模式:不注册 /api/dev/* 与 /api/auth/sms-*(见 backend/app.py 的 PROD 开关)
|
||||
|
||||
@@ -4,13 +4,20 @@
|
||||
# sudo useradd -r -s /bin/false errortopic
|
||||
# sudo mkdir -p /opt/errortopic /var/lib/errortopic
|
||||
# sudo cp -r backend prototype brand /opt/errortopic/
|
||||
# sudo mkdir -p /opt/errortopic/data && sudo cp data/kp_graph.json /opt/errortopic/data/
|
||||
# sudo chown -R errortopic:errortopic /opt/errortopic /var/lib/errortopic
|
||||
#
|
||||
# 2) 密钥放 /etc/errortopic/env(权限 600,属主 errortopic)
|
||||
# QINGLING_ENV=prod
|
||||
# WX_APPID=...
|
||||
# WX_SECRET=...
|
||||
# WX_TMPL_DAILY=...
|
||||
# OCR_HTTP_URL=...
|
||||
# WX_TMPL_EXPIRE=...
|
||||
# TENCENT_SECRET_ID=... # 拍照识题主链路(Linux 没有本机 OCR,必配)
|
||||
# TENCENT_SECRET_KEY=...
|
||||
# TENCENT_REGION=ap-guangzhou
|
||||
# OCR_MONTHLY_LIMIT=900 # 可选:到顶就停,不发请求
|
||||
# OCR_HTTP_URL=... # 可选:本机 OCR 的 HTTP 兜底
|
||||
# OCR_HTTP_KEY=...
|
||||
#
|
||||
# 3) 装服务
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
# 文档索引
|
||||
|
||||
按「你想知道什么」排。每条都写清**它能回答什么问题**,以及格式(md 直接在仓库里读,pdf/docx 要下载)。
|
||||
|
||||
> 只读一份的话,读 [`项目总览.md`](项目总览.md)——需求、竞品、优势、现状、缺口,一份讲完。
|
||||
|
||||
## 一、先读这几份
|
||||
|
||||
| 想知道 | 看这个 | 格式 |
|
||||
|---|---|---|
|
||||
| 这项目是什么、凭什么、做到哪了 | [`项目总览.md`](项目总览.md) | md · `report/错题毕业-项目总览.docx` / `.pdf` |
|
||||
| 需求是怎么被证明的(一手数据) | `report/错题需求报告-数据版.pdf`(12 页) | pdf |
|
||||
| 竞品在骂什么、用户在原话里要什么 | `data/out/report.md`(1,097 条应用商店评论 + 554 条小红书评论的归因) | md |
|
||||
| 产品怎么设计、为什么这么定 | `report/错题毕业-产品方案书.pdf`(28 页) | pdf |
|
||||
| 现在做到哪一步(对内汇报) | `report/错题毕业-阶段汇报-2026-11-23.docx` | docx |
|
||||
|
||||
## 二、需求与市场
|
||||
|
||||
| 想知道 | 看这个 | 备注 |
|
||||
|---|---|---|
|
||||
| 家长在网上到底在说什么 | `data/out/report.md` | 220 篇笔记 / 554 条评论,含 Top 互动、需求信号分布、每类原话 |
|
||||
| 竞品的差评结构 | `data/out/report.md` 第「应用商店差评」节 | 6 个竞品、1,097 条评论、差评率与问题归因 |
|
||||
| 分学段的需求差异(小学/初中/高中/其他) | `report/错题毕业-产品方案-小学版.pdf`、`-初中版.pdf`、`-高中版.pdf`、`-其他学段版.pdf` | 各 7–9 页 |
|
||||
| 竞品与我们的位置 | [`项目总览.md`](项目总览.md) 第三节 | 六类玩家 / 五种活法 / 空档在哪 |
|
||||
| 错题本这件事的来龙去脉 | `report/错题本产品起源与实现.pdf`(14 页) | 谁在什么时候开始做、为什么大多数做成了「收集」 |
|
||||
|
||||
## 三、产品设计
|
||||
|
||||
| 想知道 | 看这个 | 备注 |
|
||||
|---|---|---|
|
||||
| 完整产品方案(机制、功能、定价、路线) | `report/错题毕业-产品方案书.pdf` | 28 页,主文档 |
|
||||
| 小学版 PRD(判题单位、错因码、准确率红线) | `report/错题毕业-小学版-PRD.pdf` | 34 页,含附录 D 错因码、附录 E 准确率专项 |
|
||||
| 初中版 PRD(孩子主账号、家长授权、变式替代连对) | `report/错题毕业-初中版-PRD.pdf` | 29 页 |
|
||||
| 小程序该有哪几个菜单 | `report/错题毕业-小程序三菜单规划.pdf` | 16 页 |
|
||||
| 小学版怎么上市 | `report/错题毕业-小学版-上市打法.pdf` | 渠道、节奏、价格 |
|
||||
| 知识点怎么切、怎么判 | `report/错题毕业-小学-知识点对照表.xlsx` | 248 条判题单位(A 可判 / B 只判结果 / C 不判) |
|
||||
| 解析的三步从哪来 | `report/错题毕业-小学-解析模板表.xlsx` | 147 条「三步 + 知识点 + 易错点」 |
|
||||
| 语文成语释义与褒贬 | `report/错题毕业-小学-成语卡.xlsx` | 120 条,运行时按题干匹配注入 |
|
||||
|
||||
## 四、实现手册(给写代码的人)
|
||||
|
||||
| 想知道 | 看这个 |
|
||||
|---|---|
|
||||
| 怎么跑、接口怎么调、状态机怎么走 | `backend/README.md`(60 条接口 / 23 张表 / 26 个专题小节) |
|
||||
| 工作台 11 个视图怎么用、解析怎么生成 | `prototype/workbench/README.md` |
|
||||
| 小程序 8 页怎么改、接口约定 | `miniprogram/README.md` |
|
||||
| 初中版为什么单独一套 | `junior/README.md` |
|
||||
| 哪些代码是两个产品共用的 | `core/README.md` |
|
||||
| 怎么部署、怎么备份、上线检查清单 | `deploy/README.md` |
|
||||
| 怎么评测、金标怎么标、成本怎么算 | `bench/README.md` |
|
||||
|
||||
## 五、数据与评测(数字的出处)
|
||||
|
||||
| 想知道 | 看这个 | 关键数字 |
|
||||
|---|---|---|
|
||||
| 拍题链路到底行不行 | `report/错题毕业-拍题评测-230张.md` | 230 张真卷:切题 98.7%、题干可用 92.3%、可判 37.0%、自算 95.9% |
|
||||
| 判分准不准 | 同上第五节 + `bench/gold.json` | 330 道人工金标:认对 96.4%、误判 0(CI 0–1.19) |
|
||||
| 解析有没有胡说 | `data/plan_verify.md` | 425 道真题三步解析逐句重算,错句 0 |
|
||||
| OCR 花了多少钱 | `bench/README.md`「额度纪律」+ `data/ocr_usage.json` | 缓存 + 月度预算;一张卷 1.4 次调用 |
|
||||
|
||||
## 六、界面长什么样
|
||||
|
||||
- 原型代码:`prototype/workbench/index.html`(家长端工作台,双击可看演示)、`prototype/primary/index.html`(小学版早期 23 屏静态稿)、`miniprogram/`(小程序)
|
||||
- 截图:`report/预览-*.png`——工作台、手机三屏、拍照入库、逐条勾选、退一层、A5 周报、会但不稳等
|
||||
|
||||
## 七、历史决策(想知道「当初为什么这么定」)
|
||||
|
||||
| 决策 | 记在哪 |
|
||||
|---|---|
|
||||
| 为什么改名「错题毕业」 | `report/错题本产品起源与实现.pdf` |
|
||||
| 为什么不用「清零」 | 同上 |
|
||||
| 为什么只做小学 | `report/错题毕业-产品方案-小学版.pdf` |
|
||||
| 为什么把 3 次才入库、连对两次、讲清才毕业定成硬规则 | `report/错题毕业-产品方案书.pdf` 第三节 + `backend/README.md`「核心规则」 |
|
||||
| 为什么换掉 TextIn、改用腾讯切题 | `backend/README.md` 四点十九、四点二十一 |
|
||||
| 为什么补扫默认关 | `backend/README.md` 四点二十二 |
|
||||
| 为什么「会但不稳」要单独一个状态 | `backend/README.md` 四点二十三 |
|
||||
| 为什么加「退一层」 | `backend/README.md` 四点二十四 + `core/README.md` |
|
||||
|
||||
---
|
||||
|
||||
维护约定:**改了行为就改 `backend/README.md` 对应小节**;`项目总览.md` 由 `report/build_overview.py` 生成,不要手改(手改会被下次生成覆盖)。
|
||||
@@ -0,0 +1,115 @@
|
||||
# 错题毕业 · v1.3 版本方案
|
||||
|
||||
**日期**:2026-11-23 | **依据**:当天的六轮讨论(学习方法 → 理论对账 → 先修图 → 游戏化反馈)
|
||||
**一句话**:这一版不加新机制,把已有机制「补上最后一口气」——**看得见进度、说得出口、卡得住位置**。
|
||||
|
||||
---
|
||||
|
||||
## 一、今天讨论了什么,结论是什么
|
||||
|
||||
| # | 议题 | 结论(一句话) |
|
||||
|---|---|---|
|
||||
| 1 | 一个人怎么掌握知识、为什么会错题(费曼 / 四类断裂点 / 四步闭环) | 错题不是「粗心」,是四个环节之一断了;断点必须能被**点选**记录,否则永远只能「再讲一遍」 |
|
||||
| 2 | 小学 1–6 年级语文数学的差异与节奏 | 数学是树状依赖(前置不懂全塌),语文是网状积累;两者不能用同一套判定 |
|
||||
| 3 | 有没有系统框架能跑通(日清 / 周结 / 月测 + 三色状态机) | 有;我们的日清(5 道)和周报已经有,**缺「周结」派活**与**三色那一层可数性** |
|
||||
| 4 | 这些做法是按费曼 / 艾宾浩斯 / 脑发育来的吗 | **费曼最实、艾宾浩斯最虚(固定表 1/3/7/15/30 是手写的)、脑发育基本没落地**(零图示、零语音) |
|
||||
| 5 | 小学 1–6 数学有逻辑依赖吗?回退有没有 | 有,且很硬(三条主干)。回退**已实现**但只到 3 年级(39 点/60 边),**缺 4–6 年级与「同点跨册」边** |
|
||||
| 6 | 学习能不能像游戏一样有正向反馈(XP 积分表) | 方向对(即时反馈 / 进度可视化 / 难度匹配),但**积分表不适合我们**:记账是家长的活,且与客观进度重复计量 |
|
||||
|
||||
### 被当场纠正的三个说法
|
||||
|
||||
1. 「高年级是低年级合成来的」→ 应为 **同构复用 + 螺旋上升**。所以回退的正确目标是「同一个知识点的前一册版本」,不是「两年前的那个知识点」。
|
||||
2. 「多巴胺分泌翻倍」→ 误读。多巴胺编码预测误差(想要),不是快乐;游戏粘性靠可变比率强化与沉没成本。
|
||||
3. 「3 秒内给反馈」→ 伪精确;但「反馈要即时」这个方向成立。
|
||||
|
||||
---
|
||||
|
||||
## 二、v1.3 要做的八件事(按优先级)
|
||||
|
||||
> 排序依据:**先改「明天还来不来」,再改「算不算真会」**。前四件不动判分逻辑,不会被推翻。
|
||||
|
||||
### 第一批:闭环补气(1.5 天)
|
||||
|
||||
| 编号 | 做什么 | 依据 | 涉及文件 | 工作量 | 验收 |
|
||||
|---|---|---|---|---|---|
|
||||
| **W1** | 错题本默认**三色视图**(红=待复习/观察中、黄=会但不稳+待讲清+已对一次、绿=已毕业);原 7 个状态名降为副标签;「全部」变筛选 | 目标梯度效应;家长要的是「还剩几道」不是「我有几道」 | `prototype/workbench/index.html`(`renderWrong`、筛选条) | 0.5d | 默认视图不含已毕业行;红色数 = 到期题数;7 个状态仍可筛 |
|
||||
| **W2** | 每轮做完 5 道的**收尾页**:`今天 5 道 · 一次就对 3 道 · 你把第 4 道讲明白了` + 小狮跳一格 | 即时反馈 + 过程表扬(Dweck);现在整轮无反馈 | `index.html`(`submit` 末尾、`#qResult`)、`backend/services.py`(`attempt` 返回本轮累计) | 0.5d | 做完第 5 道出现收尾屏;文案基于行为而非「你真棒」 |
|
||||
| **W3** | 小狮**落库**:`children` 加 `pet_stage`、`pet_fed_at`;每天首次完成更新,跨设备一致 | 现在的 stage 是算出来的,关页面就没了,没有仪式感 | `backend/db.py`(迁移)、`services.py`、`index.html` | 0.5d | 换浏览器登录,小狮形态一致;当天第二次完成不重复「喂」 |
|
||||
|
||||
### 第二批:把断点记下来(1.5 天)
|
||||
|
||||
| 编号 | 做什么 | 依据 | 涉及文件 | 工作量 | 验收 |
|
||||
|---|---|---|---|---|---|
|
||||
| **W4** | `mistakes` 加 `stuck_at`(`read/plan/calc/check` 四值)。**只在讲清失败时**弹一次四按钮「刚才卡在哪」;入库不问 | 归因三层缺「卡点」;147 条模板按知识点分、不按卡点分,需要这个数据才能重排 | `db.py`(迁移 + `ensure_columns`)、`services.explain`、`index.html`(讲一遍弹窗) | 1d | 讲清失败后可点选并落库;`stuck_at` 出现在错题详情;「其他」占比 >20% 则加第五类 |
|
||||
| **W5** | 小程序「讲一遍」支持**录音**(1–3 年级默认语音):`RecorderManager` 录 → 上传 → 存音频,不强制转写 | 低年级写字慢(工作记忆未成熟),要求打字等于把费曼变作文 | `miniprogram/pages/queue`(或讲清页)、`backend/app.py`(上传路由)、`data/uploads/` | 1d | 真机录 10 秒能上传并回放;不打字也能提交讲清 |
|
||||
|
||||
### 第三批:让「毕业」变严(2 天)
|
||||
|
||||
| 编号 | 做什么 | 依据 | 涉及文件 | 工作量 | 验收 |
|
||||
|---|---|---|---|---|---|
|
||||
| **W6** | 变式**自校验** + 「严档」开关:`practice.similar()` 出的题必须能算、答案唯一;开关打开后第二次连对改为「做对一道没见过」;1–3 年级用换数字(近迁移)、4–6 用换情境(远迁移) | 迁移理论(只有新变式才算真会);初中版已是变式,小学版偏松 | `backend/practice.py`、`scheduler.on_attempt`、`index.html`(设置) | 2d | 自校验抽样 100 道 0 错;严档开启后毕业需要变式通过;默认关闭 |
|
||||
|
||||
### 第四批:先修图扩到 6 年级(1 天草稿 + 审核)
|
||||
|
||||
| 编号 | 做什么 | 依据 | 涉及文件 | 工作量 | 验收 |
|
||||
|---|---|---|---|---|---|
|
||||
| **W7** | `data/kp_graph.json` 扩到 4–6 年级(约 60–80 点、90–120 边),新增**同点跨册 soft 边**(分数的初步认识 → 意义与性质 → 四则运算) | 依赖真实存在;现在 4–6 年级回退无效 | `data/kp_graph.json`、`backend/kp_graph.py`(无需改逻辑) | 1d 草稿 + 老师审 1h | `validate()` 无环、无年级倒挂;hard 边逐条有人签字 |
|
||||
| **W8** | 同一类题**连续错第三次**也触发回退(现在只有讲清失败才退) | 连错说明前置缺失,不该再排一次同题 | `services.attempt`、`scheduler.on_attempt` | 0.5d | 连错三次返回 `retreat`;讲清路径不受影响 |
|
||||
|
||||
---
|
||||
|
||||
## 三、明确不做,以及为什么
|
||||
|
||||
### A. 与我们的约束冲突(会拖垮家长)
|
||||
|
||||
| 不做 | 原因 |
|
||||
|---|---|
|
||||
| **XP 记账 + 兑换商城** | 每天多 2 分钟记账 + 每周结算 + 兑换协商,而家长只有 20 分钟;且毕业数、连对次数已经是**客观、不可作弊**的进度,再加一套货币是重复计量 |
|
||||
| **盲盒抽奖** | 可变比率强化最容易产生「消退」:不抽就不做;而且它正是文章自己反对的物质奖励 |
|
||||
| **便利贴贴墙 + 撕纸** | 对「怕错」的孩子是公开羞辱(有客人时更糟);且依赖家长持续维护 |
|
||||
| **1–3 年级段位(青铜→王者)** | 太抽象;低年级认的是贴纸与盖章,不是称号 |
|
||||
| **活页本 + 三色笔 + 错题打印机** | 每多一道物理流程就多一个放弃点;A5 周报已承担「打印」这一环 |
|
||||
| **让孩子自己抄题** | 抄题是最大的时间黑洞,也是用户最先放弃的一步(产品原则) |
|
||||
|
||||
### B. 理论上不成立或证据不足
|
||||
|
||||
| 不做 | 原因 |
|
||||
|---|---|
|
||||
| **合书复述、白纸写框架** | 我们没有纸笔环境;硬做就是「在输入框打字」,孩子当成又一份作业。用「讲一遍」(口述 3 句)替代,负担低 5 倍 |
|
||||
| **「多巴胺翻倍」式的激励设计** | 前提是误读;按它设计会得到「抽奖依赖」而不是「习惯」 |
|
||||
| **自适应难度算法(IRT / 贝叶斯知识追踪)** | 单个孩子一学期约 200 道题,样本量不足以拟合模型,只会拟合噪声。现在的「错题优先 + 每天 5 道」已经够 |
|
||||
| **课标映射(周报写「对应课标第 X 条」)** | 没有可商用的课标条目数据,自己编号就是假精确 |
|
||||
| **AI 讲解加长 / 加视频** | 讲解不是壁垒(豆包免费且更好);长讲解与「一天 4 分钟」直接冲突。要补的是**低年级的图示**,不是更长的文字 |
|
||||
|
||||
### C. 今天讨论里被降级的两件(不是永远不做)
|
||||
|
||||
| 暂缓 | 原因 | 什么时候做 |
|
||||
|---|---|---|
|
||||
| **间隔从固定表改自适应** | `1/3/7/15/30` 是手写表,但**没有「第二次做对率 vs 间隔」的数据**,现在调参是瞎调 | 攒够 4 周 `stuck_at` 与作答数据后 |
|
||||
| **1–3 年级讲解加图示**(小棒/数轴/线段图) | 最贴脑发育,但要设计 30–50 张静态图,不是写代码;且需要教研把关 | v1.4,单独排期 |
|
||||
|
||||
---
|
||||
|
||||
## 四、排期与验收
|
||||
|
||||
| 周 | 内容 | 交付 |
|
||||
|---|---|---|
|
||||
| 第 1 周 | W1 → W2 → W3(1.5d),W4 → W5(1.5d) | v1.3.0:三色 + 收尾页 + 小狮落库 + 卡点 + 语音讲清 |
|
||||
| 第 2 周 | W6(2d)、W7 草稿(1d)、W8(0.5d) | v1.4.0:严档变式 + 4–6 年级先修图(待审) + 连错回退 |
|
||||
|
||||
**新增三个过程指标**(现在只有结果指标「消灭率」):
|
||||
|
||||
| 指标 | 定义 | 目标 |
|
||||
|---|---|---|
|
||||
| 次日回收率 | 当天错的题,第二天做对的比例 | ≥55% |
|
||||
| 讲清一次通过率 | 第一次讲就过 rubric 的比例 | 40–60%(过高=太水,过低=门槛高) |
|
||||
| 红色剩余 | 三色里红色题数中位数 | ≤8 道 |
|
||||
|
||||
---
|
||||
|
||||
## 五、风险
|
||||
|
||||
1. **W1 改默认视图**:老用户找不到「已毕业」→ 保留筛选入口 + 首次进入提示一次。
|
||||
2. **W4 多一次点击**:讲清失败时家长本就在气头上,四按钮必须即点即走,不能弹输入框。
|
||||
3. **W6 变式质量**:出错的变式比不做更糟 → 自校验先行,抽样 100 道 0 错才开放开关。
|
||||
4. **W7 hard 边写错**:会把孩子退到无关知识点,家长立刻不信任 → hard 边只写「教材明确先学」的,其余一律 soft;上线后看「回退后被否」的比例逐条修。
|
||||
@@ -0,0 +1,155 @@
|
||||
# 错题毕业 · 项目总览
|
||||
|
||||
> 把「错题本」从「收集工具」改成「消灭流程」
|
||||
|
||||
*v1.0 · 2026-11-23 · 这份文档面向:新加入的人、投资人、合作方*
|
||||
|
||||
## 一、一页纸
|
||||
|
||||
> 每天 4 分钟,只做 5 道。做对两次、并且讲得清,这道题才算「毕业」。
|
||||
|
||||
| 问题 | 我们的回答 |
|
||||
|---|---|
|
||||
| 是什么 | 家长端(电脑/手机浏览器)+ 小程序(拍题、扫码确认)的错题闭环;小学版 69 元/学期,含 2 个孩子 |
|
||||
| 解决什么 | 错题整理了却不复习,复习了却没真懂——问题不在「收集」,在「消灭」 |
|
||||
| 凭什么 | 机制:到点提醒重做 / 做不对重讲 / 讲不清不算过 / 会但不稳 / 讲不清退一层;<br>工程:一张真卷能切出 98.7% 的题,题干可用 92.3% |
|
||||
| 到哪了 | 60 个接口、240 个单测、11 个工作台视图、8 页小程序;本机已经能从头走到尾 |
|
||||
| 卡在哪 | 主体资质、支付开通、真机联调、家长访谈——四件都在人,不在技术 |
|
||||
|
||||
## 二、需求:不是「整理难」,是「消灭不了」
|
||||
|
||||
我们采了三份一手数据(脚本在 `collector/`,原始数据在 `data/`):
|
||||
|
||||
| 数据 | 规模 | 看到了什么 |
|
||||
|---|---|---|
|
||||
| 小红书 | 220 篇笔记 / 554 条评论 | 收藏赞比常 >1(存下来照着做);高频词:错题 318、整理 138、时间 69、方法 63 |
|
||||
| 应用商店 | 1,097 条评论 / 6 个竞品 | 1–2 星 146 条(13.3%);差评里收费/会员 32.9%、功能缺失 21.2%、导出/还原 17.1%、识别不准 15.8% |
|
||||
| 评论信号 | 554 条 | 科目/年级 16.2%、打印/导出 7.4%、怎么买/在哪用 2.2%、质疑劝退 2.0% |
|
||||
|
||||
**应用商店这份最说明问题**:用户在花钱买,但买回来「用不上」。试卷宝 4.10 分、差评率 20.4%,蜜蜂试卷 3.82 分、差评率 24.8%,最集中的抱怨是「又要开会员」「功能砍了」,而不是「不好用」。
|
||||
|
||||
### 用户自己发明的三个办法
|
||||
|
||||
- **手抄/剪贴**:把错题抄到本子上、把卷子剪下来贴——「错题婆罗门」那套说法,本质是嫌工具不好用。
|
||||
|
||||
- **A4 打印重做**:「整理成文档打印,A4 纸剪下就行」——用户已经在替我们做「重做」这一步。
|
||||
|
||||
- **家长盯**:「大部分时间是老母亲整理,初中娃时间宝贵」——采集和验收都落在家长身上。
|
||||
|
||||
### 四条需求结论
|
||||
|
||||
- 要的是**重做**,不是**收集**:本子越厚越不敢翻,能「变少」才是正反馈。
|
||||
|
||||
- 要**到点提醒**:没有提醒的错题本 = 一次性工具。
|
||||
|
||||
- 要**讲得清**:看懂了答案 ≠ 会了;能用自己的话讲出来才算。
|
||||
|
||||
- **不要抄题**:抄题是最大的时间黑洞,也是用户最先放弃的一步。
|
||||
|
||||
## 三、竞品:六类玩家,五种活法
|
||||
|
||||
| 类别 | 代表 | 怎么活 | 强在哪 | 弱在哪(有据) |
|
||||
|---|---|---|---|---|
|
||||
| 工具型 App | 试卷宝、蜜蜂试卷、橙果、错题本-拍照整理 | 会员 / 超级会员,靠题库和试卷库 | 题库大、拍照搜题快 | 收费墙与砍功能是差评第一因;500 题只能下载 100 题;题图分离处理不了 |
|
||||
| 大厂学习 App | 作业帮、学而思、豆包爱学 | 免费或低价引流,靠内容与直播变现 | 流量大、AI 能力强 | AI 会讲错(差评 7.2% 集中在此);不跟踪进度、不闭环 |
|
||||
| 硬件打印 | 喵喵机、咕咕机 | 卖机器与耗材 | 即拍即印,手感好 | 只解决「印出来」,不解决「做没做对」 |
|
||||
| 学校/机构平台 | 校本题库、智慧课堂 | 招投标、B 端采购 | 有校本数据、老师背书 | 家长在家用不上;无法按一个孩子调难度 |
|
||||
| 通用 AI | 豆包、夸克、Kimi | 免费,靠生态 | 免费、什么都能问 | 不记进度、不提醒、不验收;判分不可靠 |
|
||||
| 个体卖家 | 小红书上的手作工具(如 29 元 7 天 / 198 元一年) | 私域卖卡,网页交付 | 便宜、灵活、离用户近 | 积分陷阱(日均可用户积分 43 vs 年费 1.2,差 35 倍);网页无推送;采集在手机、加工在电脑 |
|
||||
|
||||
### 六类里没有一类在做的事
|
||||
|
||||
> 「到点重做 + 做不对重讲 + 讲不清不算过」这条链,没人把它做成默认流程。
|
||||
|
||||
工具型做的是「收」,大厂做的是「讲」,硬件做的是「印」,学校做的是「布置」,通用 AI 做的是「答」,个体卖家做的是「卖」。**中间那条「盯到会为止」的缝,是空的。**
|
||||
|
||||
## 四、优势:四条,每条都有数字
|
||||
|
||||
### 1. 机制:一条别人没有的链
|
||||
|
||||
| 环节 | 规则 | 为什么这么定 |
|
||||
|---|---|---|
|
||||
| 入库 | 同一道题错三次才进错题本 | 错一次多半是手滑,不配占孩子的时间 |
|
||||
| 隔离 | 当天做错、24 小时内做对 → 进「粗心小记」 | 粗心不该重做,该练「检查」 |
|
||||
| 重做 | 次日同一时间再做一次 | 隔一天才验得出记没记住 |
|
||||
| 会但不稳 | 当天错了又对,不算连对,明天从头再来 | 当场做对只是「听完会了」 |
|
||||
| 毕业 | 连对两次 + 讲一遍讲清 | 讲不清 = 没懂,回炉 |
|
||||
| 退一层 | 讲不清时退到前置知识点,做对两道再回来 | 前置缺了,讲十遍也不会过 |
|
||||
|
||||
### 2. 工程:拍题是真的能用
|
||||
|
||||
- **切题**:230 张真卷,227 张切开(98.7%);题块 1,804 个,题干可用 92.3%。
|
||||
|
||||
- **判分**:可自动判的题里自算 95.9%(Fraction 精确算,`0.6` 与 `3/5` 等价)。
|
||||
|
||||
- **金标**:330 道人工标注,认对 96.4%(CI 93.8–97.9),**误判 0**(CI 0–1.19)。
|
||||
|
||||
- **解析**:425 道真题的三步解析逐句重算,错句 0(这项修掉了三类静默算错)。
|
||||
|
||||
这几项的意思不是「比别人准」,而是**这套流程可以真跑**——拍一张卷子,家长点几下,第二天孩子就能做题,不用重抄、不用打印机。
|
||||
|
||||
### 3. 成本:一学期 1.4–2.8 元
|
||||
|
||||
OCR 是最容易失控的一项。现在四道闸:结果缓存(同图不重复花钱)、月度预算(到顶自动停)、整块够好就不裁剪、补扫默认关。一张卷从 4 次调用降到 **1.4 次**;一学期 20 张 ≈ 28 次 ≈ **1.4–2.8 元**,占 69 元学费的 2–4%。改造之前是 12–17 元(20% 以上),模型不成立。
|
||||
|
||||
### 4. 形态与隐私
|
||||
|
||||
- **不要求重抄**:整页拍 → 点框选错题 → 一块多道时逐条勾 → 只入库勾中的。
|
||||
|
||||
- **不绑硬件**:周报是一张 A5,家里有打印机就打,没有就在屏幕上看。
|
||||
|
||||
- **数据在你自己机器上**:SQLite 单文件、照片 90 天自动删、不做模型训练;可以自己部署(Docker + Caddy)。
|
||||
|
||||
### 诚实的边界:这些不是我们的优势
|
||||
|
||||
- **AI 讲解本身不是壁垒**——豆包免费,讲得也不差。我们赌的是「盯到会」的流程。
|
||||
|
||||
- **知识覆盖还薄**:147 条解析模板、实际在用 18 个知识点;先修图只做了小学 1–3 年级 39 个点、60 条边。
|
||||
|
||||
- **评测偏窄**:只覆盖小学 1–5 年级数学口算;语文是「判不准就交给人」,不是自动判分。
|
||||
|
||||
- **没有 App**:小程序 + 网页,召回手段只有订阅消息。
|
||||
|
||||
## 五、现在能跑什么
|
||||
|
||||
| 端 | 已经能做的 | 状态 |
|
||||
|---|---|---|
|
||||
| 家长端<br>(工作台 11 个视图) | 今日训练 5 道、错题本(按 8 种状态筛)、复习计划、学情分析、周报(A5 可打印)、已毕业、粗心小记、多孩切换、扫码登录、拍照入库(点选 + 逐条勾)、讲一遍(含退一层) | 可跑 |
|
||||
| 孩子端<br>(小程序 8 页) | 扫码确认登录、拍题(点框 → 逐条勾 → 入库)、首页、我的、工作台 web-view | 可跑,需真机联调 |
|
||||
| 后端 | 60 条接口、23 张表、240 个单测 + 4 套冒烟(41/22/21/29) | 全绿 |
|
||||
| 运营/交付 | Docker + Caddy 部署、systemd 加固、SQLite 备份脚本(留 14 份)、隐私与同意流程 | 脚本就绪,未上真机 |
|
||||
|
||||
## 六、技术一图(文字版)
|
||||
|
||||
小程序 / 浏览器 → `backend/`(零依赖 http.server + SQLite)→ 腾讯云 QuestionSplitOCR(外挂缓存 + 月度预算)→ 判分(算式自算 / 选择比对 / 人工自评)→ 调度(简化 SM-2:1 / 3 / 7 / 15 / 30 天)→ 周报、A5 打印、订阅消息。
|
||||
|
||||
两个产品共用 `core/`(时间、SQLite 连接、文本归一、Fraction 求值);小学版在 `backend/`,初中版在 `junior/`(独立端口与库),刻意不合并业务层。
|
||||
|
||||
## 七、怎么跑起来(三步)
|
||||
|
||||
- **起后端**:`python -m backend.app --host 0.0.0.0 --port 8000`
|
||||
|
||||
- **打开工作台**:浏览器访问 `http://127.0.0.1:8000/workbench`,点「模拟确认」即可登录(dev 模式)
|
||||
|
||||
- **手机**:同一 Wi-Fi 下访问 `http://<你的内网IP>:8000/workbench`;不想连后端就直接双击 `prototype/workbench/index.html` 看演示
|
||||
|
||||
自检:`python tools/run_tests.py`(240 个用例)、`python tools/scan_e2e.py`(拍题三接口端到端)。唯一花钱的是拍照入库,本月用量见 `data/ocr_usage.json`,到顶会自动停。
|
||||
|
||||
## 八、还没做完的,以及谁来做
|
||||
|
||||
| 类别 | 事项 | 谁能推 |
|
||||
|---|---|---|
|
||||
| 上线硬门槛 | 主体与教育类目资质、支付开通(代码里 `pay_enabled: false`) | 只有你能推 |
|
||||
| 上线硬门槛 | 真机联调(微信开发者工具 + 局域网 IP) | 只有你能推 |
|
||||
| 上线硬门槛 | 5 个家长访谈,验证「19:30 那 4 分钟」 | 只有你能推 |
|
||||
| 上线硬门槛 | 部署到真服务器 + 备份恢复演练 | 我能做 |
|
||||
| 体验缺口 | 公式与图形的解析(现在只有文字) | 我能做 |
|
||||
| 体验缺口 | 召回只有订阅消息一条,缺站内提醒/周报回流 | 我能做 |
|
||||
| 技术债 | CI + UI 截图基线;SQLite 并发压测与限流;告警 | 我能做 |
|
||||
| 明确不做 | 不做题库、不做硬件、不做直播课——这三件都是别人的强项 | 已拍板 |
|
||||
|
||||
建议顺序:**真机联调 → 支付 → 部署演练 → 公式图形 → 召回**。前两件不通,后面的优化都看不到效果。
|
||||
|
||||
## 九、想看更细的
|
||||
|
||||
文档索引见 `docs/README.md`:需求证据、竞品对比、产品方案、PRD、拍题评测、接口手册、工作台手册、小程序手册、部署手册,各自对应一份文件,标注了「它能回答什么问题」。
|
||||
@@ -1,6 +1,6 @@
|
||||
# 错题毕业 · 小学版小程序
|
||||
|
||||
原生微信小程序(无第三方依赖),3 个 tab(首页 / 排题 / 我的)+ 4 个二级页,对接 `backend\` 的接口。
|
||||
原生微信小程序(无第三方依赖),3 个 tab(首页 / 拍题 / 我的)+ 4 个二级页,对接 `backend\` 的接口。
|
||||
配色与交互原型 `prototype\primary\index.html` 一致:纸色 `#FFF3DF`、品牌红 `#B3272D`、土金 `#A9761A`、墨绿 `#2F6B57`。
|
||||
|
||||
> 这一版是**能跑通的骨架**:登录、建档、拍卷(题库版)、今日 5 道、判对错、讲清、周报、A5 打印、激活码、订阅额度都通了。
|
||||
@@ -60,7 +60,7 @@ curl -X POST http://127.0.0.1:8000/api/auth/wx-login -H "Content-Type: applicati
|
||||
| 监护人同意 | `pages/consent` | 收什么 / 存多久 / 不做什么,两个必须手勾 | P22 |
|
||||
| 孩子档案 | `pages/children` | 昵称、年级、科目开关、多孩切换、填充演示数据 | P23 / P11 |
|
||||
| 首页 | `pages/home` | 今天几道(附「约 N 分钟」)、待讲清、本周三个数、去工作台 | P01 |
|
||||
| 排题 | `pages/queue` | 拍一张 / **手输一道** → OCR 切题 → 勾选 → 入库 → 题单预览(N 道 · 约 X 分钟) | P03 / P04 / P05 |
|
||||
| 拍题 | `pages/queue` | 拍一张 → 切块带框 → **在图上点哪几道错了** → 一块多道时逐条勾 → 入库 → 题单预览(N 道 · 约 X 分钟);也能手输一道 | P03 / P04 / P05 |
|
||||
| 工作台 | `pages/wb` | web-view 打开电脑端工作台(做题、讲一遍、解析、周报) | 工作台 |
|
||||
| 我的 | `pages/me` | 六组:孩子 / 科目 / 提醒 / 开通 / 数据 / 关于;含删号 7 天冷静期与撤销 | P19 / P20 |
|
||||
|
||||
@@ -68,7 +68,7 @@ curl -X POST http://127.0.0.1:8000/api/auth/wx-login -H "Content-Type: applicati
|
||||
|
||||
原来的 `quiz` / `explain` / `report` / `print` 四个页面已移到 `miniprogram/_legacy/`(不在 `app.json` 的 pages 里,不参与编译),保留代码是为了以后要做「手机也能做题」时能捡回来。
|
||||
|
||||
底部没有 tabBar:主流程是「拍一张 → 去工作台」,走完就结束,不引导逗留。
|
||||
底部三个 tab:首页 / 拍题 / 我的。主流程仍是「拍一张 → 去工作台」,走完就结束,不引导逗留。
|
||||
|
||||
---
|
||||
|
||||
@@ -79,13 +79,16 @@ curl -X POST http://127.0.0.1:8000/api/auth/wx-login -H "Content-Type: applicati
|
||||
- 一开始画的是线性,实际缩到 tab 上只有 27px、线宽剩 2px,浅色底(`#FFFDF7`)上会**发虚**、像没对齐;
|
||||
面性缩到 27px 仍是完整剪影,对比更强。这也是为什么细节只能靠**镂空**、不能靠描边。
|
||||
- 未选中 `#9A8C7A`、选中 `#E4634A`,与 tabBar 文字色一致;底色透明,所以深色模式或换底都不用重画。
|
||||
- 排题图标刻意**不放算式**:`+`、`-` 在 27px 下会糊成一团。圆点 + 长条读作「题单/排队」,语义比算式准。
|
||||
- 拍题图标是**描边**相机(`shoot.png` / `shoot-on.png`):镜头是空心圆,做剪影会糊成一坨,所以这一枚是 2px 描边、27px 下仍能认出是相机。改名时一并换掉(旧版是圆点 + 长条,读作题单)。
|
||||
|
||||
## 三、接口对照(后端 39 条里用到的 18 条)
|
||||
## 三、接口对照(后端 60 条里用到的这些)
|
||||
|
||||
| 小程序动作 | 接口 |
|
||||
|---|---|
|
||||
| 登录 | `POST /api/auth/wx-login {code}` |
|
||||
| 拍题·切块 | `POST /api/papers/scan/detect {image_b64, filename}` → `{draft_id, width, height, blocks[{i, box, stem, judge_type, subs}]}` |
|
||||
| 拍题·逐条预览 | `POST /api/papers/scan/prepare {child_id, subject, draft_id, picks}` → `items[{block, sub, stem, tag}]` |
|
||||
| 拍题·入库 | `POST /api/papers/scan/import {child_id, subject, draft_id, picks}`,`picks` 可为 `3` 或 `{i:3, subs:[0,2]}` |
|
||||
| 同意 | `POST /api/consent {version:"v1"}` |
|
||||
| 建档 / 切孩子 | `POST /api/children`、`GET /api/children`、`GET /api/children/{cid}` |
|
||||
| 拍卷 | `POST /api/papers {child_id, subject, image_count}` |
|
||||
|
||||
@@ -30,9 +30,9 @@
|
||||
},
|
||||
{
|
||||
"pagePath": "pages/queue/queue",
|
||||
"text": "排题",
|
||||
"iconPath": "images/tab/queue.png",
|
||||
"selectedIconPath": "images/tab/queue-on.png"
|
||||
"text": "拍题",
|
||||
"iconPath": "images/tab/shoot.png",
|
||||
"selectedIconPath": "images/tab/shoot-on.png"
|
||||
},
|
||||
{
|
||||
"pagePath": "pages/me/me",
|
||||
@@ -46,3 +46,4 @@
|
||||
"sitemapLocation": "sitemap.json",
|
||||
"lazyCodeLoading": "requiredComponents"
|
||||
}
|
||||
|
||||
|
||||
|
Before Width: | Height: | Size: 1.6 KiB |
|
Before Width: | Height: | Size: 1.6 KiB |
|
After Width: | Height: | Size: 3.6 KiB |
|
After Width: | Height: | Size: 3.6 KiB |
@@ -70,7 +70,7 @@ Page({
|
||||
wx.navigateTo({ url: "/pages/wb/wb" });
|
||||
},
|
||||
|
||||
/** 排题是 tab,必须用 switchTab */
|
||||
/** 拍题是 tab,必须用 switchTab */
|
||||
onQueue() {
|
||||
wx.switchTab({ url: "/pages/queue/queue" });
|
||||
},
|
||||
@@ -80,3 +80,4 @@ Page({
|
||||
wx.stopPullDownRefresh();
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -27,7 +27,7 @@
|
||||
<view class="card empty" wx:elif="{{!loading}}">
|
||||
<view class="emptyh">今天没有到期的题</view>
|
||||
<view class="muted">明天再来,或者现在去拍一张今天做错的作业。</view>
|
||||
<button class="btn ghost" style="margin-top:14px" bindtap="onQueue">去排题</button>
|
||||
<button class="btn ghost" style="margin-top:14px" bindtap="onQueue">去拍题</button>
|
||||
</view>
|
||||
|
||||
<!-- ② 提醒 -->
|
||||
@@ -66,3 +66,4 @@
|
||||
</view>
|
||||
</view>
|
||||
</view>
|
||||
|
||||
|
||||
@@ -11,25 +11,42 @@ function estimate(queue) {
|
||||
return Math.max(1, Math.round(sec / 60));
|
||||
}
|
||||
|
||||
/** 一块里有几道:口算卡一块十几道,靠 subs 判断。 */
|
||||
function qtyOf(block) {
|
||||
const n = (block && block.subs && block.subs.length) || 0;
|
||||
return n > 1 ? n : 1;
|
||||
}
|
||||
|
||||
Page({
|
||||
data: {
|
||||
mode: "photo",
|
||||
images: [],
|
||||
subject: "math",
|
||||
subjects: [
|
||||
{ k: "math", name: "数学" },
|
||||
{ k: "chinese", name: "语文" },
|
||||
],
|
||||
questions: [],
|
||||
|
||||
// 拍照 → 切块 → 点选
|
||||
photo: "",
|
||||
draft: "",
|
||||
blocks: [],
|
||||
pickedBlocks: 0,
|
||||
pickedQty: 0,
|
||||
detecting: false,
|
||||
cutInfo: "",
|
||||
cutting: false,
|
||||
|
||||
// 逐条勾选(一块多道)
|
||||
pickItems: [],
|
||||
pickOpen: false,
|
||||
importing: false,
|
||||
|
||||
// 手输
|
||||
stem: "",
|
||||
answer: "",
|
||||
isChoice: false,
|
||||
optionsText: "",
|
||||
saving: false,
|
||||
|
||||
// 题单预览
|
||||
queue: { n: 0, minutes: 0 },
|
||||
},
|
||||
@@ -43,11 +60,12 @@ Page({
|
||||
},
|
||||
|
||||
onSubject(e) {
|
||||
this.setData({ subject: e.currentTarget.dataset.k, questions: [] });
|
||||
this.setData({ subject: e.currentTarget.dataset.k, blocks: [], pickedBlocks: 0, pickedQty: 0, cutInfo: "" });
|
||||
},
|
||||
|
||||
onToggleMode() {
|
||||
this.setData({ mode: this.data.mode === "photo" ? "manual" : "photo", cutInfo: "" });
|
||||
const mode = this.data.mode === "photo" ? "manual" : "photo";
|
||||
this.setData({ mode, cutInfo: "" });
|
||||
},
|
||||
|
||||
/** 排完看一眼今天几道、大概几分钟 */
|
||||
@@ -64,7 +82,7 @@ Page({
|
||||
|
||||
onPick() {
|
||||
wx.chooseMedia({
|
||||
count: 3,
|
||||
count: 1,
|
||||
mediaType: ["image"],
|
||||
sourceType: ["camera", "album"],
|
||||
camera: "back",
|
||||
@@ -72,7 +90,9 @@ Page({
|
||||
const images = (res.tempFiles || []).map((f) => f.tempFilePath);
|
||||
if (!images.length) return;
|
||||
this.checkSize(images).then((ok) => {
|
||||
if (ok) this.setData({ images });
|
||||
if (!ok) return;
|
||||
this.setData({ photo: images[0], blocks: [], pickedBlocks: 0, pickedQty: 0, cutInfo: "" });
|
||||
this.onDetect();
|
||||
});
|
||||
},
|
||||
});
|
||||
@@ -111,131 +131,214 @@ Page({
|
||||
});
|
||||
},
|
||||
|
||||
onCut() {
|
||||
if (!this.data.images.length) {
|
||||
wx.showToast({ title: "先拍一张", icon: "none" });
|
||||
return;
|
||||
}
|
||||
if (this.data.cutting) return;
|
||||
this.setData({ cutting: true });
|
||||
|
||||
/** 整页 → 切成块 → 把框画在图上,等家长点 */
|
||||
onDetect() {
|
||||
if (!this.data.photo || this.data.detecting) return;
|
||||
const child = getApp().globalData.child;
|
||||
const fs = wx.getFileSystemManager();
|
||||
wx.showLoading({ title: "识别中", mask: true });
|
||||
if (!child) return;
|
||||
this.setData({ detecting: true, cutInfo: "" });
|
||||
wx.showLoading({ title: "切题中", mask: true });
|
||||
|
||||
// 手机拍出来 3–8MB,直接 base64 会撞 wx.request 的包体上限,先压到长边 1600、质量 72。
|
||||
const send = (filePath) => {
|
||||
fs.readFile({
|
||||
filePath,
|
||||
encoding: "base64",
|
||||
success: (f) => {
|
||||
api
|
||||
.post("/api/papers/ocr", {
|
||||
child_id: child.id,
|
||||
subject: this.data.subject,
|
||||
image_b64: f.data,
|
||||
filename: "page.jpg",
|
||||
fallback_demo: false,
|
||||
})
|
||||
.then((p) => this.afterCut(p))
|
||||
.catch((e) => this.onCutFail(e))
|
||||
.then(() => wx.hideLoading());
|
||||
},
|
||||
fail: () => {
|
||||
wx.hideLoading();
|
||||
wx.showToast({ title: "读不到这张图", icon: "none" });
|
||||
this.setData({ cutting: false });
|
||||
},
|
||||
const done = () => {
|
||||
wx.hideLoading();
|
||||
this.setData({ detecting: false });
|
||||
};
|
||||
const fail = (e) => {
|
||||
done();
|
||||
const msg = (e && e.message) || "这次没切出来";
|
||||
wx.showModal({
|
||||
title: "这次没切出来",
|
||||
content: msg + "\n\n可以:① 卷子放平、光线亮一点重拍;② 换个科目试试;③ 这道题改成手输。",
|
||||
showCancel: false,
|
||||
});
|
||||
};
|
||||
|
||||
// 手机拍出来 3–8MB,直接 base64 会撞 wx.request 的包体上限,先压到长边 1600、质量 72。
|
||||
wx.compressImage({
|
||||
src: this.data.images[0],
|
||||
src: this.data.photo,
|
||||
quality: 72,
|
||||
compressedWidth: 1600,
|
||||
success: (r) => send(r.tempFilePath || this.data.images[0]),
|
||||
fail: () => send(this.data.images[0]),
|
||||
success: (r) => this.sendDetect(r.tempFilePath || this.data.photo, done, fail),
|
||||
fail: () => this.sendDetect(this.data.photo, done, fail),
|
||||
});
|
||||
},
|
||||
|
||||
afterCut(p) {
|
||||
const questions = (p.questions || []).map((q) => ({
|
||||
...q,
|
||||
checked: true,
|
||||
tag: (q.judge_type === "manual" ? "你自己判" : "机器判") + " · " + (q.subject === "chinese" ? "语文" : "数学"),
|
||||
}));
|
||||
const ocr = p.ocr || {};
|
||||
let info = "";
|
||||
if (ocr.ok) {
|
||||
info = "识别到 " + ocr.lines + " 行,切出 " + questions.length + " 道题";
|
||||
if (ocr.warn) info += "\n" + ocr.warn;
|
||||
} else {
|
||||
info = "没认出题,可以手动拍清楚一点,或者改成手输";
|
||||
// 小图 / 太糊时,后端会带一句「这张图只有 400×520」——比「没认出题」有用得多
|
||||
if (ocr.warn) info = ocr.warn + "\n" + info;
|
||||
}
|
||||
this.setData({ questions, cutting: false, cutInfo: info });
|
||||
},
|
||||
|
||||
/** 识别失败:给「用演示题库」这条后路,而不是卡死在这儿。 */
|
||||
onCutFail(e) {
|
||||
this.setData({ cutting: false });
|
||||
wx.hideLoading();
|
||||
const msg = (e && e.message) || "没认出来";
|
||||
wx.showModal({
|
||||
title: "这次没认出来",
|
||||
content: msg + "\n\n可以:① 把卷子放平、光线亮一点重拍;② 这道题改成手输;③ 先用演示题库走一遍流程。",
|
||||
confirmText: "用演示题库",
|
||||
cancelText: "重新拍",
|
||||
success: (r) => {
|
||||
if (!r.confirm) return;
|
||||
this.setData({ cutting: true });
|
||||
sendDetect(filePath, done, fail) {
|
||||
wx.getFileSystemManager().readFile({
|
||||
filePath,
|
||||
encoding: "base64",
|
||||
success: (f) => {
|
||||
api
|
||||
.post("/api/papers/ocr", {
|
||||
child_id: getApp().globalData.child.id,
|
||||
subject: this.data.subject,
|
||||
image_b64: "ZGVtbw==",
|
||||
filename: "demo.jpg",
|
||||
fallback_demo: true,
|
||||
})
|
||||
.then((p) => this.afterCut(p))
|
||||
.catch((err) => api.toastError(err))
|
||||
.then(() => this.setData({ cutting: false }));
|
||||
.post("/api/papers/scan/detect", { image_b64: f.data, filename: "page.jpg" })
|
||||
.then((r) => this.afterDetect(r))
|
||||
.catch((e) => fail(e))
|
||||
.then(done);
|
||||
},
|
||||
fail: () => {
|
||||
done();
|
||||
wx.showToast({ title: "读不到这张图", icon: "none" });
|
||||
},
|
||||
});
|
||||
},
|
||||
|
||||
toggleQ(e) {
|
||||
const i = Number(e.currentTarget.dataset.i);
|
||||
const questions = this.data.questions.slice();
|
||||
questions[i].checked = !questions[i].checked;
|
||||
this.setData({ questions });
|
||||
afterDetect(r) {
|
||||
const w = r.width || 1;
|
||||
const h = r.height || 1;
|
||||
const blocks = (r.blocks || []).map((b) => {
|
||||
const box = b.box || { x: 0, y: 0, w: 0, h: 0 };
|
||||
const n = qtyOf(b);
|
||||
return {
|
||||
i: b.i,
|
||||
stem: b.stem || "",
|
||||
judge_type: b.judge_type || "manual",
|
||||
n,
|
||||
on: false,
|
||||
px: (box.x / w) * 100,
|
||||
py: (box.y / h) * 100,
|
||||
pw: (box.w / w) * 100,
|
||||
ph: (box.h / h) * 100,
|
||||
};
|
||||
});
|
||||
const info = blocks.length
|
||||
? "切出 " + blocks.length + " 块。点你觉得做错的那几道(可多选),再点下面的按钮。"
|
||||
: "这一页没切出整块的题。可以重拍一张,或者改成手输。";
|
||||
this.setData({ draft: r.draft_id || "", blocks, cutInfo: info, pickedBlocks: 0, pickedQty: 0 });
|
||||
},
|
||||
|
||||
toggleBlock(e) {
|
||||
const i = Number(e.currentTarget.dataset.i);
|
||||
const blocks = this.data.blocks.slice();
|
||||
const idx = blocks.findIndex((b) => b.i === i);
|
||||
if (idx < 0) return;
|
||||
blocks[idx].on = !blocks[idx].on;
|
||||
if (wx.vibrateShort) wx.vibrateShort({ type: "light" });
|
||||
const on = blocks.filter((b) => b.on);
|
||||
this.setData({
|
||||
blocks,
|
||||
pickedBlocks: on.length,
|
||||
pickedQty: on.reduce((s, b) => s + b.n, 0),
|
||||
});
|
||||
},
|
||||
|
||||
onRetake() {
|
||||
this.setData({ photo: "", draft: "", blocks: [], pickedBlocks: 0, pickedQty: 0, cutInfo: "" });
|
||||
},
|
||||
|
||||
/** 入库前:一块多道就先摊开逐条勾;都是单题就直接入库 */
|
||||
onImport() {
|
||||
const ids = this.data.questions.filter((q) => q.checked).map((q) => q.id);
|
||||
if (!ids.length) {
|
||||
wx.showToast({ title: "一道都没选", icon: "none" });
|
||||
const picked = this.data.blocks.filter((b) => b.on);
|
||||
if (!picked.length) {
|
||||
wx.showToast({ title: "先点选做错的题", icon: "none" });
|
||||
return;
|
||||
}
|
||||
if (this.data.importing) return;
|
||||
this.setData({ importing: true });
|
||||
|
||||
if (!picked.some((b) => b.n > 1)) {
|
||||
this.doImport(picked.map((b) => b.i));
|
||||
return;
|
||||
}
|
||||
this.preparePicks(picked.map((b) => b.i));
|
||||
},
|
||||
|
||||
preparePicks(picks) {
|
||||
const child = getApp().globalData.child;
|
||||
this.setData({ importing: true });
|
||||
wx.showLoading({ title: "整理中", mask: true });
|
||||
api
|
||||
.post("/api/mistakes/import", {
|
||||
child_id: getApp().globalData.child.id,
|
||||
question_ids: ids,
|
||||
.post("/api/papers/scan/prepare", {
|
||||
child_id: child.id,
|
||||
subject: this.data.subject,
|
||||
draft_id: this.data.draft,
|
||||
picks,
|
||||
})
|
||||
.then((r) => {
|
||||
const n = (r.created || []).length;
|
||||
this.setData({ importing: false, questions: [] });
|
||||
const items = (r.items || []).map((it, k) => ({
|
||||
k,
|
||||
block: it.block,
|
||||
sub: it.sub,
|
||||
stem: it.stem || "",
|
||||
tag: it.sub === null || it.sub === undefined ? "单题" : "第 " + (it.sub + 1) + " 道",
|
||||
on: true,
|
||||
}));
|
||||
this.setData({ pickItems: items, pickOpen: true, importing: false });
|
||||
})
|
||||
.catch((e) => {
|
||||
api.toastError(e);
|
||||
this.setData({ importing: false });
|
||||
})
|
||||
.then(() => wx.hideLoading());
|
||||
},
|
||||
|
||||
togglePick(e) {
|
||||
const k = Number(e.currentTarget.dataset.k);
|
||||
const pickItems = this.data.pickItems.slice();
|
||||
if (!pickItems[k]) return;
|
||||
pickItems[k].on = !pickItems[k].on;
|
||||
if (wx.vibrateShort) wx.vibrateShort({ type: "light" });
|
||||
this.setData({ pickItems });
|
||||
},
|
||||
|
||||
onPickAll() {
|
||||
const pickItems = this.data.pickItems.map((it) => ({ ...it, on: true }));
|
||||
this.setData({ pickItems });
|
||||
},
|
||||
|
||||
onPickNone() {
|
||||
const pickItems = this.data.pickItems.map((it) => ({ ...it, on: false }));
|
||||
this.setData({ pickItems });
|
||||
},
|
||||
|
||||
closePick() {
|
||||
this.setData({ pickOpen: false, pickItems: [] });
|
||||
},
|
||||
|
||||
confirmPick() {
|
||||
const on = this.data.pickItems.filter((it) => it.on);
|
||||
if (!on.length) {
|
||||
wx.showToast({ title: "一道都没勾", icon: "none" });
|
||||
return;
|
||||
}
|
||||
// 单题还原成块号;多道按块归组 {i, subs:[...]}
|
||||
const singles = [];
|
||||
const grouped = {};
|
||||
on.forEach((it) => {
|
||||
if (it.sub === null || it.sub === undefined) singles.push(it.block);
|
||||
else {
|
||||
grouped[it.block] = grouped[it.block] || [];
|
||||
grouped[it.block].push(it.sub);
|
||||
}
|
||||
});
|
||||
const picks = singles.slice();
|
||||
Object.keys(grouped).forEach((b) => picks.push({ i: Number(b), subs: grouped[b] }));
|
||||
this.setData({ pickOpen: false, pickItems: [] });
|
||||
this.doImport(picks);
|
||||
},
|
||||
|
||||
doImport(picks) {
|
||||
const child = getApp().globalData.child;
|
||||
if (this.data.importing) return;
|
||||
this.setData({ importing: true });
|
||||
wx.showLoading({ title: "入库中", mask: true });
|
||||
|
||||
api
|
||||
.post("/api/papers/scan/import", {
|
||||
child_id: child.id,
|
||||
subject: this.data.subject,
|
||||
draft_id: this.data.draft,
|
||||
picks,
|
||||
})
|
||||
.then((r) => {
|
||||
const ocr = r.ocr || {};
|
||||
const n = ocr.created === undefined ? (ocr.questions || 0) : ocr.created;
|
||||
this.setData({ photo: "", draft: "", blocks: [], pickedBlocks: 0, pickedQty: 0, cutInfo: "", importing: false });
|
||||
wx.showToast({ title: "入库 " + n + " 道", icon: "success" });
|
||||
this.loadQueue();
|
||||
})
|
||||
.catch((e) => {
|
||||
api.toastError(e);
|
||||
this.setData({ importing: false });
|
||||
});
|
||||
})
|
||||
.then(() => wx.hideLoading());
|
||||
},
|
||||
|
||||
// ---------------- 手输一道
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
{
|
||||
"navigationBarTitleText": "排题",
|
||||
"navigationBarTitleText": "拍题",
|
||||
"enablePullDownRefresh": false
|
||||
}
|
||||
|
||||
|
||||
@@ -4,25 +4,42 @@
|
||||
<view class="chip mode" bindtap="onToggleMode">{{mode === "photo" ? "改成手输" : "改成拍一张"}}</view>
|
||||
</view>
|
||||
|
||||
<!-- ① 拍一张 -->
|
||||
<!-- ① 拍一张 → 切块 → 点选 -->
|
||||
<block wx:if="{{mode === 'photo'}}">
|
||||
<view class="shot {{subject === 'chinese' ? 'chn' : 'math'}}" bindtap="onPick">
|
||||
<block wx:if="{{images.length}}">
|
||||
<image class="thumb" src="{{images[0]}}" mode="aspectFill" />
|
||||
<view class="shot-n">已选 {{images.length}} 张,点一下重拍</view>
|
||||
</block>
|
||||
<block wx:else>
|
||||
<view class="plus">+</view>
|
||||
<view class="shot-t">整页拍一张</view>
|
||||
<view class="shot-s">卷子放平、光打亮,一次拍半页(5–8 道)最准</view>
|
||||
</block>
|
||||
<view wx:if="{{!photo}}" class="shot {{subject === 'chinese' ? 'chn' : 'math'}}" bindtap="onPick">
|
||||
<view class="plus">+</view>
|
||||
<view class="shot-t">整页拍一张</view>
|
||||
<view class="shot-s">卷子放平、光打亮,一次拍半页(5–8 道)最准</view>
|
||||
</view>
|
||||
|
||||
<button class="btn" bindtap="onCut" disabled="{{cutting}}">
|
||||
{{cutting ? "识别中…" : "识别这一页"}}
|
||||
</button>
|
||||
<block wx:else>
|
||||
<view class="stage">
|
||||
<image class="page" src="{{photo}}" mode="widthFix" />
|
||||
<view class="overlay">
|
||||
<view
|
||||
wx:for="{{blocks}}"
|
||||
wx:key="i"
|
||||
class="blk {{item.on ? 'on' : ''}}"
|
||||
style="left:{{item.px}}%; top:{{item.py}}%; width:{{item.pw}}%; height:{{item.ph}}%"
|
||||
data-i="{{item.i}}"
|
||||
catchtap="toggleBlock"
|
||||
>
|
||||
<view class="blk-n">{{item.i + 1}}<text wx:if="{{item.n > 1}}" class="blk-more">×{{item.n}}</text></view>
|
||||
</view>
|
||||
</view>
|
||||
</view>
|
||||
|
||||
<view class="cutinfo" wx:if="{{cutInfo}}">{{cutInfo}}</view>
|
||||
<view class="cutinfo" wx:if="{{cutInfo}}">{{cutInfo}}</view>
|
||||
|
||||
<view class="row2" wx:if="{{blocks.length}}">
|
||||
<button class="btn plain half" bindtap="onRetake" disabled="{{importing}}">重拍</button>
|
||||
<button class="btn half" bindtap="onImport" disabled="{{detecting || importing || !pickedBlocks}}">
|
||||
{{importing ? "入库中…" : (pickedBlocks ? "入库选中的 " + pickedQty + " 道" : "先点选做错的")}}
|
||||
</button>
|
||||
</view>
|
||||
</block>
|
||||
|
||||
<view class="muted small" wx:if="{{photo}}" style="margin-top:8px">看不清就点「重拍」;切多切少无所谓,最后是你在图上点。</view>
|
||||
</block>
|
||||
|
||||
<!-- ② 手输一道 -->
|
||||
@@ -57,35 +74,42 @@
|
||||
</view>
|
||||
</block>
|
||||
|
||||
<!-- ③ 切出来的题:勾选 -->
|
||||
<view class="card" style="margin-top:18px" wx:if="{{questions.length}}">
|
||||
<view class="card-title">切出 {{questions.length}} 道,把做错的勾上</view>
|
||||
<view class="muted" style="margin-bottom:6px">默认全选,你只需要取消勾选「做对了」的。</view>
|
||||
<view class="q" wx:for="{{questions}}" wx:key="id" data-i="{{index}}" bindtap="toggleQ">
|
||||
<view class="box {{item.checked ? 'on' : ''}}">{{item.checked ? "✓" : ""}}</view>
|
||||
<!-- ③ 一块多道:逐条勾选 -->
|
||||
<view class="card" style="margin-top:16px" wx:if="{{pickOpen}}">
|
||||
<view class="card-title">这块里有几道?</view>
|
||||
<view class="muted" style="margin-bottom:8px">口算卡一块十几道,切题时会把没做错的也一起切进来。取消不要的那几道再入库。</view>
|
||||
|
||||
<view class="q" wx:for="{{pickItems}}" wx:key="k" data-k="{{index}}" bindtap="togglePick">
|
||||
<view class="box {{item.on ? 'on' : ''}}">{{item.on ? "✓" : ""}}</view>
|
||||
<view class="qmain">
|
||||
<view class="qstem">{{item.stem}}</view>
|
||||
<view class="qstem {{item.on ? '' : 'off'}}">{{item.stem}}</view>
|
||||
<view class="muted small">{{item.tag}}</view>
|
||||
</view>
|
||||
</view>
|
||||
<button class="btn" style="margin-top:14px" bindtap="onImport" disabled="{{importing}}">
|
||||
{{importing ? "入库中…" : "加入错题本"}}
|
||||
|
||||
<view class="row2" style="margin-top:12px">
|
||||
<button class="btn plain half" bindtap="onPickNone">全不勾</button>
|
||||
<button class="btn plain half" bindtap="onPickAll">全勾</button>
|
||||
</view>
|
||||
<button class="btn" style="margin-top:10px" bindtap="confirmPick" disabled="{{importing}}">
|
||||
{{importing ? "入库中…" : "入库勾上的"}}
|
||||
</button>
|
||||
<view class="muted small" style="margin-top:6px" bindtap="closePick">先不入库,回去重新点</view>
|
||||
</view>
|
||||
|
||||
<!-- ④ 题单预览:排完就地显示今天的量 -->
|
||||
<!-- ④ 题单预览 -->
|
||||
<view class="card queue" wx:if="{{queue.n > 0}}">
|
||||
<view class="card-title">排好了</view>
|
||||
<view class="card-title">今天的题单</view>
|
||||
<view class="qbig">
|
||||
<text class="qnum">{{queue.n}}</text>
|
||||
<text class="qunit">道 · 约 {{queue.minutes}} 分钟</text>
|
||||
</view>
|
||||
<view class="muted">按遗忘曲线排的,错的多的先做。做完这两件事就结束:连对两次、讲一遍。</view>
|
||||
<button class="btn" style="margin-top:12px" bindtap="onWorkbench">去工作台做题</button>
|
||||
<view class="muted small" style="margin-top:8px">手机上只排题,做题在电脑或平板上——题目和解析要横着看。</view>
|
||||
<view class="muted small" style="margin-top:8px">手机上拍题,做题在电脑或平板上——题目和解析要横着看。</view>
|
||||
</view>
|
||||
|
||||
<view class="note">
|
||||
{{mode === "photo" ? "识别用的是本机的 Windows 中文 OCR(不联网、不上传第三方)。算式的答案会自己算出来;应用题、看拼音写词这类没有标准答案的,标成「你自己判」。" : "手输适合几种情况:卷子已经扔了、老师口头报的题、错题想马上记一道。题干抄关键词就行,不用一字不差。"}}
|
||||
{{mode === "photo" ? "拍一整页,系统先切成块;你在图上点哪几道做错了,只把点中的裁出来单独识别。算式的答案会自己算出来;应用题、看拼音写词这类没有标准答案的,标成「你自己判」。" : "手输适合几种情况:卷子已经扔了、老师口头报的题、错题想马上记一道。题干抄关键词就行,不用一字不差。"}}
|
||||
</view>
|
||||
</view>
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
.chip.on { background: var(--brand); border-color: var(--brand); color: #fff; }
|
||||
.chip.mode { margin-left: auto; color: var(--brand); border-color: #f0cfc4; background: #fff7f4; }
|
||||
|
||||
/* 空着的时候:一个大方框让人点 */
|
||||
.shot {
|
||||
position: relative; height: 210px; border-radius: 16px; border: 2px dashed #e0d5c9;
|
||||
display: flex; flex-direction: column; align-items: center; justify-content: center;
|
||||
@@ -13,8 +14,28 @@
|
||||
.plus { font-size: 40px; color: #c9bda9; line-height: 1; }
|
||||
.shot-t { margin-top: 8px; font-size: 15px; font-weight: 700; }
|
||||
.shot-s { margin-top: 4px; font-size: 12px; color: var(--muted); }
|
||||
.thumb { width: 100%; height: 100%; }
|
||||
.shot-n { position: absolute; bottom: 10px; font-size: 11px; color: #6b6560; background: rgba(255,255,255,.9); padding: 3px 10px; border-radius: 999px; }
|
||||
|
||||
/* 拍完:图 + 切块框 */
|
||||
.stage { position: relative; margin-bottom: 10px; border-radius: 16px; overflow: hidden; border: 1px solid var(--line); background: #fff; }
|
||||
.page { display: block; width: 100%; }
|
||||
.overlay { position: absolute; left: 0; top: 0; right: 0; bottom: 0; }
|
||||
.blk {
|
||||
position: absolute; border: 2px dashed rgba(140,130,120,.55); border-radius: 8px;
|
||||
background: rgba(255,255,255,.04);
|
||||
}
|
||||
.blk.on { border: 2px solid var(--brand); background: rgba(179,39,45,.16); }
|
||||
.blk-n {
|
||||
position: absolute; left: -2px; top: -2px; min-width: 18px; height: 18px; line-height: 18px;
|
||||
padding: 0 5px; border-radius: 8px 0 8px 0; background: rgba(140,130,120,.92);
|
||||
color: #fff; font-size: 11px; text-align: center;
|
||||
}
|
||||
.blk.on .blk-n { background: var(--brand); }
|
||||
.blk-more { font-size: 10px; }
|
||||
|
||||
/* 并排两个按钮 */
|
||||
.row2 { display: flex; gap: 10px; }
|
||||
.row2 .btn { flex: 1; }
|
||||
.btn.half { width: auto; }
|
||||
|
||||
/* 手输 */
|
||||
.ta {
|
||||
@@ -28,6 +49,7 @@
|
||||
background: #fff; font-size: 15px;
|
||||
}
|
||||
|
||||
/* 逐条勾选 */
|
||||
.q { display: flex; gap: 10px; align-items: flex-start; padding: 11px 0; border-bottom: 1px solid #f5efe8; }
|
||||
.q:last-of-type { border-bottom: none; }
|
||||
.box {
|
||||
@@ -38,9 +60,10 @@
|
||||
.box.on { background: var(--brand); border-color: var(--brand); }
|
||||
.qmain { flex: 1; }
|
||||
.qstem { font-size: 14px; line-height: 1.5; }
|
||||
.qstem.off { color: #b7afa8; text-decoration: line-through; }
|
||||
|
||||
/* 题单预览 */
|
||||
.queue { border: 1px solid #f0cfc4; background: #fffaf7; }
|
||||
.queue { border: 1px solid #f0cfc4; background: #fffaf7; margin-top: 16px; }
|
||||
.qbig { display: flex; align-items: baseline; gap: 8px; margin: 6px 0 8px; }
|
||||
.qnum { font-size: 34px; font-weight: 800; color: var(--brand); line-height: 1; }
|
||||
.qunit { font-size: 13px; color: #6b6560; }
|
||||
@@ -48,7 +71,7 @@
|
||||
.note { margin-top: 18px; padding: 11px 13px; background: #fff; border: 1px solid var(--line); border-radius: 12px; font-size: 11px; color: #9a938c; line-height: 1.7; }
|
||||
|
||||
.cutinfo {
|
||||
margin-top: 10px; padding: 8px 12px; border-radius: 10px;
|
||||
margin: 0 0 12px; padding: 9px 12px; border-radius: 10px;
|
||||
background: #fbf2e1; border: 1px solid #ecd9b6; color: #7a6440; font-size: 12px;
|
||||
white-space: pre-line; line-height: 1.6;
|
||||
}
|
||||
|
||||
@@ -231,3 +231,91 @@ node tools/verify_plan.mjs # → data/plan_verify.md
|
||||
数字对、话是废话。改成按小数位数缩放后取最低位。
|
||||
4. **没有闸门**:新增 `planClaims()` / `planConsistent()`,生成完回头重算,
|
||||
算不通或答案没出现就 `return null`,由上层退回通用三步。
|
||||
|
||||
## 十三、这块里有几道:入库前逐条勾选
|
||||
|
||||
口算卡一块十几道。切题偶尔会把孩子没做错的题切进来,或者把 `27+69` 读成
|
||||
`77+69`。上一版的做法是「宁多不漏」——整块入库,让家长事后一条条删。这一版把
|
||||
最后这个决定权还给家长:
|
||||
|
||||
1. 在图上点错题(原有流程,不变);
|
||||
2. 点「入库选中的 N 道」后,只要勾中的块里有**一块多道**,就先弹一张单子,
|
||||
把这块里认出来的每一道摊开,默认全勾,家长取消掉没做错的;
|
||||
3. 确认后只入库勾上的那几道:单题的块传块序号,多题的块传 `{i, subs:[…]}`。
|
||||
|
||||
单子里的序号(第 1 道、第 2 道…)与 `subs` 数组下标一一对应,取消的会划掉,
|
||||
计数按钮同步变。预览这一步只读不写,`recognize_block` 的裁剪图按 sha1 命中
|
||||
OCR 缓存,所以预览过一遍之后,正式入库不会再花一次调用。
|
||||
|
||||
只有一块一道题的时候不会弹这张单子——多一次点击换不来任何信息。
|
||||
|
||||
## 十四、三色与收尾页
|
||||
|
||||
错题本原来的筛选是「七个状态」,家长看不懂「待讲清」和「会但不稳」有什么区别。
|
||||
现在默认只显示两个颜色,状态名藏到第二行里。
|
||||
|
||||
| 颜色 | 里面是哪几个状态 | 家长要做的事 |
|
||||
|---|---|---|
|
||||
| 红 | `observing`、`queued` | 还没过关,等它到期 |
|
||||
| 黄 | `unstable`、`passed_once`、`to_explain` | 今天/这几天要重做或要讲 |
|
||||
| 绿 | `graduated` | 不用再看了 |
|
||||
| 灰 | `careless` | 粗心小记,不重做 |
|
||||
|
||||
- 默认筛「待做」=红+黄;标题下一行写「还剩 7 道:红 3 · 黄 4;绿叶 2 道不用再看了。」
|
||||
- 每个 chip 后面带计数,数字由 `renderWrong()` 现算,不是写死的。
|
||||
- 第二行 chips 保留原来的状态筛选(观察中/待复习/已对一次/待讲清/会但不稳/已毕业),
|
||||
需要精确看某一类时才用。
|
||||
- 顺手修了一个真 bug:「已对一次」原来写 `data-s="recalled"`,而状态名是 `passed_once`,
|
||||
点它永远是空列表。
|
||||
|
||||
**收尾页**(`endRound()`,一轮做完之后):不再停在第 5 题的解析上,而是给三句话——
|
||||
「今天到此为止,5 道做完了」「一次就对 4 · 明天再来 1 · 今天毕业 1」,
|
||||
外加一句具体的话:
|
||||
|
||||
- 有题毕业:`你把「36 × 24 =」讲明白了——它从本子上消失了,不用再做了。`
|
||||
- 一道没对:`没关系,明天同一时间再来一次,只要 4 分钟。`
|
||||
- 中间的档:按对了几道说「今天稳住了 X 道」。
|
||||
|
||||
规矩:**表扬行为,不表扬人**(不写「你真棒」「你真聪明」),也不发积分/贴纸——
|
||||
外部奖励一停就失效,而且会和「错题变少」这个客观进度重复计量。
|
||||
|
||||
## 十五、刚才卡在哪(`stuck_at`)
|
||||
|
||||
讲清失败时才问一次,四个按钮,即点即走,**不弹输入框**:
|
||||
|
||||
| 值 | 按钮文案 | 意思 |
|
||||
|---|---|---|
|
||||
| `read` | 题没读懂 | 卡在审题 |
|
||||
| `plan` | 不知道从哪下手 | 卡在思路 |
|
||||
| `calc` | 会做,算错了 | 卡在计算 |
|
||||
| `check` | 没检查 | 卡在验收 |
|
||||
|
||||
- 只在 `explain` 返回 `ask_stuck_at: true` 时出现(失败、且这道题还没记过卡点)。
|
||||
- 点一下 → `POST /api/mistakes/<id>/stuck` → 变成绿条「记下了:会做,算错了」,不打断流程。
|
||||
- 记过就不再问第二次;同一道题反复失败也只记第一次,避免家长被追问。
|
||||
- 这个数据的用处:147 条解析模板是按知识点分的,等 `stuck_at` 攒够了才能按**卡点**重排。
|
||||
|
||||
## 十六、说一遍(语音讲清)
|
||||
|
||||
1–3 年级写字慢,要求打字等于把费曼变成作文。所以「讲一遍」弹窗里多了一条:
|
||||
|
||||
`开始录音` → 说完 `停止` → 回放出 audio → 勾三项 → `就这段录音`。
|
||||
|
||||
- 三项是:说清了错在哪 / 说出了正确的走法 / 说了下次怎么防。**勾全了才算讲清**。
|
||||
- 为什么是勾选不是自动判:机器判语义要 ASR + 大模型,误差比家长亲耳听大;
|
||||
这一版先保证「不打字也能提交」,等语音识别的错字率降下来再收紧成机器判。
|
||||
- 浏览器不支持 `MediaRecorder` 时按钮会提示,不影响打字那条路。
|
||||
|
||||
|
||||
## 十七、严档:第二次换一道
|
||||
|
||||
默认的毕业标准是「同一道题第二次做对」。严档把它换成「换一道没见过的同类题做对」——
|
||||
因为同题第二次常常只是记住了答案。
|
||||
|
||||
- 开关位置:设置 → 严档(默认关)。打开后写进 `children.strict_variant`。
|
||||
- 状态:原题做对 → `variant_pending`(界面显示「换一道」)→ 变式做对才 `passed_once`。
|
||||
- 界面:进训练页时如果这道题在 `variant_pending`,只保留下面那道变式的输入框,
|
||||
原题题干留着当上下文,不让孩子对着原题再写一遍。
|
||||
- 变式从哪来:`practice.similar()`,出题后过一遍 `practice.verify()`
|
||||
(能算、答案和题干一致、选择题答案在选项里),过不了的**丢弃**——出错的变式比不练更糟。
|
||||
- 代价:1–3 年级的变式是换数字(近迁移),4–6 年级还没有换情境的题库,所以目前不分档。
|
||||
|
||||
@@ -101,6 +101,7 @@ h1{font-size:22px;margin:0 0 4px}
|
||||
|
||||
.grid3{display:grid;grid-template-columns:repeat(3,1fr);gap:14px}
|
||||
.grid2{display:grid;grid-template-columns:1.55fr 1fr;gap:14px;align-items:start}
|
||||
.four{display:grid;grid-template-columns:repeat(4,1fr);gap:10px}
|
||||
.stat{padding:16px 16px 14px}
|
||||
.stat .k{font-size:12px;color:var(--muted)}
|
||||
.stat .v{font-size:26px;font-weight:700;margin:6px 0 2px;letter-spacing:.5px}
|
||||
@@ -110,6 +111,7 @@ h1{font-size:22px;margin:0 0 4px}
|
||||
.pill{display:inline-flex;align-items:center;gap:5px;font-size:11.5px;padding:2px 9px;border-radius:999px;
|
||||
background:var(--ochre-soft);color:var(--ochre);font-weight:600}
|
||||
.pill.c{background:var(--brand-soft);color:var(--brand-d)}
|
||||
.pill.r{background:var(--red-soft);color:var(--red)}
|
||||
.pill.g{background:var(--green-soft);color:var(--green)}
|
||||
.pill.b{background:var(--blue-soft);color:var(--blue)}
|
||||
.pill.o{background:var(--ochre-soft);color:var(--ochre)}
|
||||
@@ -223,6 +225,20 @@ td .t{font-family:"Consolas",monospace;font-size:13.5px}
|
||||
.chips{display:flex;gap:8px;flex-wrap:wrap;margin-bottom:14px}
|
||||
.chips button{border:1px solid var(--line);background:#fff;border-radius:999px;padding:7px 14px;font-size:12.5px;color:#5A5048}
|
||||
.chips button.on{background:var(--brand);border-color:var(--brand);color:#fff;font-weight:600}
|
||||
.chips.sub{margin-top:-6px}
|
||||
.chips.sub button{padding:5px 11px;font-size:11.5px;color:#8C8175}
|
||||
|
||||
/* 收尾页:一轮做完之后的交代(W2) */
|
||||
.round{display:grid;gap:14px}
|
||||
.round .hi{font-size:19px;font-weight:700;letter-spacing:.2px}
|
||||
.round .hi b{color:var(--brand);font-size:26px;margin:0 2px}
|
||||
.round .facts{display:flex;gap:10px;flex-wrap:wrap}
|
||||
.round .fact{background:#FBF6EC;border-radius:12px;padding:10px 14px;min-width:104px}
|
||||
.round .fact i{display:block;font-style:normal;font-size:11.5px;color:#A2958A;margin-bottom:3px}
|
||||
.round .fact b{font-size:19px}
|
||||
.round .say{background:var(--green-soft);color:var(--green);border-radius:12px;padding:11px 14px;font-size:13.5px;line-height:1.7}
|
||||
.round .say.warm{background:var(--ochre-soft);color:#7A5410}
|
||||
.round .acts{display:flex;gap:10px;flex-wrap:wrap;margin-top:2px}
|
||||
|
||||
/* 学情 */
|
||||
.barlist{display:flex;flex-direction:column;gap:12px}
|
||||
@@ -261,6 +277,45 @@ td .t{font-family:"Consolas",monospace;font-size:13.5px}
|
||||
.grid2{grid-template-columns:1fr}
|
||||
}
|
||||
|
||||
/* ---------- 手机:侧栏变底部导航,三屏可用(今日训练 / 周报 / 错题本) ---------- */
|
||||
@media (max-width:760px){
|
||||
.app{display:block;height:auto;overflow:visible}
|
||||
/* 侧栏整体下沉成底部 tab 栏 */
|
||||
.side{
|
||||
position:fixed;left:0;right:0;bottom:0;top:auto;width:auto;flex:0 0 auto;
|
||||
flex-direction:row;padding:6px 6px 8px;border-right:0;border-top:1px solid var(--line);
|
||||
background:rgba(255,253,247,.97);backdrop-filter:blur(8px);z-index:70;
|
||||
box-shadow:0 -8px 22px rgba(90,70,50,.10);
|
||||
}
|
||||
.side .logo,.side .scene,.side .foot{display:none}
|
||||
/* 底部只留六个常按的:工作台 / 今日训练 / 拍照入库 / 错题本 / 周报 / 设置 */
|
||||
.nav a[data-v="plan"],.nav a[data-v="analysis"],.nav a[data-v="grad"],
|
||||
.nav a[data-v="careless"],.nav a[data-v="kids"]{display:none}
|
||||
.nav{flex-direction:row;justify-content:space-between;gap:0;flex:1;overflow:visible;padding:0}
|
||||
.nav a{flex:1;flex-direction:column;gap:3px;padding:6px 2px;font-size:10.5px;white-space:nowrap;border-radius:12px}
|
||||
.nav a svg{width:19px;height:19px;flex:none}
|
||||
.nav .badge{margin-left:0}
|
||||
.main{height:100dvh;overflow:hidden}
|
||||
.top{height:52px;flex:0 0 52px;padding:0 12px;gap:8px}
|
||||
.top .search{display:none}
|
||||
.scroll{padding:14px 12px 96px}
|
||||
h1{font-size:20px}
|
||||
h2{font-size:16px}
|
||||
.grid2,.train{grid-template-columns:1fr}
|
||||
.rail{order:3}
|
||||
.four{grid-template-columns:1fr 1fr}
|
||||
/* 错题本:手机上收掉「错因/下次复习」两列,只留题目+状态,避免每个字竖排 */
|
||||
#wrongTable th:nth-child(3),#wrongTable td:nth-child(3),
|
||||
#wrongTable th:nth-child(5),#wrongTable td:nth-child(5){display:none}
|
||||
table{font-size:12.5px}
|
||||
th,td{padding:10px 6px;white-space:nowrap}
|
||||
.answer{flex-wrap:wrap}
|
||||
.answer .unit{flex:1 0 100%;margin-left:2px}
|
||||
#pet{display:none!important}
|
||||
.exdlg{width:100%;max-width:none;border-radius:16px 16px 0 0;padding:18px 16px}
|
||||
.mask{align-items:flex-end}
|
||||
}
|
||||
|
||||
/* ================= 宠物:墨兽 ================= */
|
||||
#pet{position:fixed;left:20px;bottom:14px;width:168px;z-index:60;user-select:none}
|
||||
#pet[hidden]{display:none}
|
||||
@@ -398,6 +453,15 @@ td .t{font-family:"Consolas",monospace;font-size:13.5px}
|
||||
.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); }
|
||||
/* 口算卡逐条勾选 */
|
||||
.pklist { max-height: 46vh; overflow: auto; margin: 6px 0 14px; border: 1px solid var(--line); border-radius: 12px; }
|
||||
.pkrow { display: flex; align-items: center; gap: 10px; padding: 10px 12px; border-bottom: 1px solid #F6EFE4; cursor: pointer; }
|
||||
.pkrow:last-child { border-bottom: 0; }
|
||||
.pkrow:hover { background: #FDF8EF; }
|
||||
.pkrow input { width: 17px; height: 17px; accent-color: var(--brand); flex: none; }
|
||||
.pkrow .pks { font-size: 14px; }
|
||||
.pkrow .pkn { font-size: 11.5px; color: var(--muted); margin-left: auto; flex: none; }
|
||||
.pkrow.off .pks { color: var(--muted); text-decoration: line-through; }
|
||||
|
||||
/* ---- 讲一遍 ---- */
|
||||
.exdlg { position: relative; width: 560px; max-width: 92vw; max-height: 88vh; overflow: auto;
|
||||
@@ -427,6 +491,19 @@ td .t{font-family:"Consolas",monospace;font-size:13.5px}
|
||||
padding: 2px 9px; font-weight: 700; margin: 2px 0; }
|
||||
.retreat .rt-why { color: #8A6A3E; font-size: 12.5px; }
|
||||
.retreat .rt-chain { color: #A07C46; font-size: 12px; margin-top: 6px; }
|
||||
.va { margin-top: 12px; padding: 12px 14px; border: 1px dashed #E2D8C9; border-radius: 12px; background: #FDFBF7; }
|
||||
.va-head { font-size: 13px; color: #6B6560; }
|
||||
.va-hint { color: #9A9086; font-size: 12px; }
|
||||
.va-row { display: flex; align-items: center; gap: 10px; margin-top: 10px; }
|
||||
.va-state { font-size: 12.5px; color: #8C8175; }
|
||||
.va-body { margin-top: 10px; }
|
||||
.va-body audio { width: 100%; height: 34px; }
|
||||
.va-checks { display: flex; flex-wrap: wrap; gap: 14px; margin: 10px 0; font-size: 13px; }
|
||||
.va-checks label { display: flex; align-items: center; gap: 6px; cursor: pointer; }
|
||||
.stuck { margin-top: 12px; padding: 14px 16px; border: 1px dashed #DCD3C6; border-radius: 12px; background: #FDFBF6; }
|
||||
.st-h { font-weight: 600; margin-bottom: 10px; }
|
||||
.st-btns { display: flex; gap: 8px; flex-wrap: wrap; }
|
||||
.st-done { margin-top: 12px; padding: 12px 16px; border-radius: 12px; background: var(--green-soft); color: #2F6B47; font-size: 13.5px; }
|
||||
.retreat .rt-go { margin-top: 10px; }
|
||||
.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;
|
||||
@@ -674,6 +751,8 @@ td .t{font-family:"Consolas",monospace;font-size:13.5px}
|
||||
<p style="margin:14px 0 0;font-size:11.5px;color:#A2958A;line-height:1.8">
|
||||
做错的题不进「错题本」,明天再来一次;连对两次后要讲一遍,讲清才算毕业。
|
||||
</p>
|
||||
|
||||
<div id="roundDone" hidden></div>
|
||||
</div>
|
||||
|
||||
<div class="card" style="margin-top:14px;padding:16px 18px">
|
||||
@@ -681,7 +760,7 @@ td .t{font-family:"Consolas",monospace;font-size:13.5px}
|
||||
<b style="font-size:13.5px">这道题之后会发生什么</b>
|
||||
<span style="margin-left:auto;font-size:11.5px;color:#A2958A">四步,不需要你做任何额外操作</span>
|
||||
</div>
|
||||
<div style="display:grid;grid-template-columns:repeat(4,1fr);gap:10px">
|
||||
<div class="four">
|
||||
<div style="background:#FBF6EC;border-radius:10px;padding:11px 12px">
|
||||
<div style="font-size:11px;color:var(--ochre);font-weight:700">今天</div>
|
||||
<div style="font-size:12.5px;color:#3A342E;line-height:1.7;margin-top:4px">答错的话,明天同一时间再来一次</div>
|
||||
@@ -739,16 +818,22 @@ td .t{font-family:"Consolas",monospace;font-size:13.5px}
|
||||
<!-- ======== 错题本 ======== -->
|
||||
<section class="view" id="v-wrong" hidden>
|
||||
<h1>错题本</h1>
|
||||
<p class="sub">只收「会做但错了」和「错三次以上」的题。粗心错不进来。</p>
|
||||
<p class="sub" id="wrongLeft">只收「会做但错了」和「错三次以上」的题。粗心错不进来。</p>
|
||||
<div class="chips" id="wrongChips">
|
||||
<button class="on" data-s="">全部</button>
|
||||
<button class="on" data-s="todo">待做</button>
|
||||
<button data-s="red">红的</button>
|
||||
<button data-s="amber">黄的</button>
|
||||
<button data-s="green">绿的</button>
|
||||
<button data-s="careless">粗心小记</button>
|
||||
<button data-s="">全部</button>
|
||||
</div>
|
||||
<div class="chips sub" id="wrongChips2">
|
||||
<button data-s="observing">观察中</button>
|
||||
<button data-s="queued">待复习</button>
|
||||
<button data-s="recalled">已对一次</button>
|
||||
<button data-s="passed_once">已对一次</button>
|
||||
<button data-s="to_explain">待讲清</button>
|
||||
<button data-s="unstable">会但不稳</button>
|
||||
<button data-s="graduated">已毕业</button>
|
||||
<button data-s="careless">粗心小记</button>
|
||||
</div>
|
||||
<div class="card"><div class="bd" style="padding:6px 8px"><table id="wrongTable"></table></div></div>
|
||||
</section>
|
||||
@@ -786,6 +871,10 @@ td .t{font-family:"Consolas",monospace;font-size:13.5px}
|
||||
<section class="view" id="v-weekly" hidden>
|
||||
<h1>周日那张纸</h1>
|
||||
<p class="sub">A5 一张,留答题区、答案可折叠、有家长签字栏。可以交给老师。</p>
|
||||
<div style="display:flex;gap:10px;flex-wrap:wrap;margin:14px 0 16px">
|
||||
<button class="primary" id="weeklyPrint">打开可打印版(A5)</button>
|
||||
<button class="ghost" id="weeklyReload">刷新本周数字</button>
|
||||
</div>
|
||||
<div class="grid2">
|
||||
<div class="card"><div class="hd"><b>本周数字</b></div><div class="bd" id="weeklyNums"></div></div>
|
||||
<div class="card"><div class="hd"><b>预览</b><span class="pill g">A5</span></div>
|
||||
@@ -836,6 +925,8 @@ td .t{font-family:"Consolas",monospace;font-size:13.5px}
|
||||
<button class="switch on" data-sw><i></i></button></div>
|
||||
<div class="setrow"><div class="k">语文</div><div class="v">听写、看拼音写词、笔顺</div>
|
||||
<button class="switch on" data-sw><i></i></button></div>
|
||||
<div class="setrow"><div class="k">严档</div><div class="v">第二次要做对一道没见过的题(默认关)</div>
|
||||
<button class="switch" id="setStrict" data-sw><i></i></button></div>
|
||||
<div class="setrow"><div class="k">照片留存</div><div class="v">90 天后自动删除</div>
|
||||
<button class="switch on" data-sw><i></i></button></div>
|
||||
</div></div>
|
||||
@@ -919,8 +1010,37 @@ td .t{font-family:"Consolas",monospace;font-size:13.5px}
|
||||
<button class="btn" id="exGo">就讲这些</button>
|
||||
<span class="ex-hint" id="exHint">讲清楚就行,不用长</span>
|
||||
</div>
|
||||
<div class="va" id="exVoice">
|
||||
<div class="va-head">不想打字?直接说<span class="va-hint">(1–3 年级写字慢,说比写快;说完自己勾三下就行)</span></div>
|
||||
<div class="va-row">
|
||||
<button class="btn line" id="exRec">开始录音</button>
|
||||
<span class="va-state" id="exRecState">还没录</span>
|
||||
</div>
|
||||
<div class="va-body" id="exVoiceBody" hidden>
|
||||
<audio id="exAudio" controls></audio>
|
||||
<div class="va-checks" id="exChecks">
|
||||
<label><input type="checkbox" data-c="wrong_reason" /> 说清了错在哪</label>
|
||||
<label><input type="checkbox" data-c="key_steps" /> 说出了正确的走法</label>
|
||||
<label><input type="checkbox" data-c="next_time" /> 说了下次怎么防</label>
|
||||
</div>
|
||||
<button class="btn" id="exVoiceGo">就这段录音</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="ex-result" id="exResult" hidden></div>
|
||||
<div class="retreat" id="exRetreat" hidden></div>
|
||||
<div class="stuck" id="exStuck" hidden></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="mask" id="pickMask">
|
||||
<div class="exdlg">
|
||||
<button class="ex-x" id="pkClose" aria-label="关闭">×</button>
|
||||
<h3>这块里有几道?</h3>
|
||||
<p class="ex-sub">口算卡一块十几道,切题有时会把没做错的、读歪的一起切进来。取消掉没做错的那几道再入库。</p>
|
||||
<div class="pklist" id="pkList"></div>
|
||||
<div class="ex-row">
|
||||
<button class="btn" id="pkGo">入库勾上的 0 道</button>
|
||||
<span class="ex-hint" id="pkHint">全都不对就直接确认</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<script>
|
||||
@@ -1154,6 +1274,7 @@ async function refresh() {
|
||||
S.mistakes = (m && m.items) || [];
|
||||
S.weekly = w || null;
|
||||
S.idx = 0; S.results = {};
|
||||
S.round = { n: 0, right: 0, grad: 0, careless: 0, gradStem: "" };
|
||||
renderAll();
|
||||
}
|
||||
|
||||
@@ -1165,6 +1286,9 @@ const STATUS_CLS = { graduated: "g", to_explain: "c", unstable: "o", careless: "
|
||||
|
||||
function renderAll() {
|
||||
setTimeout(() => petRender(), 0);
|
||||
// 严档开关跟着孩子走(切孩子时要跟着变)
|
||||
const st = document.getElementById("setStrict");
|
||||
if (st) st.classList.toggle("on", !!(S.kid && S.kid.strict_variant));
|
||||
const k = S.kid || DEMO.child;
|
||||
document.getElementById("kidName").textContent = k.nickname || "皮皮";
|
||||
document.getElementById("kidGrade").textContent = (GRADE[(k.grade || 2) - 1] || "二") + "年级";
|
||||
@@ -1245,6 +1369,16 @@ function renderTrain() {
|
||||
document.getElementById("qAnalysis").classList.remove("show");
|
||||
document.getElementById("qVariant").classList.remove("show");
|
||||
buildAnalysis(q);
|
||||
// 上次做对了原题、还没验变式就走了:这次进来就直接验变式
|
||||
if (q.status === "variant_pending") {
|
||||
S.variantStrict = true;
|
||||
// 只留变式那条输入框,别让孩子对着原题再写一遍
|
||||
document.getElementById("qAnswerRow").style.display = "none";
|
||||
document.getElementById("btnSubmit").style.display = "none";
|
||||
loadVariant(q);
|
||||
} else {
|
||||
S.variantStrict = false;
|
||||
}
|
||||
}
|
||||
|
||||
/* 选择题:A/B/C/D 四个按钮;非选择题把选项区清空、露出输入框 */
|
||||
@@ -1784,13 +1918,14 @@ async function submit() {
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
const r = await api(`/api/mistakes/${q.id}/attempt`, { method: "POST", body: { child_id: S.cid, answer: val } });
|
||||
const r = await api(`/api/mistakes/${q.id}/attempt`, { method: "POST", body: { child_id: S.cid, answer: val, variant: !!S.variantStrict } });
|
||||
correct = r.correct; detail = r.detail || "";
|
||||
unstableHint = r.unstable_hint || null;
|
||||
nextStatus = r.status || "";
|
||||
q.status_zh = r.status_zh;
|
||||
if (r.answer != null) q.answer = String(r.answer);
|
||||
if (r.judge_type) q.judge_type = r.judge_type;
|
||||
if (r.pet) { S.kid = Object.assign(S.kid || {}, { pet: r.pet }); petRender(true); }
|
||||
} catch (e) { detail = e.message; }
|
||||
}
|
||||
if (isChoice) {
|
||||
@@ -1811,6 +1946,12 @@ async function submit() {
|
||||
// 当天错了又对:不装作过了,也不打击——说清楚「明天再来一次」
|
||||
box.className = "result mid";
|
||||
box.innerHTML = `<b>会了,但还不稳</b><br>${esc(unstableHint)}`;
|
||||
} else if (nextStatus === "variant_pending") {
|
||||
// 严档:原题做对了不算数,先做对一道没见过的(下面那张变式卡会顶上来)
|
||||
box.className = "result mid";
|
||||
box.innerHTML = `<b>对了,但先别走</b><br>换一道同类的,做对才算真的会。
|
||||
<div style="margin-top:10px"><button class="btn line" id="btnGoVariant">来一道</button></div>`;
|
||||
S.variantStrict = true;
|
||||
} else if (nextStatus === "to_explain") {
|
||||
// 连对两次,到了「讲一遍」这一步——就地把入口放在结果里,不用回去翻错题本
|
||||
box.className = "result mid";
|
||||
@@ -1822,10 +1963,29 @@ async function submit() {
|
||||
S.results[S.idx] = true;
|
||||
} else {
|
||||
box.className = "result no";
|
||||
box.innerHTML = `<b>再想想</b><br>${esc(detail || "这题明天再来一次,间隔归零。")}`;
|
||||
const rt = r.retreat;
|
||||
if (rt) {
|
||||
// 同一道题已经错过三次:再排一次没有意义,先退一层补前置
|
||||
box.innerHTML = `<b>这道题已经错过三次</b><br>先别急着再来一遍——可能是前面那个知识点没扎实。
|
||||
<div class="retreat" style="margin-top:10px">
|
||||
<div class="rt-step">先补「${esc(rt.step.name)}」<span>${esc(String(rt.step.grade))} 年级</span></div>
|
||||
<div class="rt-why">${esc(rt.reason)}</div>
|
||||
<div class="rt-go">做对两道「${esc(rt.step.name)}」,再回来做这道。</div>
|
||||
</div>`;
|
||||
} else {
|
||||
box.innerHTML = `<b>再想想</b><br>${esc(detail || "这题明天再来一次,间隔归零。")}`;
|
||||
}
|
||||
S.results[S.idx] = false;
|
||||
}
|
||||
petAfterSubmit(q, correct);
|
||||
if (!S.round) S.round = { n: 0, right: 0, grad: 0, careless: 0, gradStem: "" };
|
||||
S.round.n++;
|
||||
if (correct === true) S.round.right++;
|
||||
if (nextStatus === "graduated" || q.status === "graduated") {
|
||||
S.round.grad++;
|
||||
if (!S.round.gradStem) S.round.gradStem = q.stem || "";
|
||||
}
|
||||
if (nextStatus === "careless" || q.status === "careless") S.round.careless++;
|
||||
buildAnalysis(q); // 这时才拿到正确答案,答案与步骤都得重画一次
|
||||
document.getElementById("qAnalysis").classList.add("show");
|
||||
document.getElementById("btnNext").style.display = "";
|
||||
@@ -1890,37 +2050,204 @@ async function loadVariant(q, rotate) {
|
||||
}
|
||||
|
||||
function nextQ() {
|
||||
if (S.idx < S.queue.length - 1) { S.idx++; renderTrain(); renderSheet(); }
|
||||
else {
|
||||
document.getElementById("qStem").textContent = "今天的 5 道做完了 🎉";
|
||||
document.getElementById("qAnswerRow").style.display = "none";
|
||||
document.getElementById("qAnalysis").classList.remove("show");
|
||||
document.getElementById("qVariant").classList.remove("show");
|
||||
document.getElementById("btnNext").style.display = "none";
|
||||
document.getElementById("btnSubmit").style.display = "none";
|
||||
document.getElementById("qBar").style.width = "100%";
|
||||
if (S.idx < S.queue.length - 1) {
|
||||
S.idx++; renderTrain(); renderSheet();
|
||||
document.getElementById("roundDone").hidden = true;
|
||||
document.getElementById("qStem").style.display = "";
|
||||
document.getElementById("btnPrev").style.display = "";
|
||||
document.getElementById("btnSkip").style.display = "";
|
||||
} else {
|
||||
endRound();
|
||||
}
|
||||
}
|
||||
|
||||
/* 收尾页:一轮做完之后的交代。表扬必须说行为,不说「你真棒」。 */
|
||||
function endRound() {
|
||||
const d = S.round || { n: S.queue.length, right: 0, grad: 0, careless: 0, gradStem: "" };
|
||||
const total = d.n || S.queue.length;
|
||||
const again = Math.max(0, total - d.right);
|
||||
document.getElementById("qStem").style.display = "none";
|
||||
document.getElementById("qAnswerRow").style.display = "none";
|
||||
document.getElementById("qOptions").innerHTML = "";
|
||||
document.getElementById("qAnalysis").classList.remove("show");
|
||||
document.getElementById("qVariant").classList.remove("show");
|
||||
document.getElementById("qResult").className = "result";
|
||||
document.getElementById("qResult").innerHTML = "";
|
||||
document.getElementById("btnNext").style.display = "none";
|
||||
document.getElementById("btnSubmit").style.display = "none";
|
||||
document.getElementById("btnPrev").style.display = "none";
|
||||
document.getElementById("btnSkip").style.display = "none";
|
||||
document.getElementById("qBar").style.width = "100%";
|
||||
|
||||
let say, warm = false;
|
||||
if (d.grad > 0 && d.gradStem) {
|
||||
say = `你把「${esc(shortStem(d.gradStem))}」讲明白了——它从本子上消失了,不用再做了。`;
|
||||
} else if (d.right >= Math.ceil(total * 0.6)) {
|
||||
say = `今天 ${total} 道里 ${d.right} 道一次就对,这就是在变薄。`;
|
||||
} else if (d.right > 0) {
|
||||
say = `今天 ${d.right} 道一次就对,另外 ${again} 道明天再来一遍——它们还没被记住,正常。`;
|
||||
} else {
|
||||
warm = true;
|
||||
say = `今天 ${total} 道都没一次做对。没关系,明天同一时间再来一次,只要 4 分钟。`;
|
||||
}
|
||||
|
||||
document.getElementById("roundDone").hidden = false;
|
||||
document.getElementById("roundDone").innerHTML = `
|
||||
<div class="round" style="margin-top:18px;border-top:1px dashed var(--line);padding-top:16px">
|
||||
<div class="hi">今天到此为止,${total} 道做完了</div>
|
||||
<div class="facts">
|
||||
<div class="fact"><i>一次就对</i><b>${d.right}</b></div>
|
||||
<div class="fact"><i>明天再来</i><b>${again}</b></div>
|
||||
<div class="fact"><i>今天毕业</i><b>${d.grad}</b></div>
|
||||
</div>
|
||||
<div class="say ${warm ? "warm" : ""}">${say}</div>
|
||||
<div class="acts">
|
||||
<button class="btn" id="rdWeekly">看这周的那张纸</button>
|
||||
<button class="btn line" id="rdHome">回工作台</button>
|
||||
</div>
|
||||
</div>`;
|
||||
document.getElementById("rdWeekly").addEventListener("click", () => show("weekly"));
|
||||
document.getElementById("rdHome").addEventListener("click", () => show("home"));
|
||||
petSay("今天的活儿干完了。", "bounce", 6000);
|
||||
}
|
||||
|
||||
function norm(s) { return String(s).replace(/\s/g, "").replace(/[。,,.]/g, "").toLowerCase(); }
|
||||
|
||||
/* ---- 其他视图 ---- */
|
||||
/* 三色:红=今天就该做、黄=差一步、绿=已毕业。状态名还是原来那七个,只是不再让家长去分辨。 */
|
||||
const BUCKET = {
|
||||
red: ["observing", "queued"],
|
||||
amber: ["unstable", "passed_once", "to_explain"],
|
||||
green: ["graduated"],
|
||||
careless: ["careless"],
|
||||
};
|
||||
function statusBucket(s) {
|
||||
for (const k in BUCKET) if (BUCKET[k].indexOf(s) >= 0) return k;
|
||||
return "red";
|
||||
}
|
||||
const BUCKET_ZH = { red: "红的", amber: "黄的", green: "绿的", careless: "粗心" };
|
||||
|
||||
function renderWrong() {
|
||||
const rows = S.mistakes.filter(m => !S.wrongFilter || m.status === S.wrongFilter);
|
||||
const f = S.wrongFilter || "todo";
|
||||
const inFilter = (m) => {
|
||||
if (f === "") return true;
|
||||
if (f === "todo") { const b = statusBucket(m.status); return b === "red" || b === "amber"; }
|
||||
if (BUCKET[f]) return statusBucket(m.status) === f;
|
||||
return m.status === f; // 具体状态仍可筛
|
||||
};
|
||||
const all = S.mistakes || [];
|
||||
const n = (k) => all.filter(m => statusBucket(m.status) === k).length;
|
||||
const rows = all.filter(inFilter);
|
||||
|
||||
const left = document.getElementById("wrongLeft");
|
||||
if (left) {
|
||||
const todo = n("red") + n("amber");
|
||||
left.textContent = todo
|
||||
? `还剩 ${todo} 道:红 ${n("red")} · 黄 ${n("amber")};绿叶 ${n("green")} 道不用再看了。`
|
||||
: `没有待做的题了。已毕业 ${n("green")} 道,粗心小记 ${n("careless")} 条。`;
|
||||
}
|
||||
document.querySelectorAll("#wrongChips button,#wrongChips2 button").forEach(b => {
|
||||
const s = b.dataset.s || "";
|
||||
b.classList.toggle("on", s === f);
|
||||
const cnt = s === "todo" ? n("red") + n("amber")
|
||||
: s === "" ? all.length
|
||||
: BUCKET[s] ? n(s)
|
||||
: all.filter(m => m.status === s).length;
|
||||
const label = b.textContent.replace(/\s*\(\d+\)$/, "");
|
||||
b.textContent = cnt ? `${label} (${cnt})` : label;
|
||||
});
|
||||
|
||||
document.getElementById("wrongTable").innerHTML = `
|
||||
<tr><th>题目</th><th>科目</th><th>错因</th><th>状态</th><th>下次复习</th><th></th></tr>` +
|
||||
rows.map(m => `<tr>
|
||||
rows.map(m => {
|
||||
const b = statusBucket(m.status);
|
||||
const pill = b === "red" ? "r" : b === "amber" ? "o" : b === "green" ? "g" : "gray";
|
||||
return `<tr>
|
||||
<td class="t">${esc(m.stem)}</td>
|
||||
<td>${SUBJ[m.subject] || "数学"}</td>
|
||||
<td>${m.wrong_code ? `<span class="pill gray">${m.wrong_code}</span>` : "—"}</td>
|
||||
<td><span class="pill ${STATUS_CLS[m.status] || ""}">${m.status_zh || m.status}</span></td>
|
||||
<td><span class="pill ${pill}">${m.status_zh || m.status}</span></td>
|
||||
<td style="color:var(--muted)">${m.next_due || "—"}</td>
|
||||
<td>${m.status === "to_explain" ? `<button class="lnk ex-open" data-id="${esc(m.id)}">讲一遍</button>` : ""}</td>
|
||||
</tr>`).join("");
|
||||
</tr>`; }).join("");
|
||||
}
|
||||
|
||||
/* ---- 讲一遍(讲清才算毕业;讲不清就给「退一层」) ---- */
|
||||
let EX = { mid: null, channel: "steps" };
|
||||
const STUCK = [["read", "题没读懂"], ["plan", "不知道从哪下手"], ["calc", "会做,算错了"], ["check", "没检查"]];
|
||||
|
||||
/* ---------- 语音讲一遍:MediaRecorder,说完自己勾三下 ---------- */
|
||||
let VOICE = { rec: null, chunks: [], blob: null, mime: "" };
|
||||
|
||||
function voiceReset() {
|
||||
VOICE.chunks = []; VOICE.blob = null;
|
||||
const body = document.getElementById("exVoiceBody");
|
||||
if (body) body.hidden = true;
|
||||
document.getElementById("exRecState").textContent = "还没录";
|
||||
document.getElementById("exRec").textContent = "开始录音";
|
||||
}
|
||||
|
||||
async function voiceToggle() {
|
||||
const btn = document.getElementById("exRec"), st = document.getElementById("exRecState");
|
||||
if (VOICE.rec && VOICE.rec.state === "recording") { VOICE.rec.stop(); return; }
|
||||
if (!navigator.mediaDevices || !window.MediaRecorder) { st.textContent = "这个浏览器不支持录音"; return; }
|
||||
try {
|
||||
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
|
||||
VOICE.chunks = [];
|
||||
const rec = new MediaRecorder(stream);
|
||||
VOICE.mime = rec.mimeType || "audio/webm";
|
||||
rec.ondataavailable = (e) => { if (e.data && e.data.size) VOICE.chunks.push(e.data); };
|
||||
rec.onstop = () => {
|
||||
stream.getTracks().forEach(t => t.stop());
|
||||
VOICE.blob = new Blob(VOICE.chunks, { type: VOICE.mime });
|
||||
const url = URL.createObjectURL(VOICE.blob);
|
||||
document.getElementById("exAudio").src = url;
|
||||
document.getElementById("exVoiceBody").hidden = false;
|
||||
document.getElementById("exRec").textContent = "重录";
|
||||
const sec = Math.round(VOICE.blob.size / 16000);
|
||||
st.textContent = `录好了 · 约 ${sec} 秒`;
|
||||
btn.disabled = false;
|
||||
};
|
||||
rec.start();
|
||||
VOICE.rec = rec;
|
||||
btn.textContent = "停止"; st.textContent = "正在录…";
|
||||
} catch (e) {
|
||||
st.textContent = "没拿到麦克风:" + (e.message || e.name);
|
||||
}
|
||||
}
|
||||
|
||||
function voiceSubmit() {
|
||||
const checks = {};
|
||||
document.querySelectorAll("#exChecks input[data-c]").forEach(x => { checks[x.dataset.c] = x.checked ? 1 : 0; });
|
||||
const hit = Object.values(checks).filter(Boolean).length;
|
||||
if (S.demo) {
|
||||
const passed = hit === 3;
|
||||
renderExplain({
|
||||
passed, status: passed ? "graduated" : "to_explain",
|
||||
rubric: { wrong_reason: checks.wrong_reason ? "说清了" : "没说清错在哪",
|
||||
key_steps: checks.key_steps ? "说了" : "没说出正确走法",
|
||||
next_time: checks.next_time ? "说了" : "没说下次怎么防" },
|
||||
hint: passed ? "这题你不用再做了" : "没过就换个说法,7 天内还有机会",
|
||||
retreat: null, ask_stuck_at: !passed, audio: "demo", checks,
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (!VOICE.blob) { toast("先录一段"); return; }
|
||||
const fr = new FileReader();
|
||||
fr.onload = async () => {
|
||||
try {
|
||||
const r = await api(`/api/mistakes/${encodeURIComponent(EX.mid)}/explain`, {
|
||||
method: "POST",
|
||||
body: { channel: "audio", checks, audio_b64: String(fr.result).split(",")[1] || "",
|
||||
audio_ext: (VOICE.mime.split("/")[1] || "webm").split(";")[0] },
|
||||
});
|
||||
renderExplain(r);
|
||||
if (r.passed) toast("这段讲清了,这题毕业");
|
||||
} catch (e) { toast("没交上:" + e.message); }
|
||||
};
|
||||
fr.readAsDataURL(VOICE.blob);
|
||||
}
|
||||
|
||||
|
||||
function openExplain(mid) {
|
||||
const m = S.mistakes.find(x => x.id === mid) || S.queue.find(x => x.id === mid);
|
||||
@@ -1931,6 +2258,8 @@ function openExplain(mid) {
|
||||
document.getElementById("exHint").textContent = "讲清楚就行,不用长";
|
||||
document.getElementById("exResult").hidden = true;
|
||||
document.getElementById("exRetreat").hidden = true;
|
||||
document.getElementById("exStuck").hidden = true; document.getElementById("exStuck").innerHTML = "";
|
||||
voiceReset();
|
||||
document.querySelectorAll("#exChannels button").forEach(b => b.classList.toggle("on", b.dataset.c === "steps"));
|
||||
document.getElementById("explainMask").classList.add("show");
|
||||
setTimeout(() => document.getElementById("exText").focus(), 30);
|
||||
@@ -1967,7 +2296,8 @@ async function submitExplain() {
|
||||
r = { passed, status: passed ? "graduated" : "to_explain",
|
||||
rubric: { wrong_reason: "没说清错在哪", key_steps: "先算个位再算十位,进位别忘", next_time: "下次先圈进位" },
|
||||
hint: passed ? "这题你不用再做了" : "没过就换个说法,7 天内还有机会",
|
||||
retreat: passed ? null : (DEMO_RETREAT[m.kp] || null) };
|
||||
retreat: passed ? null : (DEMO_RETREAT[m.kp] || null),
|
||||
ask_stuck_at: !passed && !m.stuck_at };
|
||||
} else {
|
||||
r = await api(`/api/mistakes/${encodeURIComponent(EX.mid)}/explain`,
|
||||
{ method: "POST", body: { channel: EX.channel, text } });
|
||||
@@ -1992,6 +2322,16 @@ function renderExplain(r) {
|
||||
<div class="rub">差在:${esc(rub.wrong_reason || "没说清错因")}<br>
|
||||
该有的一步:${esc(rub.key_steps || "先算哪一步、再算哪一步")}<br>
|
||||
${/^下次/.test(next) ? "" : "下次:"}${esc(next)}</div>`;
|
||||
// 讲不清 → 问一次「刚才卡在哪」:四个按钮,三秒点完
|
||||
const st = document.getElementById("exStuck");
|
||||
if (r.ask_stuck_at) {
|
||||
st.hidden = false;
|
||||
st.innerHTML = '<div class="st-h">刚才卡在哪?</div><div class="st-btns">'
|
||||
+ STUCK.map(([k, v]) => '<button class="btn line" data-stuck="' + k + '">' + v + "</button>").join("")
|
||||
+ "</div>";
|
||||
} else {
|
||||
st.hidden = true; st.innerHTML = "";
|
||||
}
|
||||
// 讲不清 → 退一层:问的不是这道题,是这道题背后的前置
|
||||
const rt = document.getElementById("exRetreat");
|
||||
const q = r.retreat;
|
||||
@@ -2061,7 +2401,29 @@ function renderWeekly() {
|
||||
<span>家长签字:______</span><span>孩子的话:____________</span>
|
||||
</div>
|
||||
</div>
|
||||
<p style="font-size:11.5px;color:var(--muted);margin:10px 0 0">点打印即可出 A5;打印入口在小程序「周日那张纸」。</p>`;
|
||||
<p style="font-size:11.5px;color:var(--muted);margin:10px 0 0">点上面「打开可打印版」→ 在新窗口里按 Ctrl+P 就能印 A5;也可以直接存成 PDF。</p>`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开服务端生成的 A5 周报。
|
||||
* 打印页在 /api/print/weekly,用的是 query token(和 CSV 导出同一套白名单),
|
||||
* 所以这里要把 token 拼上去——这正是之前「功能有、入口没有」的那一段。
|
||||
*/
|
||||
function onWeeklyPrint() {
|
||||
if (!S.token || S.demo) {
|
||||
toast("演示模式没有真实周报;接上后端(登录后)才能打印");
|
||||
return;
|
||||
}
|
||||
const q = new URLSearchParams({ child_id: S.cid, token: S.token });
|
||||
window.open(API + "/api/print/weekly?" + q.toString(), "_blank");
|
||||
}
|
||||
|
||||
async function onWeeklyReload() {
|
||||
if (S.demo) { toast("演示数据不刷新"); return; }
|
||||
const w = await api("/api/report/weekly?child_id=" + S.cid).catch(() => null);
|
||||
if (w) S.weekly = w;
|
||||
renderWeekly();
|
||||
toast("已刷新");
|
||||
}
|
||||
|
||||
function weekNo() { const d = new Date(); const s = new Date(d.getFullYear(), 0, 1); return Math.ceil(((d - s) / 86400000 + s.getDay() + 1) / 7); }
|
||||
@@ -2111,23 +2473,85 @@ function show(v) {
|
||||
if (v === "train") { renderTrain(); renderSheet(); }
|
||||
}
|
||||
|
||||
document.getElementById("exRec").addEventListener("click", voiceToggle);
|
||||
document.getElementById("exVoiceGo").addEventListener("click", voiceSubmit);
|
||||
document.getElementById("exStuck").addEventListener("click", async (e) => {
|
||||
const b = e.target.closest("[data-stuck]");
|
||||
if (!b) return;
|
||||
const key = b.dataset.stuck;
|
||||
const zh = (STUCK.find(x => x[0] === key) || [])[1] || key;
|
||||
const st = document.getElementById("exStuck");
|
||||
if (S.demo) { st.innerHTML = '<div class="st-done">记下了:' + zh + "</div>"; toast("记下了:" + zh); return; }
|
||||
try {
|
||||
await api("/api/mistakes/" + encodeURIComponent(EX.mid) + "/stuck", { method: "POST", body: { stuck_at: key } });
|
||||
const m = S.mistakes.find(x => x.id === EX.mid); if (m) m.stuck_at = key;
|
||||
st.innerHTML = '<div class="st-done">记下了:' + zh + "</div>";
|
||||
toast("记下了:" + zh);
|
||||
} catch (err) { toast("没记上:" + err.message); }
|
||||
});
|
||||
|
||||
document.getElementById("btnSubmit").addEventListener("click", submit);
|
||||
document.getElementById("weeklyPrint").addEventListener("click", onWeeklyPrint);
|
||||
document.getElementById("weeklyReload").addEventListener("click", onWeeklyReload);
|
||||
document.getElementById("qInput").addEventListener("keydown", e => { if (e.key === "Enter") submit(); });
|
||||
document.getElementById("btnNext").addEventListener("click", nextQ);
|
||||
document.getElementById("btnPrev").addEventListener("click", () => { if (S.idx > 0) { S.idx--; renderTrain(); renderSheet(); } });
|
||||
document.getElementById("btnSkip").addEventListener("click", () => nextQ());
|
||||
document.getElementById("btnVCheck").addEventListener("click", () => {
|
||||
document.getElementById("btnVCheck").addEventListener("click", async () => {
|
||||
const v = S.variant; if (!v) return;
|
||||
const ok = norm(document.getElementById("vInput").value) === norm(v.answer);
|
||||
document.getElementById("vResult").innerHTML = ok
|
||||
const val = document.getElementById("vInput").value;
|
||||
const out = document.getElementById("vResult");
|
||||
// 严档:这一道是用来验「换一层皮还会不会」的,答案要交给后端判、并且记进队列
|
||||
if (S.variantStrict) {
|
||||
const q = curQ();
|
||||
if (!q) return;
|
||||
try {
|
||||
const r = await api(`/api/mistakes/${q.id}/attempt`,
|
||||
{ method: "POST", body: { child_id: S.cid, answer: val, variant: true } });
|
||||
if (r.correct) {
|
||||
out.innerHTML = `<span style="color:var(--green)">✓ 换一道也做对了——这才是真的会,明天再来一次。</span>`;
|
||||
S.variantStrict = false;
|
||||
} else {
|
||||
out.innerHTML = `<span style="color:var(--red)">✗ ${esc(r.detail || "这道没对")}:明天回来再做一次。</span>`;
|
||||
S.variantStrict = false;
|
||||
}
|
||||
refresh();
|
||||
} catch (e) {
|
||||
out.innerHTML = `<span style="color:var(--red)">没交上:${esc(e.message)}</span>`;
|
||||
}
|
||||
return;
|
||||
}
|
||||
const ok = norm(val) === norm(v.answer);
|
||||
out.innerHTML = ok
|
||||
? `<span style="color:var(--green)">✓ 对了,这类题你会了</span>`
|
||||
: `<span style="color:var(--red)">✗ 再看一眼:答案是 ${esc(v.answer)}</span>`;
|
||||
});
|
||||
document.getElementById("btnVNext").addEventListener("click", () => { const q = curQ(); if (q) loadVariant(q, true); });
|
||||
document.getElementById("btnGoVariant") && document.getElementById("btnGoVariant").addEventListener("click", () => {
|
||||
const q = curQ(); if (q) loadVariant(q);
|
||||
document.getElementById("btnGoVariant").disabled = true;
|
||||
});
|
||||
// 设置:严档开关(孩子级,存后端)
|
||||
document.getElementById("setStrict").addEventListener("click", async () => {
|
||||
const el = document.getElementById("setStrict");
|
||||
const on = !el.classList.contains("on");
|
||||
el.classList.toggle("on", on);
|
||||
if (S.demo) { S.kid = Object.assign(S.kid || {}, { strict_variant: on ? 1 : 0 }); toast(on ? "演示:严档已打开" : "演示:严档已关闭"); return; }
|
||||
try {
|
||||
const r = await api(`/api/children/${S.cid}/settings`, { method: "POST", body: { child_id: S.cid, strict_variant: on ? 1 : 0 } });
|
||||
S.kid = Object.assign(S.kid || {}, { strict_variant: r.strict_variant });
|
||||
toast(r.strict_variant ? "严档已打开:第二次要做对一道没见过的题" : "已改回默认:同题第二次做对即可");
|
||||
} catch (e) { el.classList.toggle("on", !on); toast("没改成:" + e.message); }
|
||||
});
|
||||
document.getElementById("wrongChips").addEventListener("click", (e) => {
|
||||
const b = e.target.closest("button"); if (!b) return;
|
||||
document.querySelectorAll("#wrongChips button").forEach(x => x.classList.toggle("on", x === b));
|
||||
S.wrongFilter = b.dataset.s; renderWrong();
|
||||
S.wrongFilter = b.dataset.s;
|
||||
renderWrong();
|
||||
});
|
||||
document.getElementById("wrongChips2").addEventListener("click", (e) => {
|
||||
const b = e.target.closest("button"); if (!b) return;
|
||||
S.wrongFilter = b.dataset.s;
|
||||
renderWrong();
|
||||
});
|
||||
document.getElementById("wrongTable").addEventListener("click", (e) => {
|
||||
const b = e.target.closest(".ex-open"); if (!b) return;
|
||||
@@ -2207,7 +2631,11 @@ function petLoad() {
|
||||
let PET = Object.assign({ name: "", look: "star", swapped: false, off: false, collapsed: false }, petLoad());
|
||||
function petSave() { localStorage.setItem(PET_KEY, JSON.stringify(PET)); }
|
||||
function petGrad() { return (S.mistakes || []).filter(m => m.status === "graduated").length; }
|
||||
function petStage() { const g = petGrad(); return g >= 100 ? 3 : g >= 40 ? 2 : g >= 12 ? 1 : 0; }
|
||||
function petStage() {
|
||||
const sv = S.kid && S.kid.pet && typeof S.kid.pet.stage === "number" ? S.kid.pet.stage : null;
|
||||
if (!S.demo && sv !== null) return sv;
|
||||
const g = petGrad(); return g >= 100 ? 3 : g >= 40 ? 2 : g >= 12 ? 1 : 0;
|
||||
}
|
||||
function petNick() { return PET.name || "小狮"; }
|
||||
function shortStem(t) { t = String(t || ""); return t.length > 12 ? t.slice(0, 12) + "…" : t; }
|
||||
|
||||
@@ -2373,7 +2801,9 @@ function petRender(force) {
|
||||
box.classList.toggle("collapsed", !!PET.collapsed);
|
||||
document.getElementById("petName").textContent = petNick();
|
||||
const g = petGrad();
|
||||
document.getElementById("petTip").textContent = PET.collapsed ? "" : "已吃掉 " + g + " 道";
|
||||
const fed = !S.demo && S.kid && S.kid.pet && S.kid.pet.fed_today;
|
||||
document.getElementById("petTip").textContent = PET.collapsed ? ""
|
||||
: (fed ? "今天喂过了 · 已吃掉 " + g + " 道" : "已吃掉 " + g + " 道");
|
||||
document.getElementById("petInput").value = PET.name || "";
|
||||
document.querySelectorAll("#pet .lk").forEach(el => el.classList.toggle("on", el.dataset.look === PET.look));
|
||||
document.getElementById("petSwapHint").textContent = PET.swapped
|
||||
@@ -2539,6 +2969,94 @@ function updateScanCount() {
|
||||
|
||||
async function onScanImport() {
|
||||
if (!SCAN.picks.length || !SCAN.draft || SCAN.busy) return;
|
||||
// 勾中的块里有「一块多道」(口算卡/竖式区)就先摊开让家长逐条勾,否则直接入库
|
||||
const multi = SCAN.picks.some((i) => ((SCAN.blocks[i] || {}).subs || []).length > 1);
|
||||
if (multi) { await openPickSheet(); return; }
|
||||
await doScanImport(SCAN.picks);
|
||||
}
|
||||
|
||||
/* 拍题入库用哪个科目:跟着当前孩子开的科目走,默认数学 */
|
||||
function subjectNow() {
|
||||
return (S.kid && S.kid.subjects && S.kid.subjects[0]) || "math";
|
||||
}
|
||||
|
||||
/* ---- 逐条勾选:这块里到底哪几道是错的 ---- */
|
||||
let PICK = { items: [], on: [] };
|
||||
|
||||
async function openPickSheet() {
|
||||
SCAN.busy = true;
|
||||
const btn = scanEl("scanImport"), old = btn.textContent;
|
||||
btn.textContent = "认一下这块里的题…";
|
||||
try {
|
||||
const r = await api("/api/papers/scan/prepare", {
|
||||
method: "POST",
|
||||
body: { child_id: S.cid, subject: subjectNow(), draft_id: SCAN.draft, picks: SCAN.picks }
|
||||
});
|
||||
PICK.items = r.items || [];
|
||||
PICK.on = PICK.items.map(() => true);
|
||||
renderPickSheet();
|
||||
document.getElementById("pickMask").classList.add("show");
|
||||
} catch (e) {
|
||||
toast((e && e.message) || "这块里的题没认出来,试试整页在电脑上重新拍");
|
||||
} finally {
|
||||
btn.textContent = old;
|
||||
SCAN.busy = false;
|
||||
}
|
||||
}
|
||||
|
||||
function renderPickSheet() {
|
||||
const box = document.getElementById("pkList");
|
||||
box.innerHTML = PICK.items.map((it, k) => `
|
||||
<label class="pkrow${PICK.on[k] ? "" : " off"}">
|
||||
<input type="checkbox" data-k="${k}"${PICK.on[k] ? " checked" : ""}>
|
||||
<span class="pks">${esc(it.stem || "(没认出题干)")}</span>
|
||||
<span class="pkn">${it.sub === null ? "单题" : "第 " + (it.sub + 1) + " 道"}</span>
|
||||
</label>`).join("");
|
||||
box.querySelectorAll("input").forEach((el) => {
|
||||
el.onchange = () => {
|
||||
const k = Number(el.dataset.k);
|
||||
PICK.on[k] = el.checked;
|
||||
el.closest(".pkrow").classList.toggle("off", !el.checked);
|
||||
updatePickCount();
|
||||
};
|
||||
});
|
||||
updatePickCount();
|
||||
}
|
||||
|
||||
function updatePickCount() {
|
||||
const n = PICK.on.filter(Boolean).length;
|
||||
const b = document.getElementById("pkGo");
|
||||
b.disabled = n === 0;
|
||||
b.textContent = "入库勾上的 " + n + " 道";
|
||||
document.getElementById("pkHint").textContent = n === 0
|
||||
? "一道都不勾就别入库了,点右上角关掉"
|
||||
: "勾上的这几道会进「错题本」,明天开始复习";
|
||||
}
|
||||
|
||||
function closePickSheet() {
|
||||
document.getElementById("pickMask").classList.remove("show");
|
||||
PICK = { items: [], on: [] };
|
||||
}
|
||||
|
||||
async function confirmPickSheet() {
|
||||
// 按块归组:单题给块序号,多题的块给 {i, subs:[勾中的小题序号]}
|
||||
const byBlock = new Map();
|
||||
PICK.items.forEach((it, k) => {
|
||||
if (!PICK.on[k]) return;
|
||||
if (!byBlock.has(it.block)) byBlock.set(it.block, { single: false, subs: [] });
|
||||
const g = byBlock.get(it.block);
|
||||
if (it.sub === null) g.single = true; else g.subs.push(it.sub);
|
||||
});
|
||||
const picks = [];
|
||||
byBlock.forEach((g, i) => {
|
||||
if (g.single) picks.push(i); else picks.push({ i, subs: g.subs });
|
||||
});
|
||||
if (!picks.length) return;
|
||||
closePickSheet();
|
||||
await doScanImport(picks);
|
||||
}
|
||||
|
||||
async function doScanImport(picks) {
|
||||
SCAN.busy = true;
|
||||
const btn = scanEl("scanImport");
|
||||
const old = btn.textContent;
|
||||
@@ -2546,10 +3064,10 @@ async function onScanImport() {
|
||||
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 }
|
||||
body: { child_id: S.cid, subject: subjectNow(), draft_id: SCAN.draft, picks }
|
||||
});
|
||||
const picked = (r && r.ocr && r.ocr.picked) || SCAN.picks.length;
|
||||
toast("已入库 " + picked + " 道,明天开始复习");
|
||||
const created = (r && r.ocr && r.ocr.created) || 0;
|
||||
toast("已入库 " + created + " 道,明天开始复习");
|
||||
scanReset();
|
||||
await refresh();
|
||||
show("wrong");
|
||||
@@ -2567,6 +3085,8 @@ document.addEventListener("DOMContentLoaded", () => {
|
||||
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 pk = document.getElementById("pkGo"); if (pk) pk.onclick = confirmPickSheet;
|
||||
const pkc = document.getElementById("pkClose"); if (pkc) pkc.onclick = closePickSheet;
|
||||
const dr = scanEl("scanDrop");
|
||||
if (dr) {
|
||||
dr.addEventListener("dragover", (e) => { e.preventDefault(); dr.style.background = "#FBEFE4"; });
|
||||
|
||||
@@ -0,0 +1,274 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""生成「阶段汇报」docx:给明天的汇报会用的材料 + 口播稿。
|
||||
|
||||
python report/build_brief.py
|
||||
"""
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from docx import Document
|
||||
from docx.enum.text import WD_ALIGN_PARAGRAPH
|
||||
from docx.oxml.ns import qn
|
||||
from docx.shared import Cm, Pt, RGBColor
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
import docx_style as S # noqa: E402
|
||||
|
||||
OUT = Path(__file__).resolve().parent / "错题毕业-阶段汇报-2026-11-23.docx"
|
||||
|
||||
|
||||
def new_doc():
|
||||
doc = Document()
|
||||
sec = doc.sections[0]
|
||||
sec.page_width, sec.page_height = Cm(21.0), Cm(29.7)
|
||||
sec.left_margin = sec.right_margin = Cm(2.3)
|
||||
sec.top_margin = Cm(2.2)
|
||||
sec.bottom_margin = Cm(2.0)
|
||||
st = doc.styles["Normal"]
|
||||
st.font.name = S.FONT
|
||||
st.font.size = Pt(10)
|
||||
st.element.rPr.rFonts.set(qn("w:eastAsia"), S.FONT)
|
||||
S.add_page_number_footer(sec, "错题毕业 · 阶段汇报 · 2026-11-23")
|
||||
return doc
|
||||
|
||||
|
||||
def cover(doc):
|
||||
doc.add_paragraph().paragraph_format.space_after = Pt(90)
|
||||
p = doc.add_paragraph()
|
||||
r = p.add_run("阶段汇报")
|
||||
S.set_run_font(r, 30, True, S.ACCENT)
|
||||
p2 = doc.add_paragraph()
|
||||
S.space(p2, 4, 10, 1.2)
|
||||
r2 = p2.add_run("错题毕业 · 一个把错题「消灭掉」的学习工具")
|
||||
S.set_run_font(r2, 15, False, S.INK)
|
||||
S.para_border(p2, "bottom", S.ACCENT, 8, 10)
|
||||
|
||||
for line in [
|
||||
"汇报范围:2026-11-18 → 2026-11-22(5 天,26 次提交)",
|
||||
"当前形态:小学版后端 + 工作台网页 + 微信小程序 + 初中版独立应用",
|
||||
"一句话状态:能跑、能测、能量化;差主体资质与真机联调才能见家长",
|
||||
]:
|
||||
p3 = doc.add_paragraph()
|
||||
S.space(p3, 2, 3, 1.5)
|
||||
r3 = p3.add_run(line)
|
||||
S.set_run_font(r3, 9.5, False, S.MUTED)
|
||||
|
||||
doc.add_paragraph().paragraph_format.space_after = Pt(60)
|
||||
S.quote(doc, "错题不是用来整理的,是用来消灭的。一道题连对两次、还能讲清楚,才算毕业。",
|
||||
"产品定义,来自 330 条家长原话里的核心抱怨:整理完不复习,考试再遇到还是不会")
|
||||
doc.add_page_break()
|
||||
|
||||
|
||||
def part1(doc):
|
||||
S.h1(doc, "一、一页纸:三句话", first=True)
|
||||
S.lead(doc, "如果只给你三句话,讲这三句。")
|
||||
S.bullet(doc, "做了一个「把错题消灭掉」的工具:拍一整页卷子 → 家长点哪几道错了 → 到点提醒重做 → 连对两次 + 能讲清才算毕业。不是题库,不是拍照搜题。", "是什么:")
|
||||
S.bullet(doc, "后端 60 个接口、工作台 11 个页面、小程序 8 页,239 个单测 + 113 项冒烟全绿;拍题链路在 230 张真实卷子上量过,330 道人工金标里判错 0 道。", "做到哪了:")
|
||||
S.bullet(doc, "卡在两件我办不了的事:企业主体资质、微信开发者工具真机联调。这两件不通,做多少功能都见不到家长。", "卡在哪:")
|
||||
|
||||
S.callout(doc, "汇报口径",
|
||||
"先说结论、再给证据、最后要决定。不要从「我做了哪些功能」讲起——听的人记不住清单,"
|
||||
"记得住的是「这东西凭什么有人付钱」和「下一步要我拍什么板」。")
|
||||
|
||||
S.h2(doc, "明天的目标(三选一,建议全要)")
|
||||
S.bullet(doc, "让听的人承认「这条链路是通的」——用 2 分钟演示,不用讲架构。")
|
||||
S.bullet(doc, "让听的人相信「数字是量出来的」——四组数字,每组一句口径。")
|
||||
S.bullet(doc, "拿到两个决定:先做哪个学段卖、定价按 69 还是 99。")
|
||||
|
||||
|
||||
def part2(doc):
|
||||
S.h1(doc, "二、这五天做了什么", new_page=True)
|
||||
S.body(doc, "按「能不能被验证」排,不按我写的先后排。")
|
||||
S.make_table(doc,
|
||||
["模块", "做到什么程度", "怎么证明"],
|
||||
[
|
||||
["拍题入库", "整页拍 → 切块带框 → 家长在图上点错题 → 只把选中的块裁出来重认;口算卡一块十几道,入库前逐条勾选",
|
||||
"230 张真实卷:切题 98.7%、题干可用 92.3%"],
|
||||
["判分", "纯算式机器判(分数/小数精确比较),其余孩子自评;认不准就拒答,不硬判",
|
||||
"330 道人工作答:判错 0 道"],
|
||||
["解析", "口算卡/竖式区先拆成单道;每道生成三步,逐句重算校验;算不通就退回通用三步",
|
||||
"425 道真题:0 句算错"],
|
||||
["学习闭环", "错三次才入库;粗心单独隔离;连对两次 + 讲清才毕业;当天错了又对算「会但不稳」,明天重来",
|
||||
"239 个单测,状态机 7 态全覆盖"],
|
||||
["讲不清怎么办", "退一层:回头补前置知识点(39 个知识点 / 60 条先修边,小学 1–3 年级数学)",
|
||||
"「36×24 讲不清 → 先补多位数乘一位数」"],
|
||||
["家长那一张纸", "A5 周报:留答题线、答案折叠、家长签字,可直接交给老师",
|
||||
"服务端出 HTML,浏览器打印即所见"],
|
||||
["手机", "底部 6 个 tab,今日训练/错题本/周报三屏可用",
|
||||
"390×844 实测,无横向溢出"],
|
||||
["知识点归类", "拍照入库的题自动归到 147 个知识点里的一个;认不出就留空",
|
||||
"39 道补上 12 道,剩 3 道确实没有对应点"],
|
||||
],
|
||||
widths=[3.0, 8.6, 5.0], font_size=8.6)
|
||||
|
||||
|
||||
def part3(doc):
|
||||
S.h1(doc, "三、四组数字(每组一句口径)")
|
||||
S.body(doc, "怕被问「这数字怎么来的」,所以每组都写清样本和方法。完整版在 report/错题毕业-拍题评测-230张.md。")
|
||||
S.make_table(doc,
|
||||
["要证明的事", "数字", "样本 / 方法"],
|
||||
[
|
||||
["拍一张卷子,机器能不能把它切开", "切题 98.7%(227/230)", "360 图片搜来的真实试卷照片,去重后 230 张,每张调一次腾讯切题"],
|
||||
["切出来的题干能不能看", "题干可用 92.3%(1665/1804)", "同上,按「≥6 个汉字或算式+汉字」判定,人工抽检"],
|
||||
["判分会不会把孩子做对的判成错", "误判 0 / 330(95% 上界 1.19%)", "16 张卷、330 道口算,人工逐题写标准答案做金标"],
|
||||
["机判的题,机器自己算得对不对", "95.9%(535/558)", "算式级比对,240 道来自 230 张评测、90 道来自人工金标"],
|
||||
["生成的三步解释有没有算错", "0 句(425 道)", "把每句「a ○ b = c」独立重算,再核对答案是否落在步骤里"],
|
||||
],
|
||||
widths=[5.4, 4.6, 6.4], font_size=8.6)
|
||||
|
||||
S.callout(doc, "别说过头",
|
||||
"这些是**自己量的**,不是第三方评测;样本集中在小学 1–5 年级数学口算与竖式,"
|
||||
"语文、应用题、初高中没有量化。汇报时说「在我采的这批卷子上」,不要说「准确率 96%」。")
|
||||
|
||||
S.h2(doc, "成本(会被追问)")
|
||||
S.body(doc, "一张卷 1 次调用;勾到口算卡再裁出来重认一次,命中缓存就不花钱。实测一张卷平均 1.4 次。")
|
||||
S.make_table(doc,
|
||||
["口径", "一学期 20 张卷", "占 69 元定价"],
|
||||
[
|
||||
["腾讯试卷切题 0.18 元/次", "28 次 ≈ 5.0 元", "7.3%"],
|
||||
["换成整页 OCR 0.0825 元/次(自己做切块)", "28 次 ≈ 2.3 元", "3.3%"],
|
||||
["现在是免费额度 1000 次/月", "够约 35 个学生/月", "—"],
|
||||
],
|
||||
widths=[7.4, 4.6, 4.4], font_size=8.6)
|
||||
|
||||
|
||||
def part4(doc):
|
||||
S.h1(doc, "四、还没做完(按「谁能推」分,不按重要性)", new_page=True)
|
||||
S.make_table(doc,
|
||||
["类别", "事项", "为什么没做 / 卡在哪"],
|
||||
[
|
||||
["只有你能推", "企业主体 + 教育类目资质", "个人主体连小程序码都拿不到(腾讯返回 85412)"],
|
||||
["只有你能推", "微信开发者工具真机联调", "要扫码登录开发者账号,10 分钟,不通后面全空转"],
|
||||
["只有你能推", "5 个家长访谈", "验证 19:30 那 4 分钟到底存不存在"],
|
||||
["只有你能推", "定价拍板(69 / 99)", "代码里 pay_enabled 还是 false"],
|
||||
["我能做(1 天)", "支付下单(现在只有回调校验)", "没主体没商户号,做不了真链路;可先做激活码兑换"],
|
||||
["我能做(1–2 天)", "部署到真服务器 + 备份恢复演练", "deploy/ 只在本地验过 compose 语法"],
|
||||
["我能做(2–3 天)", "解析只有文字,没有公式和图形", "分数已转成 1/4×3/5,几何图形还没有"],
|
||||
["我能做(1 天)", "错题召回只有一条来源", "同一个知识点换个数字的题还没做全"],
|
||||
["上线前门槛", "合规:隐私政策、儿童个人信息、注销与导出", "现在只有退出登录和 90 天删照片"],
|
||||
["上线前门槛", "可观测:没看板没报警,只有 log_event", "出问题只能翻日志"],
|
||||
["上线前门槛", "回归基线:没有 CI,没有 UI 截图基线", "239 单测只保接口,保不了界面"],
|
||||
],
|
||||
widths=[3.0, 6.6, 6.8], font_size=8.4)
|
||||
|
||||
S.h2(doc, "明确不做的(也是决定)")
|
||||
S.bullet(doc, "不做题库、不做拍照搜题、不做 AI 批改整卷。这三件都有大厂在做,而且免费。")
|
||||
S.bullet(doc, "不做课标映射。没有可商用的课标条目数据,自己编「对应第 X 条」是假精确。")
|
||||
S.bullet(doc, "初中版暂不套「会但不稳」。那边用的是「做对一道变式」替代第二次连对,规则不同。")
|
||||
|
||||
|
||||
def part5(doc):
|
||||
S.h1(doc, "五、明天 5 分钟怎么讲", new_page=True)
|
||||
S.body(doc, "照这个顺序讲,每段都给了能直接念的话。演示在前,架构一句不提。")
|
||||
|
||||
S.make_table(doc,
|
||||
["时间", "做什么", "直接念的话"],
|
||||
[
|
||||
["0:00–0:30\n开场", "不介绍技术栈,先给一句定义",
|
||||
"「我们做的不是错题本。错题本是往里存,我们是往外清:一道题连对两次、还能讲清楚,才算毕业。」"],
|
||||
["0:30–2:30\n演示", "打开工作台,按下面六步走",
|
||||
"「我演一遍家长实际会看到的东西。」(六步见下)"],
|
||||
["2:30–3:30\n数字", "只讲四组,每组一句口径",
|
||||
"「切开率 98.7%,这是 230 张真卷子量出来的;判错 0 道,330 道人工金标;解释里算错 0 句,425 道真题逐句重算。」"],
|
||||
["3:30–4:30\n卡点", "两件办不了的事,说清楚要什么",
|
||||
"「现在卡在两件我办不了的事:企业主体资质,和微信开发者工具的真机联调。这两件不通,功能做多少都见不到家长。」"],
|
||||
["4:30–5:00\n要决定", "给选项,不要开放式提问",
|
||||
"「两件事想请你拍板:先卖哪个学段;定价 69 还是 99。你定了我按这个往下推。」"],
|
||||
],
|
||||
widths=[2.6, 5.4, 8.4], font_size=8.4)
|
||||
|
||||
S.h2(doc, "演示六步(2 分钟,别多)")
|
||||
for i, step in enumerate([
|
||||
"打开工作台首页:「今天做 5 道,约 4 分钟」——先让听的人看到「量很小」,这是卖点不是缺点。",
|
||||
"点「开始第 1 道」,故意答错一个:出现「再想想 / 应为 10,你写的是 11」。",
|
||||
"答对一次:出现「会了,但还不稳」——讲清这条规则:当天错了又对,明天再来一次。",
|
||||
"进「错题本」:状态分观察中 / 待复习 / 会但不稳 / 待讲清 / 已毕业,粗心单独一栏。",
|
||||
"进「周报与打印」→「打开可打印版」:一张 A5,留了答题线、答案折叠、有签字栏。「这张纸可以交给老师。」",
|
||||
"进「拍照入库」:整页拍 → 框出来 → 点哪几道错了 → 弹「这块里有几道」逐条勾。最后一句:「切不干净也能用,因为最后是家长点。」",
|
||||
], 1):
|
||||
S.bullet(doc, step, f"{i}. ")
|
||||
|
||||
S.callout(doc, "两个坑",
|
||||
"① 演示别用真实孩子数据,用演示数据(工作台「先看演示」);② 拍照入库这一步会调腾讯接口,"
|
||||
"现场网络不通就跳过,说「这一步要联网,会后单独看」。不要在现场 debug。")
|
||||
|
||||
S.h2(doc, "收尾一句")
|
||||
S.quote(doc, "这五天做的事可以用一句话概括:把「拍一张卷子」到「这道题毕业」这条链路,从想法变成了能跑、能量化、能给别人看的东西。剩下的是资质和联调,不是技术。",
|
||||
"建议原样念,不要临场发挥")
|
||||
|
||||
|
||||
def part6(doc):
|
||||
S.h1(doc, "六、可能被问的八个问题", new_page=True)
|
||||
S.make_table(doc,
|
||||
["他会问", "你怎么答(先给结论)"],
|
||||
[
|
||||
["跟作业帮、试卷宝有什么区别?",
|
||||
"它们卖题库和讲解,我们卖「消灭」。题库是往里加,我们是往外减——界面首页只有 5 道题,一个学期目标是让它变空。"],
|
||||
["豆包免费就能讲题,凭什么收钱?",
|
||||
"收费的不是讲题,是「到点提醒、做不对重讲、讲不清不算过」。这三件免费工具都不做,也做不了——它们不知道你孩子哪天该复习哪道。"],
|
||||
["拍不清楚怎么办?",
|
||||
"整页拍,家长在图上点哪几道错了;口算卡入库前还能逐条勾。切不干净不影响用,因为最后一道判断是人做的。"],
|
||||
["判错了怎么办?",
|
||||
"判不准就拒答,不硬判。330 道人工金标里判错 0 道,95% 置信上界 1.19%。纯算式才机器判,其余孩子自评。"],
|
||||
["成本多少?",
|
||||
"一张卷 1.4 次调用,一学期 20 张约 5 元,占 69 元的 7%。换成整页 OCR 自己做切块,能压到 2.3 元。免费额度现在够 35 个学生/月。"],
|
||||
["孩子会不会直接看答案?",
|
||||
"答完才给答案和解析,之前不给。讲清那一步是让孩子说,不是让 AI 说。"],
|
||||
["数据安全怎么保证?",
|
||||
"数据在自己服务器上的 sqlite,照片 90 天自动删,退出登录会话立刻失效。隐私政策和儿童个人信息条款还没写,这是上线前的硬门槛。"],
|
||||
["什么时候能上线?",
|
||||
"我这边一周内可以交付可上线版本;取决于主体资质和真机联调,这两件在你手上。"],
|
||||
],
|
||||
widths=[4.6, 11.8], font_size=8.4)
|
||||
|
||||
|
||||
def part7(doc):
|
||||
S.h1(doc, "七、接下来两周(如果明天点头)")
|
||||
S.make_table(doc,
|
||||
["周", "我做什么", "交付物"],
|
||||
[
|
||||
["第 1 周", "支付下单 + 激活码兑换;部署到真服务器并做一次备份恢复演练", "能在公网访问的地址 + 恢复脚本跑通的记录"],
|
||||
["第 1 周", "CI:239 单测 + 4 套冒烟 + 解析自校验串成一条命令", "一条命令,红绿灯"],
|
||||
["第 2 周", "手机端补齐(拍照/讲一遍也可用);周报入口在手机上验证", "手机四屏截图"],
|
||||
["第 2 周", "合规三件套:隐私政策、儿童个人信息、注销与导出", "可点的注销与导出入口"],
|
||||
],
|
||||
widths=[2.2, 9.0, 5.2], font_size=8.6)
|
||||
S.body(doc, "如果明天拿不到资质,就先把「一个班」跑起来:10 个家庭、2 周,用激活码发,不上架、不收款。这样至少能验证 19:30 那 4 分钟到底存不存在。")
|
||||
|
||||
|
||||
def appendix(doc):
|
||||
S.h1(doc, "附录:现场可用的命令", new_page=True)
|
||||
S.body(doc, "演示前先在电脑上跑第一条,第二条是给别人看的地址。")
|
||||
for line in [
|
||||
"python -m backend.app --host 0.0.0.0 --port 8000",
|
||||
"工作台 http://127.0.0.1:8000/workbench 接口控制台 http://127.0.0.1:8000/",
|
||||
"python tools/run_tests.py 239 个单测",
|
||||
"python tests\\smoke_http.py 41 项接口冒烟",
|
||||
]:
|
||||
p = doc.add_paragraph()
|
||||
S.space(p, 0, 3, 1.35)
|
||||
r = p.add_run(line)
|
||||
S.set_run_font(r, 8.8, False, RGBColor(0x33, 0x33, 0x33))
|
||||
|
||||
S.body(doc, "登录用 dev 模式:打开工作台会出现 8 位码,点码下面的「模拟确认」直接进,不用微信。")
|
||||
S.body(doc, "照片识别会真调腾讯云(1 张 1 次),本月已用 113/900 次。")
|
||||
|
||||
|
||||
def main():
|
||||
doc = new_doc()
|
||||
cover(doc)
|
||||
part1(doc)
|
||||
part2(doc)
|
||||
part3(doc)
|
||||
part4(doc)
|
||||
part5(doc)
|
||||
part6(doc)
|
||||
part7(doc)
|
||||
appendix(doc)
|
||||
doc.save(OUT)
|
||||
print("saved", OUT, round(OUT.stat().st_size / 1024, 1), "KB")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,383 @@
|
||||
"""生成《错题毕业 · 项目总览》:一份给人从零读懂整个项目的文档。
|
||||
|
||||
同一份内容渲染两处,避免两边漂:
|
||||
- `docs/项目总览.md`(仓库里能直接读,Gitee/GitHub 上排版正常)
|
||||
- `report/错题毕业-项目总览.docx`(发给别人看)
|
||||
|
||||
用法:
|
||||
python report/build_overview.py
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from docx import Document
|
||||
from docx.shared import Cm, RGBColor
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
ROOT = HERE.parent
|
||||
sys.path.insert(0, str(HERE))
|
||||
|
||||
from docx_style import ( # noqa: E402
|
||||
add_page_number_footer, body, bullet, callout, h1, h2, lead, make_table, quote,
|
||||
)
|
||||
|
||||
TITLE = "错题毕业 · 项目总览"
|
||||
SUB = "把「错题本」从「收集工具」改成「消灭流程」"
|
||||
META = "v1.0 · 2026-11-23 · 这份文档面向:新加入的人、投资人、合作方"
|
||||
|
||||
# ---------------------------------------------------------------- 内容
|
||||
# 段落类型:lead / p / b(要点)/ h(小标题)/ t(表格:header, rows, widths)/ q(引用框)
|
||||
SECTIONS: list[dict] = [
|
||||
{
|
||||
"title": "一、一页纸",
|
||||
"items": [
|
||||
("lead", "每天 4 分钟,只做 5 道。做对两次、并且讲得清,这道题才算「毕业」。"),
|
||||
("t", ["问题", "我们的回答"], [
|
||||
["是什么", "家长端(电脑/手机浏览器)+ 小程序(拍题、扫码确认)的错题闭环;小学版 69 元/学期,含 2 个孩子"],
|
||||
["解决什么", "错题整理了却不复习,复习了却没真懂——问题不在「收集」,在「消灭」"],
|
||||
["凭什么", "机制:到点提醒重做 / 做不对重讲 / 讲不清不算过 / 会但不稳 / 讲不清退一层;\n工程:一张真卷能切出 98.7% 的题,题干可用 92.3%"],
|
||||
["到哪了", "60 个接口、240 个单测、11 个工作台视图、8 页小程序;本机已经能从头走到尾"],
|
||||
["卡在哪", "主体资质、支付开通、真机联调、家长访谈——四件都在人,不在技术"],
|
||||
], [2.6, 12.6]),
|
||||
],
|
||||
},
|
||||
{
|
||||
"title": "二、需求:不是「整理难」,是「消灭不了」",
|
||||
"items": [
|
||||
("p", "我们采了三份一手数据(脚本在 `collector/`,原始数据在 `data/`):"),
|
||||
("t", ["数据", "规模", "看到了什么"], [
|
||||
["小红书", "220 篇笔记 / 554 条评论", "收藏赞比常 >1(存下来照着做);高频词:错题 318、整理 138、时间 69、方法 63"],
|
||||
["应用商店", "1,097 条评论 / 6 个竞品", "1–2 星 146 条(13.3%);差评里收费/会员 32.9%、功能缺失 21.2%、导出/还原 17.1%、识别不准 15.8%"],
|
||||
["评论信号", "554 条", "科目/年级 16.2%、打印/导出 7.4%、怎么买/在哪用 2.2%、质疑劝退 2.0%"],
|
||||
], [2.6, 4.2, 8.4]),
|
||||
("p", "**应用商店这份最说明问题**:用户在花钱买,但买回来「用不上」。"
|
||||
"试卷宝 4.10 分、差评率 20.4%,蜜蜂试卷 3.82 分、差评率 24.8%,"
|
||||
"最集中的抱怨是「又要开会员」「功能砍了」,而不是「不好用」。"),
|
||||
("h", "用户自己发明的三个办法"),
|
||||
("b", "**手抄/剪贴**:把错题抄到本子上、把卷子剪下来贴——「错题婆罗门」那套说法,本质是嫌工具不好用。"),
|
||||
("b", "**A4 打印重做**:「整理成文档打印,A4 纸剪下就行」——用户已经在替我们做「重做」这一步。"),
|
||||
("b", "**家长盯**:「大部分时间是老母亲整理,初中娃时间宝贵」——采集和验收都落在家长身上。"),
|
||||
("h", "四条需求结论"),
|
||||
("b", "要的是**重做**,不是**收集**:本子越厚越不敢翻,能「变少」才是正反馈。"),
|
||||
("b", "要**到点提醒**:没有提醒的错题本 = 一次性工具。"),
|
||||
("b", "要**讲得清**:看懂了答案 ≠ 会了;能用自己的话讲出来才算。"),
|
||||
("b", "**不要抄题**:抄题是最大的时间黑洞,也是用户最先放弃的一步。"),
|
||||
],
|
||||
},
|
||||
{
|
||||
"title": "三、竞品:六类玩家,五种活法",
|
||||
"items": [
|
||||
("t", ["类别", "代表", "怎么活", "强在哪", "弱在哪(有据)"], [
|
||||
["工具型 App", "试卷宝、蜜蜂试卷、橙果、错题本-拍照整理",
|
||||
"会员 / 超级会员,靠题库和试卷库",
|
||||
"题库大、拍照搜题快",
|
||||
"收费墙与砍功能是差评第一因;500 题只能下载 100 题;题图分离处理不了"],
|
||||
["大厂学习 App", "作业帮、学而思、豆包爱学",
|
||||
"免费或低价引流,靠内容与直播变现",
|
||||
"流量大、AI 能力强",
|
||||
"AI 会讲错(差评 7.2% 集中在此);不跟踪进度、不闭环"],
|
||||
["硬件打印", "喵喵机、咕咕机",
|
||||
"卖机器与耗材",
|
||||
"即拍即印,手感好",
|
||||
"只解决「印出来」,不解决「做没做对」"],
|
||||
["学校/机构平台", "校本题库、智慧课堂",
|
||||
"招投标、B 端采购",
|
||||
"有校本数据、老师背书",
|
||||
"家长在家用不上;无法按一个孩子调难度"],
|
||||
["通用 AI", "豆包、夸克、Kimi",
|
||||
"免费,靠生态",
|
||||
"免费、什么都能问",
|
||||
"不记进度、不提醒、不验收;判分不可靠"],
|
||||
["个体卖家", "小红书上的手作工具(如 29 元 7 天 / 198 元一年)",
|
||||
"私域卖卡,网页交付",
|
||||
"便宜、灵活、离用户近",
|
||||
"积分陷阱(日均可用户积分 43 vs 年费 1.2,差 35 倍);网页无推送;采集在手机、加工在电脑"],
|
||||
], [2.4, 3.6, 3.2, 3.0, 6.4]),
|
||||
("h", "六类里没有一类在做的事"),
|
||||
("lead", "「到点重做 + 做不对重讲 + 讲不清不算过」这条链,没人把它做成默认流程。"),
|
||||
("p", "工具型做的是「收」,大厂做的是「讲」,硬件做的是「印」,学校做的是「布置」,"
|
||||
"通用 AI 做的是「答」,个体卖家做的是「卖」。**中间那条「盯到会为止」的缝,是空的。**"),
|
||||
],
|
||||
},
|
||||
{
|
||||
"title": "四、优势:四条,每条都有数字",
|
||||
"items": [
|
||||
("h", "1. 机制:一条别人没有的链"),
|
||||
("t", ["环节", "规则", "为什么这么定"], [
|
||||
["入库", "同一道题错三次才进错题本", "错一次多半是手滑,不配占孩子的时间"],
|
||||
["隔离", "当天做错、24 小时内做对 → 进「粗心小记」", "粗心不该重做,该练「检查」"],
|
||||
["重做", "次日同一时间再做一次", "隔一天才验得出记没记住"],
|
||||
["会但不稳", "当天错了又对,不算连对,明天从头再来", "当场做对只是「听完会了」"],
|
||||
["毕业", "连对两次 + 讲一遍讲清", "讲不清 = 没懂,回炉"],
|
||||
["退一层", "讲不清时退到前置知识点,做对两道再回来", "前置缺了,讲十遍也不会过"],
|
||||
], [2.2, 7.4, 5.6]),
|
||||
("h", "2. 工程:拍题是真的能用"),
|
||||
("b", "**切题**:230 张真卷,227 张切开(98.7%);题块 1,804 个,题干可用 92.3%。"),
|
||||
("b", "**判分**:可自动判的题里自算 95.9%(Fraction 精确算,`0.6` 与 `3/5` 等价)。"),
|
||||
("b", "**金标**:330 道人工标注,认对 96.4%(CI 93.8–97.9),**误判 0**(CI 0–1.19)。"),
|
||||
("b", "**解析**:425 道真题的三步解析逐句重算,错句 0(这项修掉了三类静默算错)。"),
|
||||
("p", "这几项的意思不是「比别人准」,而是**这套流程可以真跑**——拍一张卷子,家长点几下,"
|
||||
"第二天孩子就能做题,不用重抄、不用打印机。"),
|
||||
("h", "3. 成本:一学期 1.4–2.8 元"),
|
||||
("p", "OCR 是最容易失控的一项。现在四道闸:结果缓存(同图不重复花钱)、月度预算(到顶自动停)、"
|
||||
"整块够好就不裁剪、补扫默认关。一张卷从 4 次调用降到 **1.4 次**;"
|
||||
"一学期 20 张 ≈ 28 次 ≈ **1.4–2.8 元**,占 69 元学费的 2–4%。改造之前是 12–17 元(20% 以上),模型不成立。"),
|
||||
("h", "4. 形态与隐私"),
|
||||
("b", "**不要求重抄**:整页拍 → 点框选错题 → 一块多道时逐条勾 → 只入库勾中的。"),
|
||||
("b", "**不绑硬件**:周报是一张 A5,家里有打印机就打,没有就在屏幕上看。"),
|
||||
("b", "**数据在你自己机器上**:SQLite 单文件、照片 90 天自动删、不做模型训练;可以自己部署(Docker + Caddy)。"),
|
||||
("h", "诚实的边界:这些不是我们的优势"),
|
||||
("b", "**AI 讲解本身不是壁垒**——豆包免费,讲得也不差。我们赌的是「盯到会」的流程。"),
|
||||
("b", "**知识覆盖还薄**:147 条解析模板、实际在用 18 个知识点;先修图只做了小学 1–3 年级 39 个点、60 条边。"),
|
||||
("b", "**评测偏窄**:只覆盖小学 1–5 年级数学口算;语文是「判不准就交给人」,不是自动判分。"),
|
||||
("b", "**没有 App**:小程序 + 网页,召回手段只有订阅消息。"),
|
||||
],
|
||||
},
|
||||
{
|
||||
"title": "五、现在能跑什么",
|
||||
"items": [
|
||||
("t", ["端", "已经能做的", "状态"], [
|
||||
["家长端\n(工作台 11 个视图)",
|
||||
"今日训练 5 道、错题本(按 8 种状态筛)、复习计划、学情分析、周报(A5 可打印)、"
|
||||
"已毕业、粗心小记、多孩切换、扫码登录、拍照入库(点选 + 逐条勾)、讲一遍(含退一层)",
|
||||
"可跑"],
|
||||
["孩子端\n(小程序 8 页)",
|
||||
"扫码确认登录、拍题(点框 → 逐条勾 → 入库)、首页、我的、工作台 web-view",
|
||||
"可跑,需真机联调"],
|
||||
["后端",
|
||||
"60 条接口、23 张表、240 个单测 + 4 套冒烟(41/22/21/29)",
|
||||
"全绿"],
|
||||
["运营/交付",
|
||||
"Docker + Caddy 部署、systemd 加固、SQLite 备份脚本(留 14 份)、隐私与同意流程",
|
||||
"脚本就绪,未上真机"],
|
||||
], [3.4, 9.6, 2.2]),
|
||||
],
|
||||
},
|
||||
{
|
||||
"title": "六、技术一图(文字版)",
|
||||
"items": [
|
||||
("p", "小程序 / 浏览器 → `backend/`(零依赖 http.server + SQLite)→ 腾讯云 QuestionSplitOCR"
|
||||
"(外挂缓存 + 月度预算)→ 判分(算式自算 / 选择比对 / 人工自评)→ 调度"
|
||||
"(简化 SM-2:1 / 3 / 7 / 15 / 30 天)→ 周报、A5 打印、订阅消息。"),
|
||||
("p", "两个产品共用 `core/`(时间、SQLite 连接、文本归一、Fraction 求值);"
|
||||
"小学版在 `backend/`,初中版在 `junior/`(独立端口与库),刻意不合并业务层。"),
|
||||
],
|
||||
},
|
||||
{
|
||||
"title": "七、怎么跑起来(三步)",
|
||||
"items": [
|
||||
("b", "**起后端**:`python -m backend.app --host 0.0.0.0 --port 8000`"),
|
||||
("b", "**打开工作台**:浏览器访问 `http://127.0.0.1:8000/workbench`,点「模拟确认」即可登录(dev 模式)"),
|
||||
("b", "**手机**:同一 Wi-Fi 下访问 `http://<你的内网IP>:8000/workbench`;不想连后端就直接双击 `prototype/workbench/index.html` 看演示"),
|
||||
("p", "自检:`python tools/run_tests.py`(240 个用例)、`python tools/scan_e2e.py`(拍题三接口端到端)。"
|
||||
"唯一花钱的是拍照入库,本月用量见 `data/ocr_usage.json`,到顶会自动停。"),
|
||||
],
|
||||
},
|
||||
{
|
||||
"title": "八、还没做完的,以及谁来做",
|
||||
"items": [
|
||||
("t", ["类别", "事项", "谁能推"], [
|
||||
["上线硬门槛", "主体与教育类目资质、支付开通(代码里 `pay_enabled: false`)", "只有你能推"],
|
||||
["上线硬门槛", "真机联调(微信开发者工具 + 局域网 IP)", "只有你能推"],
|
||||
["上线硬门槛", "5 个家长访谈,验证「19:30 那 4 分钟」", "只有你能推"],
|
||||
["上线硬门槛", "部署到真服务器 + 备份恢复演练", "我能做"],
|
||||
["体验缺口", "公式与图形的解析(现在只有文字)", "我能做"],
|
||||
["体验缺口", "召回只有订阅消息一条,缺站内提醒/周报回流", "我能做"],
|
||||
["技术债", "CI + UI 截图基线;SQLite 并发压测与限流;告警", "我能做"],
|
||||
["明确不做", "不做题库、不做硬件、不做直播课——这三件都是别人的强项", "已拍板"],
|
||||
], [2.6, 9.6, 3.0]),
|
||||
("p", "建议顺序:**真机联调 → 支付 → 部署演练 → 公式图形 → 召回**。"
|
||||
"前两件不通,后面的优化都看不到效果。"),
|
||||
],
|
||||
},
|
||||
{
|
||||
"title": "九、想看更细的",
|
||||
"items": [
|
||||
("p", "文档索引见 `docs/README.md`:需求证据、竞品对比、产品方案、PRD、拍题评测、"
|
||||
"接口手册、工作台手册、小程序手册、部署手册,各自对应一份文件,标注了「它能回答什么问题」。"),
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- Markdown
|
||||
def render_md() -> str:
|
||||
out = [f"# {TITLE}", "", f"> {SUB}", "", f"*{META}*", ""]
|
||||
for sec in SECTIONS:
|
||||
out += [f"## {sec['title']}", ""]
|
||||
for it in sec["items"]:
|
||||
kind = it[0]
|
||||
if kind == "lead":
|
||||
out += [f"> {it[1]}", ""]
|
||||
elif kind == "p":
|
||||
out += [it[1], ""]
|
||||
elif kind == "b":
|
||||
out += [f"- {it[1]}", ""]
|
||||
elif kind == "h":
|
||||
out += [f"### {it[1]}", ""]
|
||||
elif kind == "q":
|
||||
out += [f"> {it[1]}", ""]
|
||||
elif kind == "t":
|
||||
header, rows, _ = it[1], it[2], it[3]
|
||||
out.append("| " + " | ".join(header) + " |")
|
||||
out.append("|" + "|".join(["---"] * len(header)) + "|")
|
||||
for r in rows:
|
||||
cells = [c.replace("\n", "<br>") for c in r]
|
||||
out.append("| " + " | ".join(cells) + " |")
|
||||
out.append("")
|
||||
return "\n".join(out).rstrip() + "\n"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- DOCX
|
||||
def render_docx(path: Path) -> None:
|
||||
doc = Document()
|
||||
sec = doc.sections[0]
|
||||
sec.page_width, sec.page_height = Cm(21.0), Cm(29.7)
|
||||
sec.top_margin = sec.bottom_margin = Cm(2.2)
|
||||
sec.left_margin = sec.right_margin = Cm(2.3)
|
||||
|
||||
p = doc.add_paragraph()
|
||||
from docx.shared import Pt
|
||||
from docx_style import ACCENT, set_run_font
|
||||
r = p.add_run(TITLE)
|
||||
set_run_font(r, 22, True, ACCENT)
|
||||
p.paragraph_format.space_after = Pt(4)
|
||||
|
||||
p2 = doc.add_paragraph()
|
||||
r2 = p2.add_run(SUB)
|
||||
set_run_font(r2, 12, False)
|
||||
p2.paragraph_format.space_after = Pt(2)
|
||||
|
||||
p3 = doc.add_paragraph()
|
||||
r3 = p3.add_run(META)
|
||||
set_run_font(r3, 9, False, RGBColor(0x6B, 0x65, 0x60))
|
||||
p3.paragraph_format.space_after = Pt(10)
|
||||
|
||||
def plain(t: str) -> str:
|
||||
# Word 里反引号不好看:`collector/` → collector/
|
||||
return t.replace("`", "")
|
||||
|
||||
first = True
|
||||
for s in SECTIONS:
|
||||
h1(doc, s["title"], first=first, new_page=not first)
|
||||
first = False
|
||||
for it in s["items"]:
|
||||
kind = it[0]
|
||||
if kind == "lead":
|
||||
lead(doc, plain(it[1]))
|
||||
elif kind == "p":
|
||||
body(doc, plain(it[1]))
|
||||
elif kind == "b":
|
||||
bullet(doc, plain(it[1]))
|
||||
elif kind == "h":
|
||||
h2(doc, it[1])
|
||||
elif kind == "q":
|
||||
quote(doc, it[1], "")
|
||||
elif kind == "t":
|
||||
header, rows, widths = it[1], it[2], it[3]
|
||||
make_table(doc, header, rows, widths, font_size=8.5)
|
||||
|
||||
add_page_number_footer(sec, "错题毕业 · 项目总览")
|
||||
doc.save(str(path))
|
||||
|
||||
|
||||
def render_html() -> str:
|
||||
"""一页能打印的 HTML:Chrome 无头模式直接 print-to-pdf,不依赖 Office。"""
|
||||
def esc(s: str) -> str:
|
||||
return (s.replace("&", "&").replace("<", "<").replace(">", ">")
|
||||
.replace("\n", "<br>"))
|
||||
|
||||
def inline(s: str) -> str:
|
||||
"""把 **粗体** 和 `代码` 变成标签。"""
|
||||
s = esc(s).replace("<br>", "\n")
|
||||
out, bold, code = [], False, False
|
||||
i = 0
|
||||
while i < len(s):
|
||||
if s.startswith("**", i):
|
||||
out.append("<strong>" if not bold else "</strong>")
|
||||
bold = not bold
|
||||
i += 2
|
||||
elif s[i] == "`":
|
||||
out.append("<code>" if not code else "</code>")
|
||||
code = not code
|
||||
i += 1
|
||||
else:
|
||||
out.append(s[i])
|
||||
i += 1
|
||||
text = "".join(out).replace("\n", "<br>")
|
||||
return text
|
||||
|
||||
parts = [
|
||||
"<!doctype html><html lang='zh-CN'><meta charset='utf-8'>",
|
||||
f"<title>{TITLE}</title>",
|
||||
"""<style>
|
||||
@page { size: A4; margin: 18mm 16mm; }
|
||||
* { box-sizing: border-box; }
|
||||
body { font-family: "Microsoft YaHei","PingFang SC",sans-serif; color:#24211F;
|
||||
font-size:10.5pt; line-height:1.62; margin:0 auto; max-width:178mm; padding:10mm 11mm 16mm; }
|
||||
@media print { body { max-width:none; padding:0; margin:0; } }
|
||||
h1 { font-size:19pt; color:#C8483A; border-bottom:2px solid #E3C8C6; padding-bottom:5pt; margin:0 0 3pt; }
|
||||
.sub { font-size:11.5pt; color:#3A3532; margin:0 0 2pt; }
|
||||
.meta { font-size:8.5pt; color:#6B6560; margin:0 0 14pt; }
|
||||
h2 { font-size:14pt; color:#C8483A; margin:16pt 0 7pt; padding-bottom:3pt;
|
||||
border-bottom:1px solid #EDE2D6; page-break-after:avoid; }
|
||||
h3 { font-size:11pt; margin:11pt 0 4pt; page-break-after:avoid; }
|
||||
p { margin:0 0 6pt; }
|
||||
.lead { background:#FFF6EC; border-left:3px solid #E4634A; padding:7pt 9pt; margin:7pt 0 9pt;
|
||||
font-size:11pt; color:#7A3B2E; }
|
||||
ul { margin:0 0 7pt; padding-left:15pt; }
|
||||
li { margin:0 0 3.5pt; }
|
||||
table { width:100%; border-collapse:collapse; margin:6pt 0 10pt; font-size:9pt; }
|
||||
th { background:#FBEEE6; text-align:left; padding:5pt 6pt; border-bottom:1px solid #E3C8C6;
|
||||
font-weight:600; color:#8A4B3E; }
|
||||
td { padding:5pt 6pt; border-bottom:1px solid #F3EADD; vertical-align:top; }
|
||||
tr { page-break-inside:avoid; }
|
||||
code { font-family:Consolas,monospace; font-size:9pt; background:#F6F1E9; padding:0 2pt; border-radius:2pt; }
|
||||
strong { color:#8A3A2A; }
|
||||
</style>""",
|
||||
f"<h1>{TITLE}</h1><p class='sub'>{esc(SUB)}</p><p class='meta'>{esc(META)}</p>",
|
||||
]
|
||||
for sec in SECTIONS:
|
||||
parts.append(f"<h2>{esc(sec['title'])}</h2>")
|
||||
for it in sec["items"]:
|
||||
kind = it[0]
|
||||
if kind == "lead":
|
||||
parts.append(f"<div class='lead'>{inline(it[1])}</div>")
|
||||
elif kind == "p":
|
||||
parts.append(f"<p>{inline(it[1])}</p>")
|
||||
elif kind == "b":
|
||||
parts.append(f"<ul><li>{inline(it[1])}</li></ul>")
|
||||
elif kind == "h":
|
||||
parts.append(f"<h3>{esc(it[1])}</h3>")
|
||||
elif kind == "q":
|
||||
parts.append(f"<div class='lead'>{inline(it[1])}</div>")
|
||||
elif kind == "t":
|
||||
header, rows, widths = it[1], it[2], it[3]
|
||||
total = float(sum(widths))
|
||||
cols = "".join(f"<col style='width:{w / total * 100:.1f}%'>" for w in widths)
|
||||
parts.append("<table><colgroup>" + cols + "</colgroup><tr>"
|
||||
+ "".join(f"<th>{esc(c)}</th>" for c in header) + "</tr>")
|
||||
for r in rows:
|
||||
parts.append("<tr>" + "".join(f"<td>{esc(c)}</td>" for c in r) + "</tr>")
|
||||
parts.append("</table>")
|
||||
parts.append("</html>")
|
||||
return "\n".join(parts)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
md_path = ROOT / "docs" / "项目总览.md"
|
||||
docx_path = HERE / "错题毕业-项目总览.docx"
|
||||
html_path = HERE / "_overview.html"
|
||||
md_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
md_path.write_text(render_md(), encoding="utf-8")
|
||||
render_docx(docx_path)
|
||||
html_path.write_text(render_html(), encoding="utf-8")
|
||||
print(f"md {md_path.relative_to(ROOT)} {md_path.stat().st_size:,} bytes")
|
||||
print(f"docx {docx_path.relative_to(ROOT)} {docx_path.stat().st_size:,} bytes")
|
||||
print(f"html {html_path.relative_to(ROOT)} {html_path.stat().st_size:,} bytes")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
After Width: | Height: | Size: 28 KiB |
|
After Width: | Height: | Size: 96 KiB |
|
After Width: | Height: | Size: 123 KiB |
|
After Width: | Height: | Size: 78 KiB |
|
After Width: | Height: | Size: 210 KiB |
|
After Width: | Height: | Size: 92 KiB |
|
After Width: | Height: | Size: 106 KiB |
|
After Width: | Height: | Size: 166 KiB |
|
After Width: | Height: | Size: 135 KiB |
|
After Width: | Height: | Size: 173 KiB |
|
After Width: | Height: | Size: 159 KiB |
|
After Width: | Height: | Size: 135 KiB |
|
After Width: | Height: | Size: 92 KiB |
|
After Width: | Height: | Size: 147 KiB |
|
After Width: | Height: | Size: 208 KiB |
|
After Width: | Height: | Size: 140 KiB |
@@ -153,8 +153,11 @@ def main():
|
||||
and d["data"]["status"] == "graduated", d)
|
||||
|
||||
st, d = call(base, "GET", f"/api/report/weekly?child_id={cid}", None, token)
|
||||
# 注意:dev_advance 会把 attempts 的日期一起往前挪(不然「当天错了又对」永远成立),
|
||||
# 所以跑到这里,前面的做题记录已经不在本周了。这里只校验结构 + 至少一条记录。
|
||||
check("周报有数字和一句话", st == 200 and "numbers" in d["data"]
|
||||
and d["data"]["numbers"]["attempts_this_week"] >= 2, d)
|
||||
and d["data"]["numbers"]["attempts_this_week"] >= 1
|
||||
and d["data"]["one_line"], d)
|
||||
|
||||
st, d = call(base, "GET", f"/api/print/weekly?child_id={cid}&token={token}")
|
||||
check("周日那张纸是 HTML 且含签字栏/答案折叠", st == 200
|
||||
|
||||
@@ -64,7 +64,7 @@ try:
|
||||
|
||||
st, r = call("GET", "/api/health")
|
||||
check("health 200", st == 200, r)
|
||||
check("routes=59", r["data"]["routes"] == 59, r["data"].get("routes"))
|
||||
check("routes=62", r["data"]["routes"] == 62, 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)
|
||||
@@ -131,3 +131,4 @@ finally:
|
||||
print()
|
||||
print("通过 %d 项,失败 %d 项" % (sum(ok), len(ok) - sum(ok)))
|
||||
sys.exit(0 if all(ok) else 1)
|
||||
|
||||
|
||||
@@ -63,7 +63,7 @@ try:
|
||||
|
||||
st, r = call("GET", "/api/health")
|
||||
check("health 200", st == 200, r)
|
||||
check("routes=59", r["data"]["routes"] == 59, r["data"].get("routes"))
|
||||
check("routes=62", r["data"]["routes"] == 62, r["data"].get("routes"))
|
||||
|
||||
st, r = call("POST", "/api/auth/wx-login", {"code": "demo"})
|
||||
tok = r["data"]["token"]
|
||||
@@ -143,3 +143,4 @@ finally:
|
||||
p.unlink()
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
"""W5:语音讲一遍。"""
|
||||
import base64
|
||||
import unittest
|
||||
|
||||
import backend.db as dbm
|
||||
import backend.services as svc
|
||||
from backend.services import ApiError
|
||||
from ._tmpdir import workdir
|
||||
|
||||
|
||||
class AudioBase(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.conn = dbm.connect(workdir("audio") / (self._testMethodName + ".db"))
|
||||
dbm.init_db(self.conn)
|
||||
self.gid = svc.login(self.conn, "demo")["guardian_id"]
|
||||
svc.give_consent(self.conn, self.gid, "v1")
|
||||
self.cid = svc.create_child(self.conn, self.gid, "皮皮", 2)["id"]
|
||||
|
||||
def tearDown(self):
|
||||
self.conn.close()
|
||||
|
||||
def _to_explain(self, stem="36 + 47 ="):
|
||||
r = svc.add_manual_mistake(self.conn, self.gid, self.cid, "math", stem, "83")
|
||||
mid = r["created"][0]["mistake_id"]
|
||||
for _ in range(3):
|
||||
self.conn.execute("UPDATE mistakes SET next_due=? WHERE id=?", (svc.today(), mid))
|
||||
svc.attempt(self.conn, self.gid, self.cid, mid, "999")
|
||||
svc.dev_advance(self.conn, 1)
|
||||
self.conn.execute("UPDATE mistakes SET next_due=? WHERE id=?", (svc.today(), mid))
|
||||
svc.attempt(self.conn, self.gid, self.cid, mid, "83")
|
||||
svc.dev_advance(self.conn, 1)
|
||||
self.conn.execute("UPDATE mistakes SET next_due=? WHERE id=?", (svc.today(), mid))
|
||||
svc.attempt(self.conn, self.gid, self.cid, mid, "83")
|
||||
return mid
|
||||
|
||||
|
||||
class AudioTest(AudioBase):
|
||||
AUDIO = base64.b64encode(b"OggS" + b"\x00" * 4000).decode()
|
||||
|
||||
def test_audio_with_all_checks_graduates(self):
|
||||
mid = self._to_explain()
|
||||
r = svc.explain(self.conn, self.gid, self.cid, mid, "audio", "",
|
||||
checks={"wrong_reason": 1, "key_steps": 1, "next_time": 1},
|
||||
audio_b64=self.AUDIO, audio_ext="webm")
|
||||
self.assertTrue(r["passed"])
|
||||
self.assertIsNotNone(r["audio"])
|
||||
self.assertEqual(r["status"], "graduated")
|
||||
path = svc.UPLOAD_DIR / r["audio"]
|
||||
self.assertTrue(path.exists())
|
||||
self.assertEqual(path.read_bytes()[:4], b"OggS")
|
||||
path.unlink()
|
||||
|
||||
def test_audio_missing_check_fails(self):
|
||||
mid = self._to_explain("82 + 35 =")
|
||||
r = svc.explain(self.conn, self.gid, self.cid, mid, "audio", "",
|
||||
checks={"wrong_reason": 1, "key_steps": 0, "next_time": 1},
|
||||
audio_b64=self.AUDIO, audio_ext="webm")
|
||||
self.assertFalse(r["passed"])
|
||||
self.assertIn("正确走法", r["rubric"]["key_steps"])
|
||||
self.assertTrue(r["ask_stuck_at"], "没过就该问卡点")
|
||||
(svc.UPLOAD_DIR / r["audio"]).unlink(missing_ok=True)
|
||||
|
||||
def test_audio_required(self):
|
||||
mid = self._to_explain("7 + 8 =")
|
||||
with self.assertRaises(ApiError) as ctx:
|
||||
svc.explain(self.conn, self.gid, self.cid, mid, "audio", "", checks={"wrong_reason": 1})
|
||||
self.assertEqual(ctx.exception.code, "NO_AUDIO")
|
||||
|
||||
def test_audio_extension_whitelist(self):
|
||||
mid = self._to_explain("9 + 9 =")
|
||||
with self.assertRaises(ApiError) as ctx:
|
||||
svc.explain(self.conn, self.gid, self.cid, mid, "audio", "",
|
||||
checks={"wrong_reason": 1}, audio_b64=self.AUDIO, audio_ext="exe")
|
||||
self.assertEqual(ctx.exception.code, "BAD_AUDIO_EXT")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -19,7 +19,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parent)) # tests/ 自己
|
||||
from _tmpdir import workdir as _workdir # noqa: E402
|
||||
|
||||
from backend import db as dbm # noqa: E402
|
||||
from backend import judging, scheduler # noqa: E402
|
||||
from backend import app, judging, scheduler # noqa: E402
|
||||
from backend import seed, services as svc # noqa: E402
|
||||
from backend.services import ApiError # noqa: E402
|
||||
|
||||
@@ -584,5 +584,34 @@ class DeletionGraceTest(unittest.TestCase):
|
||||
(self.gid,)).fetchone())
|
||||
|
||||
|
||||
class HealthOcrTest(unittest.TestCase):
|
||||
"""上线自查要能一眼看出 OCR 配没配、这个月用了几次。"""
|
||||
|
||||
def test_health_reports_ocr_state(self):
|
||||
tmp = _workdir("shared")
|
||||
tmp.mkdir(exist_ok=True)
|
||||
path = tmp / f"health_{id(self)}.db"
|
||||
conn = dbm.connect(path)
|
||||
dbm.init_db(conn)
|
||||
try:
|
||||
ctx = app.Ctx(conn=conn, method="GET", path="/api/health",
|
||||
query={}, body={}, headers={})
|
||||
d = app.health(ctx)
|
||||
finally:
|
||||
conn.close()
|
||||
for suffix in ("", "-wal", "-shm"):
|
||||
f = Path(str(path) + suffix)
|
||||
if f.exists():
|
||||
try:
|
||||
f.unlink()
|
||||
except OSError:
|
||||
pass
|
||||
self.assertIn("ocr", d)
|
||||
self.assertIn("configured", d["ocr"]) # 只暴露「有没有」,不暴露密钥
|
||||
self.assertIn("mode", d["ocr"])
|
||||
self.assertIsInstance(d["ocr"].get("used"), int)
|
||||
self.assertEqual(d["version"], "1.2.0")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main(verbosity=2)
|
||||
|
||||
@@ -53,12 +53,16 @@ class GapScanTest(unittest.TestCase):
|
||||
]}
|
||||
m = self._calls(second)
|
||||
with mock.patch.object(scanflow.tencent_ocr, "split_questions", m):
|
||||
d = scanflow.detect(_page(), "p.jpg")
|
||||
d = scanflow.detect(_page(), "p.jpg", gap_scan=True)
|
||||
self.assertEqual(len(d["blocks"]), 2, "漏掉的条带应当被补回来")
|
||||
added = d["blocks"][1]
|
||||
self.assertTrue(added.get("from_gap"))
|
||||
# 坐标要平移回整页:补扫裁的是 y≈476 以下
|
||||
self.assertGreater(added["box"]["y"], 400)
|
||||
# 补扫图放大过 1.4 倍,框要除回去,并且不能跑出页面
|
||||
box = added["box"]
|
||||
self.assertLessEqual(box["y"] + box["h"], 800)
|
||||
self.assertLessEqual(box["x"] + box["w"], 400)
|
||||
|
||||
def test_no_duplicate_when_same_stem(self):
|
||||
second = {"ok": True, "questions": [
|
||||
@@ -66,14 +70,21 @@ class GapScanTest(unittest.TestCase):
|
||||
]}
|
||||
m = self._calls(second)
|
||||
with mock.patch.object(scanflow.tencent_ocr, "split_questions", m):
|
||||
d = scanflow.detect(_page(), "p.jpg")
|
||||
d = scanflow.detect(_page(), "p.jpg", gap_scan=True)
|
||||
self.assertEqual(len(d["blocks"]), 1, "同一道题不能进两次")
|
||||
self.assertEqual(m.call_count, 2, "仍然会补扫一次,只是结果被去重")
|
||||
|
||||
def test_default_is_off(self):
|
||||
"""默认不补扫:这是钱,上一次证明过救不回来。"""
|
||||
m = self._calls({"ok": True, "questions": []})
|
||||
with mock.patch.object(scanflow.tencent_ocr, "split_questions", m):
|
||||
scanflow.detect(_page(), "p.jpg")
|
||||
self.assertEqual(m.call_count, 1, "默认不该补扫;要用就显式开")
|
||||
|
||||
def test_blank_page_no_extra_call(self):
|
||||
m = self._calls({"ok": True, "questions": []})
|
||||
with mock.patch.object(scanflow.tencent_ocr, "split_questions", m):
|
||||
d = scanflow.detect(_page(band=None), "p.jpg")
|
||||
d = scanflow.detect(_page(band=None), "p.jpg", gap_scan=True)
|
||||
self.assertEqual(len(d["blocks"]), 1)
|
||||
self.assertEqual(m.call_count, 1, "页面没有未覆盖的墨迹,不该再调用")
|
||||
|
||||
@@ -92,7 +103,7 @@ class GapScanTest(unittest.TestCase):
|
||||
]}
|
||||
m = self._calls(many)
|
||||
with mock.patch.object(scanflow.tencent_ocr, "split_questions", m):
|
||||
d = scanflow.detect(_page(band=(200, 760)), "p.jpg")
|
||||
d = scanflow.detect(_page(band=(200, 760)), "p.jpg", gap_scan=True)
|
||||
# GAP_MAX=2 条带 → 最多 2 次补扫 + 1 次整页
|
||||
self.assertLessEqual(m.call_count, 1 + scanflow.GAP_MAX)
|
||||
|
||||
|
||||
@@ -35,10 +35,10 @@ class GraphShapeTest(unittest.TestCase):
|
||||
self.assertEqual(missing, [], f"这些知识点在 kpt.json 里找不到:{missing}")
|
||||
|
||||
def test_size_is_mini(self):
|
||||
"""迷你图就该迷你:30–60 个点、40–90 条边。"""
|
||||
"""先修图:1–3 年级已审、4–6 年级是草稿;规模 60–90 个点、80–120 条边。"""
|
||||
topics, par = kp_graph._load()
|
||||
self.assertTrue(30 <= len(topics) <= 60, len(topics))
|
||||
self.assertTrue(40 <= sum(len(v) for v in par.values()) <= 90)
|
||||
self.assertTrue(60 <= len(topics) <= 90, len(topics))
|
||||
self.assertTrue(80 <= sum(len(v) for v in par.values()) <= 120)
|
||||
|
||||
def test_every_edge_has_reason(self):
|
||||
"""每条边都要写人话理由——家长点开要能看懂「为什么退到这」。"""
|
||||
@@ -149,5 +149,24 @@ class ExplainRetreatTest(unittest.TestCase):
|
||||
self.assertIsNone(r["retreat"])
|
||||
|
||||
|
||||
class GraphMissingTest(unittest.TestCase):
|
||||
"""数据文件缺失时不能 500——「退一层」只是建议。"""
|
||||
|
||||
def test_missing_file_degrades_to_empty(self):
|
||||
import tempfile
|
||||
from backend import kp_graph
|
||||
orig = kp_graph.GRAPH_PATH
|
||||
try:
|
||||
kp_graph.GRAPH_PATH = Path(tempfile.gettempdir()) / "no_such_kp_graph.json"
|
||||
kp_graph._load.cache_clear()
|
||||
self.assertIsNone(kp_graph.topic("M041"))
|
||||
self.assertEqual(kp_graph.parents("M041"), [])
|
||||
self.assertIsNone(kp_graph.retreat("M041"))
|
||||
self.assertEqual(kp_graph.validate(), [])
|
||||
finally:
|
||||
kp_graph.GRAPH_PATH = orig
|
||||
kp_graph._load.cache_clear()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
"""知识点归类规则的测试:认得出、认不准就不给、名字都能对上模板。"""
|
||||
|
||||
import unittest
|
||||
|
||||
from backend import kp_match
|
||||
|
||||
|
||||
class RulesHealthTest(unittest.TestCase):
|
||||
"""规则表本身不能烂:候选名必须在 kpt.json 里存在。"""
|
||||
|
||||
def test_every_candidate_resolves(self):
|
||||
bad = kp_match.rules_ok()
|
||||
self.assertEqual(bad, [], f"这些候选名在 kpt.json 里找不到:{bad}")
|
||||
|
||||
def test_templates_loaded(self):
|
||||
self.assertGreaterEqual(len(kp_match._templates()), 100)
|
||||
|
||||
|
||||
class MathTest(unittest.TestCase):
|
||||
def test_two_number_sum(self):
|
||||
self.assertEqual(kp_match.classify("math", "36 + 47 ="), "M026")
|
||||
|
||||
def test_multiplication(self):
|
||||
self.assertEqual(kp_match.classify("math", "7 × 8 ="), "M039")
|
||||
|
||||
def test_division(self):
|
||||
self.assertEqual(kp_match.classify("math", "72 ÷ 8 ="), "M040")
|
||||
|
||||
def test_decimal_beats_integer(self):
|
||||
# 小数乘法要排在整数乘法前面,否则会被「×」那条先抓走
|
||||
self.assertEqual(kp_match.classify("math", "2.5 × 4 ="), "M077")
|
||||
|
||||
def test_decimal_division(self):
|
||||
self.assertEqual(kp_match.classify("math", "4.8 ÷ 6 ="), "M078")
|
||||
|
||||
def test_fraction(self):
|
||||
self.assertEqual(kp_match.classify("math", "1/4 × 3/5 ="), "M087")
|
||||
|
||||
def test_area(self):
|
||||
self.assertEqual(kp_match.classify("math", "一个长方形的面积是多少"), "M051")
|
||||
|
||||
def test_units(self):
|
||||
self.assertEqual(kp_match.classify("math", "一袋大米重 5 千克"), "M046")
|
||||
|
||||
def test_chain(self):
|
||||
self.assertEqual(kp_match.classify("math", "8 × 7 + 6 ="), "M039")
|
||||
|
||||
def test_fraction_beats_unit(self):
|
||||
# 「吨」和「7/10」同时出现:这是分数应用题,不是单位换算
|
||||
self.assertEqual(
|
||||
kp_match.classify("math", "一批货物重20吨,这批货物的7/10是多少吨"), "M086")
|
||||
|
||||
|
||||
class ChineseTest(unittest.TestCase):
|
||||
def test_pinyin_write(self):
|
||||
self.assertEqual(kp_match.classify("chinese", "看拼音写词:xióng māo"), "C011")
|
||||
|
||||
def test_measure_word(self):
|
||||
self.assertEqual(kp_match.classify("chinese", "填量词:一( )书"), "C015")
|
||||
|
||||
def test_synonym(self):
|
||||
self.assertEqual(kp_match.classify("chinese", "写出近义词:高兴—( )"), "C032")
|
||||
|
||||
def test_punctuation(self):
|
||||
self.assertEqual(kp_match.classify("chinese", "给下面的句子加标点"), "C018")
|
||||
|
||||
def test_idiom(self):
|
||||
self.assertEqual(kp_match.classify("chinese", "成语填空:守株待( )"), "C034")
|
||||
|
||||
|
||||
class NoGuessTest(unittest.TestCase):
|
||||
"""认不准的时候宁可不给。"""
|
||||
|
||||
def test_empty(self):
|
||||
self.assertIsNone(kp_match.classify("math", ""))
|
||||
self.assertIsNone(kp_match.classify("math", None))
|
||||
|
||||
def test_unrelated(self):
|
||||
self.assertIsNone(kp_match.classify("math", "下列哪个不是三角形"))
|
||||
|
||||
def test_name_of(self):
|
||||
self.assertEqual(kp_match.name_of("M026"), "加减法(混合)/万以内加减法")
|
||||
self.assertEqual(kp_match.name_of(None), "")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,67 @@
|
||||
# 小狮落库 + 三色/收尾页的数据侧回归
|
||||
import os
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
from tests._tmpdir import workdir
|
||||
|
||||
import backend.db as dbm
|
||||
import backend.services as svc
|
||||
import backend.seed as seed
|
||||
|
||||
|
||||
class PetStageTest(unittest.TestCase):
|
||||
def test_stage_thresholds(self):
|
||||
self.assertEqual(svc.pet_stage_of(0), 0)
|
||||
self.assertEqual(svc.pet_stage_of(11), 0)
|
||||
self.assertEqual(svc.pet_stage_of(12), 1)
|
||||
self.assertEqual(svc.pet_stage_of(40), 2)
|
||||
self.assertEqual(svc.pet_stage_of(100), 3)
|
||||
|
||||
|
||||
class PetSyncTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.db_path = str(workdir("pet") / (self._testMethodName + ".db"))
|
||||
if os.path.exists(self.db_path):
|
||||
os.unlink(self.db_path)
|
||||
self.conn = dbm.connect(self.db_path)
|
||||
dbm.init_db(self.conn)
|
||||
self.gid = svc.login(self.conn, "demo")["guardian_id"]
|
||||
svc.give_consent(self.conn, self.gid, "v1")
|
||||
self.cid = svc.create_child(self.conn, self.gid, "皮皮", 2)["id"]
|
||||
|
||||
def tearDown(self):
|
||||
self.conn.close()
|
||||
|
||||
def test_columns_exist(self):
|
||||
cols = {r["name"] for r in self.conn.execute("PRAGMA table_info(children)")}
|
||||
self.assertIn("pet_stage", cols)
|
||||
self.assertIn("pet_fed_at", cols)
|
||||
|
||||
def test_new_child_is_unfed(self):
|
||||
pet = svc.get_child(self.conn, self.gid, self.cid)["pet"]
|
||||
self.assertEqual(pet["stage"], 0)
|
||||
self.assertEqual(pet["graduated"], 0)
|
||||
self.assertFalse(pet["fed_today"])
|
||||
|
||||
def test_not_fed_while_work_left(self):
|
||||
# 刚入库的题 next_due 是明天(当天不做),要模拟「今天还有活」
|
||||
# 得把它挪成今天到期——否则 left_today 天然是 0。
|
||||
r = svc.add_manual_mistake(self.conn, self.gid, self.cid, "math", "36 + 47 =", "83")
|
||||
mid = r["created"][0]["mistake_id"]
|
||||
self.conn.execute("UPDATE mistakes SET next_due=? WHERE id=?", (svc.today(), mid))
|
||||
pet = svc.get_child(self.conn, self.gid, self.cid)["pet"]
|
||||
self.assertGreaterEqual(pet["left_today"], 1)
|
||||
self.assertFalse(pet["fed_today"])
|
||||
|
||||
def test_list_children_carries_pet(self):
|
||||
items = svc.list_children(self.conn, self.gid)
|
||||
self.assertTrue(items)
|
||||
self.assertIn("pet", items[0])
|
||||
self.assertIn("fed_today", items[0]["pet"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -151,6 +151,61 @@ class ScanFlowTest(unittest.TestCase):
|
||||
self.assertEqual(len(got), 3)
|
||||
self.assertTrue(any("40×65" in s for s in got))
|
||||
|
||||
def test_prepare_lists_every_sub(self):
|
||||
"""入库前预览:一块三道的口算卡要摊成 3 条,且带上 block/sub 坐标。"""
|
||||
d = self._detect()
|
||||
subs = [{"stem": f"{e} =", "answer": a, "judge_type": "calc"}
|
||||
for e, a in [("34+25", "59"), ("78-25", "53"), ("27+69", "96")]]
|
||||
with mock.patch.object(scanflow, "recognize_block",
|
||||
return_value={"stem": "34+25= 78-25= 27+69=", "judge_type": "card",
|
||||
"options": None, "answer": None, "page_answer": None,
|
||||
"source": "page", "subs": subs}):
|
||||
pv = svc.prepare_scan_picks(
|
||||
self.conn, self.gid, self.cid, "math", d["draft_id"], [d["blocks"][0]["i"]])
|
||||
self.assertEqual(len(pv["items"]), 3)
|
||||
self.assertEqual([it["sub"] for it in pv["items"]], [0, 1, 2])
|
||||
self.assertTrue(all(it["block"] == d["blocks"][0]["i"] for it in pv["items"]))
|
||||
# 预览只读:预览完库里还是空的
|
||||
n = self.conn.execute("SELECT COUNT(*) FROM questions").fetchone()[0]
|
||||
self.assertEqual(n, 0)
|
||||
|
||||
def test_import_only_checked_subs(self):
|
||||
"""逐条勾选:5 道口算里只勾第 0、2 道,就只入库这 2 道。"""
|
||||
d = self._detect()
|
||||
subs = [{"stem": f"{e} =", "answer": a, "judge_type": "calc"}
|
||||
for e, a in [("34+25", "59"), ("78-25", "53"), ("27+69", "96"),
|
||||
("77+69", "146"), ("90-49", "41")]]
|
||||
bi = d["blocks"][0]["i"]
|
||||
with mock.patch.object(scanflow, "recognize_block",
|
||||
return_value={"stem": "口算卡", "judge_type": "card",
|
||||
"options": None, "answer": None, "page_answer": None,
|
||||
"source": "page", "subs": subs}):
|
||||
paper = svc.import_scan_picks(
|
||||
self.conn, self.gid, self.cid, "math", d["draft_id"],
|
||||
[{"i": bi, "subs": [0, 2]}])
|
||||
self.assertEqual(len(paper["questions"]), 2)
|
||||
got = [r["stem"] for r in self.conn.execute(
|
||||
"SELECT stem FROM mistakes WHERE child_id=? ORDER BY id", (self.cid,))]
|
||||
self.assertEqual(len(got), 2)
|
||||
self.assertTrue(any("34+25" in s for s in got))
|
||||
self.assertTrue(any("27+69" in s for s in got))
|
||||
self.assertFalse(any("77+69" in s for s in got), "没勾的(读歪那条)不该入库")
|
||||
|
||||
def test_import_empty_sub_list_falls_back_to_nothing(self):
|
||||
"""subs 全取消:这块就不该入库,不能退化成「整块都要」。"""
|
||||
d = self._detect()
|
||||
subs = [{"stem": "1+1 =", "answer": "2", "judge_type": "calc"},
|
||||
{"stem": "2+2 =", "answer": "4", "judge_type": "calc"}]
|
||||
bi = d["blocks"][0]["i"]
|
||||
with mock.patch.object(scanflow, "recognize_block",
|
||||
return_value={"stem": "x", "judge_type": "card", "options": None,
|
||||
"answer": None, "page_answer": None,
|
||||
"source": "page", "subs": subs}):
|
||||
with self.assertRaises(ApiError) as ctx:
|
||||
svc.import_scan_picks(self.conn, self.gid, self.cid, "math",
|
||||
d["draft_id"], [{"i": bi, "subs": []}])
|
||||
self.assertEqual(ctx.exception.code, "NO_PICKS")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
"""W4:讲清失败记卡点(stuck_at)。"""
|
||||
import unittest
|
||||
|
||||
import backend.db as dbm
|
||||
import backend.services as svc
|
||||
from backend.services import ApiError
|
||||
from ._tmpdir import workdir
|
||||
|
||||
|
||||
class StuckBase(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.conn = dbm.connect(workdir("stuck") / (self._testMethodName + ".db"))
|
||||
dbm.init_db(self.conn)
|
||||
self.gid = svc.login(self.conn, "demo")["guardian_id"]
|
||||
svc.give_consent(self.conn, self.gid, "v1")
|
||||
self.cid = svc.create_child(self.conn, self.gid, "皮皮", 2)["id"]
|
||||
|
||||
def tearDown(self):
|
||||
self.conn.close()
|
||||
|
||||
def _to_explain(self, stem="36 + 47 ="):
|
||||
"""造一道走到「待讲清」的题:连错三次 → 隔天对一次 → 再隔天对一次。"""
|
||||
r = svc.add_manual_mistake(self.conn, self.gid, self.cid, "math", stem, "83")
|
||||
mid = r["created"][0]["mistake_id"]
|
||||
for _ in range(3):
|
||||
self.conn.execute("UPDATE mistakes SET next_due=? WHERE id=?", (svc.today(), mid))
|
||||
svc.attempt(self.conn, self.gid, self.cid, mid, "999")
|
||||
svc.dev_advance(self.conn, 1)
|
||||
self.conn.execute("UPDATE mistakes SET next_due=? WHERE id=?", (svc.today(), mid))
|
||||
svc.attempt(self.conn, self.gid, self.cid, mid, "83")
|
||||
svc.dev_advance(self.conn, 1)
|
||||
self.conn.execute("UPDATE mistakes SET next_due=? WHERE id=?", (svc.today(), mid))
|
||||
svc.attempt(self.conn, self.gid, self.cid, mid, "83")
|
||||
row = self.conn.execute("SELECT status FROM mistakes WHERE id=?", (mid,)).fetchone()
|
||||
self.assertEqual(row["status"], "to_explain")
|
||||
return mid
|
||||
|
||||
|
||||
class StuckTest(StuckBase):
|
||||
def test_explain_failure_asks_for_stuck_at(self):
|
||||
mid = self._to_explain()
|
||||
r = svc.explain(self.conn, self.gid, self.cid, mid, "steps", "我算错了")
|
||||
self.assertFalse(r["passed"])
|
||||
self.assertTrue(r["ask_stuck_at"], "第一次失败应该问卡点")
|
||||
|
||||
def test_set_stuck_at_and_stop_asking(self):
|
||||
mid = self._to_explain()
|
||||
svc.explain(self.conn, self.gid, self.cid, mid, "steps", "我算错了")
|
||||
out = svc.set_stuck_at(self.conn, self.gid, self.cid, mid, "calc")
|
||||
self.assertEqual(out["stuck_at"], "calc")
|
||||
self.assertEqual(out["stuck_at_zh"], "会做,算错了")
|
||||
row = self.conn.execute("SELECT stuck_at FROM mistakes WHERE id=?", (mid,)).fetchone()
|
||||
self.assertEqual(row["stuck_at"], "calc")
|
||||
# 记过之后,下一次讲清失败不再问(失败会退回队列,所以另起一道)
|
||||
mid2 = self._to_explain("82 + 35 =")
|
||||
self.conn.execute("UPDATE mistakes SET stuck_at='read' WHERE id=?", (mid2,))
|
||||
r2 = svc.explain(self.conn, self.gid, self.cid, mid2, "steps", "我算错了")
|
||||
self.assertFalse(r2["ask_stuck_at"])
|
||||
|
||||
def test_rejects_unknown_value(self):
|
||||
mid = self._to_explain()
|
||||
with self.assertRaises(ApiError) as ctx:
|
||||
svc.set_stuck_at(self.conn, self.gid, self.cid, mid, "tired")
|
||||
self.assertEqual(ctx.exception.code, "BAD_STUCK_AT")
|
||||
|
||||
def test_rejects_unknown_mistake(self):
|
||||
with self.assertRaises(ApiError) as ctx:
|
||||
svc.set_stuck_at(self.conn, self.gid, self.cid, "m_nope", "read")
|
||||
self.assertEqual(ctx.exception.code, "NO_MISTAKE")
|
||||
|
||||
def test_passed_explain_does_not_ask(self):
|
||||
mid = self._to_explain()
|
||||
r = svc.explain(self.conn, self.gid, self.cid, mid, "steps",
|
||||
"我先算个位,忘了进位,所以少了十。下次先圈进位,再检查一遍。")
|
||||
self.assertTrue(r["passed"])
|
||||
self.assertFalse(r["ask_stuck_at"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,114 @@
|
||||
"""W6:变式自校验 + 严档毕业。"""
|
||||
import unittest
|
||||
|
||||
import backend.db as dbm
|
||||
import backend.practice as practice
|
||||
import backend.services as svc
|
||||
from backend.services import ApiError
|
||||
from ._tmpdir import workdir
|
||||
|
||||
|
||||
class VerifyTest(unittest.TestCase):
|
||||
def test_good_calc(self):
|
||||
ok, why = practice.verify({"stem": "36 + 24 =", "answer": "60", "judge_type": "calc"})
|
||||
self.assertTrue(ok, why)
|
||||
|
||||
def test_wrong_answer_rejected(self):
|
||||
ok, why = practice.verify({"stem": "36 + 24 =", "answer": "61", "judge_type": "calc"})
|
||||
self.assertFalse(ok)
|
||||
self.assertIn("对不上", why)
|
||||
|
||||
def test_uncomputable_rejected(self):
|
||||
ok, _ = practice.verify({"stem": "一个数加 3 等于几?", "answer": "5", "judge_type": "calc"})
|
||||
self.assertFalse(ok)
|
||||
|
||||
def test_empty_answer_rejected(self):
|
||||
ok, why = practice.verify({"stem": "36 + 24 =", "answer": "", "judge_type": "calc"})
|
||||
self.assertFalse(ok)
|
||||
self.assertIn("没有答案", why)
|
||||
|
||||
def test_choice_answer_must_be_in_options(self):
|
||||
ok, _ = practice.verify({"stem": "哪个对?", "answer": "E", "judge_type": "choice",
|
||||
"options": {"A": "1", "B": "2"}})
|
||||
self.assertFalse(ok)
|
||||
ok2, _ = practice.verify({"stem": "哪个对?", "answer": "B", "judge_type": "choice",
|
||||
"options": {"A": "1", "B": "2"}})
|
||||
self.assertTrue(ok2)
|
||||
|
||||
def test_similar_only_returns_verified(self):
|
||||
items = practice.similar("36 + 47 =", "83", "calc", "math", 2, n=3)
|
||||
for it in items:
|
||||
self.assertTrue(practice.verify(it)[0], it)
|
||||
|
||||
|
||||
class StrictBase(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.conn = dbm.connect(workdir("w6") / (self._testMethodName + ".db"))
|
||||
dbm.init_db(self.conn)
|
||||
self.gid = svc.login(self.conn, "demo")["guardian_id"]
|
||||
svc.give_consent(self.conn, self.gid, "v1")
|
||||
self.cid = svc.create_child(self.conn, self.gid, "皮皮", 2)["id"]
|
||||
|
||||
def tearDown(self):
|
||||
self.conn.close()
|
||||
|
||||
def _queued(self, stem="36 + 47 ="):
|
||||
import backend.judging as judging
|
||||
ans = judging.fmt_qty(judging.safe_eval(stem.rstrip("== ")))
|
||||
r = svc.add_manual_mistake(self.conn, self.gid, self.cid, "math", stem, ans)
|
||||
mid = r["created"][0]["mistake_id"]
|
||||
for _ in range(3):
|
||||
self.conn.execute("UPDATE mistakes SET next_due=? WHERE id=?", (svc.today(), mid))
|
||||
svc.attempt(self.conn, self.gid, self.cid, mid, "999")
|
||||
# 隔一天再做对:否则会先命中「当天错了又对 → 会但不稳」,走不到严档分支
|
||||
svc.dev_advance(self.conn, 1)
|
||||
return mid
|
||||
|
||||
def _ans(self, mid):
|
||||
return self.conn.execute("SELECT answer FROM mistakes WHERE id=?", (mid,)).fetchone()["answer"]
|
||||
|
||||
def _strict(self, on=True):
|
||||
return svc.set_settings(self.conn, self.gid, self.cid, 1 if on else 0)["strict_variant"]
|
||||
|
||||
|
||||
class StrictFlowTest(StrictBase):
|
||||
def test_strict_requires_variant_before_passed_once(self):
|
||||
mid = self._queued()
|
||||
self.assertEqual(self._strict(), 1)
|
||||
r = svc.attempt(self.conn, self.gid, self.cid, mid, self._ans(mid))
|
||||
self.assertEqual(r["status"], "variant_pending")
|
||||
self.assertTrue(r["need_variant"])
|
||||
# 变式做对 → 才算第一次
|
||||
r2 = svc.attempt(self.conn, self.gid, self.cid, mid, self._ans(mid), is_variant=True)
|
||||
self.assertEqual(r2["status"], "passed_once")
|
||||
|
||||
def test_variant_wrong_resets(self):
|
||||
mid = self._queued("52 + 39 =")
|
||||
self._strict()
|
||||
svc.attempt(self.conn, self.gid, self.cid, mid, self._ans(mid))
|
||||
r = svc.attempt(self.conn, self.gid, self.cid, mid, "999", is_variant=True)
|
||||
self.assertEqual(r["status"], "queued")
|
||||
self.assertFalse(r["correct"])
|
||||
|
||||
def test_default_off_keeps_old_behaviour(self):
|
||||
mid = self._queued("18 + 27 =")
|
||||
r = svc.attempt(self.conn, self.gid, self.cid, mid, self._ans(mid))
|
||||
self.assertEqual(r["status"], "passed_once")
|
||||
|
||||
def test_cannot_fake_variant(self):
|
||||
mid = self._queued("66 + 18 =")
|
||||
with self.assertRaises(ApiError) as ctx:
|
||||
svc.attempt(self.conn, self.gid, self.cid, mid, self._ans(mid), is_variant=True)
|
||||
self.assertEqual(ctx.exception.code, "NOT_VARIANT_PENDING")
|
||||
|
||||
def test_pending_requires_variant_flag(self):
|
||||
mid = self._queued("77 + 16 =")
|
||||
self._strict()
|
||||
svc.attempt(self.conn, self.gid, self.cid, mid, self._ans(mid))
|
||||
with self.assertRaises(ApiError) as ctx:
|
||||
svc.attempt(self.conn, self.gid, self.cid, mid, self._ans(mid))
|
||||
self.assertEqual(ctx.exception.code, "NEED_VARIANT")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,61 @@
|
||||
"""W8:同一道题连错三次也触发回退(原来只有讲清失败才退)。"""
|
||||
import unittest
|
||||
|
||||
import backend.db as dbm
|
||||
import backend.judging as judging
|
||||
import backend.services as svc
|
||||
from ._tmpdir import workdir
|
||||
|
||||
|
||||
class RetreatOnRepeatTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.conn = dbm.connect(workdir("w8") / (self._testMethodName + ".db"))
|
||||
dbm.init_db(self.conn)
|
||||
self.gid = svc.login(self.conn, "demo")["guardian_id"]
|
||||
svc.give_consent(self.conn, self.gid, "v1")
|
||||
self.cid = svc.create_child(self.conn, self.gid, "皮皮", 2)["id"]
|
||||
|
||||
def tearDown(self):
|
||||
self.conn.close()
|
||||
|
||||
def _one(self, stem, kp=None):
|
||||
ans = judging.fmt_qty(judging.safe_eval(stem.rstrip("== ")))
|
||||
r = svc.add_manual_mistake(self.conn, self.gid, self.cid, "math", stem, ans)
|
||||
mid = r["created"][0]["mistake_id"]
|
||||
if kp:
|
||||
self.conn.execute("UPDATE mistakes SET kp=? WHERE id=?", (kp, mid))
|
||||
return mid
|
||||
|
||||
def test_third_wrong_returns_retreat(self):
|
||||
mid = self._one("36 × 24 =", kp="M041")
|
||||
outs = []
|
||||
for _ in range(3):
|
||||
self.conn.execute("UPDATE mistakes SET next_due=? WHERE id=?", (svc.today(), mid))
|
||||
outs.append(svc.attempt(self.conn, self.gid, self.cid, mid, "999"))
|
||||
self.assertIsNone(outs[0]["retreat"])
|
||||
# 建题时 wrong_count 已是 1,所以第二次做错就凑够三次
|
||||
self.assertIsNotNone(outs[1]["retreat"])
|
||||
self.assertEqual(outs[1]["retreat"]["step"]["id"], "M039")
|
||||
|
||||
def test_correct_answer_has_no_retreat(self):
|
||||
mid = self._one("36 × 24 =", kp="M041")
|
||||
for _ in range(2):
|
||||
self.conn.execute("UPDATE mistakes SET next_due=? WHERE id=?", (svc.today(), mid))
|
||||
svc.attempt(self.conn, self.gid, self.cid, mid, "999")
|
||||
svc.dev_advance(self.conn, 1)
|
||||
r = svc.attempt(self.conn, self.gid, self.cid, mid, "864")
|
||||
self.assertTrue(r["correct"])
|
||||
self.assertIsNone(r["retreat"])
|
||||
|
||||
def test_no_kp_no_retreat(self):
|
||||
mid = self._one("36 × 24 =")
|
||||
# 入库时会按题干自动归类(kp_match),这里手动清空,模拟判不出知识点的题
|
||||
self.conn.execute("UPDATE mistakes SET kp=NULL WHERE id=?", (mid,))
|
||||
for _ in range(3):
|
||||
self.conn.execute("UPDATE mistakes SET next_due=? WHERE id=?", (svc.today(), mid))
|
||||
out = svc.attempt(self.conn, self.gid, self.cid, mid, "999")
|
||||
self.assertIsNone(out["retreat"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,62 @@
|
||||
"""把历史题目里空着的知识点补上(一次性维护脚本,可重复跑,幂等)。
|
||||
|
||||
python tools/backfill_kp.py # 只看会补哪些,不写库
|
||||
python tools/backfill_kp.py --apply # 真写
|
||||
|
||||
判据用的是运行时同一套规则(`backend.kp_match`),所以补出来的结果和
|
||||
新入库的题完全一致。认不准的仍然留空——不硬猜。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import sqlite3
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
from backend import kp_match # noqa: E402
|
||||
|
||||
|
||||
def db_path() -> Path:
|
||||
return Path(os.environ.get("QINGLING_DB") or ROOT / "data" / "app.db")
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
ap = argparse.ArgumentParser(description="补空知识点")
|
||||
ap.add_argument("--apply", action="store_true", help="真的写库(默认只看)")
|
||||
ap.add_argument("--db", default=None, help="数据库路径(默认 data/app.db 或 $QINGLING_DB)")
|
||||
args = ap.parse_args(argv)
|
||||
|
||||
path = Path(args.db) if args.db else db_path()
|
||||
if not path.exists():
|
||||
print(f"没有这个库:{path}")
|
||||
return 1
|
||||
conn = sqlite3.connect(str(path))
|
||||
rows = conn.execute(
|
||||
"SELECT id, subject, stem FROM questions WHERE kp IS NULL OR kp=''").fetchall()
|
||||
todo = []
|
||||
for qid, subject, stem in rows:
|
||||
kp = kp_match.classify(subject, stem)
|
||||
if kp:
|
||||
todo.append((qid, kp, (stem or "").replace("\n", " ")[:48]))
|
||||
print(f"空知识点 {len(rows)} 道,能认出 {len(todo)} 道:")
|
||||
for _qid, kp, stem in todo:
|
||||
print(f" {stem} -> {kp} {kp_match.name_of(kp)}")
|
||||
if not args.apply:
|
||||
print("\n(只看不写;加 --apply 才写)")
|
||||
return 0
|
||||
with conn:
|
||||
for qid, kp, _stem in todo:
|
||||
conn.execute("UPDATE questions SET kp=? WHERE id=?", (kp, qid))
|
||||
left = conn.execute(
|
||||
"SELECT COUNT(*) FROM questions WHERE kp IS NULL OR kp=''").fetchone()[0]
|
||||
print(f"\n写好了 {len(todo)} 道,还剩 {left} 道空着(认不准,留空)")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,66 @@
|
||||
"""变式自校验抽样:跑 100 道题,看 practice.verify 拦下多少、留下来的有没有算错的。
|
||||
|
||||
独立重算不调用 judging:直接按 "a op b" 用 Fraction 算,和变式自己带的答案比。
|
||||
"""
|
||||
import json
|
||||
import re
|
||||
from fractions import Fraction
|
||||
|
||||
import backend.practice as practice
|
||||
|
||||
OP = {"+": 1, "-": -1, "×": 0, "x": 0, "X": 0, "*": 0, "÷": 2, "/": 2}
|
||||
TERM = re.compile(r"(-?\d+(?:\.\d+)?)\s*([+\-×xX*÷/])\s*(-?\d+(?:\.\d+)?)")
|
||||
|
||||
|
||||
def independent(expr):
|
||||
m = TERM.fullmatch(expr.strip())
|
||||
if not m:
|
||||
return None
|
||||
a, op, b = Fraction(m.group(1)), m.group(2), Fraction(m.group(3))
|
||||
if op == "+":
|
||||
return a + b
|
||||
if op == "-":
|
||||
return a - b
|
||||
if op in "×xX*":
|
||||
return a * b
|
||||
return None if b == 0 else a / b
|
||||
|
||||
|
||||
def stems():
|
||||
out = []
|
||||
p = "data/bench/results.jsonl"
|
||||
for line in open(p, encoding="utf-8"):
|
||||
try:
|
||||
rec = json.loads(line)
|
||||
except ValueError:
|
||||
continue
|
||||
for b in rec.get("blocks") or []:
|
||||
if b.get("type") == "calc" and b.get("stem") and b.get("derived"):
|
||||
out.append((b["stem"], b.get("answer") or ""))
|
||||
return out
|
||||
|
||||
|
||||
def main():
|
||||
pool = stems()[:100]
|
||||
kept = rejected = 0
|
||||
bad = []
|
||||
for stem, ans in pool:
|
||||
for it in practice.similar(stem, ans, "calc", "math", 2, n=3):
|
||||
kept += 1
|
||||
want = independent(it["stem"])
|
||||
if want is None:
|
||||
continue
|
||||
if abs(float(want) - float(it["answer"])) > 1e-9:
|
||||
bad.append((it["stem"], it["answer"], float(want)))
|
||||
# 反向:被 verify 拦掉的不统计(它们没进来)
|
||||
# 再跑一遍原始生成(不经 verify),看 verify 总共拦了多少
|
||||
raw = 0
|
||||
for stem, ans in pool:
|
||||
raw += len(practice._math_variants(stem, 3)) if "×" in stem or True else 0
|
||||
print(f"题样 {len(pool)} 道;生成变式 {raw} 道;通过自校验 {kept} 道;独立重算不符 {len(bad)} 道")
|
||||
for x in bad[:5]:
|
||||
print(" 不符:", x)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,33 @@
|
||||
"""一条命令跑全部单测:python tools/run_tests.py
|
||||
|
||||
为什么不用 `unittest discover`:`tests/` 不是包(没有 `__init__.py`,故意的,
|
||||
省得 import 时踩相对导入),`discover -s tests -t .` 会直接报
|
||||
`Start directory is not importable`。这里按文件名显式列出,稳。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import glob
|
||||
import os
|
||||
import sys
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
sys.path.insert(0, str(ROOT))
|
||||
os.chdir(ROOT)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
mods = ["tests." + os.path.basename(p)[:-3]
|
||||
for p in sorted(glob.glob("tests/test_*.py"))]
|
||||
if not mods:
|
||||
print("没找到 tests/test_*.py")
|
||||
return 1
|
||||
suite = unittest.defaultTestLoader.loadTestsFromNames(mods)
|
||||
res = unittest.TextTestRunner(verbosity=1).run(suite)
|
||||
return 0 if res.wasSuccessful() else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,44 @@
|
||||
"""整页拍端点自检:detect → prepare → import 各跑一次。
|
||||
|
||||
python tools/scan_e2e.py http://127.0.0.1:8000
|
||||
先起后端;图片走 OCR 缓存,重复跑不花钱。
|
||||
"""
|
||||
import base64, json, pathlib, sys, urllib.request as u
|
||||
|
||||
BASE = (sys.argv[1] if len(sys.argv) > 1 else "http://127.0.0.1:8000")
|
||||
def call(path, body=None, tok=None, method=None):
|
||||
req = u.Request(BASE + path, data=None if body is None else json.dumps(body).encode(),
|
||||
method=method or ("POST" if body is not None else "GET"),
|
||||
headers={"Content-Type": "application/json",
|
||||
**({"Authorization": "Bearer " + tok} if tok else {})})
|
||||
try:
|
||||
with u.urlopen(req, timeout=60) as r:
|
||||
return json.loads(r.read().decode())
|
||||
except u.HTTPError as e:
|
||||
return json.loads(e.read().decode())
|
||||
|
||||
h = call("/api/health")["data"]
|
||||
print("routes", len(h["routes"]) if isinstance(h.get("routes"), list) else h.get("routes"), "wx", h.get("wx_mode"))
|
||||
|
||||
d = call("/api/auth/sms-code", {"phone": "13800000001"})["data"]
|
||||
tok = call("/api/auth/sms-login", {"phone": "13800000001", "code": d["dev_code"]})["data"]["token"]
|
||||
call("/api/consent", {"version": "v1"}, tok)
|
||||
cid = call("/api/children", {"nickname": "小满", "grade": 2}, tok)["data"]["id"]
|
||||
print("child", cid)
|
||||
|
||||
img = pathlib.Path("data/bench/raw/4111381f63283328.jpg").read_bytes()
|
||||
r = call("/api/papers/scan/detect", {"image_b64": base64.b64encode(img).decode(), "filename": "page.jpg"}, tok)["data"]
|
||||
blocks = r["blocks"]
|
||||
print("draft", r["draft_id"], "size", r["width"], r["height"], "blocks", len(blocks))
|
||||
for b in blocks[:6]:
|
||||
print(" ", b["i"], b["box"], "subs", len(b.get("subs") or []), "|", (b["stem"] or "")[:28].replace("\n", " "))
|
||||
|
||||
picked = [b["i"] for b in blocks[:2]]
|
||||
prep = call("/api/papers/scan/prepare", {"child_id": cid, "subject": "math", "draft_id": r["draft_id"], "picks": picked}, tok)["data"]
|
||||
print("prepare items", len(prep["items"]))
|
||||
for it in prep["items"][:6]:
|
||||
print(" block", it["block"], "sub", it["sub"], "|", (it["stem"] or "")[:30].replace("\n", " "))
|
||||
|
||||
imp = call("/api/papers/scan/import", {"child_id": cid, "subject": "math", "draft_id": r["draft_id"], "picks": picked}, tok)["data"]
|
||||
print("import ->", {k: imp["ocr"].get(k) for k in ("picked", "created", "blocks")})
|
||||
|
||||