dsh-chaoxing-assistant 2.3.8 → 2.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/tools.mjs CHANGED
@@ -523,7 +523,7 @@ export function createToolDefinitions(deps) {
523
523
  const examTool = {
524
524
  name: 'chaoxing_exam',
525
525
  description:
526
- '章节测验与作业(只操作本地浏览器):quiz_fetch=打开某个知识点的测验页并抓题(自动解码学习通的反爬字体,返回题干/选项/填空数量);quiz_submit=把你作答的计划回填并提交(必须 confirm:true,可 save 缓存答案供 chaoxing_run 的 quizPolicy=cached 使用);work_list=列出一门课的作业;work_fetch=打开作业并抓题(含图片题干提示);work_submit=回填并提交作业(必须 confirm:true);captcha=把人工识别的验证码交给卡住的后台任务。抓题不会提交任何东西;不要用猜测的答案提交计分测验或作业。',
526
+ '章节测验与作业(只操作本地浏览器):quiz_fetch=打开某个知识点的测验页并抓题(自动解码学习通的反爬字体,并识别题干/选项里的图片符号如 Ω、μ、220,返回题干/选项/填空数量与图片识别摘要);quiz_submit=把你作答的计划回填并提交(必须 confirm:true,可 save 缓存答案供 chaoxing_run 的 quizPolicy=cached 使用);work_list=列出一门课的作业;work_fetch=打开作业并抓题(含图片题干提示);work_submit=回填并提交作业(必须 confirm:true);captcha=把人工识别的验证码交给卡住的后台任务。抓题不会提交任何东西;不要用猜测的答案提交计分测验或作业。',
527
527
  parameters: {
528
528
  type: 'object',
529
529
  properties: {
@@ -595,6 +595,13 @@ export function createToolDefinitions(deps) {
595
595
  fontFound: q.fontFound,
596
596
  mapped: q.mapped,
597
597
  md5: q.md5,
598
+ images: {
599
+ total: q.imgTotal,
600
+ resolved: q.imgResolved,
601
+ unresolved: q.imgUnresolved,
602
+ sig: q.imgSig,
603
+ detail: (q.images || []).map((x) => ({ src: x.src, w: x.w, h: x.h, text: x.text, ok: x.ok, engine: x.engine, score: x.score, error: x.error })),
604
+ },
598
605
  items: q.items,
599
606
  hint: '把每题的答案整理成 [{i, letters:["A"], texts:["选项文字前12字"]}](多选就多个字母),再调 quiz_submit 并传 confirm:true',
600
607
  };
@@ -618,6 +625,14 @@ export function createToolDefinitions(deps) {
618
625
  result = { ok: false, reason: q.reason || 'fetch-failed', imagePath: q.imagePath, log: sink.slice(-8) };
619
626
  } else if (q.alreadySubmitted) {
620
627
  result = { ok: true, alreadySubmitted: true, hint: '这套测验已经提交/判分过了,没有重复提交' };
628
+ } else if (Number(q.imgUnresolved) > 0) {
629
+ // 自动流程有同样的闸门;手工 quiz_submit 也必须拦:缺单位的题干(R=125, C=31.8F)
630
+ // 会让人/模型按错的数值作答,提交出去就是低分卷。
631
+ result = {
632
+ ok: false,
633
+ error: '题干/选项里有无法识别的图片,缺单位/数值时作答会算错,已拒绝提交',
634
+ images: { total: q.imgTotal, resolved: q.imgResolved, unresolved: q.imgUnresolved, detail: (q.images || []).filter((x) => !x.ok).map((x) => ({ src: x.src, error: x.error })) },
635
+ };
621
636
  } else {
622
637
  const plan = normalizePlan(answers);
623
638
  const fill = await fillQuiz(page, plan, ctx);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-chaoxing-assistant",
3
- "version": "2.3.8",
3
+ "version": "2.4.0",
4
4
  "description": "学习通(超星)任务助手:真实 Edge 或 Windows 客户端完成视频/文档、章节测验与作业,右侧栏面板 + 5 个工具。人工验证自动停机、空题不交卷、播完先等平台确认。",
5
5
  "type": "module",
6
6
  "main": "./index.js",
@@ -0,0 +1,360 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """识别学习通测验题干/选项里的内嵌图片。
4
+
5
+ 背景:题目把 Ω、μ、° 等单位符号做成 <img>(p.ananas.chaoxing.com 的透明 PNG),
6
+ 以前插件用 innerText 抓题干,图片直接消失,模型看到 "R = 125, C = 31.8F" 就会答错。
7
+ 本脚本先把透明图合成到白底,再分两路识别:
8
+ * 多字符(如 220、10)走 RapidOCR;
9
+ * 单个字形用 Windows 字体渲染模板做形状匹配(OCR 会把 μ 认成 H,只能当兜底)。
10
+ 识别不了的返回 ok=false,由 Node 侧把整题标成「图片未识别」并拒绝交卷。
11
+ 结果按图片 sha256 缓存,同一张图只识别一次。
12
+ """
13
+ import argparse
14
+ import hashlib
15
+ import json
16
+ import os
17
+ import sys
18
+ import tempfile
19
+ import traceback
20
+
21
+ # 常见单位/数学符号 + 拉丁字母数字;顺序不重要,模板会按字体去重。
22
+ SYMBOLS = list("Ωμ°±×÷≈≤≥≠∞παβγθλφωΔ√∑∫²³½¼¾Å·—–’“”")
23
+ LATIN = list("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789")
24
+ CANDIDATES = SYMBOLS + LATIN
25
+
26
+ # (路径, ttc index);只保留本机存在的。SimSun 覆盖最全,Arial/Times 形状最常用。
27
+ FONT_FILES = [
28
+ (r"C:\Windows\Fonts\simsun.ttc", 0),
29
+ (r"C:\Windows\Fonts\cambria.ttc", 0),
30
+ (r"C:\Windows\Fonts\times.ttf", 0),
31
+ (r"C:\Windows\Fonts\segoeui.ttf", 0),
32
+ (r"C:\Windows\Fonts\calibri.ttf", 0),
33
+ (r"C:\Windows\Fonts\seguisym.ttf", 0),
34
+ ]
35
+ # 字形只有 10-20px 高,按小字号渲染模板才匹配得上;大字号反而因笔画细节对不上。
36
+ SIZES = (11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 22)
37
+
38
+ _TEMPLATES = {}
39
+ _ENGINE = None
40
+ _FONTS = None
41
+ # 算法升级时改这个数:旧缓存里的识别结果不会再被复用
42
+ CACHE_VERSION = 3
43
+
44
+
45
+ def _fonts():
46
+ global _FONTS
47
+ if _FONTS is not None:
48
+ return _FONTS
49
+ from PIL import ImageFont
50
+ out = []
51
+ for path, idx in FONT_FILES:
52
+ if not os.path.exists(path):
53
+ continue
54
+ for size in SIZES:
55
+ try:
56
+ f = ImageFont.truetype(path, size, index=idx)
57
+ except Exception:
58
+ continue
59
+ out.append(f)
60
+ _FONTS = out
61
+ return out
62
+
63
+
64
+ def _flatten(path):
65
+ """打开图片并把透明背景合成到白底(透明像素的 RGB 是 0,直接转灰度会全黑)。"""
66
+ from PIL import Image
67
+ im = Image.open(path)
68
+ im.load()
69
+ if im.mode == "P":
70
+ im = im.convert("RGBA") if "transparency" in im.info else im.convert("RGB")
71
+ if im.mode in ("RGBA", "LA"):
72
+ bg = Image.new("RGBA", im.size, (255, 255, 255, 255))
73
+ im = Image.alpha_composite(bg, im).convert("RGB")
74
+ else:
75
+ im = im.convert("RGB")
76
+ return im
77
+
78
+
79
+ def _bbox(im, th=200):
80
+ import numpy as np
81
+ arr = np.array(im.convert("L"))
82
+ mask = arr < th
83
+ ys, xs = np.where(mask)
84
+ if not len(xs):
85
+ return None
86
+ return int(xs.min()), int(ys.min()), int(xs.max()) + 1, int(ys.max()) + 1
87
+
88
+
89
+ def _mask28(im, th=180):
90
+ """裁掉白边,等比缩放到 28x28 画布中心,返回 bool 蒙版。"""
91
+ import numpy as np
92
+ from PIL import Image
93
+ g = im.convert("L")
94
+ bb = _bbox(g, th)
95
+ if not bb:
96
+ return None
97
+ x0, y0, x1, y1 = bb
98
+ if x1 - x0 < 2 or y1 - y0 < 2:
99
+ return None
100
+ crop = g.crop(bb)
101
+ w, h = crop.size
102
+ scale = min(24.0 / max(1, w), 24.0 / max(1, h))
103
+ nw = max(1, int(round(w * scale)))
104
+ nh = max(1, int(round(h * scale)))
105
+ crop = crop.resize((nw, nh), Image.LANCZOS)
106
+ canvas = Image.new("L", (28, 28), 255)
107
+ canvas.paste(crop, ((28 - nw) // 2, (28 - nh) // 2))
108
+ arr = np.array(canvas) < th
109
+ return arr if arr.any() else None
110
+
111
+
112
+ def _render_mask(ch, font):
113
+ from PIL import Image, ImageDraw
114
+ try:
115
+ bbox = font.getbbox(ch)
116
+ if not bbox:
117
+ return None
118
+ w = max(1, bbox[2] - bbox[0])
119
+ h = max(1, bbox[3] - bbox[1])
120
+ size = max(12, int(getattr(font, "size", 16)) * 2)
121
+ canvas = Image.new("L", (size, size), 255)
122
+ d = ImageDraw.Draw(canvas)
123
+ d.text((size / 2 - w / 2 - bbox[0], size / 2 - h / 2 - bbox[1]), ch, font=font, fill=0)
124
+ return _mask28(canvas)
125
+ except Exception:
126
+ return None
127
+
128
+
129
+ def _templates():
130
+ global _TEMPLATES
131
+ if _TEMPLATES:
132
+ return _TEMPLATES
133
+ fs = _fonts()
134
+ if not fs:
135
+ _TEMPLATES = {}
136
+ return _TEMPLATES
137
+ for ch in CANDIDATES:
138
+ masks = []
139
+ for f in fs:
140
+ m = _render_mask(ch, f)
141
+ if m is not None:
142
+ masks.append(m)
143
+ if masks:
144
+ _TEMPLATES[ch] = masks
145
+ return _TEMPLATES
146
+
147
+
148
+ def _iou(a, b):
149
+ import numpy as np
150
+ best = 0.0
151
+ for dy in (-1, 0, 1):
152
+ for dx in (-1, 0, 1):
153
+ bb = np.roll(np.roll(b, dy, axis=0), dx, axis=1)
154
+ inter = np.logical_and(a, bb).sum()
155
+ union = np.logical_or(a, bb).sum()
156
+ if union:
157
+ v = float(inter) / float(union)
158
+ if v > best:
159
+ best = v
160
+ return best
161
+
162
+
163
+ def _match_glyph(im):
164
+ import numpy as np
165
+ m = _mask28(im)
166
+ if m is None:
167
+ return None
168
+ tpl = _templates()
169
+ scores = []
170
+ for ch, masks in tpl.items():
171
+ s = max((_iou(m, t) for t in masks), default=0.0)
172
+ scores.append((s, ch))
173
+ if not scores:
174
+ return None
175
+ scores.sort(key=lambda x: (-x[0], x[1]))
176
+ top = scores[0]
177
+ second = scores[1] if len(scores) > 1 else (0.0, "")
178
+ return {
179
+ "ch": top[1],
180
+ "score": round(top[0], 4),
181
+ "margin": round(top[0] - second[0], 4),
182
+ "runner": second[1],
183
+ "runnerScore": round(second[0], 4),
184
+ }
185
+
186
+
187
+ def _ocr(im, cache_dir):
188
+ """RapidOCR 识别整张图;返回 {text, score, lines}。"""
189
+ global _ENGINE
190
+ from PIL import Image
191
+ import numpy as np
192
+ if _ENGINE is None:
193
+ from rapidocr_onnxruntime import RapidOCR
194
+ _ENGINE = RapidOCR()
195
+ w, h = im.size
196
+ scale = max(4.0, 80.0 / max(1, h))
197
+ scale = min(scale, 1600.0 / max(1, max(w, h)))
198
+ big = im.resize((max(1, int(w * scale)), max(1, int(h * scale))), Image.LANCZOS)
199
+ canvas = Image.new("RGB", (big.width + 40, big.height + 40), (255, 255, 255))
200
+ canvas.paste(big, (20, 20))
201
+ fd, tmp = tempfile.mkstemp(prefix="stemocr_", suffix=".png", dir=cache_dir or None)
202
+ os.close(fd)
203
+ try:
204
+ canvas.save(tmp)
205
+ res, _elapse = _ENGINE(tmp)
206
+ finally:
207
+ try:
208
+ os.unlink(tmp)
209
+ except OSError:
210
+ pass
211
+ if not res:
212
+ return {"text": "", "score": 0.0, "lines": []}
213
+ lines = []
214
+ for row in res:
215
+ try:
216
+ box, text, score = row[0], str(row[1]), float(row[2])
217
+ except Exception:
218
+ continue
219
+ if not text or not text.strip():
220
+ continue
221
+ ys = [p[1] for p in box]
222
+ lines.append((min(ys), text.strip(), score))
223
+ lines.sort(key=lambda x: (x[0], x[1]))
224
+ text = " ".join(x[1] for x in lines).strip()
225
+ score = min((x[2] for x in lines), default=0.0)
226
+ return {"text": text, "score": round(score, 4), "lines": lines}
227
+
228
+
229
+ def _is_cjk(ch):
230
+ return any("\u4e00" <= c <= "\u9fff" for c in ch)
231
+
232
+
233
+ def _decorative(im, bb):
234
+ """细线、纯色小方块视为装饰线,不当作题干内容。"""
235
+ w = bb[2] - bb[0]
236
+ h = bb[3] - bb[1]
237
+ if h <= 2 or w <= 2:
238
+ return True
239
+ if w >= 40 and h <= 4:
240
+ return True
241
+ return False
242
+
243
+
244
+ def _ocr_safe(text):
245
+ """多字符 OCR 结果能不能直接当题干用。
246
+
247
+ 单位/数值图(220、10、kV)OCR 出来很短、没有公式符号,可信。
248
+ 公式/线路图 OCR 往往缺项——实测 132x29 的公式图识别成 "1. =311sin(314+) 6"
249
+ (score 0.74),比看不到图更危险:模型会拿这个残缺式子算。这里一律判为
250
+ 无法识别,让 engine 跳过整卷(imgUnresolved>0),宁可不交也不交错。
251
+ """
252
+ t = (text or "").strip()
253
+ if not t or len(t) > 20:
254
+ return False
255
+ for ch in "={}[]\\^_":
256
+ if ch in t:
257
+ return False
258
+ return True
259
+
260
+
261
+ def _decide(im, ocr, glyph, w, h):
262
+ text = (ocr.get("text") or "").strip()
263
+ score = float(ocr.get("score") or 0.0)
264
+ # 长条图 / 多字符:OCR 可信就用(Ω 的 OCR 只有 0.21,不会被这里收走)
265
+ if len(text) >= 2:
266
+ if score >= 0.60 and _ocr_safe(text):
267
+ return {"ok": True, "text": text, "engine": "ocr", "score": score}
268
+ if score >= 0.60 and len(text) > 20:
269
+ return {"ok": False, "error": "complex-image"}
270
+ if score >= 0.60 and not _ocr_safe(text):
271
+ return {"ok": False, "error": "complex-image"}
272
+ # 单个汉字:模板集里没有汉字,只能信高分 OCR
273
+ if len(text) == 1 and _is_cjk(text) and score >= 0.80:
274
+ return {"ok": True, "text": text, "engine": "ocr", "score": score}
275
+ # 单字形模板匹配(主路径)
276
+ if glyph and glyph["score"] >= 0.78 and glyph["margin"] >= 0.08:
277
+ return {"ok": True, "text": glyph["ch"], "engine": "glyph", "score": glyph["score"], "margin": glyph["margin"]}
278
+ # OCR 与模板给出同一个字符
279
+ if glyph and len(text) == 1 and text == glyph["ch"] and score >= 0.55:
280
+ return {"ok": True, "text": text, "engine": "both", "score": score}
281
+ # 数字/拉丁单字符的高分 OCR(有些字体模板没覆盖)
282
+ if len(text) == 1 and text.isalnum() and score >= 0.96 and w * h <= 80 * 80:
283
+ return {"ok": True, "text": text, "engine": "ocr", "score": score}
284
+ return {"ok": False, "error": "unrecognized"}
285
+
286
+
287
+ def recognize(path, cache_dir=""):
288
+ try:
289
+ im = _flatten(path)
290
+ bb = _bbox(im)
291
+ if not bb:
292
+ return {"ok": True, "text": "", "engine": "blank", "score": 0.0, "w": im.width, "h": im.height}
293
+ w = bb[2] - bb[0]
294
+ h = bb[3] - bb[1]
295
+ if _decorative(im, bb):
296
+ return {"ok": True, "text": "", "engine": "decorative", "score": 0.0, "w": w, "h": h}
297
+ glyph = _match_glyph(im)
298
+ ocr = {"text": "", "score": 0.0, "lines": []}
299
+ # 很小的图不跑 OCR:12x12 以下基本是装饰点/裁切标记
300
+ if w >= 8 and h >= 8:
301
+ try:
302
+ ocr = _ocr(im, cache_dir)
303
+ except Exception as e:
304
+ ocr = {"text": "", "score": 0.0, "lines": [], "error": str(e)[:200]}
305
+ out = _decide(im, ocr, glyph, w, h)
306
+ out.update({"w": w, "h": h, "ocr": ocr, "glyph": glyph})
307
+ return out
308
+ except Exception as e:
309
+ return {"ok": False, "error": str(e)[:300], "trace": traceback.format_exc()[-800:]}
310
+
311
+
312
+ def main():
313
+ # Windows 上重定向 stdout 时默认可能是 GBK,Ω/μ 会被替换成 ?;强制按 UTF-8 字节输出。
314
+ try:
315
+ sys.stdout.reconfigure(encoding="utf-8")
316
+ except Exception:
317
+ pass
318
+ ap = argparse.ArgumentParser()
319
+ ap.add_argument("--jobs", required=True)
320
+ ap.add_argument("--cache", default="")
321
+ args = ap.parse_args()
322
+ with open(args.jobs, "r", encoding="utf-8") as f:
323
+ jobs = json.load(f)
324
+ cache_dir = args.cache or ""
325
+ if cache_dir:
326
+ os.makedirs(cache_dir, exist_ok=True)
327
+ results = {}
328
+ for job in jobs:
329
+ sha = str(job.get("sha") or "")
330
+ path = job.get("path") or ""
331
+ if not sha or not path or not os.path.exists(path):
332
+ results[sha or path] = {"ok": False, "error": "file-missing"}
333
+ continue
334
+ cf = os.path.join(cache_dir, "v%d_%s.json" % (CACHE_VERSION, sha)) if cache_dir else ""
335
+ if cf and os.path.exists(cf):
336
+ try:
337
+ with open(cf, "r", encoding="utf-8") as f:
338
+ results[sha] = json.load(f)
339
+ continue
340
+ except Exception:
341
+ pass
342
+ res = recognize(path, cache_dir)
343
+ results[sha] = res
344
+ if cf:
345
+ try:
346
+ with open(cf, "w", encoding="utf-8") as f:
347
+ json.dump(res, f, ensure_ascii=False)
348
+ except Exception:
349
+ pass
350
+ payload = "RESULT " + json.dumps({"results": results}, ensure_ascii=False) + "\n"
351
+ try:
352
+ sys.stdout.buffer.write(payload.encode("utf-8"))
353
+ sys.stdout.buffer.flush()
354
+ except Exception:
355
+ print(payload, end="")
356
+ return 0
357
+
358
+
359
+ if __name__ == "__main__":
360
+ sys.exit(main())